[英]ANTLR4 parser generation: issue with simple grammar for conditional expressions
我正在嘗試為一種簡單的語言生成一個詞法分析器和解析器。 目前,該語言只能解析條件表達式。 條件表達式很像C語言中的條件表達式,並且由於我只是在這里學習基礎知識,因此我們使用諸如CI之類的語言獲得的所有陷阱都不會在意實現。
我有以下語法:
grammar Simple ;
cond_expr : left_paren operand operator operand right_paren ;
operand : function_expr | ID | literal | cond_expr ;
function_expr : ID left_paren paramList right_paren ;
paramList : param (',' param)* ;
param : ID | function_expr ;
literal : string | number ;
string : '"' sentence '"' ;
sentence : (WORD | WORD (' ' WORD)*)* ;
number : INTEGER | FLOAT ;
left_paren : LEFT_PAREN ;
right_paren : RIGHT_PAREN ;
operator : OPERATOR ;
INTEGER : [0-9]+ ;
FLOAT : INTEGER '.' INTEGER | '.' INTEGER ;
LEFT_PAREN : '(' ;
RIGHT_PAREN : ')' ;
ID : [A-Za-z]+[A-Za-z0-9_]* ;
WORD : [A-Za-z]+ ;
OPERATOR : ('==' | '>=' | '<=' | '!=' | '&&' | '||' | '~') ;
WS : (' '|'\r'|'\n'|'\t') -> channel(HIDDEN);
當我在其上運行解析器時,我沒有得到預期的結果。 這是不正確的輸出的示例:
~/sandbox $ grun Simple cond_expr -tree
(a (c, d (e, f)) != b)
line 1:2 mismatched input ' ' expecting OPERATOR
line 1:5 mismatched input ',' expecting OPERATOR
line 1:8 mismatched input ' ' expecting ')'
(cond_expr (left_paren () (operand a) (operator ) (operand (cond_expr (left_paren () (operand c) (operator , ) (operand d) (right_paren ( e , f))) (right_paren )))
我的語法有什么錯誤? 任何幫助表示贊賞。
似乎語法是所需DSL的EBNF表示的直接實現。 要使其在ANTLR中正常工作,還需要做更多的工作。 照原樣:
1)規則function_expr
, paramList
和param
存在相互左遞歸問題;
2) sentence
不能匹配;
3) WS
隱藏在詞法分析器中,因此sentence
無論如何都不會匹配;);
4) ID
規則遮蓋了WORD
,因此將永遠不會發出WORD
令牌。
(你應該已經收到警告工具對1和2;從不忽略,因為警告表明,運行時的行為可能會受到影響。)
表達式規則的基本形式是在一條規則中列出表達式的所有替代形式。
expr : LPAREN expr RPAREN
| expr operator expr
| function
| string
| number
| ID
;
function : ID LPAREN ( ID | function ) (',' ( ID | function ))* RPAREN ;
string : STRING ;
number : INTEGER | FLOAT ;
operator : OPERATOR ;
STRING : '"' .*? '"' ;
(未試)
因此(a (c, d (e, f)) != b)
應該正確計算為
expr (function ( ID, function ( ID, ID ) ) operator ID
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.