Jison全局变量

Mar*_*rgo 10 compiler-construction jison flex-lexer

在以前的Jison版本中,可以使用类似Flex的功能,允许在词法分析器和解析器上下文中定义变量,例如:

%{
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) ; };
Run Code Online (Sandbox Code Playgroud)

参考: Flex喜欢的功能?

虽然,在最新版本的Jison中,这是无效的.chars,words并且lines无法从解析器上下文到达,生成错误.

在搜索有关新版本的更多信息时,我发现应该可以通过在解析器的上下文中定义输出%{ ... %},但它不起作用,尽管它用于多行语句.我正在生成从源代码到目标语言的代码,我将对这些代码进行美化,应用正确的缩进,由作用域控制并直接从解析器生成,而不构建AST.

全球定义目前如何在Jison中运作?

hee*_*nee 10

当前版本的Jison有一个名为变量的变量,yy其目的是允许在词法动作,语义动作和其他模块之间共享数据.如果将所有这些变量存储在yy以下内容中,则代码示例可以正常工作:

%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); };
Run Code Online (Sandbox Code Playgroud)

上面的代码在Jison 的try页面上使用Jison 0.4.13进行了测试.