資源簡介
目的:熟練掌握自下而上的語法分析方法,并能用程序實現。
要求:
1. 使用如下文法:
E E+T | T
T T*F | F
F (E) | id
2. 對于任意給定的輸入串(詞法記號流)進行語法分析,要求采用LR分析器來完成。手工構造LR分析表,利用移進-歸約分析算法(P69 圖3.12)輸出(P70 表3.8)對應的動作部分。如:
輸入:id*+id/(id+id)#
輸出:移進
按 F->id歸約
移進
error
……
3. 要有一定的錯誤處理功能。即對錯誤能提示,并且能在一定程度上忽略盡量少的記號來進行接下來的分析。
例如:
從狀態0開始的記號流為:bm
將b移進之后,棧里的情況應該為: 0 b 2
此時查表發現 action[2,m]=error
輸出打?。篹rror
把A和狀態1相繼壓入棧,用戶指針后移到FOLLOW(A)對應的元素繼續分析。
代碼片段和文件信息
#include
#include
#include
#include
using?namespace?std;
class?getstring
{
public:list??istream;
???stack?label;
???bool?flag;
???list::iterator?getite(int?i)
???{
???int?j=0;
???list::iterator?it1=istream.begin();
???while(j!=i)
???{
???j++;it1++;
???}
???return?it1;
???}
???void?getis()
???{
???string?s1s2;
???cout<<“請輸入表達式:“< ???cin>>s1;
???for(int?i=0;i ???{
???if(s1[i]==‘+‘||s1[i]==‘*‘||s1[i]==‘(‘||s1[i]==‘)‘)
???{
???s2.push_back(s1[i]);istream.push_back(s2);s2.clear();
???}
???else?if(s1[i]==‘i‘)
???{
???s2.push_back(s1[i]);i++;
???if(s1[i]==‘d‘){s2.push_back(s1[i]);istream.push_back(s2);s2.clear();}
???else{error();}
???}
???else?if(s1[i]==‘\0‘)
???{
???continue;
???}
???else
???{error();}
???}
???istream.push_back(“$“);flag=false;
???}
???void?error()
???{
???cout<<“錯誤!“< ???exit(0);
???}
???void?test()
???{
???if(label.empty()||istream.empty()){exit(0);}
???}
???void?gototable(string?s1string?s2)
???{
???if(s1==“0“&&s2==“E“)
???{
???label.push(“1“);
???}
???if((s1==“0“||s1==“4“)&&s2==“T“)
???{
???label.push(“2“);
???}
???if((s1==“0“||s1==“4“||s1==“6“)&&s2==“F“)
???{
???label.push(“3“);
???}
???if(s1==“4“&&s2==“E“)
???{
???label.push(“8“);
???}
???if(s1==“6“&&s2==“T“)
???{
???label.push(“9“);
???}
???if(s1==“7“&&s2==“F“)
???{
???label.push(“10“);
???}
???}
???void?analyse()
???{
???label.push(“0“);
???string?stoplistops1;
???while(!(label.empty()||istream.empty())&&!(label.top()==“1“&&istream.front()==“$“))
???{
???stop=label.top();listop=istream.front();
???if((stop==“0“||stop==“4“||stop==“6“||stop==“7“)&&listop==“id“)
???{
???label.push(“id“);label.push(“5“);istream.pop_front();cout<<“移進“< ???}
???if((stop==“0“||stop==“4“||stop==“6“||stop==“7“)&&listop==“(“)
???{
???label.push(“(“);label.push(“4“);istream.pop_front();cout<<“移進“< ???}
???if((stop==“1“||stop==“8“)&&listop==“+“)
???{
???label.push(“+“);label.push(“6“);istream.pop_front();cout<<“移進“< ???}
???if((stop==“2“||stop==“9“)&&listop==“*“)
???{
???label.push(“*“);label.push(“7“);istream.pop_front();cout<<“移進“< ???}
???if(stop==“8“&&listop==“)“)
???{
???label.
評論
共有 條評論