Create a lexical analysis program, which supports analyzing regular grammar. You must use DFA (Deterministic Finite Automata) or NFA (Nondeterministic Finite Automata) to implement this program. The inputs of the program are a text document including a set of productions of 3º grammar (the regular grammar) and a source code text document contains a set of strings to be recoganized. The output of the program is a token table which consists of 5 types token: key words, identifier, const, limiter and operator.
while (!stop) { char c = peekChar(); //预读一个字符 if (c == EOF) //判断文件是否结束 { state = -2; return"EOF"; } c = transform(c); pair<int, map<string, int> > res = dfa.find(state); char s[2]; s[0] = c; s[1] = '\0'; map<string, int>::iterator i = res.second.find(s); if (i == res.second.end()) { //DFA中找不到可行通路 stop = true; string temp = buffer.substr(nearestAccept); buffer.erase(nearestAccept); nextRead.insert(0, temp); if (nearestAccept == 0) //没有可接受字符串,报错 { cout << "错误:" << line << ":" << column << endl; state = -1; getNextChar(); } } else { //字符可行,加入到buffer中,并进行状态转移 state = i->second; getNextChar(); buffer.push_back(currentChar); pair<int, map<string, int> > res = dfa.find(state); i = res.second.find("&"); if (i != res.second.end()) //判断是否是终结状态 { nearestAccept = buffer.size(); } } } return buffer; //返回Token }
编写目标语言的正规文法
我理想中的目标语言是Pascal,所以下面我所写的,是Pascal的词法规则。 为了简化程序的编写,我以begin作为NFA的起始状态,&符号作为结束的标志,!作为空白字符。 文法的表示方式如下: $A \rightarrow aB$ 表示为: A a B $A \rightarrow a$ 表示为: A a
begin +|- integer-1 begin digit integer integer-1 digit integer integer digit integer integer &
浮点数
1 2 3 4
integer . real-1 real-1 digit real//保证小数点后一定要有数字 real digit real real &
科学计数法
1 2 3 4 5 6 7 8 9
integer e science-1 integer E science-1 real e science-1 real E science-1 science-1 +|- science-2//保证e和正负号后面要有数字 science-1 digit science science-2 digit science science digit science science &