Skip to content

Latest commit

 

History

History
109 lines (80 loc) · 3.39 KB

README.md

File metadata and controls

109 lines (80 loc) · 3.39 KB

ts-jison

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.

Status:

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.

Components:

Example grammar:

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);} ;

Example compilation:

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

Example invocation:

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');

Docs

See parser-generator docs for more details.

How to contribute

See CONTRIBUTING.md for contribution guidelines, how to run the tests, etc.

Projects using Jison

View them on the wiki, or add your own.

Contributors

Githubbers

Special thanks to Jarred Ligatti, Manuel E. Bermúdez

Please see the license in this directory.