ExpressionParser icon indicating copy to clipboard operation
ExpressionParser copied to clipboard

How to support negative literals like `-1`?

Open blueloveTH opened this issue 3 months ago • 0 comments

I am using this library with custom language:

function buildParser(globals: any) {
    const arithmeticLanguage = {
        INFIX_OPS: {
            '+': function (a: any, b: any) {
                return a() + b();
            },
            '-': function (a: any, b: any) {
                return a() - b();
            },
            '*': function (a: any, b: any) {
                return a() * b();
            },
            '/': function (a: any, b: any) {
                return a() / b();
            },
            '//': function (a: any, b: any) {
                return Math.floor(a() / b());
            },
            '%': function (a: any, b: any) {
                return a() % b();
            },
            '**': function (a: any, b: any) {
                return a() ** b();
            }
        },
        PREFIX_OPS: {
            'math.log': function (a: any) {
                return Math.log(a());
            },
            'int': function (a: any) {
                return Math.floor(a());
            },
            'round': function (a: any) {
                return Math.round(a());
            },
        },
        PRECEDENCE: [['math.log', 'int', 'round'], ['**'], ['*', '/', '//', '%'], ['+', '-']],
        GROUP_OPEN: '(',
        GROUP_CLOSE: ')',
        SEPARATORS: [','],
        WHITESPACE_CHARS: [" "],
        SYMBOLS: ['(', ')', '+', '-', '*', '/', '//', '%', '**', ','],
        AMBIGUOUS: {},
        ESCAPE_CHAR: '\\',
        LITERAL_OPEN: '"',
        LITERAL_CLOSE: '"',
        termDelegate: function (term: string) {
            if (term === 'x') return globals.x;
            if (term === 'y') return globals.y;
            return Number(term);
        },
    };
    return new ExpressionParser(arithmeticLanguage);
}

However, it does not recogize x * -1.

blueloveTH avatar Oct 06 '25 11:10 blueloveTH