我正在尝试用野牛构建一个解析器,并将我的所有错误缩小到一个难度。
以下是bison的调试输出,其中包含错误所在的状态:
state 120
12 statement_list: statement_list . SEMICOLON statement
24 if_statement: IF conditional THEN statement_lists ELSE statement_list .
SEMICOLON shift, and go to state 50
SEMICOLON [reduce using rule 24 (if_statement)]
$default reduce using rule 24 (if_statement)
以下是parser.y source
中的翻译规则%%
program : ID COLON block ENDP ID POINT
;
block : CODE statement_list
| DECLARATIONS declaration_block CODE statement_list
;
declaration_block : id_list OF TYPE type SEMICOLON
| declaration_block id_list OF TYPE type SEMICOLON
;
id_list : ID
| ID COMMA id_list
;
type : CHARACTER
| INTEGER
| REAL
;
statement_list : statement
| statement_list SEMICOLON statement
;
statement_lists : statement
| statement_list SEMICOLON statement
;
statement : assignment_statement
| if_statement
| do_statement
| while_statement
| for_statement
| write_statement
| read_statement
;
assignment_statement : expression OUTPUTTO ID
;
if_statement : IF conditional THEN statement_lists ENDIF
| IF conditional THEN statement_lists ELSE statement_list
;
do_statement : DO statement_list WHILE conditional ENDDO
;
while_statement : WHILE conditional DO statement_list ENDWHILE
;
for_statement : FOR ID IS expression BY expressions TO expression DO statement_list ENDFOR
;
write_statement : WRITE BRA output_list KET
| NEWLINE
;
read_statement : READ BRA ID KET
;
output_list : value
| value COMMA output_list
;
condition : expression comparator expression
;
conditional : condition
| NOT conditional
| condition AND conditional
| condition OR conditional
;
comparator : ASSIGNMENT
| BETWEEN
| LT
| GT
| LESSEQUAL
| GREATEREQUAL
;
expression : term
| term PLUS expression
| term MINUS expression
;
expressions : term
| term PLUS expressions
| term MINUS expressions
;
term : value
| value MULTIPLY term
| value DIVIDE term
;
value : ID
| constant
| BRA expression KET
;
constant : number_constant
| CHARCONST
;
number_constant : NUMBER
| MINUS NUMBER
| NUMBER POINT NUMBER
| MINUS NUMBER POINT NUMBER
;
%%
当我删除if_statement规则时没有错误,所以我大大缩小了它,但仍然无法解决错误。
感谢您的帮助。
答案 0 :(得分:3)
考虑这个陈述:如果条件则s2否则s3; S4
有两种解释:
if condition then
s1;
else
s2;
s3;
另一个是:
if condition then
s1;
else
s2;
s3;
在第一个中,法规列表由if
语句和s3
组成。而另一个语句只由一个if
语句组成。这就是歧义的来源。当存在shift-reduce冲突时,Bison会选择shift to reduce,因此在上述情况下,解析器将选择转换s3
。
由于ENDIF
语句中有if-then
,请考虑在ENDIF
语句中引入if-then-else
,然后问题就解决了。
答案 1 :(得分:2)
我认为您在ENDIF
规则中缺少IF-THEN-ELSE-ENDIF
。