1

我正在构建一个解析器,但我有一些我无法解决的错误,我对 bison 和 flex 很陌生,请帮助我解决它们并理解它们为什么会在这里发生是我得到的错误:

   lexical.l:3:20: error: common.h: No such file or directory
In file included from lexical.l:5:
bison.tab.h:81: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before âyylvalâ
bison.tab.c:1155: error: conflicting types for âyylvalâ
bison.tab.h:81: note: previous declaration of âyylvalâ was here
bison.y: In function âyyparseâ:
bison.y:96: error: incompatible types when assigning to type âSTYPEâ from type âNODEPTRâ

这是我的解析器文件 bison.y:

%{
#include <stdio.h>
#include "bison.tab.h"
#include "common.h"
//int yylex();
void yyerror (char const *);

typedef struct STYPE {
    NODEPTR pointer;
} STYPE;

#define YYSTYPE STYPE

%}



/* Bison declarations. */

%token ELSE REAL INTEGER XWRITE WHILE END DO IF THEN XPROGRAM FUNCTION XRETURN XREAD VAR FOR XBEGIN CALL ID NUM  
%token RELOP ADDOP MULOP ASSIGN AND OR NOT  
%left '-' '+'
%left '*' '/'
%nonassoc LOWER_THAN_ELSE
%nonassoc ELSE
4

2 回答 2

2

如果你#define YYSTYPE在你的野牛文件中,你还需要#define YYSTYPE在你的 flex 文件中,因为野牛不会将#define 放入生成的头文件中。您需要在#include 生成的头文件之前执行此操作。

Bison 不会将#define 放在生成的标头中,因为它无法知道您是否这样做,因为您可能会在包含的文件中执行此操作。事实上,如果你打算#define YYSTYPE这样做,你应该在一个公共头文件中进行,以及#include在野牛和 flex 程序中的公共头文件(如上所述,在你包含野牛生成的头文件之前)。

此外,当您重新生成生成的代码时,请记住始终首先生成 bison 程序,因为 flex 程序依赖于生成的头文件。这与您的操作方式相反。

只是为了让这一切更清楚一点,这里有一个例子:

 common.h:

   struct MyType {
     /* ... /
   };

   #define YYSTYPE struct MyType;


 lexer.l:

   %{
      /* All your standard includes go here */
      /* Must go in this order */
      #include "common.h"
      #include "bison.tab.h"

   %}

 bison.y:

   %{
      /* Whatever library includes you need */
      #include "common.h"
      /* Don't include bison.tab.h; it will get inserted automatically */
   %}
于 2012-12-11T17:26:54.080 回答
1

要修复 yytext 错误,请将其添加到 bison.y :-

extern char *yytext

要修复 yyerror 错误,请在 bison.y 顶部的原型匹配以下定义:-

int yyerror(const char *message);

修复 yylval 错误需要做更多的工作,我对此不太了解,无法提供帮助。我建议尝试一个简单的 hello、world 类型的词法分析器、解析器,然后从那里继续前进。

这是我使用的 common.h :-

typedef struct STYPE {
    int pointer;
} STYPE;

词法分析器的标题:-

%{
#include "common.h"
#define YYSTYPE STYPE
#include <stdio.h>
#include"bison.tab.h"
void showToken(char*);
%}

以及解析器的标题:-

%{
#include <stdio.h>
#include "common.h"
extern char *yytext;
#define YYSTYPE STYPE
%}

这给了我一个错误和一些警告,但这些是由于未定义的函数。请注意,我已将 STYPE 的声明移至 lexer 和 parser 的顶部

于 2012-12-11T11:21:04.920 回答