Skip to content

Commit

Permalink
Avoid using moo.keywords which requires unsafe eval
Browse files Browse the repository at this point in the history
# This method, instead of custom-built then eval-ed switch-case statements,
# is about half the speed of the original. But it avoids the need for
# unsafe-eval in the CSP.
  • Loading branch information
jsharkey13 committed Apr 16, 2020
1 parent 4044754 commit d9b75a6
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion assets/grammar.ne
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
@{%
const greekLetterMap = { "alpha": "α", "beta": "β", "gamma": "γ", "delta": "δ", "epsilon": "ε", "varepsilon": "ε", "zeta": "ζ", "eta": "η", "theta": "θ", "iota": "ι", "kappa": "κ", "lambda": "λ", "mu": "μ", "nu": "ν", "xi": "ξ", "omicron": "ο", "pi": "π", "rho": "ρ", "sigma": "σ", "tau": "τ", "upsilon": "υ", "phi": "ϕ", "chi": "χ", "psi": "ψ", "omega": "ω", "Gamma": "Γ", "Delta": "Δ", "Theta": "Θ", "Lambda": "Λ", "Xi": "Ξ", "Pi": "Π", "Sigma": "Σ", "Upsilon": "Υ", "Phi": "Φ", "Psi": "Ψ", "Omega": "Ω" }
// See https://github.com/no-context/moo/blob/v0.5.1/moo.js#L337-L371
function keywordTransformSafe(map) {
let reverseMap = Object.create(null);
let types = Object.getOwnPropertyNames(map);
for (let i = 0; i < types.length; i++) {
let tokenType = types[i];
let item = map[tokenType];
let keywordList = Array.isArray(item) ? item : [item];
keywordList.forEach(function(keyword) {
if (typeof keyword !== 'string') {
throw new Error("keyword must be string (in keyword '" + tokenType + "')");
}
reverseMap[keyword] = tokenType;
})
}
return function(k) {
return reverseMap[k];
}
}
const moo = require("moo")
const lexer = moo.compile({
Int: /[0-9]+/,
IdMod: /[a-zA-Z]+_(?:prime)/,
Id: { match: /[a-zA-Z]+(?:_[a-zA-Z0-9]+)?/, type: moo.keywords({
Id: { match: /[a-zA-Z]+(?:_[a-zA-Z0-9]+)?/, type: keywordTransformSafe({
TrigFn: ['cos', 'sin', 'tan',
'cosec', 'sec', 'cot',
'cosh', 'sinh', 'tanh', 'cosech', 'sech', 'coth',
Expand Down

0 comments on commit d9b75a6

Please sign in to comment.