JavaScript, Python

Ein mit Node ausgeführter - Backus-Naur Parser in JavaScript

/*
expr ::= expr + term | term
term ::= term * factor | factor
factor ::= '(' expr ')' | const

Bzw.

expr ::= term | term '+' expr
term ::= factor | factor '*' term
factor ::= '(' expr ')' | const

const ::= '9', '8', ..., '0'
*/

/* Lexer */
let i = 0;
let s = "((4+5*(4+2))+1)*3";

function nexttoken () {
    return s [i++];
}

function tokenback () {
    i--;
}

function expr () {
    let x;
    let y = 0;

    x = term ();
    if (nexttoken () == '+')  {
        y = expr ();
    }
    else
        tokenback ();
return x + y;
}

function term () {
    let x;
    let y = 1;

    x = factor ();
    if (nexttoken () == '*')
        y = term ();
    else
        tokenback ();
return x * y;
}

function factor () {
    let s = nexttoken ();
    let x1 = parseInt (s);
    let x;

    if (s == '(') {
        x = expr ();
        if (nexttoken () != ')')
            throw new Error("Missing closing bracket");
    }
    else if ((x1 >= 0) \&amp;\&amp; (x1 <= 9))
        x = x1;
    else
        throw new Error("Unknown or wrong character");
return x;
}

console.log (expr ());
console.log (((4+5*(4+2))+1)*3);