我的问题是在Rascal语法定义中处理保留关键字。采用以下Rascal模块,该模块源自在线文档:
module Test
// Taken from http://tutor.rascal-mpl.org/Rascal/Declarations/SyntaxDefinition/SyntaxDefinition.html
start syntax Top = Identifier | ReservedKeyword;
layout MyLayout = [\t\n\ \r\f]*;
// Is OK, parse(#Top,"if") succeeds, parse(#Identifier,"if") fails
lexical Identifier = [a-z] !<< [a-z]+ !>> [a-z] \ MyKeywords;
// Goes wrong, parse(#Top,"if") fails, parse(#Identifier,"if") succeeds,
// so "if" is not exluded
//lexical Identifier = [a-z0-9] !<< [a-z][a-z0-9]* !>> [a-z0-9] \ MyKeywords;
keyword MyKeywords = "if" | "then" | "else" | "fi";
syntax ReservedKeyword = "if" | "then" | "else" | "fi";
关键是保留关键字构造\ MyKeywords
仅在词法定义为[a-z] !<< [a-z]+ !>> [a-z]
时才有效。如果词汇变得稍微复杂[a-z0-9] !<< [a-z][a-z0-9]* !>> [a-z0-9]
,则不再排除关键字。
我在这里做错了什么?如果标识符为[a-z][a-z0-9]*
?
答案 0 :(得分:0)
问题的原因是[a-z]
旁边的[a-z0-9]+
等符号的并置不如\
运算符和!>>
运算符强。
所以我们只在标识符的尾MyKeywords
中保留[a-z0-9]+
:
lexical Identifier = [a-z] !<< [a-z][a-z0-9]+ \ MyKeywords;
要解决此问题,您可以添加括号以从整个序列中删除MyKeywords
:
lexical Identifier = [a-z] !<< ([a-z][a-z0-9]+) \ MyKeywords;
然后您可以再次添加限制:
lexical Identifier = [a-z] !<< ([a-z][a-z0-9]+) \ MyKeywords !>> [a-z];
或者像这样,等同于:
lexical Identifier = [a-z] !<< ([a-z][a-z0-9]+) !>> [a-z] \ MyKeywords;