野牛YYSTYPE:尝试使用char *

时间:2009-11-22 07:26:03

标签: bison flex-lexer

我需要使用flex和bison来解析一些代码。

YYSTYPE的默认类型是int,即使我从未这样说过。这是野牛的默认值吗?

将字符串传回来会对我有很大帮助。我读到这个: How to solve Bison warning "... has no declared type"这看起来很好。 (我不需要联盟的全部功能,只需要char *部分,但我不妨使用联盟,因为它可能会在以后有用。)

这不适合我。我收到这些错误:

y:111.37-38: $1 of `ConstExpression' has no declared type
y:113.34-35: $1 of `ConstFactor' has no declared type
y:114.35-36: $1 of `ConstFactor' has no declared type
y:119.34-35: $1 of `Type' has no declared type
y:109.23-48: warning: type clash on default action: <str> != <>
y:115.23-27: warning: type clash on default action: <str> != <>
[...more of the same snipped...]

以下是我的y语法文件中的声明:

%union {
     char *str;
 }

%type<str> ConstExpression ConstFactor Type

以下是我.l文件中的一行:

[a-zA-Z]+[a-zA-Z0-9]*   { yylval.str = strdup(yytext); return yident;}

我还需要做些什么才能解决错误?

2 个答案:

答案 0 :(得分:6)

实际上,如果没有看到语法,我很确定我知道什么是错的。

有必要声明终端符号的类型,因为它们可以并且经常返回语义值。考虑IDNUMBER等具有yyval数据的内容。但yacc无法知道它只是'x'还是更多,而且规则中的默认操作是:$$ = $1

例如,以下语法可以很好地通过yacc,但请尝试从下面的%type中删除一个以上的符号:

%union {
  char *s;
}

%type <s> r1 r2 'x'

%%

r1: r2;

r2: 'x'   { printf("%s\n", $1); };

答案 1 :(得分:3)

您可能只需要在yacc文件中定义令牌的类型

%token<str> yident