-
Notifications
You must be signed in to change notification settings - Fork 518
[fix] Replace eval() with safe math expression parser #9263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import { describe, expect, test } from 'vitest' | ||
|
|
||
| import { evaluateMathExpression } from '@/lib/litegraph/src/utils/mathParser' | ||
|
|
||
| describe('evaluateMathExpression', () => { | ||
| test.each([ | ||
| ['2+3', 5], | ||
| ['10-4', 6], | ||
| ['3*7', 21], | ||
| ['15/3', 5] | ||
| ])('basic arithmetic: %s = %d', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['2+3*4', 14], | ||
| ['(2+3)*4', 20], | ||
| ['10-2*3', 4], | ||
| ['10/2+3', 8] | ||
| ])('operator precedence: %s = %d', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['3.14*2', 6.28], | ||
| ['.5+.5', 1], | ||
| ['1.5+2.5', 4], | ||
| ['0.1+0.2', 0.1 + 0.2], | ||
| ['123.', 123], | ||
| ['123.+3', 126] | ||
| ])('decimals: %s', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test.each([ | ||
| [' 2 + 3 ', 5], | ||
| [' 10 - 4 ', 6], | ||
| [' ( 2 + 3 ) * 4 ', 20] | ||
| ])('whitespace handling: "%s" = %d', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['((2+3))', 5], | ||
| ['(1+(2*(3+4)))', 15], | ||
| ['((1+2)*(3+4))', 21] | ||
| ])('nested parentheses: %s = %d', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['-5', -5], | ||
| ['-(3+2)', -5], | ||
| ['--5', 5], | ||
| ['+5', 5], | ||
| ['-3*2', -6], | ||
| ['2*-3', -6], | ||
| ['1+-2', -1], | ||
| ['2--3', 5], | ||
| ['-2*-3', 6], | ||
| ['-(2+3)*-(4+5)', 45] | ||
| ])('unary operators: %s = %d', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['2 /2+3 * 4.75- -6', 21.25], | ||
| ['2 / (2 + 3) * 4.33 - -6', 7.732], | ||
| ['12* 123/-(-5 + 2)', 492], | ||
| ['((80 - (19)))', 61], | ||
| ['(1 - 2) + -(-(-(-4)))', 3], | ||
| ['1 - -(-(-(-4)))', -3], | ||
| ['12* 123/(-5 + 2)', -492], | ||
| ['12 * -123', -1476], | ||
| ['((2.33 / (2.9+3.5)*4) - -6)', 7.45625], | ||
| ['123.45*(678.90 / (-2.5+ 11.5)-(80 -19) *33.25) / 20 + 11', -12042.760875], | ||
| [ | ||
| '(123.45*(678.90 / (-2.5+ 11.5)-(((80 -(19))) *33.25)) / 20) - (123.45*(678.90 / (-2.5+ 11.5)-(((80 -(19))) *33.25)) / 20) + (13 - 2)/ -(-11) ', | ||
| 1 | ||
| ] | ||
| ])('complex expression: %s', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBeCloseTo(expected as number) | ||
| }) | ||
|
|
||
| test.each(['', 'abc', '2+', '(2+3', '2+3)', '()', '*3', '2 3', '.', '123..'])( | ||
| 'invalid input returns undefined: "%s"', | ||
| (input) => { | ||
| expect(evaluateMathExpression(input)).toBeUndefined() | ||
| } | ||
| ) | ||
|
|
||
| test('division by zero returns Infinity', () => { | ||
| expect(evaluateMathExpression('1/0')).toBe(Infinity) | ||
| }) | ||
|
|
||
| test('0/0 returns NaN', () => { | ||
| expect(evaluateMathExpression('0/0')).toBeNaN() | ||
| }) | ||
|
|
||
| test.each([ | ||
| ['10%3', 1], | ||
| ['10%3+1', 2], | ||
| ['7%2', 1] | ||
| ])('modulo: %s = %d', (input, expected) => { | ||
| expect(evaluateMathExpression(input)).toBe(expected) | ||
| }) | ||
|
|
||
| test('negative zero is normalized to positive zero', () => { | ||
| expect(Object.is(evaluateMathExpression('-0'), 0)).toBe(true) | ||
| }) | ||
|
|
||
| test('deeply nested parentheses exceeding depth limit returns undefined', () => { | ||
| const input = '('.repeat(201) + '1' + ')'.repeat(201) | ||
| expect(evaluateMathExpression(input)).toBeUndefined() | ||
| }) | ||
|
|
||
| test('parentheses within depth limit evaluate correctly', () => { | ||
| const input = '('.repeat(200) + '1' + ')'.repeat(200) | ||
| expect(evaluateMathExpression(input)).toBe(1) | ||
| }) | ||
| }) | ||
christian-byrne marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| type Token = { type: 'number'; value: number } | { type: 'op'; value: string } | ||
|
|
||
| function tokenize(input: string): Token[] | undefined { | ||
| const tokens: Token[] = [] | ||
| const re = /(\d+(?:\.\d*)?|\.\d+)|([+\-*/%()])/g | ||
| let lastIndex = 0 | ||
|
|
||
| for (const match of input.matchAll(re)) { | ||
| const gap = input.slice(lastIndex, match.index) | ||
| if (gap.trim()) return undefined | ||
| lastIndex = match.index + match[0].length | ||
|
|
||
| if (match[1]) tokens.push({ type: 'number', value: parseFloat(match[1]) }) | ||
| else tokens.push({ type: 'op', value: match[2] }) | ||
| } | ||
|
|
||
| if (input.slice(lastIndex).trim()) return undefined | ||
| return tokens | ||
| } | ||
|
|
||
| /** | ||
| * Evaluates a basic arithmetic expression string containing | ||
| * `+`, `-`, `*`, `/`, `%`, parentheses, and decimal numbers. | ||
| * Returns `undefined` for empty or malformed input. | ||
| */ | ||
| export function evaluateMathExpression(input: string): number | undefined { | ||
| const tokenized = tokenize(input) | ||
| if (!tokenized || tokenized.length === 0) return undefined | ||
|
|
||
| const tokens: Token[] = tokenized | ||
| let pos = 0 | ||
| let depth = 0 | ||
| const MAX_DEPTH = 200 | ||
|
|
||
| function peek(): Token | undefined { | ||
| return tokens[pos] | ||
| } | ||
|
|
||
| function consume(): Token { | ||
| return tokens[pos++] | ||
| } | ||
|
|
||
| function primary(): number | undefined { | ||
| const t = peek() | ||
| if (!t) return undefined | ||
|
|
||
| if (t.type === 'number') { | ||
| consume() | ||
| return t.value | ||
| } | ||
|
|
||
| if (t.type === 'op' && t.value === '(') { | ||
| if (++depth > MAX_DEPTH) return undefined | ||
| consume() | ||
| const result = expr() | ||
christian-byrne marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (result === undefined) return undefined | ||
| const closing = peek() | ||
| if (!closing || closing.type !== 'op' || closing.value !== ')') { | ||
| return undefined | ||
| } | ||
| consume() | ||
| depth-- | ||
| return result | ||
| } | ||
|
|
||
| return undefined | ||
| } | ||
|
|
||
| function unary(): number | undefined { | ||
| const t = peek() | ||
| if (t?.type === 'op' && (t.value === '+' || t.value === '-')) { | ||
| consume() | ||
| const operand = unary() | ||
| if (operand === undefined) return undefined | ||
| return t.value === '-' ? -operand : operand | ||
| } | ||
| return primary() | ||
| } | ||
|
|
||
| function factor(): number | undefined { | ||
| let left = unary() | ||
| if (left === undefined) return undefined | ||
|
|
||
| while ( | ||
| peek()?.type === 'op' && | ||
| (peek()!.value === '*' || peek()!.value === '/' || peek()!.value === '%') | ||
| ) { | ||
| const op = consume().value | ||
| const right = unary() | ||
| if (right === undefined) return undefined | ||
| left = | ||
| op === '*' ? left * right : op === '/' ? left / right : left % right | ||
| } | ||
| return left | ||
| } | ||
|
|
||
| function expr(): number | undefined { | ||
| let left = factor() | ||
| if (left === undefined) return undefined | ||
|
|
||
| while ( | ||
| peek()?.type === 'op' && | ||
| (peek()!.value === '+' || peek()!.value === '-') | ||
| ) { | ||
| const op = consume().value | ||
| const right = factor() | ||
| if (right === undefined) return undefined | ||
| left = op === '+' ? left + right : left - right | ||
| } | ||
| return left | ||
| } | ||
|
|
||
| const result = expr() | ||
| if (result === undefined || pos !== tokens.length) return undefined | ||
| return result === 0 ? 0 : result | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.