This is a fork of Zach Carter [email protected]'s jison module tweaked to use just enough templates to make typescript compilers tollerate the generated parser.
This works (I'm using it in a few javascript and typescritp projects) and runs the original tests. If you want to geek about this, ping ericP on discord or ericprud on gitter.
- @ts-jison/parser-generator - A lightly-typescriptified version of jison
- @ts-jison/lexer-generator - A lightly-typescriptified version of jison-lex
- @ts-jison/parser - runtime library for parsers
- @ts-jison/lexer - runtime library for lexers
- @ts-jison/common - functions needed by parser and lexer
This example parses and executes mathematical expressions:
%{
function hexlify (str:string): string { // elide TS types for js-compatibility
return str.split('').map(ch => '0x' + ch.charCodeAt(0).toString(16)).join(', ')
}
%}
%lex
%no-break-if (.*[^a-z] | '') 'return' ([^a-z].* | '') // elide trailing 'break;'
%%
\s+ if (yy.trace) yy.trace(`skipping whitespace ${hexlify(yytext)}`)
[0-9]+("."[0-9]+)?\b return 'NUMBER'
"-" return '-'
"+" return '+'
"(" return '('
")" return ')'
<<EOF>> return 'EOF'
. return 'INVALID'
/lex
%left '+' '-'
%left UMINUS
%start expr
%%
expr: e EOF { if (yy.trace)
yy.trace('returning', $1);
return $1; } ; // return e
e : e '+' e {$$ = $1+$3;}
| e '-' e {$$ = $1-$3;}
| '-' e %prec UMINUS {$$ = -$2;}
| '(' e ')' {$$ = $2;}
| NUMBER {$$ = Number(yytext);} ;
Convert the .jison file to a TS file:
ts-jison -t typescript -n TsCalc -n TsCalc -o ts-calculator.ts ts-calculator.jison
Convert the .jison file to a JS file:
ts-jison -n TsCalc -n TsCalc -o js-calculator.js js-calculator.jison
const ParserAndLexer = require('./ts-calculator');
const txt = ``;
const res = new ParserAndLexer.TsCalcParser().parse(txt);
console.log(txt.trim(), '=', res);
or for JS:
const ParserAndLexer = require('./js-calculator');
See parser-generator docs for more details.
See CONTRIBUTING.md for contribution guidelines, how to run the tests, etc.
View them on the wiki, or add your own.
Special thanks to Jarred Ligatti, Manuel E. Bermúdez
Please see the license in this directory.