编译原理如何调出词法编译器
‘壹’ 编译原理中的词法分析器的输入与输出是什么
编译原理中的词法分析器的输入是源程序,输出是识别的记号流。
词法分析器编制一个读单词的程序,从输入的源程序中,识别出各个具有独立意义的单词,即基本保留字、标识符、常数、运算符和分隔符五大类。并依次输出各个单词的内部编码及单词符号自身值。(遇到错误时可显示“Error”,然后跳过错误部分继续显示)。
(1)编译原理如何调出词法编译器扩展阅读
词法分析器的作用:
1、与符号表进行交互,存储和读取符号表中的标识符的信息。
2、读入源程序的输入字符,将他们组成词素,生成并输出一个词法单元序列,每个词法单元序列对应一个于一个词素。
3、过滤掉程序中的注释和空白。
4、将编译器生成的错误消息与源程序的位置联系起。
‘贰’ 关于编译原理
可以自己写一个JPanel或者JComponent的子类,然后在子类中重写paint方法,在里面绘制背景图片。下面的部分是从我的代码里截出来的,不保证这样能用,只是给你个大体的丝路。学会了这个后自己重写组件就方便多了 public class ChessBoard extends JComponent{ private Image screen = null; public void paint(Graphics g) { if (screen != null) { g.drawImage(screen, (width - BOARDWIDTH) / 2, (height - BOARDHEIGHT) / 2, this); } else { screen = ChessBoard.this.createImage(BOARDWIDTH,BOARDHEIGHT); } } }
‘叁’ 编译原理课设实现C/C++语言词法分析器
既然是c语言词法分析器,那就是用c/c++对一段c语言文本进行词法分析,c语言中的for语句、while语句、switch语句、if语句等等的进行分析并将其提取出来的一个设计和实现过程而矣
这是大学专门有一门《编译原理》的课程而矣
‘肆’ 编译原理词法分析器
用C++语言
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#include <conio.h>
#define NULL 0
FILE *fp;
char ch;
char *keyword[34]={"auto","break","case","char","const","continue","default","do","double",
"else","enum","extern","float","for","goto","if","int","long","register",
"return","short","signed","sizeof","static","struct","switch","typedef", "printf",
"union","unsigned","void","volatile","while","main"};
char *operatornum[6]={"+","-","*","/","++","--"};
char *comparison[8]={"<","<=","=",">",">=","<>","==","!="};
char *interpunction[8]={",",";",":=",".","(",")","{","}"};
char *biaoshifu[6]={"%","$","^","&","_","#"};//特殊标识符
char *zhushifu[3]={"//","/*","*/"};//注释符
char *luoji[3]={"&&","||","!"};//逻辑运算符
//////////////////////////////////////////////////////////////////////////////////////////
bool search(char searchstr[],int wordtype)
{
int i;
switch (wordtype)
{
case 1:for(i=0;i<=33;i++)
{
if(strcmp(keyword[i],searchstr)==0)
return(true);
}
case 2:{
for(i=0;i<=5;i++)
{
if(strcmp(operatornum[i],searchstr)==0)
return(true);
}
break;
}
case 3: {
for(i=0;i<=7;i++)
{
if(strcmp(comparison[i],searchstr)==0)
return(true);
}
break;
}
case 4: for(i=0;i<=7;i++)
{
if(strcmp(interpunction[i],searchstr)==0)
return(true);
}
break;
case 5: for(i=0;i<=5;i++)
{
if(strcmp(biaoshifu[i],searchstr)==0)
return(true);
}break;
case 6: for(i=0;i<=2;i++)
{
if(strcmp(zhushifu[i],searchstr)==0)
return(true);
}break;
case 7: for(i=0;i<=2;i++)
{
if(strcmp(luoji[i],searchstr)==0)
return(true);
}break;
}
return(false);
}
///////////////////////////////////////////////////////////////////////////////////////////
char letterprocess (char ch)//字母处理函数
{
int i=-1;
char letter[20];
while (isalnum(ch)!=0)
{
letter[++i]=ch;
ch=fgetc(fp);
};
letter[i+1]='\0';
if (search(letter,1))
{
printf("<%s,关键字>\n",letter);
//strcat(letter,"\n");
//fputs('<' letter '>\n',outp);
}
else
{
printf("<%s,自定义变量>\n",letter);
//strcat(letter,"\n");
//fputs(letter,outp);
}
return(ch);
}
///////////////////////////////////////////////////////////////////////////////////////////
char numberprocess(char ch)//数字处理程序
{
int i=-1;
char num[20];
while (isdigit(ch)!=0)
{
num[++i]=ch;
ch=fgetc(fp);
}
if(isalpha(ch)!=0)
{
while(isspace(ch)==0)
{
num[++i]=ch;
ch=fgetc(fp);
}
num[i+1]='\0';
printf("错误!非法标识符:%s\n",num);
goto u;
}
num[i+1]='\0';
printf("<%s,数字>\n",num);
//strcat(num,"\n");
//fputs(num,outp);
u: return(ch);
}
//////////////////////////////////////////////////////////////////////////////////////////////
char otherprocess(char ch)
{
int i=-1;
char other[20];
if (isspace(ch)!=0)
{
ch=fgetc(fp);
goto u;
}
while ((isspace(ch)==0)&&(isalnum(ch)==0))
{
other[++i]=ch;
ch=fgetc(fp);
}
other[i+1]='\0';
if (search(other,2))
printf("<%s,算数运算符>\n",other);
else
if (search(other,3))
printf("<%s,关系运算符号>\n",other);
else
if (search(other,4))
printf("<%s,分隔符号>\n",other);
else
if (search(other,5))
printf("<%s,特殊标识符号>\n",other);
else
if (search(other,6))
printf("<%s,注释符号>\n",other);
else
if (search(other,7))
printf("<%s,逻辑运算符号>\n",other);
else
printf("错误!非法字符:%s\n",other);
u: return (ch);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void main ()
{
char str,c;
printf("**********************************词法分析器************************************\n");
//outp=fopen("二元式表.txt","w");
if ((fp=fopen("源程序.txt","r"))==NULL)
printf("源程序无法打开!\n");
else
{
str =fgetc(fp);
while (str!=EOF)
{
if (isalpha(str)!=0)
str=letterprocess(str);
else
{
if (isdigit(str)!=0)
str=numberprocess(str);
else
str=otherprocess(str);
}
};
printf("词法分析结束,谢谢使用!\n");
printf("点任意键退出!\n");
}
c=getch();
}
‘伍’ 编译原理
这个是1型语言
‘陆’ 有人知道编译原理实验之词法分析器用C++怎么做吗
#include "globals.h"
#include "util.h"
#include "scan.h"
#include "parse.h"
static TokenType token; /* holds current token */
/* function prototypes for recursive calls */
static TreeNode * stmt_sequence(void);
static TreeNode * statement(void);
static TreeNode * if_stmt(void);
static TreeNode * repeat_stmt(void);
static TreeNode * assign_stmt(void);
static TreeNode * read_stmt(void);
static TreeNode * write_stmt(void);
static TreeNode * exp(void);
static TreeNode * simple_exp(void);
static TreeNode * term(void);
static TreeNode * factor(void);
static void syntaxError(char * message)
{ fprintf(listing,"\n>>> ");
fprintf(listing,"Syntax error at line %d: %s",lineno,message);
Error = TRUE;
}
static void match(TokenType expected)
{ if (token == expected) token = getToken();
else {
syntaxError("unexpected token -> ");
printToken(token,tokenString);
fprintf(listing," ");
}
}
TreeNode * stmt_sequence(void)
{ TreeNode * t = statement();
TreeNode * p = t;
while ((token!=ENDFILE) && (token!=END) &&
(token!=ELSE) && (token!=UNTIL))
{ TreeNode * q;
match(SEMI);
q = statement();
if (q!=NULL) {
if (t==NULL) t = p = q;
else /* now p cannot be NULL either */
{ p->sibling = q;
p = q;
}
}
}
return t;
}
TreeNode * statement(void)
{ TreeNode * t = NULL;
switch (token) {
case IF : t = if_stmt(); break;
case REPEAT : t = repeat_stmt(); break;
case ID : t = assign_stmt(); break;
case READ : t = read_stmt(); break;
case WRITE : t = write_stmt(); break;
default : syntaxError("unexpected token -> ");
printToken(token,tokenString);
token = getToken();
break;
} /* end case */
return t;
}
TreeNode * if_stmt(void)
{ TreeNode * t = newStmtNode(IfK);
match(IF);
if (t!=NULL) t->child[0] = exp();
match(THEN);
if (t!=NULL) t->child[1] = stmt_sequence();
if (token==ELSE) {
match(ELSE);
if (t!=NULL) t->child[2] = stmt_sequence();
}
match(END);
return t;
}
TreeNode * repeat_stmt(void)
{ TreeNode * t = newStmtNode(RepeatK);
match(REPEAT);
if (t!=NULL) t->child[0] = stmt_sequence();
match(UNTIL);
if (t!=NULL) t->child[1] = exp();
return t;
}
TreeNode * assign_stmt(void)
{ TreeNode * t = newStmtNode(AssignK);
if ((t!=NULL) && (token==ID))
t->attr.name = String(tokenString);
match(ID);
match(ASSIGN);
if (t!=NULL) t->child[0] = exp();
return t;
}
TreeNode * read_stmt(void)
{ TreeNode * t = newStmtNode(ReadK);
match(READ);
if ((t!=NULL) && (token==ID))
t->attr.name = String(tokenString);
match(ID);
return t;
}
TreeNode * write_stmt(void)
{ TreeNode * t = newStmtNode(WriteK);
match(WRITE);
if (t!=NULL) t->child[0] = exp();
return t;
}
TreeNode * exp(void)
{ TreeNode * t = simple_exp();
if ((token==LT)||(token==EQ)) {
TreeNode * p = newExpNode(OpK);
if (p!=NULL) {
p->child[0] = t;
p->attr.op = token;
t = p;
}
match(token);
if (t!=NULL)
t->child[1] = simple_exp();
}
return t;
}
TreeNode * simple_exp(void)
{ TreeNode * t = term();
while ((token==PLUS)||(token==MINUS))
{ TreeNode * p = newExpNode(OpK);
if (p!=NULL) {
p->child[0] = t;
p->attr.op = token;
t = p;
match(token);
t->child[1] = term();
}
}
return t;
}
TreeNode * term(void)
{ TreeNode * t = factor();
while ((token==TIMES)||(token==OVER))
{ TreeNode * p = newExpNode(OpK);
if (p!=NULL) {
p->child[0] = t;
p->attr.op = token;
t = p;
match(token);
p->child[1] = factor();
}
}
return t;
}
TreeNode * factor(void)
{ TreeNode * t = NULL;
switch (token) {
case NUM :
t = newExpNode(ConstK);
if ((t!=NULL) && (token==NUM))
t->attr.val = atoi(tokenString);
match(NUM);
break;
case ID :
t = newExpNode(IdK);
if ((t!=NULL) && (token==ID))
t->attr.name = String(tokenString);
match(ID);
break;
case LPAREN :
match(LPAREN);
t = exp();
match(RPAREN);
break;
default:
syntaxError("unexpected token -> ");
printToken(token,tokenString);
token = getToken();
break;
}
return t;
}
/****************************************/
/* the primary function of the parser */
/****************************************/
/* Function parse returns the newly
* constructed syntax tree
*/
TreeNode * parse(void)
{ TreeNode * t;
token = getToken();
t = stmt_sequence();
if (token!=ENDFILE)
syntaxError("Code ends before file\n");
return t;
}
上面是一个语法分析器的主代码部分它可以识别类似下面的代码,但是由于篇幅有限,上面的代码不是完整代码,完整代码太长,还有好几个文件。
read x; { input an integer }
if 0 < x then { don't compute if x <= 0 }
fact := 1;
repeat
fact := fact * x;
x := x - 1
until x = 0;
write fact { output factorial of x }
end
‘柒’ 编译原理 词法分析器的问题
#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <fstream>
#include <algorithm>
#include <cstdlib>
using namespace std;
//用来存储目标文件名
string file_name;
//提取文本文件中的信息。
string GetText();
//获得一个单词符号,从位置i开始查找。
//并且有一个引用参数j,用来返回这个单词最后一个字符在str的位置。
string GetWord(string str,int i,int& j);
//这个函数用来除去字符串中连续的空格和换行
//第一个参数为目标字符串,第二个参数为开始位置
//返回值为连续的空格和换行后的第一个有效字符在字符串的位置
int DeleteNull(string str,int i);
//判断i当前所指的字符是否为一个分界符,是的话返回真,反之假
bool IsBoundary(string str,int i);
//判断i当前所指的字符是否为一个运算符,是的话返回真,反之假
bool IsOperation(string str,int i);
//此函数将一个pair数组输出到一个文件中
void OutFile(vector<pair<int,string> > v);
//此函数接受一个字符串数组,对它进行词法分析,返回一个pair型数组
vector<pair<int,string> > analyst(vector<string> vec);
//此函数判断传递的参数是否为关键字,是的话,返回真,反之返回假
bool IsKey(string str);
int main()
{
cout<<"###########################\n";
cout<<"###right: Giftedbird###\n";
cout<<"###########################\n";
string com1=" ";
string com2="\n";
string fileline=GetText();
int begin=0,end=0;
vector<string> array;
do
{
begin=DeleteNull(fileline,begin);
string nowString;
nowString=GetWord(fileline,begin,end);
if(end==-1)
break;
if(nowString.compare(com1)&&nowString.compare(com2))
array.push_back(nowString);
begin=end+1;
}while(true);
vector<pair<int,string> > mid_result;
mid_result=analyst(array);
OutFile(mid_result);
cout<<"**********************************************************************\n";
cout<<"***程序已完成词法分析,分析结果已经存储在文件"<<file_name<<"中!!!***\n";
cout<<"**********************************************************************\n";
system("pause");
return 0;
}
//提取文本文件中的信息
string GetText()
{
string file_name1;
cout<<"请输入源文件名(包括路径和后缀名):";
cin>>file_name1;
ifstream infile(file_name1.c_str(),ios::in);
if (!infile)
{
cerr<<"哦!无法打开文件 "<<file_name1.c_str()<<" !!!"<<endl;
exit(-1);
}
cout<<endl;
char f[1000];
infile.getline(f,1000,EOF);
infile.close();
return f;
}
//获得一个单词符号,从位置i开始查找。
//并且有一个引用参数j,用来返回这个单词最后一个字符在原字符串的位置。
string GetWord(string str,int i,int& j)
{
string no_use("(){} , ; \n+=*/-<>\"");
j=str.find_first_of(no_use,i);
if(j==-1)
return "";
if(i!=j)
j--;
return str.substr(i,j-i+1);
}
//这个函数用来除去字符串中连续的空格和换行
//第一个参数为目标字符串,第二个参数为开始位置
//返回值为连续的空格和换行后的第一个有效字符在字符串的位置
int DeleteNull(string str,int i)
{
for(;;i++)
if(str[i]!=' '&&str[i]!='\n')
return i;
}
//判断i当前所指的字符是否为一个分界符,是的话返回真,反之假
bool IsBoundary(string str,int i)
{
int t;
char arr[7]={',',';','{','}','(',')','\"'};
for (t=0;t<7;t++)
if(str[i]==arr[t])
return true;
return false;
}
//判断i当前所指的字符是否为一个运算符,是的话返回真,反之假
bool IsOperation(string str,int i)
{
int t;
char arr[7]={'+','-','*','/','=','<','>'};
for (t=0;t<7;t++)
if(str[i]==arr[t])
return true;
return false;
}
//此函数将一个个字符串数组输出到一个文件中
void OutFile(vector<pair<int,string> > v)
{
cout<<"请输入目标文件名(包括路径和后缀名):";
cin>>file_name;
ofstream outfile(file_name.c_str(),ios::out);
if (!outfile)
{
cerr<<"哦!无法打开文件 "<<file_name.c_str()<<" !!!"<<endl;
exit(-1);
}
cout<<endl;
int i;
outfile<<"###########################\n";
outfile<<"###right: Giftedbird###\n";
outfile<<"###########################\n\n";
for(i=0;i<v.size();i++)
outfile<<"<"<<v[i].first<<" , \""<<v[i].second<<"\">"<<endl;
outfile<<"\n\n*********************************\n";
outfile.close();
return;
}
//此函数接受一个字符串数组,对它进行词法分析,返回一个pair型数组
vector<pair<int,string> > analyst(vector<string> vec)
{
vector<pair<int,string> > temp;
int i;
for(i=0;i<vec.size();i++)
{
if(vec[i].size()==1)
{
if((vec[i]==">"||vec[i]=="<"||vec[i]=="!")&&vec[i+1]=="=")
{
string jk=vec[i];
jk.append(vec[++i],0,1);
pair<int,string> pp(4,jk);
temp.push_back(pp);
continue;
}
if((vec[i]=="+"&&vec[i+1]=="+")||(vec[i]=="-"&&vec[i+1]=="-"))
{
string jk=vec[i];
jk.append(vec[++i],0,1);
pair<int,string> pp(4,jk);
temp.push_back(pp);
continue;
}
if(IsBoundary(vec[i],0))
{
pair<int,string> pp(5,vec[i]);
temp.push_back(pp);
}
else if(IsOperation(vec[i],0))
{
pair<int,string> pp(4,vec[i]);
temp.push_back(pp);
}
else if(vec[i][0]<='9'&&vec[i][0]>='0')
{
pair<int,string> pp(3,vec[i]);
temp.push_back(pp);
}
else
{
pair<int,string> pp(2,vec[i]);
temp.push_back(pp);
}
}
else if(vec[i][0]<='9'&&vec[i][0]>='0')
{
pair<int,string> pp(3,vec[i]);
temp.push_back(pp);
}
else if(IsKey(vec[i]))
{
pair<int,string> pp(1,vec[i]);
temp.push_back(pp);
}
else
{
pair<int,string> pp(2,vec[i]);
temp.push_back(pp);
}
}
return temp;
}
//此函数判断传递的参数是否为关键字,是的话,返回真,反之返回假
bool IsKey(string str)
{
string p[16]={"char","double","int","long","double","float","for","while","do","break","continue","switch","short","case","return","if"};
vector<string> ppp(p,p+16);
int u;
for(u=0;u<ppp.size();u++)
if(!str.compare(ppp[u]))
return true;
return false;
}
//finished