Minic词法,语法,语义实现
jjt文件实现,上面部分是和界面的连接:
/** * JJTree template file created by SF JavaCC plugin 1.5.28+ wizard for JavaCC 1.5.0+ */ options { static = false; } PARSER_BEGIN(Minic) package Minic; import util.*; import java.io.*; import java.util.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintStream; public class Minic { public static String cifaFile = ".//src//file//lexical.txt"; public static String yufaFile = ".//src//file//yufa.txt"; public static String yuyiFile = ".//src//file//yuyi.txt"; public static String errorFile = ".//src//file//error.txt"; public static Boolean existF = false; //用来进行错误分析使用 public static String S = ""; public static ArrayList < Symbol > mylist = new ArrayList < Symbol > (); public static SymbolTable symbollist = new SymbolTable(mylist); QTList qtList = new QTList(); public void printQTList() { qtList.printQTTable(); } public static void main(String args []) { try { File file = new File(".//src//file//1.txt"); FileInputStream fis = new FileInputStream(file); Minic mm = new Minic(fis); run(".//src//file//2.txt"); } catch (Exception e) { e.printStackTrace(); } } public static void run(String FilePath) throws FileNotFoundException { try { //词法部分 File file = new File(FilePath); SimpleCharStream scs = new SimpleCharStream(new FileInputStream(file)); //输出流 FileOutputStream fos1 = new FileOutputStream(cifaFile); //词法 FileOutputStream fos2 = new FileOutputStream(yufaFile); //语法 FileOutputStream fos3 = new FileOutputStream(yuyiFile); //语义 PrintStream LexicalStream1 = new PrintStream(fos1); PrintStream LexicalStream2 = new PrintStream(fos2); PrintStream LexicalStream3 = new PrintStream(fos3); //词法部分 MinicTokenManager mtm = new MinicTokenManager(scs); Token a = mtm.getNextToken(); String lexicalStr = ""; while (a.kind != EOF) { lexicalStr += a.kind; lexicalStr += "\t"; lexicalStr += a.image; lexicalStr += "\n"; System.out.println(a.kind + "\t" + a.image); a = mtm.getNextToken(); } //将流传送到文件 LexicalStream1.print(lexicalStr); Minic tmp = new Minic(new FileInputStream(new File(FilePath))); SimpleNode n = tmp.Start(); System.setOut(LexicalStream2); n.dump(""); //语义分析 System.setOut(LexicalStream3); tmp.printQTList(); fos1.close(); LexicalStream1.close(); fos2.close(); LexicalStream2.close(); fos3.close(); LexicalStream3.close(); } catch (Exception e) { e.printStackTrace(); } } public static void yuyi(Minic mm) throws FileNotFoundException { try { SimpleNode n = mm.Start(); FileOutputStream fos = new FileOutputStream(yuyiFile); PrintStream ps = new PrintStream(fos); System.setOut(ps); dumps("", n, ps); fos.close(); ps.close(); } catch (Exception e) { System.out.println("error\n" + e.getMessage()); e.printStackTrace(); } } public static void dumps(String prefix, SimpleNode sn, PrintStream ps) { ps.println(prefix); if (sn.children != null) { for (int i = 0; i < sn.children.length; ++i) { SimpleNode n = (SimpleNode) sn.children [i]; if (n != null) { n.dump(prefix + " "); } } } } public static void cifa(String FilePath) throws FileNotFoundException { try { File file = new File(FilePath); SimpleCharStream scs = new SimpleCharStream(new FileInputStream(file)); FileOutputStream fos = new FileOutputStream(cifaFile); PrintStream LexicalStream = new PrintStream(fos); MinicTokenManager mtm = new MinicTokenManager(scs); Token a = mtm.getNextToken(); String lexicalStr = ""; while (a.kind != EOF) { lexicalStr += a.kind; lexicalStr += "\t"; lexicalStr += a.image; lexicalStr += "\n"; System.out.println(a.kind + "\t" + a.image); a = mtm.getNextToken(); } LexicalStream.print(lexicalStr); fos.close(); LexicalStream.close(); } catch (Exception e) { System.out.println("Oops."); System.out.println(e.getMessage()); } } } PARSER_END(Minic) SKIP : { " " | "\t" | "\n" | "\r" | < "//" (~[ "\n", "\r" ])* ( "\n" | "\r" | "\r\n" ) > | < "/*" (~[ "*" ])* "*" ( ~[ "/" ] (~[ "*" ])* "*" )* "/" > } TOKEN : /*keyword关键字*/ { < IF : "if" > | < ELSE : "else" > | < RETURN : "return" > | < CHAR : "char" > | < DOUBLE : "double" > | < ENUM : "enum" > | < FLOAT : "float" > | < INT : "int" > | < LONG : "long" > | < SHORT : "short" > | < SIGNED : "signed" > | < STRUCT : "struct" > | < UNION : "union" > | < UNSIGNED : "unsigned" > | < VOID : "void" > | < FOR : "for" > | < DO : "do" > | < WHILE : "while" > | < BREAK : "break" > | < CONTINUE : "continue" > | < GOTO : "goto" > | < SWITCH : "switch" > | < CASE : "case" > | < dEFAULT : "default" > | < AUTO : "auto" > | < EXTERN : "extern" > | < REGISTER : "register" > | < STATIC : "static" > | < CONST : "const" > | < SIZEOF : "sizeof" > | < TYPEDEF : "typedef" > | < VOLATUIVE : "volatile" > | < MAIN : "main"> } TOKEN : /*separater分隔符*/ { < semicolon : ";" > | < comma : "," > | < leftbracket : "(" > | < rightbracket : ")" > | < leftmidbracket : "[" > | < rightmidbracket : "]" > | < leftbigbracket : "{" > | < rightbigbracket : "}" > } TOKEN : /* OPERATOR运算符*/ { < ADD : "+" > | < SUBTRACT : "-" > | < MULTIPLY : "*" > | < DIVIDE : "/" > | < BE : ">" > | < LE : "<" > | < EQUAL : "=" > | < AND : "&&" > | < OR : "||" > | < NOT : "!"> | < AUTOADD :"++"> | < AUTOSUBTRACT :"--"> } TOKEN : /* LITERALS常量 */ { < INTEGER_LITERAL : < DECIMAL_LITERAL > ([ "l", "L" ])? | < HEX_LITERAL > ([ "l", "L" ])? | < OCTAL_LITERAL > ([ "l", "L" ])? > | < #DECIMAL_LITERAL : [ "1"-"9" ] ([ "0"-"9" ])* > | < #HEX_LITERAL : "0" [ "x", "X" ] ([ "0"-"9", "a"-"f", "A"-"F" ])+ > | < #OCTAL_LITERAL : "0" ([ "0"-"7" ])* > } TOKEN : /* IDENTIFIERS标识符 */ { < IDENTIFIER : < LETTER > ( < LETTER > | < DIGIT > )* > | < #LETTER : [ "_", "a"-"z", "A"-"Z" ] > | < #DIGIT : [ "0"-"9" ] > } //**************************************************// SimpleNode Start() : {} { Program() < EOF> { return jjtThis; } } void Program() : //程序 {} { ( < INT > | < VOID> ) < MAIN > "(" ")" "{" ( StatementBlock() )* "}" } void StatementBlock() : //语句块 {} { ( Statement() )+ /*| "{" ( StatementBlock() )* "}" */ } void Statement() : //语句 {} { DeclarationStatement() //声明语句 | AssignmentStatement() //赋值语句 | ifelseStatement() //if-else语句 | whileStatement() //while语句 | dowhileStatement() //dowhile语句 | forStatement() //for语句 | switcaStatement() //switchcase语句 } Token type() : { Token t = null; } { t = < INT > { return t; } | t = < FLOAT > { return t; } | t = < DOUBLE > { return t; } | t = < CHAR > { return t; } | t = < VOID > { return t; } } //声明语句 void DeclarationStatement() : { Token Sbo1 = null; Token Sbo2 = null; Token Sbo3 = null; String name = null; String str = null; Symbol tempsymbol = null; } { Sbo1 = type() Sbo2 = < IDENTIFIER > //标识符 { //查看错误 name = Sbo2.image; if (symbollist.exist(name)) { str = name + "变量已声明过,错误:重复声明" + "\n"; S += str; str = null; existF = true; } else { //将变量加入符号表 tempsymbol = new Symbol(name, Sbo1.image); symbollist.addS(tempsymbol); } } ( "," Sbo3 = < IDENTIFIER > { //查看错误 name = Sbo3.image; if (symbollist.exist(name)) { str = name + "变量已声明过,错误:重复声明" + "\n"; S += str; str = null; existF = true; } else { //将变量加入符号表 tempsymbol = new Symbol(name, Sbo1.image); symbollist.addS(tempsymbol); } } )* ";" } //赋值语句 void AssignmentStatement() : { Token id; Token a; String e = null; //若是有错误,用来存放错误信息 String str = null; } { //将IDENTIFIER赋给id,将等号赋给a,将表达式赋给e id = < IDENTIFIER > a = "=" e = Expression() { //生成四元式,入链表 QTInfo qt = new QTInfo("=",e,"_",id.image); qtList.addQTInfo(qt); } { if (symbollist.getSize() != 0) { if (!symbollist.exist(id.image)) { str = id.image + "变量未曾声明,错误:使用未声明" + "\n"; S += str; str = null; existF = true; } } } ";" } //if-else条件语句 void ifelseStatement() : { ConditionValue chain = null; int quad; int fquad; } { "if" "(" chain = orboolExpression() ")" { quad = QTInfo.size + 1; } { //回填真链 chain.backpatchTrueChain(QTInfo.size + 1); } "{" StatementBlock() "}" { fquad = QTInfo.size + 1; } ( LOOKAHEAD(1) < ELSE > { //else前的无条件跳转为“qt”四元式 QTInfo qt = new QTInfo("J", "_", "_","0"); qtList.addQTInfo(qt); fquad++; } StatementBlock() { //得到此时下一个四元式的序号,用来回填上面的无条件跳转“qt” qt.setResult(QTInfo.size + 1); } )? { chain.backpatchFalseChain(fquad); } } //while语句 void whileStatement() : { ConditionValue chain = null; int quad; } { < WHILE > "(" { quad = QTInfo.size + 1; } chain = Condition() ")" //OrBooleanExpression() { //回填真链 chain.backpatchTrueChain(QTInfo.size + 1); } "{" StatementBlock() "}" { //while的一次跳转,回到上面去 qtList.addQTInfo(new QTInfo("J", "_", "_", quad)); chain.backpatchFalseChain(QTInfo.size +1); } } ConditionValue Condition(): //while,if关系 { String e1 = null; String e2 = null; String rop = null; ConditionValue chain = new ConditionValue(); } { e1 = Expression() ( rop = rop() e2 = Expression() )? { if(rop != null) //rop是 > { //生成四元式,加入列表,合并真链 QTInfo info = new QTInfo("J" + rop,e1,e2,"T"); qtList.addQTInfo(info); chain.mergeTrue(info); } else { QTInfo info = new QTInfo("Jnz",e1,"_","T"); qtList.addQTInfo(info); chain.mergeTrue(info); } QTInfo info = new QTInfo("J","_","_","F"); qtList.addQTInfo(info); chain.mergeFalse(info); return chain; } } String rop(): { Token t = null; } { t = < BE > //大于 { return t.image; } } //for语句 void forStatement() : { ConditionValue chain = new ConditionValue(); int quad; int fquad; int mquad; int cquad; } { < FOR> "(" /*AssignmentStatement()后面已自带“;”,所以不需要再加了*/ AssignmentStatement() //赋值 { cquad = QTInfo.size + 1; } chain = Condition() //条件 ";" { mquad = QTInfo.size + 1; } autoinc() { qtList.addQTInfo(new QTInfo("J", "_", "_", cquad)); } ")" "{" { quad = QTInfo.size + 1; } StatementBlock() "}" { //跳转到自增或自减语句之前,进行自增或自减操作 qtList.addQTInfo(new QTInfo("J", "_", "_", mquad)); } { fquad = QTInfo.size + 1; //回填假链 chain.backpatchFalseChain(fquad); //回填真链 chain.backpatchTrueChain(quad); } } //自增自减 void autoinc() : { Token id; Token op; String newTemp; } { id = < IDENTIFIER > ( op = < AUTOADD> { //生成四元式,入链表,自增 //newTemp = VariableNameGenerator.genVariableName(); QTInfo qt = new QTInfo("+",id.image,"1",id.image); qtList.addQTInfo(qt); } | op = < AUTOSUBTRACT> { //生成四元式,入链表,自减 newTemp = VariableNameGenerator.genVariableName(); QTInfo info = new QTInfo("-",id.image,"1",newTemp); QTInfo info1 = new QTInfo("=",newTemp,"_",id.image); qtList.addQTInfo(info); qtList.addQTInfo(info1); } ) } //do-while语句 void dowhileStatement() : { int quad; ConditionValue chain = new ConditionValue(); } { < DO > { quad = QTInfo.size + 1; } "{" StatementBlock() "}" < WHILE > "(" chain = Condition() ")" ";" { //回填真链 chain.backpatchTrueChain(quad); } { //不需要回跳,在条件为真的情况下已经回跳了 //qtList.addQTInfo(new QTInfo("J", "_", "_", quad)); chain.backpatchFalseChain(QTInfo.size +1); } } //switch-case语句 void switcaStatement() : { int quad; int quad1; String res = null; //存放E的结果 Token rmi; //存放匹配的选项 } { < SWITCH> "(" res = AdditiveExpression() ")" "{" ( < CASE> rmi = < INTEGER_LITERAL> ":" { //得到下一个四元式的序号,进行回填操作 quad = QTInfo.size + 1; } { /*Goto L语句,采用定义性出现,即以S产生的第一个四元式的序号作为 标号L的地址*/ quad++; //如果res等于rmi.image,就跳转到quad四元式 QTInfo info = new QTInfo("case",res,rmi.image,quad); qtList.addQTInfo(info); } Statement() < BREAK> ";" )+ < dEFAULT> ":" { quad1 = QTInfo.size + 1; } { //如果前面都无法匹配,则进行default quad1++; QTInfo info = new QTInfo("case",res,"default",quad1); qtList.addQTInfo(info); } Statement() "}" } //&&布尔表达式 ConditionValue andboolExpression() : { ConditionValue chain1 = new ConditionValue(); ConditionValue chain2 = new ConditionValue(); int quad; } { chain1 = Condition() { quad = QTInfo.size + 1; } /*当下面括号内不存在时,与布尔表达式就相当于一个Condition(), 当括号内的存在时, 需要将chain2返回,当括号内的不存在时,需要将chain1返回,所以将chain1赋给chain2*/ { chain2 = chain1; } ( "&&" chain2 = Condition() { //回填真链 chain1.backpatchTrueChain(quad); //合并假链chain1,chain2 chain2.mergeFalse(chain1.falseChain); } )? { return chain2; } } //||布尔表达式 ConditionValue orboolExpression() : { //布尔左右两边需要判断的 ConditionValue chain1 = new ConditionValue(); ConditionValue chain2 = new ConditionValue(); int quad; } { //让||两边格式一个&&表达式 chain1 = andboolExpression() /*与与布尔表达式一样*/ { chain2 = chain1; } ( { quad = QTInfo.size + 1; } "||" chain2 = andboolExpression() { //回填假链 chain1.backpatchFalseChain(quad); //合并真链 chain2.mergeTure(chain1.trueChain); } )? { return chain2; } } String Expression() : //表达式 { String first; String middle; String newTemp; Token op; } { //first = MultiplicativeExpression() first = AdditiveExpression() { newTemp = first; } ( ( op = < ADD > | op = < MULTIPLY > | op = < SUBTRACT > ) //middle = MultiplicativeExpression() middle = AdditiveExpression() { newTemp = VariableNameGenerator.genVariableName(); QTInfo qt = new QTInfo(op.image,first,middle,newTemp); qtList.addQTInfo(qt); first = newTemp; } )* { return newTemp; } } void Operator() : //运算符 {} { "+" | "-" | "*" | "/" } String Relation() : //关系符 { Token op; } { op = "<" | op = "<=" | op = ">" | op = ">=" | op = "==" | op = "!=" { return op.image; } } //加法表达式 String AdditiveExpression() : { String first; String middle; String newTemp; Token op; } { first = MultiplicativeExpression() //first是返回的字符串 { newTemp = first; } ( ( op = "+" //op是Token对象 | op = "-" ) middle = MultiplicativeExpression() // middle是返回的字符串 { newTemp = VariableNameGenerator.genVariableName(); QTInfo qt = new QTInfo(op.image,first,middle,newTemp); qtList.addQTInfo(qt); first = newTemp; } )* { return newTemp; } } //乘法表达式 String MultiplicativeExpression() : { String first; String middle; String newTemp; Token op; } { first = UnaryExpression() //first是返回的字符串 { newTemp = first; } ( ( op = "*" //op是Token对象 | op = "/" | op = "%" ) middle = UnaryExpression() // middle是返回的字符串 { newTemp = VariableNameGenerator.genVariableName(); QTInfo qt = new QTInfo(op.image,first,middle,newTemp); qtList.addQTInfo(qt); first = newTemp; } )* { return newTemp; } } String UnaryExpression() : { String str = null; Token t = null; } { "(" str = Expression() ")" { return str; } | t = < IDENTIFIER > { str = t.image; return str; } | t = < INTEGER_LITERAL > { str = t.image; return str; } } void Identifier() : {} { < IDENTIFIER > } void Integer() : {} { < INTEGER_LITERAL > }
QTInfo:定义四元式
package util; //定义四元式的信息 public class QTInfo { public static int size = 0; // 四元式全局个数 private int innerId; // 当前四元式ID private String operator; private String arg1; private String arg2; private String result; public QTInfo(String operator, String arg1, String arg2, String result) { super(); this.innerId = ++size; this.operator = operator; this.arg1 = arg1; this.arg2 = arg2; this.result = result; } public QTInfo(String operator, String arg1, String arg2, int result) { this(operator, arg1, arg2, result + ""); } public String getOperator() { return this.operator; } public void setResult(String result) { this.result = result; } public void setResult(int result) { this.result = "" + result; } public String getResult() { return this.result; } public void setInnerId(int innerID) { this.innerId = innerID; } public int getInnerIdSeqen() { return size; } public String toString() { // TODO Auto-generated method stub return this.innerId + ":\t(" + this.operator + ",\t" + this.arg1 + ",\t" + this.arg2 + ",\t" + this.result + "\t)\n"; } }
QTList:存放四元式的列表:
package util; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; public class QTList { public ArrayList<QTInfo> QTList = new ArrayList<QTInfo>(); public static boolean flag = true; public void addQTInfo(QTInfo info) { QTList.add(info); } public void addQTInfo(int index, QTInfo info) { QTList.add(index, info); } public QTInfo get(int index) { return (QTInfo) QTList.get(index); } public QTInfo remove(int index) { return QTList.remove(index - 1); } public void clear() { QTList.clear(); QTInfo.size = 0; } public void printQTTable() { // System.out.println(toString()); Iterator<QTInfo> itr = QTList.iterator(); try { while (itr.hasNext()) { QTInfo tmp = (QTInfo) itr.next(); System.out.println(tmp.toString()); } } catch (Exception e) { e.printStackTrace(); } } }
ConditionValue真链和假链
package util; import java.util.ArrayList; import java.util.Iterator; public class ConditionValue { public ArrayList<QTInfo> trueChain = new ArrayList<QTInfo>(); public ArrayList<QTInfo> falseChain = new ArrayList<QTInfo>(); //增加一个四元式 public void mergeTrue(QTInfo qtTrue){ trueChain.add(qtTrue); } //增加多个四元式,即合并两条真链 public void mergeTure(ArrayList<QTInfo> chaint) { Iterator<QTInfo> itr = chaint.iterator(); while(itr.hasNext()){ trueChain.add(itr.next()); } } public void mergeFalse(QTInfo qtFalse){ falseChain.add(qtFalse); } public void mergeFalse(ArrayList<QTInfo> chainf) { Iterator<QTInfo> itr = chainf.iterator(); while(itr.hasNext()){ falseChain.add(itr.next()); } } public void backpatchTrueChain(int result){ Iterator<QTInfo> itr = trueChain.iterator(); while(itr.hasNext()){ itr.next().setResult(result); } } public void backpatchFalseChain(int result){ Iterator<QTInfo> itr = falseChain.iterator(); while(itr.hasNext()){ itr.next().setResult(result); } } }
VariableNameGenerator变量产生器
package util; /** * 变量名产生器 * */ public class VariableNameGenerator { private static final String VAR_PREFIX = "T"; // 前缀 private static int sequenceId = 0; // 序号 T1、T2、T3... public static String genVariableName() { ++sequenceId; return VAR_PREFIX + sequenceId; } public void clear() { // TODO Auto-generated method stub sequenceId = 0; } }
Symbol符号
package util; public class Symbol { public String name; public String type; public Symbol(String name, String type) { super(); this.name = name; this.type = type; } }
SymbolTable符号表
package util; import java.util.ArrayList; public class SymbolTable { public ArrayList<Symbol> mylist=null; public SymbolTable(ArrayList<Symbol> mylist) { super(); this.mylist = mylist; } //返回链表中存放的变量个数 public int getSize() { return mylist.size(); } //查看变量是否在表中已经存在 public boolean exist(String name){ boolean index=false; for(Symbol temp:mylist){ if(temp.name.equals(name)){ index=true; } } return index; } //往符号表中增加变量 public void addS(Symbol temp){ mylist.add(temp); } }
界面部分就不上传了,只有jjt文件的上面涉及到界面,直接删掉就可以。