基于语法树生成代码

原创 2013年12月04日 10:10:18
package com.xxx.xx.xxx.ast;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.TypeLiteral;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;

import com.xxx.uxxxat.testcode.analyze.object.ClassInfo;

public  class ASTWriter {
	protected static AST ast = null;
	protected static CompilationUnit compilUnit = null;
	protected static TypeDeclaration classType = null;
	protected static List<?> types = null;
	protected static ClassInfo classInfo = null;
	protected static String testedClassName = "";
	protected static String className = "";
	protected static String instanceName = "";
	protected static ASTRewrite rewriter = null;
	protected static String packageName = "";
	protected static String testFile = "";
	protected static char[] contents = {};
	protected static List<String> importDeclarationNames = new LinkedList<String>();
	
	
	public static String springFilePath = "";
	public static String excelFilePath = "";
	
	
 
        public ASTWriter(char[] content, ClassInfo classInfo) {
		
		if (content.length == 0 || content == null) {
			contents = "class Tmp{\n}".toCharArray();
		}
		else {
			contents = content;
		}
		
		ASTParser parsert = ASTParser.newParser(AST.JLS3);
		parsert.setSource(contents); 
               
                compilUnit = (CompilationUnit) parsert.createAST(null);
		types = compilUnit.types();
		ast = compilUnit.getAST();
		classType = (TypeDeclaration) types.get(0);
		rewriter = ASTRewrite.create(ast);
		
		ASTWriter.classInfo = classInfo;
		ASTWriter.testedClassName = classInfo.getClassName();
	}

	public ASTWriter() {
	}


	// This method only be used by create new test file ;
	@SuppressWarnings("unchecked")
	protected void addClassInfo(String className, String supperName) {
		Type type = ast.newSimpleType(ast.newSimpleName(supperName));		
		classType.setInterface(false);
		classType.setSuperclassType(type);
		classType.setName(ast.newSimpleName(className));
		classType.modifiers().add(ast.newModifiers(Modifier.PUBLIC).get(0));		
		
		compilUnit.types();//.add(classType);
	}

        //添加package 语句 ,例如package com.test.package
	protected void addPackageInfo(String PackageName) {
		PackageDeclaration pkgDecl = ast.newPackageDeclaration();
		pkgDecl.setName(ast.newName(PackageName));
		compilUnit.setPackage(pkgDecl);
	}

        //添加import 语句, 例如import java.io.*;
	@SuppressWarnings("unchecked")
	protected void addImportDeclaration(List<String> importNames) {
		for(String importstr:importNames){
			ImportDeclaration importDeclaration = ast.newImportDeclaration();  
			if(importstr.endsWith("*")){
				String simpleName = "";
				simpleName = importstr.substring(0, importstr.indexOf("*")-1);
				importDeclaration.setName(ast.newName(simpleName));
				importDeclaration.setOnDemand(true);  
			}
			else if(importstr.startsWith("static")){				
				String simpeName = importstr.substring(importstr.indexOf("static")+7).trim();
				importDeclaration.setName(ast.newName(simpeName));
				importDeclaration.setOnDemand(false);  
				importDeclaration.setStatic(true);
			}
			else{
				String simpeName = importstr.trim();
				importDeclaration.setName(ast.newName(simpeName));
				importDeclaration.setOnDemand(false);  
			}			
			compilUnit.imports().add(importDeclaration);  
		}
	}

        //添加方法定义语句 例如 public void test1(){}
	@SuppressWarnings("unchecked")
	protected void addDeclareMethod(MethodDeclaration methodDeclaration) {
		classType.bodyDeclarations().add(methodDeclaration);
	}

        //批量添加方法定义语句
	protected void addBatchMDeclareMethod(Collection<MethodDeclaration> methods) {
		for (Iterator<MethodDeclaration> iter = methods.iterator(); iter.hasNext();) {
			this.addDeclareMethod(iter.next());
		}
	}

        //添加注解语句
	@SuppressWarnings("unchecked")
	protected void addAnnOnClass(String annName,Set<String> initlist){
		NormalAnnotation normalAnnotation = ast.newNormalAnnotation();
		Name name = ast.newName(annName);
		normalAnnotation.setTypeName(name);
		ArrayInitializer arrayInit = ast.newArrayInitializer();;
		MemberValuePair memberValuePair = ast.newMemberValuePair();
		memberValuePair.setName(ast.newSimpleName("value"));
		
		System.out.println(classType.modifiers().get(0).toString());
		if(classType.modifiers().get(0).toString().contains(annName)){
			NormalAnnotation normalAnnotationtmp = (NormalAnnotation)classType.modifiers().get(0);
			MemberValuePair mp = (MemberValuePair) normalAnnotationtmp.values().get(0);
			for(Object obj : ((ArrayInitializer) mp.getValue()).expressions()){
				TypeLiteral tl = (TypeLiteral)obj;
				SimpleType st = (SimpleType) tl.getType();
				String valueName = st.getName().toString();
				initlist.add(valueName);						
			}
			for (String value : initlist) {
				if (!arrayInit.toString().contains(value)) {
					TypeLiteral tL = ast.newTypeLiteral();
					tL.setType(ast.newSimpleType(ast.newName(value)));
					arrayInit.expressions().add(tL);
				}
			}
			memberValuePair.setValue(arrayInit);
			normalAnnotation.values().add(memberValuePair);		
			classType.modifiers().set(0, normalAnnotation);
		}
		else{
			for(String value : initlist){
				  TypeLiteral tL = ast.newTypeLiteral();
				  tL.setType(ast.newSimpleType(ast.newName(value)));
				  arrayInit.expressions().add(tL);
			}	
			memberValuePair.setValue(arrayInit);
			normalAnnotation.values().add(memberValuePair);		
			classType.modifiers().set(0, normalAnnotation);
		}
	}

        //添加变量定义语句	
	@SuppressWarnings("unchecked")
	protected void addFieldDeclaration(String className, String instanceName) {
		// className instanceName ;
		VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
		Expression express = ast.newNullLiteral();
		fragment.setInitializer(express);
		fragment.setName(ast.newSimpleName(instanceName));

		FieldDeclaration classVariDeclaration = ast.newFieldDeclaration(fragment);
		Type type = ast.newSimpleType(ast.newSimpleName(className));
		classVariDeclaration.setType(type);

		classType.bodyDeclarations().add(classVariDeclaration);

		// Object retObjc = null
		VariableDeclarationFragment fragment1 = ast.newVariableDeclarationFragment();
		fragment1.setName(ast.newSimpleName("retObj"));

		FieldDeclaration classVariDeclaration1 = ast.newFieldDeclaration(fragment1);
		Type type1 = ast.newSimpleType(ast.newSimpleName("Object"));
		classVariDeclaration1.setType(type1);
		classType.bodyDeclarations().add(classVariDeclaration1);
		
		// public static DBManage  dbManage = new DBManage();
		VariableDeclarationFragment fragment2 = ast.newVariableDeclarationFragment();
		Expression express2 = ast.newNullLiteral();
		fragment2.setInitializer(express2);
		fragment2.setName(ast.newSimpleName("dbManage"));

		FieldDeclaration classVariDeclaration2 = ast.newFieldDeclaration(fragment2);
		Type type2 = ast.newSimpleType(ast.newSimpleName("DBManage"));
		classVariDeclaration2.setType(type2);
		
		classType.bodyDeclarations().add(classVariDeclaration2);
	}

        //修改方法定义语句
	@SuppressWarnings("unchecked")
	protected void modifyDeclareMethod(MethodDeclaration oldmethod,MethodDeclaration newMethod) {
		int index = classType.bodyDeclarations().indexOf(oldmethod);
		classType.bodyDeclarations().add(index + 1, newMethod);
		classType.bodyDeclarations().remove(index);
	}

	public static String getInstanceName() {
		return instanceName;
	}

	public static void setInstanceName(String instanceName) {
		ASTWriter.instanceName = instanceName;
	}

	protected void setTestedClassName(String testedclassName) {
		ASTWriter.testedClassName = testedclassName;
	}

	protected String getTestedClassName() {
		return ASTWriter.testedClassName;
	}

	protected void setClassName(String className) {
		classType.setName(ast.newSimpleName(className));
		ASTWriter.className = className;
	}

	protected String getClassName() {
		return ASTWriter.className;
	}

	protected String getPackageName() {
		return compilUnit.getPackage().getName().toString();
	}

	protected int getClassModifiers() {
		return classType.getModifiers();
	}

	protected MethodDeclaration[] getDeclaredMethod() {
		return classType.getMethods();
	}

	public CompilationUnit getCompilationUnit() {
		return ASTWriter.compilUnit;
	}

	public static void setSpringFilepath(String springFilePath) {
		ASTWriter.springFilePath = springFilePath;
	}
	
	/**
	 * @return the spring_File_path
	 */
	public static final String getSpringFilepath() {
		return springFilePath;
	}


	

	/*
	 * NormalAnnotation normalAnnotation = ast.newNormalAnnotation(); Name name
	 * = ast.newName(annotationName); normalAnnotation.setTypeName(name);
	 * ArrayInitializer arrayInit = ast.newArrayInitializer(); for(String value
	 * : values){ TypeLiteral tL = ast.newTypeLiteral();
	 * tL.setType(ast.newSimpleType(ast.newName(value)));
	 * arrayInit.expressions().add(tL); }
	 * 
	 * MemberValuePair memberValuePair = ast.newMemberValuePair();
	 * memberValuePair.setName(ast.newSimpleName("value"));
	 * memberValuePair.setValue(arrayInit);
	 * 
	 * normalAnnotation.values().add(memberValuePair);
	 */

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

自己实现一个SQL解析引擎

SQL的解析引擎包括查询编译与查询优化和查询的运行,主要包括3个步骤: 查询分析: 制定逻辑查询计划(优化相关) 制定物理查询计划(优化相关) 查询分析: 将SQL语句表示成某种有用的语法树. 制定...

二、 Hive语法树的生成

HiveQL是一个非标准的sql语言,实现了sql的大部分规范,同时添加了一些hive独有的特性。Hive使用antlr3定义HiveQL语言。 1.1 antlr3简介 ANTLR(ANother ...

Java代码分析器(二)- 使用DOM API操作抽象语法树

上篇博客末尾提到了一棵抽象语法树长什么样子。JDT提供了一套DOM API来让我们顺利地控制这样一棵树。 读完本篇后请继续完成上篇的延伸阅读:http://help.eclipse.org/ 点击J...

JSP编译成Servlet(一)语法树的生成——语法解析

一般来说,语句按一定规则进行推导后会形成一个语法树,这种树状结构有利于对语句结构层次的描述。同样Jasper对JSP语法解析后也会生成一棵树,这棵树各个节点包含了不同的信息,但对于JSP来说解析后的语...

解 放“房 奴”

在我们的国家,因为文化的差异,很多年轻人都持有以下观点,尤其以女性为最。他们总以为要结婚就一定要买房子,只有买了房子才觉得稳定,才有安全感。这也是很多有创业能力的年轻人,仅仅是因为没有“创业起步资金”...

Hive解析HiveQL语句生成抽象语法树和逻辑计划

试了下解析TPCH里面的Q9,解释如下: hive> explain insert overwrite table q9_product_type_profit     > select ...

[WebKit内核] JavaScriptCore深度解析--基础篇(一)字节码生成及语法树的构建详情分析

看到HorkeyChen写的文章《[WebKit] JavaScriptCore解析--基础篇(三)从脚本代码到JIT编译的代码实现》,写的很好,深受启发。想补充一些Horkey没有写到的细节比如字节...
  • yistn
  • yistn
  • 2015-03-27 09:21
  • 327

ANTLR中抽象语法树(AST)的生成和使用

ANTLR中抽象语法树(AST)的生成和使用直接在语法文件中嵌入求值处理代码的方式在ANTLR中称为嵌入式动作。复杂情况下需要基于语法树遍历生成目标代码。前者语法复杂时使语法文件臃肿。另外,语法可能经...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)