这是我的 yacc 文件,当我使用 yacc -d xxx.y 时,它显示警告,我不明白为什么它会犯这个错误,我不明白为什么它不知道什么是 $2,请伙计们,我需要你们的帮助。
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lex.yy.c"
extern int yylex();
extern FILE* yyin;
void yyerror(const char *s);
int yywrap() {
return 1;
}
%}
%union {
char* str;
}
%token TYPEDEF STRUCT CHAR SHORT INT FLOAT DOUBLE IDENTIFIER SEMICOLON LBRACE RBRACE LBRACKET RBRACKET
%type <str>structDeclaration memDeclaration
%%
program:
structDeclaration { printf("public class %s {\n", $1);}
;
structDeclaration:
TYPEDEF STRUCT IDENTIFIER LBRACE memDeclaration RBRACE IDENTIFIER SEMICOLON
{
printf("}\n");)
}
;
memDeclaration:
INT IDENTIFIER SEMICOLON { printf(" private int %s;\n", $2);}
|CHAR IDENTIFIER SEMICOLON { printf(" private String %s;\n", $2);}
|SHORT IDENTIFIER SEMICOLON { printf(" private short %s;\n", $2);}
|FLOAT IDENTIFIER SEMICOLON { printf(" private float %s;\n", $2);}
|DOUBLE IDENTIFIER SEMICOLON {printf(" private double %s;\n", $2);}
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Unvalid %s\n", argv[0]);
return 1;
}
yyin = fopen(argv[1], "r");
if (!yyin) {
perror("fopen");
return 1;
}
yyparse();
fclose(yyin);
return 0;
}
当我使用 yacc xxx.y 时, 它警告: yacc: e - “cstruct.y”的第 37 行,$2 (IDENTIFIER) 未键入 我不知道哪个部分是错误的
我还不知道该怎么办。
在几行中,您引用了未键入的 IDENTIFIER。这是一个例子:
INT IDENTIFIER SEMICOLON { printf(" private int %s;\n", $2);}
修复这些错误后,稍后您会收到更多错误,因为您既没有为
char *
也没有为 structDeclaration
分配 memDeclaration
。