java语义分析

java语义分析

供学弟学妹们参考,借诸位金口,留下“考研顺利”,吾当不甚感激。

尚未完善地方:

只定义了整数类型数据; 必须以int main()开头; 必须有返回return。

MyParser.jjt
/**
 * JJTree template file created by SF JavaCC plugin 1.5.28+ wizard for JavaCC 1.5.0+
 */
options
{
  static = false;
}

PARSER_BEGIN(MyParser)
package ParserM;
import ytil.*;

public class MyParser
{
  public static QuadrupleList List = new QuadrupleList();

  public static void mprint()
  {
    List.printqu();
  }

  public static void main(String args [])
  {
    System.out.println("Reading from standard input...");
    System.out.print("Enter an expression like \"1+(2+3)*var;\" :");
    MyParser parser = new MyParser(System.in);
    try
    {
      SimpleNode n = parser.Start();
      n.dump("");
      System.out.println("Thank you.");
    }
    catch (Exception e)
    {
      System.out.println("Oops.");
      System.out.println(e.getMessage());
    }
  }
}

PARSER_END(MyParser)

SKIP :
{
  " "
| "\t"
| "\n"
| "\r"
| < "//" (~[ "\n", "\r" ])*
    (
      "\n"
    | "\r"
    | "\r\n"
    ) >
| < "/*" (~[ "*" ])* "*"
    (
      ~[ "/" ] (~[ "*" ])* "*"
    )*
    "/" >
}

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 : /*KEYWORD*/
{
  < IF : "if" >
| < ELSE : "else" >
| < WHILE : "while" >
| < RETURN : "return" >
| < VOID : "void" >
| < MAIN : "main" >
| < INT : "int" >
| < DOUBLE : "double" >
}

TOKEN : /* IDENTIFIERS */
{
  < IDENTIFIER :
    < LETTER >
    (
      < LETTER >
    | < DIGIT >
    )* >
| < #LETTER : [ "_", "a"-"z", "A"-"Z" ] >
| < #DIGIT : [ "0"-"9" ] >
}

TOKEN : /*SEPARATER*/
{
  < SEMI : ";" >
| < COMMA : "," >
| < BLBRACKET : "{" >
| < BRBRACKET : "}" >
| < MLBRACKET : "[" >
| < MRBRACKET : "]" >
| < SLBRACKET : "(" >
| < SRBRACKET : ")" >
}

TOKEN : /*OPERATOR*/
{
  < ADD : "+" >
| < MINUS : "-" >
| < MUTIPLY : "*" >
| < DIVIDE : "/" >
| < GIVE : "=" >
}

TOKEN : /*RELATION*/
{
  < B : ">" >
| < S : "<" >
| < EQUAL : "==" >
| < BEQUAL : " >=" >
| < SEQUAL : "<=" >
| < NEQUAL : "!=" >
}

SimpleNode Start() :
{}
{
  Program()
  {
    return jjtThis;
  }
}

String Expression() :
{
  String str = null;
}
{
  str = AdditiveExpression()
  {
    return str;
  }
}

void Program() :
{}
{
  < INT > 
  < MAIN > 
  < SLBRACKET > 
  < SRBRACKET > 
  < BLBRACKET >
  (
    StatementBlock()
  )*
  < RETURN > Integer() < SEMI > 
  < BRBRACKET >
}

void StatementBlock() :
{}
{
  Sentence()
|
  (
    < BLBRACKET >
    (
      StatementBlock()
    )*
    < BRBRACKET >
  )
}

void Sentence() :
{}
{
  Condition()
| 	LOOP()
| 	Sequential()
}

void Declaration() :
{}
{
  < INT > Identifier()
  (
    < COMMA > 
    Identifier()
  )*
}

//赋值
void Assignment() :
{
  String str1 = null, str2 = null;
  Token op;
}
{
  str1 = Identifier() 
  op = < GIVE > 
  str2 = Expression()
  {
    Quadruple qt = new Quadruple(op.image, str2, "_", str1);
    List.addQuadruple(qt);
  }
  (
    < COMMA > 
    str1 = Identifier() 
    op = < GIVE > 
    str2 = Expression()
    {
      Quadruple qt2 = new Quadruple(op.image, str2, "_", str1);
      List.addQuadruple(qt2);
    }
  )*	
}

void Sequential() :
{}
{
  [
    Declaration()
  | Assignment()
  ]
  < SEMI >
}

void Condition() :
{
  ConditionValue Value = null;
}
{
  < IF > 
  < SLBRACKET > 
  Value = CON()
  < SRBRACKET >
  {
    Value.backfillTrueChain(Quadruple.size );
    Value.getTrueChain().clear();
  }
  StatementBlock()
  
  (
    LOOKAHEAD(2)
    < ELSE >
    {
    Quadruple qt=new Quadruple("J","_","_","F");
    Value.mergeFalseChain(qt);
    List.addQuadruple(qt);
    }
    StatementBlock()
  )?

  {
      Value.backfillFalseChain(Quadruple.size);
      Value.getFalseChain().clear();
  }
}

void LOOP() :
{
  int nxq = Quadruple.size;
  ConditionValue Value = null;
}
{
  < WHILE > 
  < SLBRACKET > 
  Value = CON() 
  < SRBRACKET >
  {
    Value.backfillTrueChain(Quadruple.size);
    Value.getTrueChain().clear();
  }
  StatementBlock()
  {
    Quadruple jump = new Quadruple("J", "_", "_", "" + nxq);
    List.addQuadruple(jump);
    Value.backfillFalseChain(Quadruple.size );
  }
}

ConditionValue CON() :
{
  ConditionValue Value = null;
}
{
  Value = LORCON()
  {
    return Value;
  }
}

ConditionValue LANDCON() :
{
  ConditionValue Value = null;
}
{
  (
    Value = BasicExp() 
    Value = LANDCON_1(Value)
  )
  {
    return Value;
  }
}

ConditionValue LANDCON_1(ConditionValue Value) :
{
  ConditionValue Value2 = null;
}
{
  [
    (
      "&&"
      {
        Value.backfillTrueChain(Quadruple.size);
        Value.getTrueChain().clear();
      }
      Value2 = BasicExp()
      {
        Value2.mergeFalseChain(Value);
        Value = Value2;
      }
      Value = LANDCON_1(Value)
    )
  ]
  {
    return Value;
  }
}

ConditionValue LORCON() :
{
  ConditionValue Value;
}
{
  (
    Value = LANDCON() 
    Value = LORCON_1(Value)
  )
  {
    return Value;
  }
}

ConditionValue LORCON_1(ConditionValue Value) :
{
  ConditionValue Value2 = null;
}
{
  [
    (
      "||"
      {
        Value.backfillFalseChain(Quadruple.size);
        Value.getFalseChain().clear();
      }
      Value2 = LANDCON()
      {
        Value2.mergeTrueChain(Value);
        Value = Value2;
      }
      Value = LORCON_1(Value)
    )
  ]
  {
    return Value;
  }
}

ConditionValue BasicExp() :
{
  String str1 = null, str2 = null, rst = null;
  Token op = null, op2 = null;
  ConditionValue Value = new ConditionValue();
}
{
  (
    (op2 = "!")? str1 = Expression()
  )
  {
    if (op2 != null)
    {
      rst = VariableNameGenerator.genVariableName();
      Quadruple qt = new Quadruple("J"+op2.image, str1, "_", rst);
      List.addQuadruple(qt);
      //str1 = rst;
    }
    rst = str1;
  }
  (
    op = RELATIONSYM() 
    str2 = Expression()
  )?
  {
    if (op == null)
    {
      Quadruple trueQuad = new Quadruple("Jnz", rst, "_", "T");
      List.addQuadruple(trueQuad);
      Value.mergeTrueChain(trueQuad);
      Quadruple falseQuad = new Quadruple("J", "_", "_", "F");
      List.addQuadruple(falseQuad);
      Value.mergeFalseChain(falseQuad);
    }
    else
    {
      Quadruple trueQuad = new Quadruple("J" + op.image, rst, str2, "T");
      List.addQuadruple(trueQuad);
      Value.mergeTrueChain(trueQuad);
      Quadruple falseQuad = new Quadruple("J", "_", "_", "F");
      List.addQuadruple(falseQuad);
      Value.mergeFalseChain(falseQuad);
    }
    return Value;
  }
}

Token RELATIONSYM() :
{
  Token op;
}
{
  (
    op = < B >
  | op = < S >
  | op = < EQUAL >
  | op = < BEQUAL >
  | op = < SEQUAL >
  | op = < NEQUAL >
  )
  {
    return op;
  }
}

String AdditiveExpression() :
{
  String str1 = null, str2 = null, rst = null;
  Token op;
}
{
  str1 = MultiplicativeExpression()
  {
    rst = str1;
  }
  (
    (
      op = "+"
    | op = "-"
    )
    str2 = MultiplicativeExpression()
    {
      rst = VariableNameGenerator.genVariableName();
      Quadruple qt = new Quadruple(op.image, str1, str2, rst);
      List.addQuadruple(qt);
      str1 = rst;
    }
  )*
  {
    return rst;
  }
}

String MultiplicativeExpression() :
{
  String str1 = null, str2 = null, rst = null;
  Token op;
}
{
  str1 = UnaryExpression()
  {
    rst = str1;
  }
  (
    (
      op = "*"
    | op = "/"
    | op = "%"
    )
    str2 = UnaryExpression()
    {
      rst = VariableNameGenerator.genVariableName();
      Quadruple qt = new Quadruple(op.image, str1, str2, rst);
      List.addQuadruple(qt);
      str1 = rst;
    }
  )*
  {
    return rst;
  }
}

String UnaryExpression() :
{
  String str = null;
}
{
  (
    "(" str = Expression() ")"
  | str = Identifier()
  | str = Integer()
  )
  {
    return str;
  }
}

String Identifier() :
{
  Token t = null;
}
{
  t = < IDENTIFIER >
  {
    return t.image;
  }
}

String Integer() :
{
  Token t = null;
}
{
  t = < INTEGER_LITERAL >
  {
    return t.image;
  }
}

ConditionValue.java

用于拉链和回填

package ytil;
import java.util.LinkedList;

public class ConditionValue {
	private LinkedList<Quadruple> trueChain=new LinkedList<>();
	private LinkedList<Quadruple> falseChain=new LinkedList<>();
	
	public LinkedList<Quadruple> getTrueChain(){
		return trueChain;
	}
	
	public LinkedList<Quadruple> getFalseChain(){
		return falseChain;
	}
	
	public void setTrueChain(LinkedList<Quadruple> truechain) {
		this.trueChain=truechain;
	}
	
	public void setFalseChain(LinkedList<Quadruple> falsechain) {
		this.falseChain=falsechain;
	}
	
	public void mergeTrueChain(Quadruple qt) {
		trueChain.add(qt);
	}
	
	public void mergeFalseChain(Quadruple qt) {
		falseChain.add(qt);
	}
	
	public void mergeTrueChain(ConditionValue value) {
		trueChain.addAll(value.trueChain);
	}
	
	public void mergeFalseChain(ConditionValue value) {
		falseChain.addAll(value.falseChain);
	}
	
	public void backfillTrueChain(String trueExit) {
		trueChain.forEach((quad)->{quad.setResult(trueExit);});
	}
	
	public void backfillTrueChain(int trueExit) {
		backfillTrueChain(""+trueExit);
	}
	
	public void backfillFalseChain(String falseExit) {
		falseChain.forEach((quad)->{quad.setResult(falseExit);});
	}
	
	public void backfillFalseChain(int falseExit) {
		backfillFalseChain(""+falseExit);
	}
}

QuadrupleList.java

存储四元式的列表

package ytil;
import java.util.ArrayList;
import java.util.Iterator;
public class QuadrupleList {
	public ArrayList<Quadruple> quadrupleList=new ArrayList<Quadruple>();
	public static boolean flag=true;
	
	public void addQuadruple(Quadruple qu) {
		Quadruple.size++;
		quadrupleList.add(qu);
	}
	
	//~~~
	public void addQuadruple(int index, Quadruple qu) {
		quadrupleList.add(index, qu);
	}
	
	public Quadruple get(int index) {
		return quadrupleList.get(index);
	}
	
	//~~~
	public Quadruple remove(int index) {
		return quadrupleList.remove(index-1);
	}
	
	//~~~
	public void clear() {
		quadrupleList.clear();
		Quadruple.size=0;
	}
	
	public void printqu() {
		Iterator<Quadruple> it=quadrupleList.iterator();
		try {
			while(it.hasNext()) {
				Quadruple tmp=it.next();
				System.out.println(tmp.toString());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

Quadruple.java

四元式类

package ytil;

public class Quadruple {
	public static int size=1;
	public static int k=0;
	String op;
	String former;
	String latter;
	String Result;
	
	public Quadruple(String op, String former, String latter, String Result) {
		setOp(op);
		setFormer(former);
		setLatter(latter);
		setResult(Result);
	}
	
	public void setOp(String op) {
		this.op=op;
	}
	
	public void setFormer(String former) {
		this.former=former;
	}
	
	public void setLatter(String latter) {
		this.latter=latter;
	}
	
	public void setResult(String Result) {
		this.Result=Result;
	}
	
	public String toString() {
		k++;
		return k+
		"("
		+op+", "
        +former+", "
        +latter+", "
        +Result
        +")";
	}
}

主程序
package test;
import ParserM.*;
import java.io.*;
public class test1 {
	public static void main(String[] args){
		File file = new File("./src/te.txt");
//		File file = new File("./src/te2.txt");
//		File file = new File("./src/te3.txt");
//		File file = new File("./src/te4.txt");
		FileInputStream re = null;
		try {
			re = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    MyParser parser = new MyParser(re);
	    try
	    {
	      SimpleNode n = parser.Start();
	      MyParser.mprint();
	      n.dump("");
	      System.out.println("Thank you.");
	    }catch (Exception e)
	    {
	        System.out.println("Oops.");
	        System.out.println(e.getMessage());
	    }

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值