『壹』 學習編譯原理之前需要學哪些知識
1.你要學到什麼水平?是想考試考好還是想實際寫出來一個足夠強度的編譯器?如果是前者,就一句:努力當學霸才是你唯一的出路。
2.對於scanner &parser的話,對於書上所講的演算法的要求是很高的,有很大的依賴性,所以必須理解透徹,即使沒有機會實現也要自己動手畫畫。同時這也是本科階段所學的編譯原理的所有內容。雖然flex和bison很好使,但是強烈不建議使用。
3.對於生成器、連接器或者解釋器的話,那麼你要了解匯編語言、微處理器、微機介面等計算機基礎學科。簡單的說就是從底層學到高級語言的層面。這個要求是很高的,畢竟涉及到二進制代碼優化等很麻煩的。
『貳』 學完編譯原理這門課,用c語言或者c++語言,編一個預測分析的程序,對預測分析也至少測試三個句子(含錯誤
我寫好的.
scan.h
/*
* scan.h
* ccompiler
*
* Created by on 09-10-12.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _SCAN_H_
#define _SCAN_H_
#include <string>
#include <fstream>
using namespace std;
typedef enum
{
ENDFILE,ERROR,
ELSE,IF,INT,RETURN,VOID,WHILE,
ID,NUM,
ASSIGN,EQ,LT,GT,LE,GE,NE,ADD,SUB,MUL,DIV,SEMI,LPAREN,RPAREN,LZK,RZK,LDK,RDK,COMMA
}
TokenType;
class Scan
{
private:
string tokenStr;
string linebuffer;
ifstream * in;
int linepos;
int lineno;
bool EOF_Flag;
bool traceScan;
void printToken(TokenType tt,const string &tok);
public:
Scan(ifstream * in)
{
this->in=in;
linepos=0;
linebuffer="";
lineno=0;
EOF_Flag=false
traceScan=true;
}
char getNextChar();
void ungetNextChar();
TokenType reservedLookup(string &s);
void setTraceScan(bool f);
bool getTraceScan();
TokenType getToken();
string getTokenStr();
};
#endif
scan.cpp
/*
* scan.cpp
* ccompiler
*
* Created by on 09-10-12.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
#include "scan.h"
typedef enum
StateType;
static struct
{
string str;
TokenType tok;
} reservedWords[6]
=,,,,,};
char Scan::getNextChar()
{
if(linepos>=linebuffer.size())
{
if(getline(*in,linebuffer))
{
linebuffer+="\n";
lineno++;
linepos=0;
return linebuffer[linepos++];
}
else
{
EOF_Flag=true;
return EOF;
}
}
else
return linebuffer[linepos++];
}
void Scan::ungetNextChar()
{
if(!EOF_Flag) linepos--;
}
TokenType Scan::reservedLookup(string &s)
{
for(int i=0;i<6;i++)
if(s==reservedWords[i].str)
return reservedWords[i].tok;
return ID;
}
void Scan::setTraceScan(bool f)
{
traceScan=f;
}
bool Scan::getTraceScan()
{
return traceScan;
}
TokenType Scan::getToken()
{
tokenStr="";
TokenType currentToken;
StateType state=START;
while(state!=DONE)
{
bool save=false;
char c=getNextChar();
switch (state) {
case START:
if(c>='0'&&c<='9'){
state=INNUM;
save=true;
}
else if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
state=INID;
save=true;
}
else if(c==' '||c=='\t'||c=='\n')
{
state=START;
}
else if(c=='/'){
state=SLASH;
}
else if(c=='='){
state=TEMPE;
}
else if(c=='>')
state=TEMPG;
else if(c=='<')
state=TEMPL;
else if(c=='!')
state=INNOTEQ;
else
{
state=DONE;
switch (c) {
case EOF:
currentToken=ENDFILE;
break;
case '+':
currentToken=ADD;
break;
case '-':
currentToken=SUB;
break;
case '*':
currentToken=MUL;
break;
case '(':
currentToken=LPAREN;
break;
case ')':
currentToken=RPAREN;
break;
case '[':
currentToken=LZK;
break;
case ']':
currentToken=RZK;
break;
case '{':
currentToken=LDK;
break;
case '}':
currentToken=RDK;
break;
case ';':
currentToken=SEMI;
break;
case ',':
currentToken=COMMA;
break;
default:
currentToken=ERROR;
break;
}
}
break;
case INNUM:
if(c<'0'||c>'9')
{
ungetNextChar();
state=DONE;
currentToken=NUM;
}
else
save=true;
break;
case INID:
if(!((c>='a'&&c<='z')||(c>='A'&&c<='Z')))
{
ungetNextChar();
state=DONE;
currentToken=ID;
}
else
save=true;
break;
case SLASH:
if (c!='*')
{
state=DONE;
currentToken=DIV;
}
else
state=INCOMMENT1;
break;
case INCOMMENT1:
if (c!='*')
state=INCOMMENT1;
else if(c==EOF){
state=DONE;
currentToken=ENDFILE;
}
else
state=INCOMMENT2;
break;
case INCOMMENT2:
if (c=='*') {
state=INCOMMENT2;
}else if(c=='/'){
state=START;
}else if(c==EOF){
state=DONE;
currentToken=ENDFILE;
}else {
state=INCOMMENT1;
}
break;
case TEMPE:
if (c=='=') {
state=DONE;
currentToken=EQ;
}else{
state=DONE;
ungetNextChar();
currentToken=ASSIGN;
}
break;
case TEMPG:
if (c=='=') {
state=DONE;
currentToken=GE;
}else{
state=DONE;
ungetNextChar();
currentToken=GT;
}
break;
case TEMPL:
if (c=='=') {
state=DONE;
currentToken=LE;
}else{
state=DONE;
ungetNextChar();
currentToken=LT;
}
break;
case INNOTEQ:
if (c=='=') {
state=DONE;
currentToken=NE;
}else {
state=DONE;
ungetNextChar();
currentToken=ERROR;
}
break;
default:
cerr<<"Scanner Bug: state= "<<state<<endl;
state=DONE;
currentToken=ERROR;
break;
}
if(save){
string newChar(1,c);
tokenStr+=newChar;
}
if (state==DONE&¤tToken==ID)
currentToken=reservedLookup(tokenStr);
}
if (traceScan) {
cout<<"Scan at line "<<lineno<<" token: ";
printToken(currentToken, tokenStr);
cout<<endl;
}
return currentToken;
}
string Scan::getTokenStr()
{
return tokenStr;
}
void Scan::printToken(TokenType tt,const string &tok)
{
string type;
switch (tt) {
case ENDFILE:
type="EOF";
break;
case ERROR:
type="ERROR";
break;
case ELSE:
case IF:
case INT:
case RETURN:
case VOID:
case WHILE:
type="reserved word";
break;
case ID:
type="ID";
break;
case NUM:
type="NUM";
break;
case ASSIGN:
type="=";
break;
case EQ:
type="==";
break;
case LT:
type="<";
break;
case GT:
type=">";
break;
case LE:
type="<=";
break;
case GE:
type=">=";
break;
case NE:
type="!=";
break;
case ADD:
type="+";
break;
case SUB:
type="-";
break;
case MUL:
type="*";
break;
case DIV:
type="/";
break;
case SEMI:
type=";";
break;
case LPAREN:
type="(";
break;
case RPAREN:
type=")";
break;
case LZK:
type="[";
break;
case RZK:
type="]";
break;
case LDK:
type="{";
case RDK:
type="}";
break;
case COMMA:
type=",";
break;
default:
break;
}
cout << type<<": "<<tok;
}
main.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "scan.h"
int main (int argc, char * const argv[]) {
string fileName="/Users/huanglongyin/scan_in.txt";
//cout<< "File name: ";
//cin>>fileName;
ifstream in(fileName.c_str());
if(!in){
cerr<<"Error occurs when openning file "<<fileName<<endl;
return -1;
}
Scan scan(&in);
while(scan.getToken()!=ENDFILE);
return 0;
}
『叄』 編譯原理的發展歷程
在20世紀40年代,由於馮·諾伊曼在存儲-程序計算機方面的先鋒作用,編寫一串代碼或程序已成必要,這樣計算機就可以執行所需的計算。開始時,這些程序都是用機器語言 (machine language )編寫的。機器語言就是表示機器實際操作的數字代碼,例如:
C7 06 0000 0002 表示在IBM PC 上使用的Intel 8x86處理器將數字2移至地址0 0 0 0 (16進制)的指令。
但編寫這樣的代碼是十分費時和乏味的,這種代碼形式很快就被匯編語言(assembly language )代替了。在匯編語言中,都是以符號形式給出指令和存儲地址的。例如,匯編語言指令 MOV X,2 就與前面的機器指令等價(假設符號存儲地址X是0 0 0 0 )。匯編程序(assembler )將匯編語言的符號代碼和存儲地址翻譯成與機器語言相對應的數字代碼。
匯編語言大大提高了編程的速度和准確度,人們至今仍在使用著它,在編碼需要極快的速度和極高的簡潔程度時尤為如此。但是,匯編語言也有許多缺點:編寫起來也不容易,閱讀和理解很難;而且匯編語言的編寫嚴格依賴於特定的機器,所以為一台計算機編寫的代碼在應用於另一台計算機時必須完全重寫。
發展編程技術的下一個重要步驟就是以一個更類似於數學定義或自然語言的簡潔形式來編寫程序的操作,它應與任何機器都無關,而且也可由一個程序翻譯為可執行的代碼。例如,前面的匯編語言代碼可以寫成一個簡潔的與機器無關的形式 x = 2。
在1954年至1957年期間,IBM的John Backus帶領的一個研究小組對FORTRAN語言及其編譯器的開發,使得上面的擔憂不必要了。但是,由於當時處理中所涉及到的大多數程序設計語言的翻譯並不為人所掌握,所以這個項目的成功也伴隨著巨大的辛勞。幾乎與此同時,人們也在開發著第一個編譯器, Noam Chomsky開始了他的自然語言結構的研究。他的發現最終使得編譯器結構異常簡單,甚至還帶有了一些自動化。Chomsky的研究導致了根據語言文法(grammar ,指定其結構的規則)的難易程度以及識別它們所需的演算法來為語言分類。正如現在所稱的-與喬姆斯基分類結構(Chomsky hierarchy )一樣-包括了文法的4個層次:0型、1型、2型和3型文法,且其中的每一個都是其前者的專門化。2型(或上下文無關文法(context-free grammar ))被證明是程序設計語言中最有用的,而且今天它已代表著程序設計語言結構的標准方式。
分析問題( parsing problem ,用於限定上下文無關語言的識別的有效演算法)的研究是在20世紀60年代和70年代,它相當完善地解決了這一問題, 現在它已是編譯理論的一個標准部分。它們與喬姆斯基的3型文法相對應。對它們的研究與喬姆斯基的研究幾乎同時開始,並且引出了表示程序設計語言的單詞(或稱為記號)的符號方式。
人們接著又深化了生成有效的目標代碼的方法,這就是最初的編譯器,它們被一直使用至今。人們通常將其誤稱為優化技術(optimization technique ),但因其從未真正地得到過被優化了的目標代碼而僅僅改進了它的有效性,因此實際上應稱作代碼改進技術(code improvement technique )。
這些程序最初被稱為編譯程序-編譯器,但更確切地應稱為分析程序生成器 (parser generator ),這是因為它們僅僅能夠自動處理編譯的一部分。這些程序中最著名的是 Yacc (yet another compiler- compiler),它是由Steve Johnson在1975年為Unix系統編寫的。
類似地,有窮自動機的研究也發展了另一種稱為掃描程序生成器 (scanner generator )的工具,Lex (與Yacc同時,由Mike Lesk為Unix系統開發的)是這其中的佼佼者。在20世紀70年代後期和80年代早期,大量的項目都關注於編譯器其他部分的生成自動化,這其中就包括代碼生成。這些嘗試並未取得多少成功,這大概是因為操作太復雜而人們又對其不甚了解。
編譯器設計最近的發展包括:首先,編譯器包括了更為復雜的演算法的應用程序,它用於推斷或簡化程序中的信息;這又與更為復雜的程序設計語言(可允許此類分析)的發展結合在一起。其中典型的有用於函數語言編譯的Hindle y - Milner類型檢查的統一演算法。
其次,編譯器已越來越成為基於窗口的交互開發環境(interactive development environment,IDE )的一部 分,它包括了編輯器、鏈接程序、調試程序以及項目管理程序。這樣的IDE的標准並沒有多少, 但是已沿著這一方向對標準的窗口環境進行開發了。
『肆』 學好「計算機編譯原理」需要具備其他一些知識么
1.你要學到什麼水平?是想考試考好還是想實際寫出來一個足夠強度的編譯器?如果是前者,就一句:努力當學霸才是你唯一的出路。
2.對於scanner &parser的話,對於書上所講的演算法的要求是很高的,有很大的依賴性,所以必須理解透徹,即使沒有機會實現也要自己動手畫畫。同時這也是本科階段所學的編譯原理的所有內容。雖然flex和bison很好使,但是強烈不建議使用。
3.對於生成器、連接器或者解釋器的話,那麼你要了解匯編語言、微處理器、微機介面等計算機基礎學科。簡單的說就是從底層學到高級語言的層面。這個要求是很高的,畢竟涉及到二進制代碼優化等很麻煩的。
『伍』 求編譯原理的名詞解釋題
詞法分析(Lexical analysis或Scanning)和詞法分析程序(Lexical analyzer或Scanner)
詞法分析階段是編譯過程的第一個階段。這個階段的任務是從左到右一個字元一個字元地讀入源程序,即對構成源程序的字元流進行掃描然後根據構詞規則識別單詞(也稱單詞符號或符號)。詞法分析程序實現這個任務。詞法分析程序可以使用lex等工具自動生成。
語法分析(Syntax analysis或Parsing)和語法分析程序(Parser)
語法分析是編譯過程的一個邏輯階段。語法分析的任務是在詞法分析的基礎上將單詞序列組合成各類語法短語,如「程序」,「語句」,「表達式」等等.語法分析程序判斷源程序在結構上是否正確.源程序的結構由上下文無關文法描述.
語義分析(Syntax analysis)
語義分析是編譯過程的一個邏輯階段. 語義分析的任務是對結構上正確的源程序進行上下文有關性質的審查, 進行類型審查.例如一個C程序片斷:
int arr[2],b;
b = arr * 10;
源程序的結構是正確的.
語義分析將審查類型並報告錯誤:不能在表達式中使用一個數組變數,賦值語句的右端和左端的類型不匹配.
Lex
一個詞法分析程序的自動生成工具。它輸入描述構詞規則的一系列正規式,然後構建有窮自動機和這個有窮自動機的一個驅動程序,進而生成一個詞法分析程序.
Yacc
一個語法分析程序的自動生成工具。它接受語言的文法,構造一個LALR(1)分析程序.因為它採用語法制導翻譯的思想,還可以接受用C語言描述的語義動作,從而構造一個編譯程序. Yacc 是 Yet another compiler compiler的縮寫.[回頁首]
源語言(Source language)和源程序(Source program)
被編譯程序翻譯的程序稱為源程序,書寫該程序的語言稱為源語言.[回頁首]
目標語言(Object language or Target language)和目標程序(Object program or Target program)
編譯程序翻譯源程序而得到的結果程序稱為目標程序, 書寫該程序的語言稱為目標語言.[回頁首]
中間語言(中間表示)(Intermediate language(representation))
在進行了語法分析和語義分析階段的工作之後,有的編譯程序將源程序變成一種內部表示形式,這種內部表示形式叫做中間語言或中間表示或中間代碼。所謂「中間代碼」是一種結構簡單、含義明確的記號系統,這種記號系統復雜性介於源程序語言和機器語言之間,容易將它翻譯成目標代碼。另外,還可以在中間代碼一級進行與機器無關的優化。
[回頁首]
文法(Grammars)
文法是用於描述語言的語法結構的形式規則。文法G定義為四元組(,,,)。其中為非終結符號(或語法實體,或變數)集;為終結符號集;為產生式(也稱規則)的集合;產生式(規則)是形如或 a ::=b 的(a , b)有序對,其中(∪)且至少含有一個非終結符,而(∪)。,和是非空有窮集。稱作識別符號或開始符號,它是一個非終結符,至少要在一條規則中作為左部出現。
一個文法的例子: G=(={A,R},={0,1} ,={A?0R,A?01,R?A1},=A) [回頁首]
文法分類(A hierarchy of Grammars)
著名語言學家Noam Chomsky定義了四類文法和四種形式語言類,文法的四種類型分別是0型、1型、2型和3型。幾類文法的差別在於對產生式施加不同的限制,分別是:
0型文法(短語結構文法)(phrase structure grammars):
設G=(,,,),如果它的每個產生式是這樣一種結構: (∪) 且至少含有一個非終結符,而(∪),則G是一個0型文法。
1型文法(上下文有關文法)(context-sensitive grammars):
設G=(,,,)為一文法,若中的每一個產生式均滿足|,僅僅 除外,則文法G是1型或上下文有關的。
2型文法(上下文無關文法)(context-free grammars):
設G=(,,,),若P中的每一個產生式滿足:是一非終結符,(∪) 則此文法稱為2型的或上下文無關的。
3型文法(正規文法)(regular grammars):
設G=(,,,),若中的每一個產生式的形式都是A→aB或A→a,其中A和B都是非終結,a是終結符,則G是3型文法或正規文法。
0型文法產生的語言稱為0型語言。
1型文法產生的語言稱為1型語言,也稱作上下文有關語言。
2型文法產生的語言稱為2型語言,也稱作上下文無關語言。
3型文法產生的語言稱為3型語言,也稱作正規語言。
『陸』 編譯原理詞法分析器
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<process.h> /*頭文件*/
void init();
char *DchangeB(char *buf);
int search(char *buf,int type,int command);
void intdeal(char *buffer);
void chardeal(char *buffer);
void errordeal(char error,int lineno);
void scanner();
void init()
{ char *key[]={"","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",
"union","unsigned","void","volatile","while"}; /*C語言所有關鍵字/
char *limit[]={" ","(",")","[","]","->",".","!","++","--","&","~",
"*","/","%","+","-","<<",">>","<","<=",">",">=","==","!=","&&","||",
"=","+=","-=","*=","/=",",",";","{","}","#","_","'"};/*運算、限界符*/
fstream outfile;
int i,j;
char *c;
outfile.open("key.txt",ios::out);
for(i=0;i<32;i++)
outfile<<key[i]<<endl;
outfile.close();
outfile.open("Limit.txt",ios::out);
for(j=0;j<38;j++)
outfile<<limit[j]<<endl;
c="";
outfile<<c;
outfile.close();
outfile.open("bsf.txt",ios::out);
outfile.close();
outfile.open("cs.txt",ios::out);
outfile.close();
outfile.open("output.txt",ios::out);
outfile.close();
}
char *DchangeB(char *buf)
{
int temp[20];
char *binary;
int value=0,i=0,j;
for(i=0;buf[i]!='\0';i++)
value=value*10+(buf[i]-48); /*將字元轉化為十進制數*/
if(value==0)
{
binary=new char[2];
binary[0]='0';
binary[1]='\0';
return(binary);
}
i=0;
while(value!=0)
{
temp[i++]=value%2;
value/=2;
}
temp[i]='\0';
binary=new char[i+1];
for(j=0;j<=i-1;j++)
binary[j]=(char)(temp[i-j-1]+48);
binary[i]='\0';
return(binary); /*十進制轉化為二進制*/
}
int search(char *buf,int type,int command)
{ int number=0;
fstream outfile;
char ch;
char temp[30];
int i=0;
switch(type)
{
case 1: outfile.open("key.txt",ios::in);break;
case 2: outfile.open("bsf.txt",ios::in);break;
case 3: outfile.open("cs.txt",ios::in);break;
case 4: outfile.open("limit.txt",ios::in);break;
}
outfile.get(ch);
while(ch!=EOF){
while(ch!='\n')
{
temp[i++]=ch;
outfile.get(ch);
}
temp[i]='\0';
i=0;
number++;
if(strcmp(temp,buf)==0)
{
outfile.close();
return number; /*若找到,返回在相應表中的序號*/
}
else
outfile.get(ch);
} //結束外層while循環
if(command==1)
{
outfile.close( );
return 0; /*找不到,當只需查表,返回0,否則還需造表*/
}
switch(type)
{
case 1: outfile.open("key.txt",ios::in);break;
case 2: outfile.open("bsf.txt",ios::in);break;
case 3: outfile.open("cs.txt",ios::in);break;
case 4: outfile.open("limit.txt",ios::in);break;
}
outfile<<buf;
outfile.close();
return number+1;
}
void intdeal(char *buffer){
fstream outfile;
int result;
result=search(buffer,1,1); /*先查關鍵字表*/
outfile.open("output.txt",ios::app);
if(result!=0)
outfile<<buffer<<result<<endl; /*若找到,寫入輸出文件*/
else
{
result=search(buffer,2,2); /*若找不到,則非關鍵字,查標識符表,還找不到則造入標識符表*/
outfile<<buffer<<result<<endl;
} /*寫入輸出文件*/
outfile.close();
}
void chardeal(char *buffer)
{ fstream outfile;
int result;
result=search(buffer,1,1); /*先查關鍵字表*/
outfile.open("output.txt",ios::app);
if(result!=0)
outfile<<buffer<<result<<endl; /*若找到,寫入輸出文件*/
else
{
result=search(buffer,2,2); /*若找不到,則非關鍵字,查標識符表,還找不到則造入標識符表*/
outfile<<buffer<<result<<endl;
} /*寫入輸出文件*/
outfile.close();
}
void errordeal(char error,int lineno)
{ cout<<"\nerror: "<<error<<" ,line"<<lineno;
}
void scanner()
{ fstream infile,outfile;
char filename[20];
char ch;
int err=0;
int i=0,line=1;
int count,result,errorno=0;
char array[30];
char *word;
printf("\n please input the file scanner name:");
scanf("%s",filename);
err=1;
infile.open(filename,ios::nocreate|ios::in);
while(! infile)
{
cout<<"cannot open file"<<endl;
printf("please input the file name again:\n");
scanf("%s",filename);
infile.open(filename,ios::nocreate|ios::in);
err++;
if(err==3)
{cout<<"SORROY YOU CAN'T VUEW THE PRGARME\n";
cout<<"TANKE YOU VIEW"<<endl;
exit(0);}
}
infile.get(ch);
while(ch!=EOF)
{ /*按字元依次掃描源程序,直至結束*/
i=0;
if(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z'))||(ch=='_'))
{ /*以字母開頭*/
while(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z'))||(ch=='_')||((ch>='0')&&(ch<='9')))
{
array[i++]=ch;
infile.get(ch);
}
word=new char[i+1];
memcpy(word,array,i);
word[i]='\0';
intdeal(word);
if(ch!=EOF)
infile.seekg(-1,ios::cur);
}
else if(ch>='0'&&ch<='9')
{ /*以數字開頭*/
while(ch>='0'&&ch<='9')
{
array[i++]=ch;
infile.get(ch);
}
word=new char[i+1];
memcpy(word,array,i);
word[i]='\0';
intdeal(word);
if(ch!=EOF)
infile.seekg(-1,ios::cur);
}
else if((ch==' ')||(ch=='\t'))
; /*消除空格符和水平製表符*/
else if(ch=='\n')
line++; /*消除回車並記錄行數*/
else if(ch=='/')
{ /*消除注釋*/
infile.get(ch);
if(ch=='=')
{ /*判斷是否為『/=』符號*/
outfile.open("output.txt",ios::noreplace|ios::app);
outfile<<"/=\t\t\t4\t\t\t32\n";
outfile.close();
}
else if(ch!='*')
{ /*若為除號,寫入輸出文件*/
outfile.open("output.txt",ios::noreplace|ios::app);
outfile<<"/\t\t\t4\t\t\t13\n";
outfile.close();
outfile.seekg(-1,ios::cur);
}
else if(ch=='*')
{ /*若為注釋的開始,消除包含在裡面的所有字元*/
count=0;
infile.get(ch);
while(count!=2)
{ /*當掃描到『*』且緊接著下一個字元為『/』才是注釋的結束*/
count=0;
while(ch!='*')
infile.get(ch);
count++;
infile.get(ch);
if(ch=='/')
count++;
else
infile.get(ch);
}
}
}
else if(ch=='"')
{ /*消除包含在雙引號中的字元串常量*/
outfile.open("output.txt",ios::noreplace|ios::app);
outfile<<ch<<"\t\t\t4\t\t\t37\n";
outfile.close();
while(ch!='"')
infile.get(ch);
infile<<ch<<"\t\t\t4\t\t\t37\n";
infile.close();
}
else
{ /*首字元為其它字元,即運算限界符或非法字元*/
array[0]=ch;
infile.get(ch); /*再讀入下一個字元,判斷是否為雙字元運算、限界符*/
if(ch!=EOF)
{ /*若該字元非文件結束符*/
array[1]=ch;
word=new char[3];
memcpy(word,array,2);
word[2]='\0';
result=search(word,4,1); /*先檢索是否為雙字元運算、限界符*/
if(result==0)
{ /*若不是*/
word=new char[2];
memcpy(word,array,1);
word[1]='\0';
result=search(word,4,1); /*檢索是否為單字元運算、限界符*/
if(result==0)
{ /*若還不是,則為非法字元*/
errordeal(array[0],line);
errorno++;
infile.seekg(-1,ios::cur);
}
else
{ /*若為單字元運算、限界符,寫入輸出文件並將掃描文件指針回退一個字元*/
outfile.open("output.txt",ios::noreplace|ios::app);
outfile<<word<<"\t\t\t4\t\t\t"<<result<<"\t"<<endl;
outfile.close();
infile.seekg(-1,ios::cur);
}
}
else
{ /*若為雙字元運算、限界符,寫入輸出文件*/
outfile.open("output.txt",ios::noreplace|ios::app);
outfile<<word<<"\t\t\t4\t\t\t"<<result<<endl;;
outfile.close( );
}
}
else
{ /*若讀入的下一個字元為文件結束符*/
word=new char[2];
memcpy(word,array,1);
word[1]='\0';
result=search(word,4,1); /*只考慮是否為單字元運算、限界符*/
if(result==0) /*若不是,轉出錯處理*/
errordeal(array[0],line);
else
{ /*若是,寫輸出文件*/
outfile.open("output.txt",ios::noreplace|ios::app);
outfile<<word<<"\t\t\t4\t\t\t"<<result<<"\t"<<endl;
outfile.close();
}
}
}
infile.get(ch);
}
infile.close();
cout<<"\nThere are "<<errorno<<" error(s).\n"; /*報告錯誤字元個數*/
}
void main()
{ char yn;
do{
init(); /*初始化*/
scanner();/*掃描源程序*/
printf("Are You continue(y/n)\n"); //判斷是否繼續?
yn=getch();
}while(yn=='y'||yn=='Y');
}
『柒』 用java 輸入兩個正整數m和n,求其最大公約數和最小公倍數。 不懂它的編譯原理執行不了求解
t=y%x;//最大公約數就為y除以x的余數
5÷3餘數2
最大公約數不是有輾轉相除法嗎
最小公倍數 lcm(x,y) = x×y÷gcd(x,y)
publicstaticintGCD(inta,intb){
if(b==0)returna;
returnGCD(b,a%b);
}
『捌』 編譯原理實驗求助
1)定義
所有token或者叫單詞的有限自動機。
2)將有限自動機用代碼實現。
3)寫分析程序,利用你定義的有限自動機來識別所有的「單詞」。並將識別出來的單詞的相關信息,如名稱,位置,類別等記錄在相關的數據結構中。
『玖』 急需編譯原理的一些程序
// the scanner implementation for the TINY compiler
#include "globals.h"
#include "util.h"
#include "scan.h"
//states in scanner DFA
typedef enum
{
START,INASSIGN,INCOMMENT,INNUM,INID,DONE
}StateType;
//lexeme of identifier or reserved word
char tokenString[MAXTOKENLEN+1];
//BUFLEN = lenght of the input buffer for source code lines
#define BUFLEN 256
static char lineBuf[BUFLEN];//holds the current lines
static int linepos = 0; //current position in linebuf
static int bufsize = 0;//current size of buffer string
//getNextChar fetches the next non-blank character from lineBuf
//reading in a new line if lineBuf is exhausted
static char getNextChar(void)
{
if(!(linepos<bufsize))
{
lineno++;
if (fgets(lineBuf,BUFLEN-1,source))
{
if(EchoSource)
fprintf(listing,"%d:%s",lineno,lineBuf);
bufsize = strlen(lineBuf);
linepos = 0;
return lineBuf[linepos++];
}
else return EOF;
}
else return lineBuf[linepos++];
}
//ungetNextChar backtracks one character in linebuf
static void ungetNextChar(void)
{
linepos--;
}
//lookup table of reserved words
static struct
{
char* str;
TokenType tok;
}reservedWords[MAXRESERVED]
={{"if",IF},{"then",THEN},{"else",ELSE},{"end",END},
{"repeat",REPEAT},{"until",UNTIL},{"read",READ},{"write",WRITE}};
//lookup an identifier to see if it is a reserved word
//uses linear search
static TokenType reservedLookup(char* s)
{
int i;
for(i=0;i<MAXRESERVED;i++)
if(!strcmp(s,reservedWords[i].str))
return reservedWords[i].tok;
return ID;
}
// the primary function of the scanner
//function getToken returns the next token in source file
TokenType getToken(void)
{
//index for storing into tokenString
int tokenStringIndex = 0;
//holds current token to be returned
TokenType currentToken;
//current state - always begins at START
StateType state = START;
//flag to indicate save to tokenString
int save;
while (state!=DONE)
{
char c = getNextChar();
save = TRUE;
switch(state)
{
case START:
if(isdigit(c))
state = INNUM;
else if(isalpha(c))
state = INID;
else if(c==':')
state = INASSIGN;
else if((c==' ')||(c=='\t')||(c=='\n'))
save = FALSE;
else if(c=='{')
{
save = FALSE;
state = INCOMMENT;
}
else{
state = DONE;
switch(c)
{
case EOF:
save = FALSE;
currentToken = ENDFILE;
break;
case '=':
currentToken = EQ;
break;
case '<':
currentToken = LT;
break;
case '+':
currentToken = PLUS;
break;
case '-':
currentToken = MINUS;
break;
case '*':
currentToken = TIMES;
break;
case '/':
currentToken = OVER;
break;
case '(':
currentToken = LPAREN;
break;
case ')':
currentToken = RPAREN;
break;
case ';':
currentToken = SEMI;
break;
default:
currentToken = ERROR;
break;
}
}
break;
case INCOMMENT:
save = FALSE;
if(c=='}')state = START;
break;
case INASSIGN:
state = DONE;
if(c=='=')
currentToken = ASSIGN;
else{
//backup in the input
ungetNextChar();
save = FALSE;
currentToken = ERROR;
}
break;
case INNUM:
if(!isdigit(c))
{
//backup in the input
ungetNextChar();
save = FALSE;
state = DONE;
currentToken = NUM;
}
break;
case INID:
if(!isalpha(c))
{
//backup in the input
ungetNextChar();
save = FALSE;
state = DONE;
currentToken = ID;
}
break;
case DONE:
default://should never happen
fprintf(listing, "Scanner Bug: state = %d\n",state);
state = DONE;
currentToken = ERROR;
break;
}
if((save)&&(tokenStringIndex <= MAXTOKENLEN))
tokenString[tokenStringIndex++] = c;
if (state == DONE)
{
tokenString[tokenStringIndex] = '\0';
if(currentToken == ID)
currentToken = reservedLookup(tokenString);
}
}
if(TraceScan){
fprintf(listing,"\t%d:",lineno);
printToken(currentToken,tokenString);
}
return currentToken;
}//end getToken
太長了,寫不過來,這只是一個非常簡單非常簡單的詞法分析部分的實現。
另附NFA->DFA的帖子,CSDN的。