Jison global variables

In previous versions of Jison, it became possible to have a Flex-like function that allowed you to define variables available both in the lexer context and in the parser, for example:

%{ var chars = 0; var words = 0; var lines = 0; %} %lex %options flex %% \s [^ \t\n\r\f\v]+ { words++; chars+= yytext.length; } . { chars++; } \n { chars++; lines++ } /lex %% E : { console.log(lines + "\t" + words + "\t" + chars) ; }; 

Link: Flex as a function?

Although in the latest version of Jison this is unacceptable. chars , words and lines cannot be reached from the parser context, generating an error.

Searching for additional information about the new version, I found that it should be possible by defining the output in the context of the parser inside %{ ... %} , but it does not work, although it is used for multi-line statements. I am generating code from a source into the target language, and I will exaggerate this code by applying the correct indentation, controlled by the scope and generating directly from the parser without creating an AST.

How do global definitions currently work in Jison?

+8
compiler-construction flex-lexer jison
source share
1 answer

The current version of Jison has a variable called yy , the purpose of which is to share data between lexical actions, semantic actions, and other modules. Your sample code may work if you store all of these variables in yy as follows:

 %lex %options flex %{ if (!('chars' in yy)) { yy.chars = 0; yy.words = 0; yy.lines = 1; } %} %% [^ \t\n\r\f\v]+ { yy.words++; yy.chars += yytext.length; } . { yy.chars++; } \n { yy.chars++; yy.lines++ } /lex %% E : { console.log( yy.lines + "\t" + yy.words + "\t" + yy.chars); }; 

The above code has been tested using Jison 0.4.13 on the Jison try page .

+5
source share

All Articles