You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Bison无法接受该语法文件?语法报错排查求助

Bison语法文件错误排查及修正

错误原因分析

  • 第8行空字符串token:在%token声明行中,"-"后出现了空的"",属于笔误,实际应为表示乘法的"*",Bison无法解析空字符串作为合法token,直接触发语法错误。
  • 带空格的token声明:" <= "和" >= "包含多余空格,Bison会将其识别为带空格的完整token,但语法规则中使用的是无空格的"<="和">=",两者不匹配,同时空格会干扰token的识别逻辑。
  • import语句语法错误:import java.util.;和import java.io.;缺少通配符*,正确写法应为import java.util.*;和import java.io.*;。
  • %union与%type顺序颠倒:Bison要求%union必须在%type之前声明,因为%type需要引用%union中定义的类型,当前顺序会导致类型未定义的潜在错误。
  • yyerror函数签名问题:Java环境下Bison生成的yyerror函数应为void返回类型,而非int,否则会出现类型不匹配问题。
  • 未声明的非终结符:ARGLIST作为非终结符使用,但未在%type中声明类型,虽不是当前直接报错原因,但会导致后续生成代码的问题。

修正后的关键代码片段

%{
import java.util.*;
import java.io.*;
%}

%start PROGRAM
%token number identifier function break call if else let read return while write
%token "(" ")" "{" "}" ";" "=" "+" "-" "*" "/" "%" "<" ">" "<=" ">=" "==" "!=" "&" "|" "~" "!"
%left "+" "-"
%left "*" "/" "%"
%left "&" "|"
%nonassoc "!"

%union {
    Node node;
    String identifier;
    int number;
}

%type <Node> PROGRAM FUNCTION PARAMLIST BLOCK STATEMENT IF ELSE EXPR ARGLIST
%type <String> identifier
%type <Integer> number

%%
// 其余语法规则保持不变
%%
void yyerror(String s) {
    System.err.println("error: " + s);
}

内容的提问来源于stack exchange,提问作者Zaheer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:40:59