Building a Safe Expression Parser to Replace eval Under a Strict CSP
A developer building a live graphing calculator could not use eval because the site's Content-Security-Policy forbids unsafe-eval, a restriction that also shields the site from XSS via user input. Instead, they wrote a roughly eighty-line expression parser that runs in four stages: tokenizing, inserting implicit multiplication, converting to reverse Polish notation via the shunting-yard method, and evaluating. The article highlights three common pitfalls: treating unary minus as ordinary subtraction (so -3^2 must equal -9), requiring right-associativity for exponentiation (so 2^3^2 equals 512), and recognizing implicit multiplication such as 2x without mistaking function names like sin(x) for variables. Parsing once and evaluating the compiled expression at each sample point keeps the plotting loop fast.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in