1
我想建立一個使用flex的小語言的詞法分析器。詞法分析器與靈活
詞法將讀取詞位的文本文件,併爲每個詞位賦予一個標記並將標記寫入另一個文件中。該代碼能夠打開文件並使用yylex()函數從中讀取。
問題是代碼沒有在指定的文件中寫入令牌。我還發現,代碼無法識別數字,並給每個字母的標識符一個IDENTIFIER標記我嘗試了很多方法來克服這些問題,我用一個c語言網站來編寫一個正確的C代碼。
有一點需要注意的是,我不想使用.y解析器讀取詞法並將其傳遞給詞法我希望我的詞法通過它自己讀取該詞法併產生該詞法。
那麼,任何一個人都可以幫我弄清楚是什麼問題?
%{
#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
#define KEY_INT 259
#define KEY_VOID 258
#define KEY_INT 259
#define KEY_FLOAT 260
#define KEY_IF 261
#define KEY_ELSE 262
#define KEY_WHILE 263
#define KEY_FOR 264
#define KEY_RETURN 265
#define KEY_BREAK 266
#define AND_OP 267
#define OR_OP 268
#define SMALL_EQ_OP 269
#define GREAT_EQ_OP 270
#define EQ_OP 271
#define SMALL_OP 272
#define GREAT_OP 273
#define NOT_EQ_OP 274
#define ASSIGN_OP 275
#define OPN__BRACKET 276
#define CLS__BRACKET 277
#define SEMICOLON_SYMBOL 278
#define COMMA_SYMBOL 279
#define DOT_SYMBOL 280
#define ADD_OP 281
#define SUB_OP 282
#define ASTERISK_SYMBOL 283
#define SLASH_SYMBOL 284
#define INT_NUM 287
#define FLOAT_NUM 288
#define IDENTIFIER 289
int yylval;
FILE *yyin,*yyout;
int c;
%}
Letters [a-zA-Z]
Digits [0-9]
Sympols [@#$%&*-+!"':;/?(),~`|^_=×{}<>]
%%
[/*][{Letters}|{Digits}|{Sympols}|\n|\t ]*[*/] {}
[-+]?[{Digits}]+ {yylval = atoi(yytext); return INT_NUM ;}
[-+]?[{Digits}]+.[{Digits}]+ {yylval = atoi(yytext);return FLOAT_NUM ;}
{Letters}[{Letters}|{Digits}|_]* {return IDENTIFIER ;}
[\t\n ]+ {}
"void" {return KEY_VOID ;}
"float" {return KEY_FLOAT ;}
"if" {printf("KEY_IF\n") ;}
"else" {return KEY_ELSE ;}
"while" {return KEY_WHILE ;}
"for" {return KEY_FOR ;}
"return" {return KEY_RETURN ;}
"break" {return KEY_BREAK ;}
"&&" {return AND_OP ;}
"||" {return OR_OP ;}
"<=" {return SMALL_EQ_OP ;}
">=" {return GREAT_EQ_OP ;}
"==" {return EQ_OP ; }
"<" {return SMALL_OP ;}
">" {return GREAT_OP ;}
"!=" {return NOT_EQ_OP ;}
"=" {return ASSIGN_OP ;}
"(" {return OPN__BRACKET ;}
")" {return CLS__BRACKET ;}
";" {return SEMICOLON_SYMBOL ;}
"," {return COMMA_SYMBOL ;}
"." {return DOT_SYMBOL ;}
"+" {return ADD_OP ;}
"-" {return SUB_OP ;}
"*" {return ASTERISK_SYMBOL ;}
"/" {return SLASH_SYMBOL ;}
. {yyerror() ;}
%%
int yyerror (void)
{
printf("Invalid input\n");
exit(1);
}
int yywrap()
{
return 1;
}
main()
{
if((yyin=fopen("C:\\ProCompFlex\\GnuWin32\\bin\\input.txt","r"))==NULL)
{
printf("input.txt Not found !\n Press any key to exit ");
getch();
return;
}
c=yylex();
while(c!=NULL)
{
yyout=fopen("C:\\ProCompFlex\\GnuWin32\\bin\\token.txt","w");
fprintf(yyout,c," ",yylex(),"\n");
getchar();
}
fclose(yyout);
}