reLexer.js

A very simple Javascript lexer and parser

To define your grammar you need to define the rules first. Also, you need to specify the root rule. After having done that, you will be able to generate a concrete syntax tree (parse tree) when lexing (tokenizing) a certain expression.

lexer = new reLexer(rules, 'expression');

Optionally, you can also define actions which will be used when parsing expressions.

lexer = new reLexer(rules, 'expression', actions);

Lexing an expression is as easy as follows:

lexer.tokenize('1 > 2 ? "Yes" : "No"');

When parsing an expression, you are able to define the environment available during parsing. Also, you can define (or override in case you have multiple parsing purposes) the actions.

lexer.parse('19 + 82');

lexer.parse('company.name', {company: {name: 'Engel Inc.'}});

lexer.parse('company.name', {company: {name: 'Engel Inc.'}}, actions);

You can try out reLexer.js right here. Just fill in the expression and environment to tokenize and parse. The grammar rules and actions used are documented in the Setup section.

# Expression # Environment Reset # Result # Parse tree

These are the grammar rules used for this demo page are as follows.

And these are the corresponding actions used for evaluation.

> Booleans

> Numbers

> Strings

> Objects

> Logical operators

> Calculations

> Ternary statements