導航:首頁 > 源碼編譯 > 編譯原理詞法分析test語言

編譯原理詞法分析test語言

發布時間:2022-10-24 22:36:14

編譯原理詞法分析器

這個只要多看看編譯原理書就明白了,這么說吧,詞法分析器就是根據語言的此法規則構造出識別其單詞的有限自動機,它呢是一個數學模型,
先給出識別各類單詞的狀態轉換圖,
將各類單詞的狀態轉換圖的初始狀態合並成一個唯一的初狀態;
然後化簡並調整沖突的狀態編號;
最後再將有限自動機變成一個可行的詞法分析器。

❷ 編譯原理 詞法分析程序的設計與實現實驗題

說他像蒼蠅,是罵蒼蠅呢還是罵他呢?

❸ 編譯原理詞法分析程序

(一)Block子程序分析

procere enter(k: object1); //填寫符號表
begin {enter object into table}
tx := tx + 1; //下標加1,tx的初始值為零,零下標不地址不填寫標志符,用於查找失敗使用
with table[tx] do //填入內容,保存標志符名和類型
begin name := id; kind := k;
case k of //根據類型判斷是否正確
constant: begin if num > amax then //如果是常量,判斷是否大於最大值,若是則報30號錯
begin error(30); num :=0 end;
val := num //否則保存數值
end;
varible: begin level := lev; adr := dx; dx := dx + 1; //如果是變數,填寫變數內部表示,LEVEl是變數的層次,adr為地址
end;
proc: level := lev //如果是過程,保存過程的層次
end
end
end {enter};

//查找符號表的位置
function position(id: alfa): integer;
var i: integer;
begin {find indentifier id in table} //從後向前查找
table[0].name := id; i := tx; //找到保存類型
while table[i].name <> id do i := i-1;
position := i //返回標志符在符號表中的位置
end {position};

procere block(lev,tx: integer; fsys: symset);
var dx: integer; {data allocation index} //數據分配索引
tx0: integer; {initial table index} //初始符號表索引
cx0: integer; {initial code index} //初始代碼索引
procere enter(k: object1); //填寫符號表,下次分析
begin {enter object into table}
tx := tx + 1;
with table[tx] do
begin name := id; kind := k;
case k of
constant: begin if num > amax then
begin error(30); num :=0 end;
val := num
end;
varible: begin level := lev; adr := dx; dx := dx + 1;
end;
proc: level := lev
end
end
end {enter};

function position(id: alfa): integer; //查找符號表,下次分析
var i: integer;
begin {find indentifier id in table}
table[0].name := id; i := tx;
while table[i].name <> id do i := i-1;
position := i
end {position};

procere constdeclaration; //常量聲明
begin if sym = ident then //如果是標志符,讀入一個TOKEN
begin getsym;
if sym in [eql, becomes] then //讀入的是等號或符值號繼續判斷
begin if sym = becomes then error(1); //如果是「=」報1號錯
getsym; //讀入下一個TOKEN
if sym = number then //讀入的是數字,填寫符號表
begin enter(constant); getsym
end
else error(2) //如果不是數字,報2號錯
end else error(3) //不是等號或符值號,報3號錯
end else error(4) //如果不是標志符,報4號錯
end {constdeclaration};

procere vardeclaration; //變數聲明
begin if sym = ident then //讀入的是標志符,填寫符號表
begin enter(varible); getsym
end else error(4) //不是標志符,報4號錯
end {vardeclaration};

procere listcode;
var i: integer;
begin {list code generated for this block}
for i := cx0 to cx-1 do
with code[i] do
writeln(i:5, mnemonic[f]:5, 1:3, a:5)
end {listcode};

procere statement(fsys: symset);
var i, cx1, cx2: integer;
procere expression(fsys: symset); //表達式分析
var addop: symbol;
procere term(fsys: symset); //項分析
var mulop: symbol;
procere factor(fsys: symset); //因子分析
var i: integer;
begin test(facbegsys, fsys, 24); //讀入的是「(」,標志符或數字
while sym in facbegsys do
begin
if sym = ident then //是標志符,查表
begin i:= position(id);
if i = 0 then error(11) else //未找到,報11號錯
with table[i] do //找到,讀入標志符類型
case kind of
constant: gen(lit, 0, val); //寫常量命令
varible: gen(lod, lev-level, adr);//寫變數命令
proc: error(21) //過程名,報21號錯
end;
getsym //讀入下一個TOKEN
end else
if sym = number then //讀入的是數字
begin if num > amax then //如果數字大於最大數,報30號錯誤
begin error(30); num := 0
end;
gen(lit, 0, num); getsym //調用數字命令,讀入下一個TOKEN
end else
if sym = lparen then //讀入的是「(」
begin getsym; expression([rparen]+fsys); //調用表達式分析函數
if sym = rparen then getsym else error(22) //如果「(」後無「)」,報22號錯
end;
test(fsys, [lparen], 23)
end
end {factor};//因子分析結束

//項分析
begin {term} factor(fsys+[times, slash]); //調用因子分析程序
while sym in [times, slash] do //取得是乘、除號循環
begin mulop:=sym;getsym;factor(fsys+[times,slash]); //記錄符號,調用因子分析
if mulop=times then gen(opr,0,4) else gen(opr,0,5) //寫乘除指令
end
end {term};
begin {expression}
if sym in [plus, minus] then //如果是加減號
begin addop := sym; getsym; term(fsys+[plus,minus]); //記錄符號,調用項分析程序
if addop = minus then gen(opr, 0,1) //寫加減指令
end else term(fsys+[plus, minus]);
while sym in [plus, minus] do //如果是加減號循環
begin addop := sym; getsym; term(fsys+[plus,minus]);
if addop=plus then gen(opr,0,2) else gen(opr,0,3)
end
end {expression};

//條件過程
procere condition(fsys: symset);
var relop: symbol;
begin
if sym = oddsym then //如果是判奇符
begin getsym; expression(fsys); gen(opr, 0, 6) //取下一個TOKEN,調用expression,填指令
end else
begin expression([eql, neq, lss, gtr, leq, geq]+fsys);
if not(sym in [eql, neq, lss, leq, gtr, geq]) then //如果不是取到邏輯判斷符號,出錯.20
error(20) else
begin relop := sym; getsym; expression(fsys);
case relop of
eql: gen(opr, 0, 8); // =,相等
neq: gen(opr, 0, 9); // #,不相等
lss: gen(opr, 0, 10); // <,小於
geq: gen(opr, 0, 11); // ],大於等於
gtr: gen(opr, 0, 12); // >,大於
leq: gen(opr, 0, 13); // [,小於等於
end
end
end
end {condition};

begin {statement}
if sym = ident then //如果是標識符
begin i := position(id); //查找符號表
if i = 0 then error(11) else //未找到,標識符未定義,報11號錯
if table[i].kind <> varible then //如果標識符不是變數,報12號錯
begin {assignment to non-varible} error(12); i := 0
end;
getsym; if sym = becomes then getsym else error(13); //如果是變數讀入下一個TOKEN,不是賦值號,報13好錯;是則讀入一個TOKEN
expression(fsys); //調用表達是過程
if i <> 0 then //寫指令
with table[i] do gen(sto, lev-level, adr)
end else
if sym = callsym then //如果是過程調用保留字,讀入下一個TOKEN
begin getsym;
if sym <> ident then error(14) else //不是標識符報14號錯
begin i := position(id);
if i = 0 then error(11) else //是標識符,未定義,報13號錯
with table[i] do // 已定義的標識符讀入類型
if kind=proc then gen(cal, lev-level, adr) //是過程名寫指令
else error(15); //不是過程名,報15號錯
getsym
end
end else
if sym = ifsym then //如果是IF
begin getsym; condition([thensym, dosym]+fsys); //讀入一個TOKEN,調用條件判斷過程
if sym = thensym then getsym else error(16); //如果是THEN,讀入一個TOKEN,不是,報16號錯
cx1 := cx; gen(jpc, 0, 0); //寫指令
statement(fsys); code[cx1].a := cx
end else
if sym = beginsym then //如果是BEGIN
begin getsym; statement([semicolon, endsym]+fsys); //讀入一個TOKEN
while sym in [semicolon]+statbegsys do
begin
if sym = semicolon then getsym else error(10); //如果讀入的是分號
statement([semicolon, endsym]+fsys)
end;
if sym = endsym then getsym else error(17) //如果是END 讀入一個TOKEN,不是,報17號錯
end else
if sym = whilesym then //如果是WHILE
begin cx1 := cx; getsym; condition([dosym]+fsys); //調用條件過程
cx2 := cx; gen(jpc, 0, 0); //寫指令
if sym = dosym then getsym else error(18); //如果是DO讀入下一個TOKEN,不是報18號錯
statement(fsys); gen(jmp, 0, cx1); code[cx2].a := cx
end;
test(fsys, [], 19)
end {statement};

begin {block}
dx:=3;
tx0:=tx;
table[tx].adr:=cx;
gen(jmp,0,0);
if lev > levmax then error(32);
repeat
if sym = constsym then //如果是CONST
begin getsym; //讀入TOKEN
repeat constdeclaration; //常量聲明
while sym = comma do
begin getsym; constdeclaration
end;
if sym = semicolon then getsym else error(5) //如果是分號讀入下一個TOKEN,不是報5號錯
until sym <> ident //不是標志符常量聲明結束
end;
if sym = varsym then 如果是VAR
begin getsym; 讀入下一個TOKEN
repeat vardeclaration; //變數聲明
while sym = comma do
begin getsym; vardeclaration
end;
if sym = semicolon then getsym else error(5) //如果是分號讀入下一個TOKEN,不是報5號錯
until sym <> ident; //不是標志符常量聲明結束
end;
while sym = procsym do //過程聲明
begin getsym;
if sym = ident then
begin enter(proc); getsym
end
else error(4); //不是標志符報4號錯
if sym = semicolon then getsym else error(5); //如果是分號讀入下一個TOKEN,不是報5號錯
block(lev+1, tx, [semicolon]+fsys);
if sym = semicolon then //如果是分號,取下一個TOKEN,不是報5號錯
begin getsym;test(statbegsys+[ident,procsym],fsys,6)
end
else error(5)
end;
test(statbegsys+[ident], declbegsys, 7)
until not(sym in declbegsys); //取到的不是const var proc結束
code[table[tx0].adr].a := cx;
with table[tx0] do
begin adr := cx; {start adr of code}
end;
cx0 := 0{cx}; gen(int, 0, dx);
statement([semicolon, endsym]+fsys);
gen(opr, 0, 0); {return}
test(fsys, [], 8);
listcode;
end {block};

❹ 編譯原理中的詞法分析器的輸入與輸出是什麼

編譯原理中的詞法分析器的輸入是源程序,輸出是識別的記號流。

詞法分析器編制一個讀單詞的程序,從輸入的源程序中,識別出各個具有獨立意義的單詞,即基本保留字、標識符、常數、運算符和分隔符五大類。並依次輸出各個單詞的內部編碼及單詞符號自身值。(遇到錯誤時可顯示「Error」,然後跳過錯誤部分繼續顯示)。

(4)編譯原理詞法分析test語言擴展閱讀

詞法分析器的作用:

1、與符號表進行交互,存儲和讀取符號表中的標識符的信息。

2、讀入源程序的輸入字元,將他們組成詞素,生成並輸出一個詞法單元序列,每個詞法單元序列對應一個於一個詞素。

3、過濾掉程序中的注釋和空白。

4、將編譯器生成的錯誤消息與源程序的位置聯系起。


❺ 怎樣較容易理解編譯原理中詞法分析的原理即實現過程,最好配上圖文解說

詞法分析的本質是讓計算機程序理解詞法規則。例如,在我們平時用的語言里,「你」是指一個人,當「你們」出現的時候就是一個詞是指多個人,這就是一種規則,但是是人能理解的規則,詞法分析要用數學的表達方式讓計算機理解,計算機的做法是對每個遇到的字先判斷是不是「你」,如果不是,那麼不符合這條規則;如果是,就要記下現在這個狀態---即已經看到一個「你」字,然後判斷下一個字是不是「們」,是則這條規則成立,也就是讓計算機理解了這一個詞,而不是單個的兩個字。詞法分析不是編譯原理才有的,在搜索、數據挖掘等領域都用到。編譯原理中的詞法分析就是把源程序中的字元按順序一個一個輸入給計算機,計算機對每個字元按照所有規則進行判斷,例如輸入了一個「a」,要判斷它是不是「and「的開頭,是不是一個變數名,函數名,還是字元串等等,每個可能性都是一條規則決定的。根據規則的復雜性,可以用多種數學方法描述,比如基本的方法是狀態機、正則表達式。

❻ 編譯原理課程設計-詞法分析器設計(C語言)

#include"stdio.h"/*定義I/O庫所用的某些宏和變數*/

#include"string.h"/*定義字元串庫函數*/

#include"conio.h"/*提供有關屏幕窗口操作函數*/

#include"ctype.h"/*分類函數*/

charprog[80]={''},

token[8];/*存放構成單詞符號的字元串*/

charch;

intsyn,/*存放單詞字元的種別碼*/

n,

sum,/*存放整數型單詞*/

m,p;/*p是緩沖區prog的指針,m是token的指針*/

char*rwtab[6]={"begin","if","then","while","do","end"};

voidscaner(){

m=0;

sum=0;

for(n=0;n<8;n++)

token[n]='';

ch=prog[p++];

while(ch=='')

ch=prog[p++];

if(isalpha(ch))/*ch為字母字元*/{

while(isalpha(ch)||isdigit(ch))/*ch為字母字元或者數字字元*/{

token[m++]=ch;

ch=prog[p++];}

token[m++]='';

ch=prog[p--];

syn=10;

for(n=0;n<6;n++)

if(strcmp(token,rwtab[n])==0)/*字元串的比較*/{

syn=n+1;

break;}}

else

if(isdigit(ch))/*ch是數字字元*/{

while(isdigit(ch))/*ch是數字字元*/{

sum=sum*10+ch-'0';

ch=prog[p++];}

ch=prog[p--];

syn=11;}

else

switch(ch){

case'<':m=0;token[m++]=ch;ch=prog[p++];

if(ch=='>'){

syn=21;

token[m++]=ch;}

elseif(ch=='='){

syn=22;

token[m++]=ch;}

else{

syn=20;

ch=prog[p--];}

break;

case'>':m=0;token[m++]=ch;ch=prog[p++];

if(ch=='='){

syn=24;

token[m++]=ch;}

else{

syn=23;

ch=prog[p--];}

break;

case':':m=0;token[m++]=ch;ch=prog[p++];

if(ch=='='){

syn=18;

token[m++]=ch;}

else{

syn=17;

ch=prog[p--];}

break;

case'+':syn=13;token[0]=ch;break;

case'-':syn=14;token[0]=ch;break;

case'*':syn=15;token[0]=ch;break;

case'/':syn=16;token[0]=ch;break;

case'=':syn=25;token[0]=ch;break;

case';':syn=26;token[0]=ch;break;

case'(':syn=27;token[0]=ch;break;

case')':syn=28;token[0]=ch;break;

case'#':syn=0;token[0]=ch;break;

default:syn=-1;}}

main()

{

printf(" Thesignificanceofthefigures: "

"1.figures1to6saidKeyword "

"2. "

"3.figures13to28saidOperators ");

p=0;

printf(" pleaseinputstring: ");

do{

ch=getchar();

prog[p++]=ch;

}while(ch!='#');

p=0;

do{

scaner();

switch(syn){

case11:printf("(%d,%d) ",syn,sum);break;

case-1:printf(" ERROR; ");break;

default:printf("(%d,%s) ",syn,token);

}

}while(syn!=0);

getch();

}

程序測試結果

對源程序beginx:=9:ifx>9thenx:=2*x+1/3;end#的源文件,經過詞法分析後輸出如下圖5-1所示:

具體的你在修改修改吧

❼ 編譯原理 詞法分析

C語言詞法分析器
#include<iostream>
#include<stdio.h>
#include<string>

using namespace std;

FILE *f; //定義一個文件變數
static int line = 1; //表示游標所在的行數
struct ID{ char *name; int count;}id[100];//用於存放ID號碼
static int I = 0; //用於記錄ID存放的數量
int Number[100]; //用於存放數字
static int P = 0; //用於記錄存放數字的個數
int error[100] = {0}; //用於記錄錯誤所在的行數
static int K = 0; //記錄錯誤次數
void Error(); //記錄錯誤
void loginID(char *); //注冊ID號
void loginNumber(int &); //記錄數字
void noteLine(char &); //記錄游標所在的行數
void print(); //輸出分析結果
int same(char *chr); //判斷單詞是否已經存在

void Error()
{ error[K++] = line; }

void loginID(char *chr) //注冊ID號
{
int k = 0;
int h = 0;
for(int i = 0; i < I; i++)
{
if(!strcmp(chr,id.name)) //如果單詞已經存在
{
id.count++;
k = 1;
}
}
if(k == 0) //該單詞不存在
{
h = I + 1;
//I = h;
id[h].count++;
id[h].name = chr;
//strcpy(id[h].name ,chr);
}

}

void loginNumber(int &nu)
{ Number[P++] = nu; }

void noteLine(char &ch)
{
if ( ch == ' ' )
++line;
}

void print()//輸出部分
{
//cout << "關鍵字以及變數:" << endl;
//for(int i = 0; i < 100; i++)
//cout << i <<" " << id.name << " " << id.count << endl;
cout << "數字:" << endl;
for(int i = 1; i <= P; i++)
cout << i << ": " << Number[i-1] << endl;
if(error[0] != 0)
{
cout << "出現的錯誤!" << endl;
for(int i = 1; i <= K; i++)
cout << "第" << i << "個錯誤: " << "第" << error[i-1] << "行" << endl;
}
else cout << "沒有錯誤!" << endl;
}

//文件處理部分
void noblank( char &ch) //跳過空格,回車
{
noteLine(ch);
while(ch == ' ' || ch == ' ')
ch = fgetc(f);
}

void identifier(char name[],char &ch)//字母變數
{

int i;
for(i = 0; i < 20; i++)
name = '';
i = 0;
while (('0'<= ch && ch <= '9')||('a'<= ch&&ch <= 'z')||('A'<= ch&&ch <='Z'))
{
name = ch;
i++;
ch = fgetc(f);
}
loginID(name);
//for(int j = 0; j < i; j++)
//{cout << name[j];}
// cout << ' ';

}

int number(char &ch)//數字
{
int num=0;
while('0'<= ch && ch <= '9')
{
num = num* 10 + (ch-'0');
ch = fgetc(f);
}
if( ('a'<= ch&&ch <= 'z')||('A'<= ch&&ch <='Z'))
{
Error();
}
else if( ch == '.')
{;}
loginNumber(num); //記錄數字
return num;
}

void test(char &ch)//符號
{
char str[2]={'0/'};
if(ch == '*')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '.')
{ str[0] = ch; ch = fgetc(f);}
if(ch == ',')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '"')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '/')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '%')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '^')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '-')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '{')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '}')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '[')
{ str[0] = ch; ch = fgetc(f);}
if(ch == ']')
{ str[0] = ch; ch = fgetc(f);}
if(ch == ';')
{str[0] = ch; ch = fgetc(f);}
if(ch == ':')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '?')
{ str[0] = ch; ch = fgetc(f);}
if(ch == '(')
{ str[0] = ch; ch = fgetc(f);}
if(ch == ')')
{str[0] = ch; ch = fgetc(f);}
if(ch =='+')
{

str[0] = ch;
if((ch = fgetc(f)) == '+' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

//cout << str[0]<< endl;
}
if(ch == '-')
{

str[0] = ch;
if((ch = fgetc(f)) == '-' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

//cout << str[0]<< endl;
}
if(ch == '&')
{

str[0] = ch;
if((ch = fgetc(f)) == '&' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

//cout << str[0]<< endl;
}
if(ch == '|')
{

str[0] = ch;
if((ch = fgetc(f)) == '|' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

//cout << str[0]<< endl;
}
if(ch == '!')
{

str[0] = ch;
if((ch = fgetc(f)) == '=' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

//cout << str[0]<< endl;
}
if(ch == '=')
{

str[0] = ch;
if((ch = fgetc(f)) == '=' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

}
if(ch == '>')
{

str[0] = ch;
if((ch = fgetc(f)) == '=' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}
else
if(ch == '>' )
{
str[1] = ch;
ch = fgetc(f);
//cout << str[0] << str[1] << endl;
}

}
if(ch == '<')
{
str[0] = ch;
if((ch = fgetc(f)) == '=' )
{
str[1] = ch;
ch = fgetc(f);
}
else
if(ch == '<' )
{
str[1] = ch;
ch = fgetc(f);
}

}

}

int main()
{
char ch;
char name[30];
for(int i = 0; i < 30; i++)
name = '/0';
f = fopen("c.txt","r"); //打開指定輸入文件
if (f == NULL)
cout<<"文件不存在!"<<endl;
ch = fgetc(f);
while(!feof(f))
{
noblank( ch ); //跳過回車,空格
if( ( ch >= 'a' && ch <= 'z' )||( ch >= 'A' && ch <= 'Z' ))
{ identifier(name,ch); } //處理字母
else if( ch >= '0'&& ch <= '9')
{ number(ch); } //處理數字
else
{ test(ch); } //處理符號
}
print(); //列印詞法分析結果
fclose(f); //關閉文件
system("pause");
return 0;
}

❽ 編譯原理的一個詞法分析題(希望

#include "word.h"

void main(){
menu();
}

///列表生成工具
void makelist(char * text){
char ch[20][20];
int i=0;
int j,k;
while(1){
cin>>ch[i];
if(strcmp(ch[i],"enterend")==0)
break;
i++;
}
char xch[20];
for(k=0;k<i;k++)
{
for(j=0;j<i-1;j++)
{
if(strcmp(ch[j],ch[j+1])>0)
{strcpy(xch,ch[j]);strcpy(ch[j],ch[j+1]);strcpy(ch[j+1],xch);}
}
}
ofstream out(text);
for(k=0;k<i;k++)
{
out<<ch[k]<<endl;
}

}

//單詞分離
void wordfind(char * text){
cout<<"請輸入要分析的文件名:"<<endl;
cin>>text;
char buf;
int i=0;
int len=0;
char buff[2048];
ifstream fin(text);
//源文件的規則化
while(!fin.eof()){
buf=fin.get();
if(buf=='\n'||buf==';')
buf=' ';
buff[len]=buf;
len++;
}
char * buffer=new char[len];
strncpy(buffer,buff,len);
//單詞提取
ofstream out(Words);
for(i=0;i<len-1;i++)
{
if((buffer[i]>='a'&&buffer[i]<='z')||(buffer[i]>='A'&&buffer[i]<='Z')||(buffer[i]>='0'&&buffer[i]<='9'))
{
out<<buffer[i];
}
else
{
if(buffer[i]!=' ')
{
if(buffer[i-1]!=' ')
out<<endl;
out<<buffer[i]<<endl;
}
else
{
if(buffer[i-1]!=' ')
out<<endl;
}

}
}
}

//單詞判斷
bool casein(char * text,char * words){
char word[10];
int k=0;
ifstream fin(text);
while(!fin.eof()){
fin>>word;
if(k=strcmp(word,words)==0)
return TRUE;
else
if(k>0)
return FALSE;
}
return FALSE;

}

//單詞分組
int switchgroup(char * word){
if(casein(Word,word))
return 1;
if(casein(Char,word))
return 2;
if(word[0]==':')
return 3;
else
return 4;
}

//使用集 各參數的使用
void fanal(){
int kind;
int lastkind=0;
char word[10];
ifstream fin(Words);
while(!fin.eof()){
fin>>word;
kind=switchgroup(word);
if(kind==3)
{
fin>>word;
kind=switchgroup(word);
if(word[0]=='=')
{
print(kind,":=",lastkind);
}
}
else
{
print(kind,word,lastkind);
}
lastkind=kind;

}
}

//單詞類型分析
int startwith(char * word){
if(word[0]>='0'&&word[0]<='9')
return NUMBER;
else
return CHAR;
}

//顯示列印
void print(int k,char * word,int l){
if(k==1)
cout<<"類型是: 關鍵字 名字是: "<<word<<" 值是:"<<word<<endl;
if(k==2)
cout<<"類型是: 特殊符號 名字是: "<<word<<" 值是:"<<word<<endl;
if(k==4)
if(l==1)
cout<<"類型是: 變數 名字是: "<<word<<" 值是:"<<word<<endl;
if((l==2)&&startwith(word))
cout<<"類型是: 變數 名字是: "<<word<<" 值是:"<<word<<endl;
if((l==2)&&!startwith(word))
cout<<"類型是: 常量 名字是: "<<word<<" 值是:"<<word<<endl;
}

#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
#define BUFSIZE 2048
#define CHAR 1
#define NUMBER 0

//函數聲明
bool casein(char *);
void wordfind(char *);
void makelist(char *);
int switchgroup(char * );
void print(int,char *,int);
void menu();
void menu2();
int startwith(char *);

//全局變數定義
char Word[]="wordlist.txt";
char Char[]="charlist.txt";
char readfile[]="readfile.txt";
char Words[]="wordslist.txt";
charlist.txt的內容 可以隨便加你要的符號
(
)
*
+
-
/
=
wordlist.txt 關鍵字表 也可以隨便寫 我寫的是
else
end
if
read
repeat
then
until
write
以上都是一個詞一行
還有readfile.txt 是被分析文件 自己寫吧.你有誠意給我沖10QB 447322160 我寫了4個小時

❾ 編譯原理詞法分析

編譯的詞法分析,一般是先畫一個狀態轉換圖,一般是有多少分支,就有多少if語句,分支裡面再分(可能有循環語句)。注意記住詞的類別和詞的字元串,請以以下代碼為例,理會一下詞法分析的大致過程。
while(s[i]!='#')
{
while(s[i]==' '||s[i]=='\t'||s[i]=='\n')
{
if(s[i]=='\n')
line++;
i++;
}
if(s[i]=='#')
break;
j=i;
if(s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z')
{
i++;
while(s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z'||s[i]>='0'&&s[i]<='9')
i++;
if((i-j)==2&&s[j]=='i'&&s[j+1]=='f')
{
strcpy(dancishuzu[dancigeshu].name,"if");
dancishuzu[dancigeshu].bianhao=4;
dancigeshu++;
}
else if((i-j)==3&&s[j]=='i'&&s[j+1]=='n'&&s[j+2]=='t')
{
strcpy(dancishuzu[dancigeshu].name,"int");
dancishuzu[dancigeshu].bianhao=2;
dancigeshu++;
}
else if((i-j)==3&&s[j]=='f'&&s[j+1]=='o'&&s[j+2]=='r')
{
strcpy(dancishuzu[dancigeshu].name,"for");
dancishuzu[dancigeshu].bianhao=6;
dancigeshu++;
}
else if((i-j)==4&&s[j]=='m'&&s[j+1]=='a'&&s[j+2]=='i'&&s[j+3]=='n')
{
strcpy(dancishuzu[dancigeshu].name,"main");
dancishuzu[dancigeshu].bianhao=1;
dancigeshu++;
}
else if ((i-j)==4&&s[j]=='c'&&s[j+1]=='h'&&s[j+2]=='a'&&s[j+3]=='r')
{
strcpy(dancishuzu[dancigeshu].name,"char");
dancishuzu[dancigeshu].bianhao=3;
dancigeshu++;
}
else if ((i-j)==4&&s[j]=='e'&&s[j+1]=='l'&&s[j+2]=='s'&&s[j+3]=='e')
{
strcpy(dancishuzu[dancigeshu].name,"else");
dancishuzu[dancigeshu].bianhao=5;
dancigeshu++;
}
else if ((i-j)==5&&s[j]=='w'&&s[j+1]=='h'&&s[j+2]=='i'&&s[j+3]=='l'&&s[j+4]=='e')
{
strcpy(dancishuzu[dancigeshu].name,"while");
dancishuzu[dancigeshu].bianhao=7;
dancigeshu++;
}
else{
dancishuzu[dancigeshu].bianhao=10;
count=0;
while(j<i)
{
dancishuzu[dancigeshu].name[count++]=s[j];
j++;
}
dancishuzu[dancigeshu].name[count]='\0';
dancigeshu++;
}
}
else if(s[i]>='0'&&s[i]<='9')
{
while(s[i]>='0'&&s[i]<='9')
i++;
dancishuzu[dancigeshu].bianhao=11;
count=0;
while(j<i)
{
dancishuzu[dancigeshu].name[count++]=s[j];
j++;
}
dancishuzu[dancigeshu].name[count]='\0';
dancigeshu++;
}

else if(s[i]=='=')
{
if(s[i+1]=='=')
{
dancishuzu[dancigeshu].bianhao=30;
strcpy(dancishuzu[dancigeshu].name,"==");
dancigeshu++;
i+=2;
}
else
{
dancishuzu[dancigeshu].bianhao=12;
strcpy(dancishuzu[dancigeshu].name,"=");
dancigeshu++;
i++;
}
}
else if(s[i]=='+')
{
dancishuzu[dancigeshu].bianhao=13;
strcpy(dancishuzu[dancigeshu].name,"+");
dancigeshu++;
i++;
}
else if(s[i]=='-')
{
dancishuzu[dancigeshu].bianhao=14;
strcpy(dancishuzu[dancigeshu].name,"-");
dancigeshu++;
i++;
}
else if(s[i]=='*')
{
dancishuzu[dancigeshu].bianhao=15;
strcpy(dancishuzu[dancigeshu].name,"*");
dancigeshu++;
i++;
}
else if(s[i]=='/')
{
dancishuzu[dancigeshu].bianhao=16;
strcpy(dancishuzu[dancigeshu].name,"/");
dancigeshu++;
i++;
}
else if(s[i]=='(')
{
i++;
dancishuzu[dancigeshu].bianhao=17;
strcpy(dancishuzu[dancigeshu].name,"(");
dancigeshu++;
}
else if(s[i]==')')
{
i++;
dancishuzu[dancigeshu].bianhao=18;
strcpy(dancishuzu[dancigeshu].name,")");
dancigeshu++;
}
else if(s[i]=='[')
{
i++;
dancishuzu[dancigeshu].bianhao=19;
strcpy(dancishuzu[dancigeshu].name,"[");
dancigeshu++;
}
else if(s[i]==']')
{
i++;
dancishuzu[dancigeshu].bianhao=20;
strcpy(dancishuzu[dancigeshu].name,"]");
dancigeshu++;
}
else if(s[i]=='{')
{
i++;
dancishuzu[dancigeshu].bianhao=21;
strcpy(dancishuzu[dancigeshu].name,"{");
dancigeshu++;
}
else if(s[i]=='}')
{
i++;
dancishuzu[dancigeshu].bianhao=22;
strcpy(dancishuzu[dancigeshu].name,"}");
dancigeshu++;
}
else if(s[i]==',')
{
i++;
dancishuzu[dancigeshu].bianhao=23;
strcpy(dancishuzu[dancigeshu].name,",");
dancigeshu++;
}
else if(s[i]==':')
{
i++;
dancishuzu[dancigeshu].bianhao=24;
strcpy(dancishuzu[dancigeshu].name,":");
dancigeshu++;
}
else if(s[i]==';')
{
i++;
dancishuzu[dancigeshu].bianhao=25;
strcpy(dancishuzu[dancigeshu].name,";");
dancigeshu++;
}
else if(s[i]=='>')
{
if(s[i+1]=='=')
{
dancishuzu[dancigeshu].bianhao=28;
strcpy(dancishuzu[dancigeshu].name,">=");
dancigeshu++;
i+=2;
}
else
{
i++;
dancishuzu[dancigeshu].bianhao=26;
strcpy(dancishuzu[dancigeshu].name,">");
dancigeshu++;
}
}
else if(s[i]=='<')
{
if(s[i+1]=='=')
{
dancishuzu[dancigeshu].bianhao=29;
strcpy(dancishuzu[dancigeshu].name,"<=");
dancigeshu++;
i+=2;
}
else
{
i++;
dancishuzu[dancigeshu].bianhao=27;
strcpy(dancishuzu[dancigeshu].name,"<");
dancigeshu++;
}
}
else if(s[i]=='!'&&s[i+1]=='=')
{
dancishuzu[dancigeshu].bianhao=31;
strcpy(dancishuzu[dancigeshu].name,"!=");
dancigeshu++;
i+=2;
}
else
{
printf("\nline:%derror!",line);
i++;
return;
}
}

❿ 編譯原理 詞法分析 要求輸入一個源文件,或是text形式的,然後對該文件進行詞法分析。要簡單一點的。

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

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<<"\n\nright: Archerzei\n\n\n";
cout<<"*****************************\n\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;
cout<<"*****************************\n";
cout<<"\n\nright: Archerzei\n\n\n";
cout<<"*****************************\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*/

已經驗收過了,在VC6.0上運行沒有問題。程序很容易看懂的,報告的話自己寫寫就可以了。要是有分就好了…………哈哈!!!

閱讀全文

與編譯原理詞法分析test語言相關的資料

熱點內容
不能修改的pdf 瀏覽:736
同城公眾源碼 瀏覽:474
一個伺服器2個埠怎麼映射 瀏覽:283
java字元串ascii碼 瀏覽:62
台灣雲伺服器怎麼租伺服器 瀏覽:461
旅遊手機網站源碼 瀏覽:316
android關聯表 瀏覽:929
安卓導航無聲音怎麼維修 瀏覽:322
app怎麼裝視頻 瀏覽:423
安卓系統下的軟體怎麼移到桌面 瀏覽:81
windows拷貝到linux 瀏覽:756
mdr軟體解壓和別人不一樣 瀏覽:889
單片機串列通信有什麼好處 瀏覽:325
游戲開發程序員書籍 瀏覽:849
pdf中圖片修改 瀏覽:275
匯編編譯後 瀏覽:480
php和java整合 瀏覽:835
js中執行php代碼 瀏覽:447
國產單片機廠商 瀏覽:62
蘋果手機怎麼設置不更新app軟體 瀏覽:289