📄 程序代码.txt
字号:
%{
/*说明部分*/
#include <stdio.h>
#include<stdlib.h>
#define al 10 //符号最大长度
#define NUM 1000 //可处理二元式的最大数目,可变
struct token{ //二元式组;
char*property; //token属性值;
char*value;
}result[NUM];
char fname[al]; //PL/0源程序文件
FILE*fpin; //测试文件指针;
FILE*fpout; //结果文件指针;
int type; //类型值
int count; //累计单词数
int error=0; //错误token的数目
int linenum=0;
void read_source (char filename[]);//从文件读入源程序
void print();
void main();
%}
digit [0-9]
letter [a-zA-Z]
bool [TRUE|FALSE]
ident {letter}({letter}|{digit})*
constant {digit}+|{digit}+["."]{digit}+|{bool}|{letter}+
boundary_operator ["("|")"|","|";"|"."]
newline [\n]
whitespace [\t|" "]+
%%
"procedure"|"call"|"begin"|"end"|"var"|"const"|"if"|"then"|"while"|"do"|"read"|"write"|"odd" {type=3;print();}
{ident} {type=1;print();}
{constant} {type=2;print();}
{boundary_operator} {type=5;print();}
"+"|"-"|"*"|"/"|"<>"|">="|"<="|":="|"="|"#"|"<"|">" {type=4;print();}
{newline} {linenum++;}
{whitespace} {;}
%%
int yywrap()
{
fclose(fpin);
return 1;
}
void print()
{
count++;
if((fpout=fopen("result.txt","a"))==NULL){
printf("cannot write the file \n");
exit(0);
}
if(type <= 5 && type >= 1){
switch(type){
case 1:result[count-1].property="identifier";break;
case 2:result[count-1].property="constant";break;
case 3:result[count-1].property="keyword";break;
case 4:result[count-1].property="operator";break;
case 5:result[count-1].property="boundary_operator";break;
}
result[count-1].value=yytext;
// yytext指向识别的单词的地址;用来保存扫描一次匹配的字符串。
fprintf(fpout,"%d ( %s , %s ) \n",count,result[count-1].property,result[count-1].value);
}
else{
error++;
result[count-1].value=yytext;
fprintf(fpout,"%d [line:%d]:%s \n",count,linenum,result[count-1].value);
}
fclose(fpout);
}
void read_source (char filename[])
{
if((fpin=fopen(filename,"r"))==NULL){
printf("cannot open the file \n");
exit(0);
}
}
void main()
{
printf("please input the PL/0 file: "); //要求输入要分析源程序的文件名
scanf("%s",&fname);
read_source (fname); //读取文件内容
yyin=fpin;
/* yyin是个FILE类型的指针,指向词法分析器要接收的待分析程序的指针。
如果不指定则默认指向标准输入终端(键盘)。
如果我们待分析的程序是文件形式我们可以将这个指针指向该文件的地址指针。
*/
yylex(); //每调用一次,yylex 的返回值为当前分析的Token类型值。当文件结束时,yylex 的返回值为0。
if((fpout=fopen("result.txt","a"))==NULL){
printf("cannot write the file \n");
exit(0);
}
fprintf(fpout,"\n%d symbol(s) found. %d error(s) found. \n",count,error);
fprintf(fpout,"***************************************\n");
fclose(fpout);
yywrap();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -