YACC:如何将令牌的字符串值传递给yacc程序

时间:2018-04-20 06:04:47

标签: flex-lexer yacc

我想使用lex和yacc设计一个程序,它将以摩尔斯电码形式输入,解析器将生成它们的英文含义。

这是lex文件:

%{
#include <stdio.h>
int i=0;
char c;
%}
NewLine ".-.-"
EOF ".-.-"
NewPara "-...-"
Over "K"
SOS "...---..."
%%
".." {  yylval=(char *)calloc(yyleng,sizeof(char));
strcpy(yylval,yytext); 
return (I);}

".-""--" { yylval=(char *)calloc(yyleng,sizeof(char));
   strcpy(yylval,yytext); 
   return (AM);}

".-""...-"".-""-."".." {yylval.value=(char *)calloc(yyleng,sizeof(char));
        strcpy(yylval,yytext); 
        return (AVANI);}

. return yytext[0];
%%

yacc文件:

%{
#include <stdio.h>
#define YYSTYPE char*
char message [20];
%}
%token I AM AVANI
%start msg
%%
msg :   Np Vp {printf("The sentence is I AM AVANI");}
;
Np  :   I 
;
Vp  :   Aux N
;
Aux :   AM  
;
N   :   AVANI 
;
%%
#include "lex.yy.c"
/*extern YYSTYPE yylval*/
void main(){
printf("Enter the message\n");
scanf("%s",message);
yyparse();
}
void yyerror(const char *s)
{
fprintf(stderr,"s\n",s);
}        
yywrap () 
{        
return 1;
}     

这表示编译时出现以下错误:

morse_code.l: In function ‘yylex’:
morse_code.l:13:10: warning: assignment makes integer from pointer
without a cast [enabled by default]
 ".." {  yylval=(char *)calloc(yyleng,sizeof(char));
          ^
morse_code.l:14:2: warning: passing argument 1 of ‘strcpy’ makes
pointer from integer without a cast [enabled by default]
  strcpy(yylval,yytext);
  ^
In file included from lex.yy.c:20:0:
/usr/include/string.h:125:14: note: expected ‘char * __restrict__’ but
argument is of type ‘YYSTYPE’
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
morse_code.l:17:9: warning: assignment makes integer from pointer
without a cast [enabled by default]
 ".-""--" { yylval=(char *)calloc(yyleng,sizeof(char));
         ^
morse_code.l:18:5: warning: passing argument 1 of ‘strcpy’ makes
pointer from integer without a cast [enabled by default]
     strcpy(yylval,yytext);
     ^
In file included from lex.yy.c:20:0:
/usr/include/string.h:125:14: note: expected ‘char * __restrict__’ but
argument is of type ‘YYSTYPE’
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
morse_code.l:21:8: error: request for member ‘value’ in something not
a structure or union
 ".-""...-"".-""-."".." {yylval=(char *)calloc(yyleng,sizeof(char));
        ^
morse_code.l:22:4: warning: passing argument 1 of ‘strcpy’ makes
pointer from integer without a cast [enabled by default]
    strcpy(yylval,yytext);
    ^
In file included from lex.yy.c:20:0: 
/usr/include/string.h:125:14: note: expected ‘char * __restrict__’ but
argument is of type ‘YYSTYPE’
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)

如果有人可以帮我正确地将令牌的字符串值传递给yacc文件,那就太棒了。

1 个答案:

答案 0 :(得分:0)

两个明显的问题

  • 您在.l文件中遗漏了yylval的声明。如果你包含yacc生成的“y.tab.h”,它将为你定义它,但你也没有。

  • 你没有用calloc为字符串的终止NUL字符分配空间,所以当你strcpy字符串时,它会在你的分配结束后写一个字节,导致未定义的行为。 / p>