源文件读取源文件一行输出读取一个字符否是否到达终态是赋值token输出token
2.1.3 各文件或函数的设计说明
扫描程序用到:scanner.h,scanner.cpp ? scanner.h:声明词法状态,词法分析 //DFA中的状态 typedef enum {
START = 1, INNUM, INID, INDBSYM, DONE
} DFAState;
//定义的Token的类型(31种),分别对应于else、if、int、return、void、while、+、-、*、/、<、<=、>、>=、==、!=、=、;、,、(、)、[、]、{、}、/*、*/、num、id、错误、结束 typedef enum {
ELSE = 1,IF,INT,RETURN,VOID,WHILE,
PLUS,MINUS,TIMES,OVER,LT,LEQ,GT,GEQ,EQ,NEQ,ASSIGN,SEMI,COMMA,LPAREN,RPAREN,LMBRACKET,RMBRACKET,LBBRACKET,RBBRACKET,LCOMMENT,RCOMMENT, NUM,ID,ERROR,ENDFILE } TokenType;
//定义的Token结构体,包括类型、对应的串、所在代码的行号 struct Token {
TokenType tokenType; string tokenString; int lineNo; };
//每种TokenType对应的串,如tokenTypeString[ELSE]==\
const string tokenTypeString[32] = {\\\\\\\\\\\\\\\\\\\\\\\\\\\\
class Scanner:定义scanner.cpp中函数 ? scanner.cpp文件函数说明
void Scanner :: scan():设置输出结果界面以及设置各种输出状态。
if(scanSuccess==false)
cout<<\词法分析出错!\cout<<\词法分析成功了!\else
printToken();/*输出Token到文件Token.txt中*/
//正在删除注释
void Scanner :: deleteComments()
TokenType Scanner :: returnTokenType(string s)//返回Token的类型 DFAState Scanner :: charType(char c)//返回字符的类型 typedef enum { ENDFILE,ERROR,
IF,ELSE,INT,RETURN,VOID,WHILE, //关键字
ID,NUM,
ASSIGN,PLUS,MINUS,TIMES,OVER,EQ,UEQ,LT,LPAREN,RPAREN,SEMI,BT,LQ,BQ, DOU,LZGH,RZGH,LDGH,RDGH,//特殊字符:= + - * / == != < 等 } TokenType;
2.1.4 测试程序说明
根据附录A后面的例子,程序输入两个整数,计算并打印出它们的最大公因子,保存为a.txt。
/* A program to perform Eucild's Algorithm to compute gcd. */ int gcd (int u, int v) {
if (v==0) return u; else return
gcd(v,u-u/v*v); /* u-u/v*v== u mod v */ }
void main(void) { int x; int y; x=input(); y=input(); output(gcd(x,y)); }
2.2、语法分析parse部分
2.2.1系统设计思想
设计思想:parser用递归下降分析方法实现,通过调用词法分析函数getToken实现语法分析。
根据C-语言的规则,得出BNF语法如下:
1.program->declaration-list
2.declaration-list->declaration-list declaration | declaration 3.declaration->var-declaration|fun-declaration
4.var-declaration->type-specifier ID;|type-specfier ID[NUM] 5.type-specifier->int|void
6.fun-specifier ID(parans) compound-stmt 7.params->params-list|void
8.param-list->param-list,param|param
9.param->type-specifier ID|type-specifier ID [] 10.compound-stmt->{local-declarations statement-list}
11.local-declarations->local-declarations var-declaration|empty 12.statement-list->statement-list statement|empty
13.statement->expression-stmt|compound-stmt|selection-stmt|iteration-stmt|return-stmt
14.expression-stmt->expression;|;
15.selection-stmt->if(expression)statement|if(expression)statement else
statement
16.iteration-stmt->while(expression)statement 17.return-stmt->return ;|return expression; 18.expression->var=expression|simple-expression 19.var->ID|ID[expression]
20.simple-expression->additive-expression
additive-expression|additive-expression
21.relop-><=|<|>|>=|==|!=
22.additive-expression->additive-expression addop term|term 23.addop->+|-
24.term->term mulop factor|factor 25.mulop->*|/
26.factor->(expression)|var|call|NUM 27.call->ID(args) 28.args->arg-list|empty
29.arg-list->arg-list,expression|expression 2.1.2语法分析程序流程图
relop