语法分析阶段:机器通过词法分析,将单词序列分物做解成不同的语法短语,确定整个输入串能够构成语法上正确的程序。
语义分析阶段:检查源程序上有没有语义错误,在代码生成阶段收集类型信息
中间代码生成阶段:在进行了上述的语法分析和语义分析阶段的工作之后,有的编译程序将源程序变成一种内部表示形式
代码优化:这一阶段的任务是对前一阶段产生的中间代码进行变换或进行改备渗造,目的是使生成的目标代码更为高效,即省时间和省空间
目标代仿蚂脊码生成:这一阶段的任务是把中间代码变换成特定机器上的绝对指令代码或可重定位的指令代码或汇编指令
我有,这是这学期刚做的谈昌,#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std
bool isLetter(char ch){
if ((ch>='A' &&ch<='Z') || (ch>='a' &&ch<='z')) return true
else return false
}
bool isDigit(char ch){
if (ch>='0' &&ch<='9') return true
else return false
}
bool isP(char ch){
if(ch=='+'||ch=='*'||ch=='-'||ch=='/') return true
//ch==':'||ch==','||ch=='='||ch==''||ch=='('||ch==')'
else return false
}
bool isJ(char ch){
if(ch==','||ch==''||ch=='.'||ch=='('||ch==')'||ch=='['||ch==']'||ch=='='||ch==':'||ch=='<'||ch=='>'||ch=='{'||ch=='}'||ch=='#') return true
//
else return false
}
bool isBlank(char ch){
if(ch==' '||ch=='\t') return true
else return false
}
int main(){
string src,ste,s
char ch0,ch,ch1[2]
char ktt[48][20]={"and","begin","const","div","do","else","end","function","if","integer",
"not","or","procedure","program","read","real","then","type","var","while","write","标识符","无符号数",
",","",":",".","(",")","[","]","..","++","--","+","-","*","/","=","<",">","<>","<="
,">=",":=","{","}","#"}
int pos=0
FILE *fp
fp=fopen("d:\\in.txt","r")
ch0=fgetc(fp)
while(ch0!=EOF)
{
//if(ch0!='\t'){src+=ch0}
src+=ch0
ch0=fgetc(fp)
}
src+='#'
cout<<src<<endl
ch=src[pos++]
ste=" "
for(int j=0j<47j++){cout<<j<<ktt[j]<<endl}
cout<<"词法分析:\n"
while(ch!='#')
{
char str[20]
if(ch!='\n')
{
if(isDigit(ch))
{ //判断常数
int i=0
while(isDigit(ch)||ch=='.')
{
str[i++]=ch
//i++
ch=src[pos++]
}
str[i]='\0'
ste=ste+"戚扮|"+"22"
cout<<str
continue
}
else if(isLetter(ch))
{ //判断字符
int i=0,j
while(isLetter(ch)||isDigit(ch))
{
str[i++]=ch
//i++
ch=src[pos++]
}
str[i]='\0'
for(j=0j<21j++){ //判断是否关键字
int t=strcmp(str,ktt[j])
if(t==0) {
stringstream ss
ste+="|"
ss<<stess<<j
ss>>ste
break
}
}
if(j==21){ste=ste+"|"+"21"}
// cout<<" "
cout<<str
continue
}
else if(isP(ch)){ ///判断是否运含仔扒算符
int i=0,j
str[i++]=ch
str[i]='\0'
for(j=34j<38j++){
int t=strcmp(str,ktt[j])
if(t==0) {
stringstream ss
ste+="|"
ss<<stess<<j
ss>>ste
break
}
}
cout<<str
ch=src[pos++]
continue
}
else if(isJ(ch)) //判断是否界符
{
int i=0,j
while(isJ(ch))
{
str[i++]=ch
ch=src[pos++]
}
str[i]='\0'
for(j=23j<47j++){
int t=strcmp(str,ktt[j])
if(t==0) {
stringstream ss
ste+="|"
ss<<stess<<j
ss>>ste
break
}
}
cout<<str
continue
}
else if(isBlank(ch))
{
cout<<ch
ch=src[pos++]
continue
}
}
else{
cout<<ste<<endl
ste=" "
}
ch=src[pos++]
}
return 0
}
还有运行效果图,和实验报告 ,你要的话留下邮箱
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)