编译原理——实验叁预习报告——基于YACC的TINY语法分析器的构建
一、實驗?zāi)康?#xff1a;
運用YACC,針對給定的文法,構(gòu)造一個語法分析器。給出實驗方案,實施并描述結(jié)果。
二、實驗預(yù)習(xí)提示
1、表達:針對5.5節(jié)中的calculator文法,設(shè)計輸入和輸出
2、觀察:觀察parsing table,解析parsing table.
3、模塊間的銜接,如何同時使用lex 和 yacc
4、能力:是否有能力有工具完成一個分析器
5、比較:用工具和手工編寫程序的比較
三、實驗過程
(1)設(shè)計基于YACC的TINY詞法分析器
(2)設(shè)計基于LEX的TINY語法分析器
(3)使用兩個分析器分析算數(shù)文法
四、程序輸入/輸出示例
1、針對TINY語言給出 yacc的y文件的代碼
%{#include <ctype.h>
#include<stdio.h>
#define MSDOS
int linecount;
extern int yylex();
extern int yyerror();
%}
%union{
char chr;
char str;
int integer;
float real;
double dbl;
}
%token number
%type expr number
%left ‘+’ ‘-’
%left '’ ‘/’
%right uminus
%%
lines: lines expr’\n’
{
printf(“l(fā)ine %d:%g\n”,linecount++,$2);
}
|lines’\n’
{
linecount++;
}
| ;
expr: expr’+'expr
{
KaTeX parse error: Can't use function '$' in math mode at position 2: =$?1+$3; } |expr…=$1-$3;
}
|expr '’ expr
{
KaTeX parse error: Can't use function '$' in math mode at position 2: =$?1*$3; } | exp…=$1/$3;
}
| ‘(’ expr ‘)’
{
KaTeX parse error: Can't use function '$' in math mode at position 2: =$?2; } | '-' ex…=-$2;
}
| number;
%%
int yyerror(s)
char s;
{
fprintf(stderr,“syntactic error:%s\n”,s);
return 0;
}
2、給出.l文件的代碼
%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define ture 1
#define false 0
#include “yacc.tab.h”
extern int lexverbose;
extern int linecount;
%}
digit [0-9]
letter [a-zA-Z]
%%
{digit}+ {
yylval.real=(float)atof(yytext);
if(lexverbose)
printf(“real:%g\n”,yylval.real);
return(number);
}
+ {
yylval.chr=yytext[0];
if(lexverbose)
printf(“opterator:%c\n”,yylval.chr);
return(’+’);
}
- {
yylval.chr=yytext[0];
if(lexverbose)
printf(“oprator:%c\n”,yylval.chr);
return(’-’);
}
* {
yylval.chr=yytext[0];
if(lexverbose)
printf(“oprator:%c\n”,yylval.chr);
return(’’);
}
/ {
yylval.chr=yytext[0];
if(lexverbose)
printf(“oprator:%c\n”,yylval.chr);
return(’/’);
}
“(” {
yylval.chr=yytext[0];
if(lexverbose)
printf(“separator:%c\n”,yylval.chr);
return(’(’);
}
“)” {
yylval.chr=yytext[0];
if(lexverbose)
printf(“separtor:%c\n”,yylval.chr);
return(’)’);
}
;
{
return(’;’);
}
\n {
printf(“l(fā)ine %d\n”,linecount);
/ linecount++; /
return(’\n’);
}
[ \t]+ {
printf(“l(fā)exical analyzer error\n”);
}
quit {
printf(“Bye!\n”);
exit(0);
}
%%
int yywrap()
{
return(1);
}
3、編譯主函數(shù)main.c
#include"lex.yy.c"
#include"yacc.tab.c"
#include <stdlib.h>
#include <stdio.h>
int lexverbose=1;
extern int yyparse();
int main(int argc, char argv[])
{
extern FILE *yyin;
printf(“Compiling…!\n”);
if((yyin=fopen(“test.c”,“rt”))==NULL){
perror(“can not open file test.txt\n”) ;
exit(1);
}
if (yyparse()==1){
fprintf(stderr,“parser error\n”);
exit(1);
}
printf(“yyparse() completed successfully!\n”);
return 0;
}
五、程序思路
先設(shè)計基于YACC的TINY詞法分析器,再設(shè)計基于LEX的TINY語法分析器,再設(shè)計主函數(shù)main.c編譯后調(diào)用兩個分析器分析算數(shù)文法
總結(jié)
以上是生活随笔為你收集整理的编译原理——实验叁预习报告——基于YACC的TINY语法分析器的构建的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ 类的静态成员(static)
- 下一篇: 一个自己写的有关数据库的treeview