《编译方法》实验指导书
- 格式:doc
- 大小:290.50 KB
- 文档页数:34
目录实验一词法分析器设计 .................................... 错误!未定义书签。
【实验目的】................................................ 错误!未定义书签。
【实验内容】................................................ 错误!未定义书签。
【流程图】 ................................................... 错误!未定义书签。
【源代码】 ................................................... 错误!未定义书签。
【程序部分截图】 (18)实验二 LL(1)语法分析程序设计 (20)【实验目的】 (20)【实验内容】 (20)【实验步骤和要求】 (20)【流程图】 (20)【源代码】 (21)【程序截图】................................................ 错误!未定义书签。
实验一词法分析器设计【实验目的】1.熟悉词法分析的基本原理,词法分析的过程以及词法分析中要注意的问题。
2.复习高级语言,进一步加强用高级语言来解决实际问题的能力。
3.通过完成词法分析程序,了解词法分析的过程。
【实验内容】用JAVA语言编写一个PL/0词法分析器,为语法语义分析提供单词,使之能把输入的字符串形式的源程序分割成一个个单词符号传递给语法语义分析,并把分析结果(基本字,运算符,标识符,常数以及界符)输出。
【源代码】package accidence_analy se;import java.io.*;import java.util.*;import buffer.*;public class AccidenceAnaly ser {private java.io.File SourceFile;private java.io.File ReserveFile;private java.io.File ClassFile;private java.io.File OutputFile;public Pretreatment pretreatment;public KeyWordT able keyWordT able;public ClassIdentity classIdentity;public Scaner scaner;public ConcreteScanBufferFactory csbFactory;/*** 2)词法分析器主程序*/public AccidenceAnaly ser() {Sy stem.out.println("[INFOR]已经建立词法分析器!");}public void initAA() {//创建缓冲工厂this.csbFactory=newConcreteScanBufferFactory();//创建字符串扫描对象scaner = new Scaner(this);//创建pre处理对象pretreatment=newPretreatment(SourceFile, this);//创建关键字表对象keyWordT able= new KeyWordT able(ReserveFile);//创建对象种别码表对象classIdentity = new ClassIdentity(ClassFile);Sy stem.out.println("[INFOR]已经初始化词法分析器!"); }public void setFilesPath(String reserveFileName, String ClassFileName,String sourceFileName, String outputFileName) {//创建文件对象SourceFile = new java.io.File(sourceFileName);//创建文件对象ReserveFile = new java.io.File(reserveFileName);//创建文件对象ClassFile = new java.io.File(ClassFileName);//创建文件对象OutputFile = new java.io.File(outputFileName);//如果文件已经存在,先删除,然后建立新文件if (OutputFile.exists()) {OutputFile.delete();}try {OutputFile.createNewFile();}catch(Exceptione){e.printStackTrace(Sy stem.err);}try {//创建文件随机读取对象java.io.RandomAccessFile ROutputFile = new java.io.RandomAccessFile(this.OutputFile, "rw");//提示信息ROutputFile.write("///////////////////////////////////////\n".getBytes());ROutputFile.write( ("//JAccidenceAnaly ser ve rsion " + getV ersion() +" design by yellowicq//\n").getBytes());ROutputFile.write("//java词法分析器//////////////\n".getBytes());ROutputFile.write("//使用java语言开发///\n".getBytes());ROutputFile.write("\n".getBytes());ROutputFile.write("词法分析结果如下:\n".getBytes());//关闭文件流ROutputFile.close();}catch (Exception e) {e.printStackTrace(Sy stem.err);}}public void startAA() {//从预处理开始词法分析this.pretreatment.startPretreatment();}public void outputAccidence(String outputString) {//把分析出来的单词写入文件outputString="\n[第" + this.pretreatment.fileRow + "行]\n" + outputString;try {//创建文件随机读取对象java.io.RandomAccessFile ROutputFile = new java.io.RandomAccessFile(this.OutputFile, "rw");//移动指针到文件末尾ROutputFile.seek(ROutputFile.length());//Start appending!ROutputFile.write(outputString.getBytes());//关闭文件流ROutputFile.close();}catch (Exception e) {e.printStackTrace(Sy stem.err);}//将分析的单词结果输出到终端Sy stem.out.print(outputString);}public void controlThread() {//控制扫描器启动扫描scaner.controlThread();}//获得版本号public String getV ersion() {return "1.0";}}package accidence_analy se;import java.util.*;import java.io.*;public class ClassIdentity {private Hashtable ClassHash;private File ClassFile;private FileReader classFileReader; //读文件对象private int TMP_BUFFER_SIZE = 30;/*** 6)类型种别码程序*/public ClassIdentity(java.io.File ClassFile) {System.out.println("[INFOR]类型种别码表已创建!");this.ClassFile = ClassFile;}//查找类型种别码public int findKey(String classW ord) {int KEY;for (Enumeration e = this.ClassHash.key s(); e.hasMoreElements(); ) {KEY=Integer.parseInt((String)e.nextElement());if( ( (String)this.ClassHash.get(Integer.toString(KEY))).equalsIgnoreCase(classW ord)) {return KEY;} }return -1;}public void initClassIdentityT able() {ClassHash = new Hashtable(); //创建hash表int intLength;char[] chrBuffer = new char[TMP_BUFFER_SIZE];String classWord;int classCounter = 0;try {if (ClassFile.exists()) { //文件存在//创建读文件对象classFileReader=newjava.io.FileReader(ClassFile);//读文件内容到hash表while((intLength=classFileReader.read(chrBuffer)) != -1) {classCounter++;//填写hash表classW ord = String.v alueOf(chrBuffer).trim();Sy stem.out.println("[INFOR]读取类型种别码: [KEY: " + classCounter + "][VALUE: " + classW ord + "]");this.ClassHash.put(Integer.toString(classCounter), classWord);}//关闭读文件对象classFileReader.close();}else { //文件不存在Sy stem.err.println("[ERROR]类型种别码文件不存在!");}}catch (Exception e) {e.printStackTrace(Sy stem.err);}}}package accidence_analy se;import java.util.*;import java.io.*;public class KeyWordT able {private Hashtable KWHash;private File ReserveFile;private FileReader resFileReader; //读文件对象private int TMP_BUFFER_SIZE = 30;/*** 5)表留字表程序*/public KeyWordT able(java.io.File ReserveFile) {Sy stem.out.println("[INFOR]关键字表已创建!");this.ReserveFile = ReserveFile;}public boolean isKeyWord(String inw) {String resW ord;//查找hash表for (Enumeration e = this.KWHash.elements(); e.hasMoreElements(); ) {resW ord = (String) e.nextElement();if (resW ord.equalsIgnoreCase(inw)) {return true;}}return false;}public void initKeyWordT able() {KWHash = new Hashtable(); //创建hash表int intLength;char[] chrBuffer = new char[TMP_BUFFER_SIZE];String resW ord;int resCounter = 0;try {if (ReserveFile.exists()) { //文件存在//创建读文件对象resFileReader = new java.io.FileReader(ReserveFile);//读文件内容到hash表while((intLength = resFileReader.read(chrBuffer))!= -1) { resCounter++;//填写hash表resW ord = String.v alueOf(chrBuffer).trim();Sy stem.out.println("[INFOR]读取关键字: [INDEX: " + resCounter +"][VALUE: " + resW ord + "]");this.KWHash.put(Integer.toString(resCounter), resW ord);}//关闭读文件对象resFileReader.close();}else { //文件不存在Sy stem.err.println("[ERROR]保留字文件不存在!");}}catch (Exception e) {e.printStackTrace(Sy stem.err);}}}package accidence_analy se;import javax.xml.parsers.*;import org.w3c.dom.*;public class main {/*** 1) 词法分析器引导文件*/public static void main(String[] args) {//读取配置文件,得到系统属性String cfgString[] = new String[4];try {cfgString = main.loadAACfg("d:\\aaCfg.xml");}catch (Exception e) {e.printStackTrace(Sy stem.err);}//设置待读文件名//保留字表文件String reserveFileName = cfgString[0];//类型种别码表文件String classFileName = cfgString[1];//需要分析的源文件String sourceFileName = cfgString[2];//输出文件String outputFileName = cfgString[3];//创建词法分析器AccidenceAnaly ser aa=new AccidenceAnalyser();aa.setFilesPath(reserveFileName, classFileName, sourceFileName,outputFileName);//建立所需要的文件对象//初始化词法分析器aa.initAA();//初始化关键字表aa.keyW ordT able.initKeyWordT able();//初始化类型种别码表aa.classIdentity.initClassIdentityT able();//开始进行词法分析aa.startAA();//分析完毕}//读取配置文件private static String[] loadAACfg(String name) throws Exception {String cfgString[] = new String[4];/*解析xml配置文件*/try {/*创建文档工厂*/DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();/*创建文档解析器*/DocumentBuilder builder = factory.newDocumentBuilder();/*解析配置文件*/Document doc = builder.parse(name);/*规范化文档*/doc.normalize();/*查找接点表*/NodeList nlists = doc.getElementsByT agName("FilePath");for (int i = 0; i < nlists.getLength(); i++) {Element item = (Element) nlists.item(i);//取得需要的配置属性cfgString[0] = item.getElementsByT agName("ReserveFileName").item(0).getFirstChild().getNodeV alue().trim();cfgString[1] = item.getElementsByT agName("ClassFileName").item(0).getFirstChild().getNodeV alue().trim();cfgString[2] = item.getElementsByT agName("SourceFileName").item(0).getFirstChild().getNodeV alue().trim();cfgString[3] = item.getElementsByT agName("OutputFileName").item(0).getFirstChild().getNodeV alue().trim();}}catch (Exception e) {e.printStackTrace();throw new Exception("[ERROR]加载配置文件" + name + " 错误!");}//返回属性数组return cfgString;}}package accidence_analy se;import java.io.*;import buffer.*;public class Pretreatment {private String tmpString;private String outputString;private int BUFFER_SIZE = 100;private AccidenceAnaly ser aa;public InputBuffer inputBuffer; //输入缓冲区--共享private java.io.File SourceFile; //文件对象private java.io.RandomAccessFile randomAFile; //随机文件对象public static int fileRow = 0;/*** 3)预处理子程序*/public Pretreatment(File SourceFile, AccidenceAnalyser aa) {try {this.SourceFile = SourceFile;this.randomAFile = new java.io.RandomAccessFile(this.SourceFile, "r");}catch (FileNotFoundException e) {e.printStackTrace(Sy stem.err);}this.aa = aa;inputBuffer = aa.csbFactory.createInputBuffer(BUFFER_SIZE);Sy stem.out.println("[INFOR]预处理器已经创建!");}public void putSourceToINBuffer(String tmpString) {this.inputBuffer.Data = tmpString.toCharArray();}public void putFinT oSCBuffer(String filtratedString) {aa.scaner.scanBuffer.Data = filtratedString.toCharArray();}public void controlThread() {int intLength;int resCounter = 0;String tmpString;String filtratedString;Sy stem.out.println("[INFOR]开始单词分析////////////////////////////////////////"); try {if (SourceFile.exists()) { //文件存在//读文件内容到缓冲区while ( (tmpString = this.randomAFile.readLine()) != null) {++fileRow;//分割符Sy stem.out.println("...................begin row " + this.fileRow +".......................");//开始这一行分析Sy stem.out.println("[INFOR]正在处理行: " + String.v alueOf(fileRow));//放入输入缓冲区this.putSourceToINBuffer(tmpString);//处理字符串filtratedString = this.filtrateSource(this.inputBuffer.Data);Sy stem.out.println("[INFOR]已过滤句子: " + filtratedString);//放入扫描缓冲区this.putFinToSCBuffer(filtratedString);aa.controlThread();}Sy stem.out.println("[INFOR]分析完毕////////////////////////////////////////////");}else { //文件不存在Sy stem.err.println("[ERROR]源文件不存在!");}}catch (Exception e) {e.printStackTrace(Sy stem.err);}}public String filtrateSource(char[] Data) {String filtratedString = String.v alueOf(Data).trim();return filtratedString;}public void startPretreatment() {this.controlThread();}}package accidence_analy se;import buffer.*;public class Scaner {public ScanBuffer scanBuffer; //扫描缓冲区--共享private String finalAccidence;private AccidenceAnaly ser aa;private int BUFFER_SIZE = 100;private String toDelString;private int senLength = 0;private char[] sentenceChar = new char[1000];private String TOKEN;private char CHAR;private int index = 0;private String IDENTITY = "identity";private String DIGIT = "digit";private String WORD_ERROR_INF = "在此行发现不能识别的单词,此行分析终止!"; private boolean ASTATE = true;/*** 4)扫描子程序*/public Scaner(AccidenceAnaly ser aa) {this.aa = aa;initBuffer();this.finalAccidence = "";System.out.println("[INFOR]扫描处理器已经创建!");}public String readFromBuffer(char[] Data) {String toDelString = String.valueOf(Data);return toDelString;}public String scan(String toDelString) {sentenceChar = toDelString.toCharArray();this.senLength = sentenceChar.length;int i = 0;//分析单词while (this.index <= this.senLength) {//state0:this.TOKEN = "";this.CHAR = GETBC(sentenceChar);if (this.CHAR == ';') {break; //';'表示这一行结束}//进入状态判断switch (this.CHAR) {//judge lettercase 'a':case 'b':case 'c':case 'd':case 'e':case 'f':case 'g':case 'h':case 'i':case 'j':case 'k':case 'l':case 'm':case 'n':case 'o':case 'p':case 'q':case 'r':case 's':case 't':case 'u':case 'v':case 'w':case 'x':case 'y': case 'z':case 'A':case 'B':case 'C':case 'D':case 'E':case 'F':case 'G':case 'H':case 'I':case 'J':case 'K':case 'L':case 'M': case 'N':case 'O':case 'P':case 'Q':case 'R':case 'S':case 'T':case 'U':case 'V':case 'W':case 'X':case 'Y':case 'Z': //dothis.TOKEN = this.CONTACT(TOKEN, CHAR);//state1CHAR = this.GETCHAR(sentenceChar);while (this.ISLETTER(CHAR) || this.ISDIGIT(CHAR)) {this.TOKEN = this.CONTACT(this.TOKEN, CHAR);CHAR = this.GETCHAR(sentenceChar);}this.RETRACT();//state2if (aa.keyWordTable.isKeyWord(TOKEN)) {this.finalAccidence = this.finalAccidence + "[保留字] " +this.returnAWord(TOKEN) + "\n";}else {this.finalAccidence = this.finalAccidence + "[标识符] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(IDENTITY)) + "\n";}//clear up tokenthis.TOKEN = "";break;//judge dititalcase '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8': case '9': //dothis.TOKEN = this.CONTACT(TOKEN, CHAR);//state3CHAR = this.GETCHAR(sentenceChar);while (this.ISDIGIT(CHAR)) {this.TOKEN = this.CONTACT(TOKEN, CHAR);CHAR = this.GETCHAR(sentenceChar);}this.RETRACT();//state4this.finalAccidence = this.finalAccidence + "[数字] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(DIGIT)) + "\n";//clear up tokenthis.TOKEN = "";break;case '='://state5this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[等号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case '+'://state6this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[加号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case '*'://state7this.TOKEN = this.CONTACT(TOKEN, CHAR);CHAR = this.GETCHAR(sentenceChar);if (CHAR == '*') {this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[乘方] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";}//state9else {this.finalAccidence = this.finalAccidence + "[乘号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";}//clear up tokenthis.TOKEN = "";break;case ','://state10this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[逗号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case '('://state11this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[左括号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case ')'://state12this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[右括号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +//clear up tokenthis.TOKEN = "";break;case '{'://state13this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[左大括号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case '}'://state14this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[右大括号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case '['://state15this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[左中括号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case ']'://state16this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[右中括号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;case '.'://state17this.TOKEN = this.CONTACT(TOKEN, CHAR);this.finalAccidence = this.finalAccidence + "[点号] " +this.returnAWord(TOKEN) + "[种别码] " +String.valueOf(aa.classIdentity.findKey(String.valueOf(CHAR))) +"\n";//clear up tokenthis.TOKEN = "";break;default://state18this.TOKEN = this.CONTACT(this.TOKEN, this.CHAR);//追加出错信息this.finalAccidence = this.finalAccidence + "[ERROR]" +this.WORD_ERROR_INF + "'" + this.TOKEN + "'" + "\n";this.ASTATE = false;//clear up tokenthis.TOKEN = "";break;}if (this.ASTATE == false) {break;}}return this.finalAccidence;}public void controlThread() {this.toDelString = this.readFromBuffer(this.scanBuffer.Data);this.aa.outputAccidence(this.scan(this.toDelString));//分割符System.out.println("...................end row " + aa.pretreatment.fileRow +".........................");//结束这一行分析//clear up the varthis.index = 0;this.finalAccidence = "";this.ASTATE = true;this.toDelString = "";this.senLength = 0;this.TOKEN = "";}public String returnAWord(String TOKEN) {return TOKEN;}public void initBuffer() {this.scanBuffer = aa.csbFactory.createScanBuffer(BUFFER_SIZE); }//以下为字符的处理方法public char GETBC(char[] sentenceChar) {try {while ( (sentenceChar[this.index]) == ' ') {this.index++;}this.index++;}catch (ng.ArrayIndexOutOfBoundsException e) {return ';'; //表示此行已经结束}return sentenceChar[index - 1];}public char GETCHAR(char[] sentenceChar) {next();return sentenceChar[this.index - 1];}public void next() {this.index++;}public boolean ISLETTER(char letter) {return ng.Character.isLetter(letter);}public boolean ISDIGIT(char letter) {return ng.Character.isDigit(letter);}public String CONTACT(String TOKEN, char CHAR) {String tmpS = TOKEN + String.valueOf(CHAR);TOKEN = tmpS;return TOKEN;}public boolean ISRESERVE(String TOKEN) {return aa.keyWordTable.isKeyWord(TOKEN);}public void RETRACT() {this.index--;}}package buffer;//abstract buffer interfacepublic interface Buffer {}package buffer;public interface BufferFactory {/*** 7)抽象扫描缓冲区工厂*/public ScanBuffer createScanBuffer(int size);public InputBuffer createInputBuffer(int size);}package buffer;public class ConcreteScanBufferFactoryimplements BufferFactory {/*** 8)缓冲区工厂*/public ConcreteScanBufferFactory() {System.out.println("[INFOR]缓冲区工厂已经建立!"); }public ScanBuffer createScanBuffer(int size) {System.out.println("[INFOR]创建扫描缓冲区!");return new ScanBuffer(size);}public InputBuffer createInputBuffer(int size) {System.out.println("[INFOR]创建输入缓冲区!");return new InputBuffer(size);}}package buffer;import java.io.*;public class InputBufferimplements Buffer {public char[] Data;/*** 10)输入缓冲区对象*/public InputBuffer(int size) {this.Data = new char[size]; }}package buffer;public class ScanBufferimplements Buffer { public char[] Data;/*** 11)扫描缓冲区对象*/public ScanBuffer(int size) {this.Data = new char[size]; }}【程序部分截图】实验二 LL(1)语法分析程序设计【实验目的】1.熟悉判断LL(1)文法的方法及对某一输入串的分析过程。