編譯原理如何調出詞法編譯器
『壹』 編譯原理中的詞法分析器的輸入與輸出是什麼
編譯原理中的詞法分析器的輸入是源程序,輸出是識別的記號流。
詞法分析器編制一個讀單詞的程序,從輸入的源程序中,識別出各個具有獨立意義的單詞,即基本保留字、標識符、常數、運算符和分隔符五大類。並依次輸出各個單詞的內部編碼及單詞符號自身值。(遇到錯誤時可顯示「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