编译原理|LL(1)语法分析实验
生活随笔
收集整理的這篇文章主要介紹了
编译原理|LL(1)语法分析实验
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
LL(1)語法分析實驗
一、實驗目的
二、實驗內容
針對CP語言中簡單算術表達式文法G[E]:
E→TE’
E’→ATE’|ε
T→FT’
T’→MFT’ |ε
F→(E) | i
A → + | -
M → * | /
求解相應的FIRST、FOLLOW集,構造預測分析表,并編寫LL(1)語法分析程序,并給出測試句子的分析過程。
(注:如果有選做專題7關于LL(1)文法判斷的同學,可以將專題7的部分整合到這個實驗的前面,自動產生預測分析表,相當于把這個程序做成一個通用的LL(1)分析器)
三、實驗要求
四、程序代碼
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <stack>using namespace std;#define MAX 100 char c[8]={'i','(','+','-','*','/',')','#'}; char w[7]={'E','e','T','t','F','A','M'}; char mapp[7][8][5]= {"Te","Te","%","%","%","%","%","%","%","%","ATe","ATe","%","%","#","#","Ft","Ft","%","%","%","%","%","%","%","%","#","#","MFt","MFt","#","#","i","(E)","%","%","%","%","%","%","%","%","+","-","%","%","%","%","%","%","%","%","*","/","%","%"};int panduan(char ch) {for(int i=0;i<8;i++){if(ch==c[i])return 1;}return 0; } int findc(char ch) {if(ch>='0'&&ch<='9')return 0;for(int i=0;i<8;i++){if(ch==c[i])return i;}return 0; } int findw(char ch) {for(int i=0;i<7;i++){if(ch==w[i])return i;}return 0;}int main() {char str[MAX];int ip;stack <char> q;cout<<"輸入的格式為算數式后跟#號"<<endl;cout<<"比如:"<<" 9+8*2#"<<endl;cout<<"“e->#”此類產生式中的#號代表空集"<<endl;cout<<"請輸入你的表達式"<<endl;cin>>str;ip=0;q.push('#');q.push('E');while(!q.empty()){char ch=q.top();if(ch=='#')break;int i=findw(ch);int j=findc(str[ip]);if(ch==str[ip]){q.pop();cout<<"匹配"<<str[ip]<<endl;ip++;}else if(str[ip]>='0'&&str[ip]<='9'&&ch=='i'){q.pop();cout<<ch<<"->"<<str[ip]<<endl;cout<<"匹配"<<str[ip]<<endl;ip++;}else if(panduan(ch)){cout<<"不匹配"<<endl;return 0;}else if(mapp[i][j][0]=='%'){cout<<"不匹配"<<endl;return 0;}else if(mapp[i][j][0]=='#'){cout<<ch<<"->"<<"#"<<endl;q.pop();}else{int n=strlen(mapp[i][j]);q.pop();for(int k=n-1;k>=0;k--){q.push(mapp[i][j][k]);}cout<<ch<<"->"<<mapp[i][j]<<endl;}}return 0; }五、結果分析
總結
以上是生活随笔為你收集整理的编译原理|LL(1)语法分析实验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python之文件批量重命名
- 下一篇: daterangepicker.js快捷