List of usage examples for org.eclipse.jdt.core.dom AST newBlock
public Block newBlock()
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.PathWithUncertaintyTestStrategy.java
License:Open Source License
/** * Generates a class to be used in executing the test plan. * The class is abstract because at this point it is unclear how to assert that a certain state has been reached. * Thus, the assertStateReached will be abstract methods. * @param stateGraph//from w w w . ja v a 2s .c om */ public Document generateTestPlan(StateMachineStateGraph stateGraph) { Document doc = new Document( "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n"); //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(doc.get().toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.recordModifications(); AST ast = cu.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram) MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration(); testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan")); testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise //create method body Block testPlanMethodBody = ast.newBlock(); testPlanMethodDeclaration.setBody(testPlanMethodBody); //create recursively the test plan by parsing the state graph starting with initial state try { generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration, new HashSet<StateMachineStateTransition>()); } catch (NoSuchStateException e) { e.printStackTrace(); } ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY); //add all generated abstract methods for (Map.Entry<String, MethodDeclaration> entry : generatedAbstractMethods.entrySet()) { listRewrite.insertLast(entry.getValue(), null); } if (generatedPlans.isEmpty()) { notifyUser("No test plans containing uncertainty states could have been generated. " + "\n Please ensure selected state machine has at least one state with at least one uncertainty" + "\n Please ensure there is at least one InitialState, one FinalState, and one path between Initial and Final states which passes through" + "at least one state with at least one uncertainty"); } int index = 1; //add generated plan methods for (Map.Entry<String, MethodDeclaration> entry : generatedPlans.entrySet()) { //rename to PLAN_METHOD_LEADING + plan index from PLAN_METHOD_LEADING + UUID MethodDeclaration method = entry.getValue(); method.setName(ast.newSimpleName(PLAN_METHOD_LEADING + index++)); listRewrite.insertLast(method, null); } //add final } listRewrite.insertLast(rewriter.createStringPlaceholder("}\n", ASTNode.EMPTY_STATEMENT), null); TextEdit edits = rewriter.rewriteAST(doc, null); try { UndoEdit undo = edits.apply(doc); } catch (MalformedTreeException | BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(doc.get()); return doc; }
From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.impl.TransitionCorrectnessTestStrategy.java
License:Open Source License
/** * Generates a class to be used in executing the test plan. * The class is abstract because at this point it is unclear how to assert that a certain state has been reached. * Thus, the assertStateReached will be abstract methods. * @param stateGraph//from ww w . j av a 2 s . c o m */ public Document generateTestPlan(StateMachineStateGraph stateGraph) { Document doc = new Document( "public abstract class TestPlanForStateMachine" + stateGraph.getStateMachineName() + " { \n"); //from here we use the cumbersome and extremely detailed Eclipse recommended DOM/AST library ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(doc.get().toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.recordModifications(); AST ast = cu.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); //create method which will contain one test plan (might be cloned and branched for each if-else in the state machine diagram) MethodDeclaration testPlanMethodDeclaration = ast.newMethodDeclaration(); testPlanMethodDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); testPlanMethodDeclaration.setName(ast.newSimpleName("testPlan")); testPlanMethodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); //return true if successful or false otherwise //create method body Block testPlanMethodBody = ast.newBlock(); testPlanMethodDeclaration.setBody(testPlanMethodBody); //create recursively the test plan by parsing the state graph starting with initial state try { generatePlanForState(stateGraph.getInitialState(), rewriter, testPlanMethodDeclaration, new HashSet<StateMachineStateTransition>()); } catch (NoSuchStateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY); //add all generated abstract methods for (Map.Entry<String, MethodDeclaration> entry : generatedAbstractMethods.entrySet()) { listRewrite.insertLast(entry.getValue(), null); } int index = 1; //add generated plan methods if (generatedPlans.isEmpty()) { notifyUser("No test plans could have been generated. " + "\n Please ensure selected state machine has at least one complete path from initial to final state." + "\n Please ensure there is at least one InitialState, one FinalState, and one path between Initial and Final states"); } for (Map.Entry<String, MethodDeclaration> entry : generatedPlans.entrySet()) { //rename to PLAN_METHOD_LEADING + plan index from PLAN_METHOD_LEADING + UUID MethodDeclaration method = entry.getValue(); method.setName(ast.newSimpleName(PLAN_METHOD_LEADING + index++)); listRewrite.insertLast(method, null); } //add final } listRewrite.insertLast(rewriter.createStringPlaceholder("}\n", ASTNode.EMPTY_STATEMENT), null); TextEdit edits = rewriter.rewriteAST(doc, null); try { UndoEdit undo = edits.apply(doc); } catch (MalformedTreeException | BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(doc.get()); return doc; }
From source file:br.com.objectos.way.core.code.jdt.ASTTest.java
License:Apache License
@SuppressWarnings("unchecked") public void stackoverflow_answer() { AST ast = AST.newAST(AST.JLS8); CompilationUnit cu = ast.newCompilationUnit(); PackageDeclaration p1 = ast.newPackageDeclaration(); p1.setName(ast.newSimpleName("foo")); cu.setPackage(p1);//from w ww .j a va 2 s. c o m ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(new String[] { "java", "util", "Set" })); cu.imports().add(id); TypeDeclaration td = ast.newTypeDeclaration(); td.setName(ast.newSimpleName("Foo")); TypeParameter tp = ast.newTypeParameter(); tp.setName(ast.newSimpleName("X")); td.typeParameters().add(tp); cu.types().add(td); MethodDeclaration md = ast.newMethodDeclaration(); md.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); md.setName(ast.newSimpleName("bar")); SingleVariableDeclaration var = ast.newSingleVariableDeclaration(); var.setType(ast.newSimpleType(ast.newSimpleName("String"))); var.setName(ast.newSimpleName("a")); md.parameters().add(var); td.bodyDeclarations().add(md); Block block = ast.newBlock(); md.setBody(block); MethodInvocation mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("x")); ExpressionStatement e = ast.newExpressionStatement(mi); block.statements().add(e); System.out.println(cu); }
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
private static void merge(CompilationUnit unit, String pkgName, String typeName, String auth, String dbName, List<String> tableCreators) { unit.recordModifications();//from w w w. j a v a 2s . c om AST ast = unit.getAST(); TypeDeclaration type = (TypeDeclaration) unit.types().get(0); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName("cn.ieclipse.aorm.Session")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.content.UriMatcher")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.database.sqlite.SQLiteDatabase")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.database.sqlite.SQLiteOpenHelper")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("java.net.Uri")); unit.imports().add(id); id = ast.newImportDeclaration(); id.setName(ast.newName("android.content.ContentValue")); unit.imports().add(id); VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("AUTH")); StringLiteral sl = ast.newStringLiteral(); sl.setLiteralValue(auth); vdf.setInitializer(sl); FieldDeclaration fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))); fd.setType(ast.newSimpleType(ast.newSimpleName("String"))); int i = 0; type.bodyDeclarations().add(i++, fd); // URI = Uri.parse("content://" + AUTH); vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("URI")); MethodInvocation mi = ast.newMethodInvocation(); mi.setExpression(ast.newSimpleName("Uri")); mi.setName(ast.newSimpleName("parse")); InfixExpression fix = ast.newInfixExpression(); fix.setOperator(InfixExpression.Operator.PLUS); sl = ast.newStringLiteral(); sl.setLiteralValue("content://"); fix.setLeftOperand(sl); fix.setRightOperand(ast.newSimpleName("AUTH")); mi.arguments().add(fix); vdf.setInitializer(mi); fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))); fd.setType(ast.newSimpleType(ast.newSimpleName("Uri"))); type.bodyDeclarations().add(i++, fd); // private mOpenHelper; vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("mOpenHelper")); fd = ast.newFieldDeclaration(vdf); fd.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD)); fd.setType(ast.newSimpleType(ast.newName("SQLiteOpenHelper"))); type.bodyDeclarations().add(i++, fd); // private static session; vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("session")); fd = ast.newFieldDeclaration(vdf); fd.modifiers().addAll(ast.newModifiers((Modifier.PRIVATE | Modifier.STATIC))); fd.setType(ast.newSimpleType(ast.newName("Session"))); type.bodyDeclarations().add(i++, fd); // public static Session getSession(){ // return session; // } MethodDeclaration md = ast.newMethodDeclaration(); md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC))); md.setReturnType2(ast.newSimpleType(ast.newName("Session"))); md.setName(ast.newSimpleName("getSession")); Block methodBlock = ast.newBlock(); ReturnStatement returnStmt = ast.newReturnStatement(); returnStmt.setExpression(ast.newSimpleName("session")); methodBlock.statements().add(returnStmt); md.setBody(methodBlock); type.bodyDeclarations().add(i, md); // modify onCreate rewriteOnCreate(unit, dbName, tableCreators); }
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
private static void rewriteOnCreate(CompilationUnit unit, String dbName, List<String> tableCreators) { AST ast = unit.getAST(); TypeDeclaration type = (TypeDeclaration) unit.types().get(0); MethodDeclaration onCreate = getMethod(type, ("onCreate"), null); if (onCreate != null) { Block methodBlock = ast.newBlock(); // mOpenHelper = new // InlineOpenHelper(this.getContext(),"person.db",null,1); Assignment a = ast.newAssignment(); a.setOperator(Assignment.Operator.ASSIGN); a.setLeftHandSide(ast.newSimpleName("mOpenHelper")); ClassInstanceCreation cc = ast.newClassInstanceCreation(); cc.setType(ast.newSimpleType(ast.newSimpleName("SQLiteOpenHelper"))); ThisExpression thisExp = ast.newThisExpression(); MethodInvocation mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("getContext")); mi.setExpression(thisExp);/* w w w .ja va 2 s .c o m*/ cc.arguments().add(mi); StringLiteral sl = ast.newStringLiteral(); sl.setLiteralValue(dbName); cc.arguments().add(sl); cc.arguments().add(ast.newNullLiteral()); cc.arguments().add(ast.newNumberLiteral("1")); a.setRightHandSide(cc); methodBlock.statements().add(ast.newExpressionStatement(a)); AnonymousClassDeclaration acd = ast.newAnonymousClassDeclaration(); cc.setAnonymousClassDeclaration(acd); genInnerSQLiteOpenHelper(acd, ast, tableCreators); a = ast.newAssignment(); a.setOperator(Assignment.Operator.ASSIGN); a.setLeftHandSide(ast.newSimpleName("session")); ClassInstanceCreation cic = ast.newClassInstanceCreation(); cic.setType(ast.newSimpleType(ast.newSimpleName("Session"))); // SingleVariableDeclaration svd = // ast.newSingleVariableDeclaration(); // svd.setName(ast.newSimpleName("mOpenHelper")); cic.arguments().add(ast.newSimpleName("mOpenHelper")); // vdf.setInitializer(cic); a.setRightHandSide(cic); // methodBlock.statements().add(vde); methodBlock.statements().add(ast.newExpressionStatement(a)); ReturnStatement returnStmt = ast.newReturnStatement(); returnStmt.setExpression(ast.newBooleanLiteral(true)); methodBlock.statements().add(returnStmt); onCreate.setBody(methodBlock); } }
From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java
License:Apache License
private static void genInnerSQLiteOpenHelper(AnonymousClassDeclaration acd, AST ast, List<String> tableCreators) { MethodDeclaration md = ast.newMethodDeclaration(); md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC))); md.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); md.setName(ast.newSimpleName("onCreate")); SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName("db")); svd.setType(ast.newSimpleType(ast.newSimpleName("SQLiteDatabase"))); md.parameters().add(svd);/*from w ww .j av a 2 s. c om*/ Block innerBlock = ast.newBlock(); md.setBody(innerBlock); VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName("sql")); StringLiteral sl = ast.newStringLiteral(); sl.setLiteralValue(""); vdf.setInitializer(sl); VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf); vds.setType(ast.newSimpleType(ast.newSimpleName("String"))); innerBlock.statements().add(vds); for (String creator : tableCreators) { String[] lines = creator.split(SourceAnalysis.LF); for (String line : lines) { Assignment a = ast.newAssignment(); a.setOperator(Assignment.Operator.PLUS_ASSIGN); a.setLeftHandSide(ast.newSimpleName("sql")); StringLiteral temp = ast.newStringLiteral(); temp.setLiteralValue(line); a.setRightHandSide(temp); innerBlock.statements().add(ast.newExpressionStatement(a)); } MethodInvocation mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("execSQL")); mi.setExpression(ast.newSimpleName("db")); mi.arguments().add(ast.newSimpleName("sql")); innerBlock.statements().add(ast.newExpressionStatement(mi)); } acd.bodyDeclarations().add(md); // onUpgrade md = ast.newMethodDeclaration(); md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC))); md.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); md.setName(ast.newSimpleName("onUpgrade")); svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName("db")); svd.setType(ast.newSimpleType(ast.newSimpleName("SQLiteDatabase"))); md.parameters().add(svd); svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName("oldVersion")); svd.setType(ast.newPrimitiveType(PrimitiveType.INT)); md.parameters().add(svd); svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName("newVersion")); svd.setType(ast.newPrimitiveType(PrimitiveType.INT)); md.parameters().add(svd); innerBlock = ast.newBlock(); md.setBody(innerBlock); acd.bodyDeclarations().add(md); }
From source file:com.crispico.flower.codesync.tests.java.JavaTestsOnSourceCode.java
License:Open Source License
@SuppressWarnings("unchecked") public void testMethod_Adders() { javaCompilationUnit = JavaSyncUtils.loadJavaFile(folder.getFile("ClassA.java"), ASTParser.newParser(AST.JLS3)); javaCompilationUnit.recordModifications(); javaClass = JavaSyncUtils.getMasterClass(javaCompilationUnit); SingleVariableDeclaration variableDeclaration = null; MethodDeclaration methodDeclaration = null; AST ast = javaClass.getAST(); methodDeclaration = ast.newMethodDeclaration();// a() javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod1")); methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "void")); methodDeclaration.setBody(ast.newBlock()); methodDeclaration = ast.newMethodDeclaration();// a():int javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod2")); methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "int")); methodDeclaration.setBody(ast.newBlock()); methodDeclaration = ast.newMethodDeclaration();// a(par1:String):int javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod3")); methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "int")); methodDeclaration.setBody(ast.newBlock()); variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.setName(ast.newSimpleName("par1")); variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, "String")); methodDeclaration.parameters().add(variableDeclaration); methodDeclaration = ast.newMethodDeclaration();// a(par1:int, par2 :ClassB) :int javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod4")); methodDeclaration.setReturnType2(JavaSyncUtils.getJavaTypeFromString(ast, "int")); methodDeclaration.setBody(ast.newBlock()); variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.setName(ast.newSimpleName("par1")); variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, "int")); methodDeclaration.parameters().add(variableDeclaration); variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.setName(ast.newSimpleName("par2")); variableDeclaration.setType(JavaSyncUtils.getJavaTypeFromString(ast, "ClassB")); methodDeclaration.parameters().add(variableDeclaration); methodDeclaration = ast.newMethodDeclaration(); javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod6")); methodDeclaration.setBody(ast.newBlock()); JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PUBLIC_LITERAL); methodDeclaration = ast.newMethodDeclaration(); javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod7")); methodDeclaration.setBody(ast.newBlock()); JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PROTECTED_LITERAL); methodDeclaration = ast.newMethodDeclaration(); javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod8")); methodDeclaration.setBody(ast.newBlock()); JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PRIVATE_LITERAL); methodDeclaration = ast.newMethodDeclaration(); javaClass.bodyDeclarations().add(methodDeclaration); methodDeclaration.setName(ast.newSimpleName("addedMethod9")); methodDeclaration.setBody(ast.newBlock()); JavaSyncUtils.updateVisibilityFromModelToJavaClass(methodDeclaration, VisibilityKind.PACKAGE_LITERAL); synchronizeAndCompareMasterClass();//from ww w . ja v a2s . c o m }
From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaClass_OwnedMethods.java
License:Open Source License
/** * @author Luiza - conditions for interface and abstract methods added * @flowerModelElementId _zbW4iZiOEd6aNMdNFvR5WQ *//* w w w . j a va 2 s. co m*/ @SuppressWarnings("unchecked") @Override protected MethodDeclaration createAndAddNewASTElement(Operation modelElement, CompilationUnit parentAstElement) { TypeDeclaration parentClass = JavaSyncUtils.getMasterClass((CompilationUnit) parentAstElement); AST ast = parentClass.getAST(); MethodDeclaration method = ast.newMethodDeclaration(); if (modelElement.getName().equals(parentClass.getName().getIdentifier())) { //create a constructor method.setConstructor(true); } parentClass.bodyDeclarations().add(method); //if this method is not in an interface and is not an abstract method then add a body if (!JavaSyncUtils.getMasterClass(parentAstElement).isInterface() && !modelElement.isAbstract()) { Block methodBlock = ast.newBlock(); method.setBody(methodBlock); } return method; }
From source file:com.google.devtools.j2cpp.translate.AnonymousClassConverter.java
License:Open Source License
/** * Adds val$N instance fields to type so references to external * variables can be resolved. Existing constructors are updated to * initialize these fields; if no constructor exists, one is added. *//*from w ww . ja v a 2 s .c o m*/ private GeneratedMethodBinding addInnerVars(TypeDeclaration node, List<IVariableBinding> innerVars, List<ReferenceDescription> references, List<Expression> invocationArguments) { @SuppressWarnings("unchecked") List<BodyDeclaration> members = node.bodyDeclarations(); // safe by definition List<IVariableBinding> innerFields = Lists.newArrayList(); AST ast = node.getAST(); ITypeBinding clazz = Types.getTypeBinding(node); for (IVariableBinding var : innerVars) { if (!isConstant(var)) { // Constants are in-lined instead. ITypeBinding varType = var.getDeclaringClass(); if (varType == null) { varType = var.getType(); } if (Types.hasIOSEquivalent(varType)) { varType = Types.mapType(varType); } String fieldName = "val$" + var.getName(); FieldDeclaration field = createField(fieldName, varType, clazz, ast); members.add(field); IVariableBinding fieldVar = Types.getVariableBinding(field.fragments().get(0)); innerFields.add(fieldVar); for (ReferenceDescription ref : references) { if (ref.binding == var && ref.innerField == null) { ref.innerField = fieldVar; } } } } // Insert new parameters into constructor, if one was added by the // InitializationNormalizer from initializer blocks. boolean needsConstructor = true; GeneratedMethodBinding defaultConstructor = null; List<MethodDeclaration> enumConstructors = Lists.newArrayList(); ITypeBinding enclosingClass = clazz.getDeclaringClass(); for (BodyDeclaration member : members) { if (member instanceof MethodDeclaration && ((MethodDeclaration) member).isConstructor()) { if (argsMatch(invocationArguments, Types.getMethodBinding(member).getParameterTypes())) { MethodDeclaration constructor = (MethodDeclaration) member; needsConstructor = false; IMethodBinding oldBinding = Types.getMethodBinding(constructor); GeneratedMethodBinding newBinding = new GeneratedMethodBinding(oldBinding); Types.addBinding(constructor, newBinding); addInnerParameters(constructor, newBinding, innerFields, ast, true); defaultConstructor = newBinding; Symbols.scanAST(constructor); assert constructor.parameters().size() == defaultConstructor.getParameterTypes().length; } if (enclosingClass.isEnum()) { enumConstructors.add((MethodDeclaration) member); } } } if (!enumConstructors.isEmpty()) { for (MethodDeclaration constructor : enumConstructors) { GeneratedMethodBinding binding = new GeneratedMethodBinding(Types.getMethodBinding(constructor)); if (!invocationArguments.isEmpty()) { // Remove super invocation added by InitializationNormalizer. @SuppressWarnings("unchecked") List<Statement> stmts = constructor.getBody().statements(); // safe by definition for (int i = 0; i < stmts.size(); i++) { if (stmts.get(i) instanceof SuperConstructorInvocation) { stmts.remove(i); break; } } // Update the binding to include the arguments, addArguments(invocationArguments, ast, clazz, constructor, binding); addInnerParameters(constructor, binding, innerFields, ast, true); Symbols.scanAST(constructor); Types.addBinding(constructor, binding); } else { defaultConstructor = binding; } } if (defaultConstructor == null) { defaultConstructor = new GeneratedMethodBinding(Types.getMethodBinding(enumConstructors.get(0))); } } else if (needsConstructor) { MethodDeclaration constructor = ast.newMethodDeclaration(); constructor.setConstructor(true); ITypeBinding voidType = ast.resolveWellKnownType("void"); GeneratedMethodBinding binding = new GeneratedMethodBinding("init", 0, voidType, clazz, true, false, true); Types.addBinding(constructor, binding); Types.addBinding(constructor.getReturnType2(), voidType); SimpleName name = ast.newSimpleName("init"); Types.addBinding(name, binding); constructor.setName(name); constructor.setBody(ast.newBlock()); if (!invocationArguments.isEmpty()) { addArguments(invocationArguments, ast, clazz, constructor, binding); } addInnerParameters(constructor, binding, innerFields, ast, true); members.add(constructor); Symbols.scanAST(constructor); defaultConstructor = binding; assert constructor.parameters().size() == defaultConstructor.getParameterTypes().length; } assert defaultConstructor != null; return defaultConstructor; }
From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java
License:Open Source License
/** * Add a method stub, the body of which throws an assertion error, to a type. */// ww w.j a v a 2s .com @SuppressWarnings("unchecked") private void generateMethodStub(AST ast, ITypeBinding scope, List<BodyDeclaration> scopeBody, IMethodBinding method, Type returnType) { MethodDeclaration decl = ast.newMethodDeclaration(); decl.setName(ast.newSimpleName(method.getName())); // Return type decl.setReturnType2(returnType); // Generic type for (ITypeBinding typeParamBinding : method.getTypeParameters()) { TypeParameter typeParam = ast.newTypeParameter(); typeParam.setName(ast.newSimpleName(typeParamBinding.getName())); for (ITypeBinding typeBound : typeParamBinding.getTypeBounds()) { typeParam.typeBounds().add(createType(ast, scope, typeBound)); } decl.typeParameters().add(typeParam); } // Parameters int paramCount = 0; for (ITypeBinding paramBinding : method.getParameterTypes()) { SingleVariableDeclaration var = ast.newSingleVariableDeclaration(); // Binding doesn't track original parameter name; generate new parameter names. String paramName = "arg" + (paramCount++); var.setName(ast.newSimpleName(paramName)); var.setType(createType(ast, scope, paramBinding)); decl.parameters().add(var); } // Modifiers int modifiers = method.getModifiers(); // Always make the new method public. Even if this method overrides a // protected method, it might also need to implement an interface. decl.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD)); if (Modifier.isStrictfp(modifiers)) { decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD)); } if (Modifier.isSynchronized(modifiers)) { decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD)); } // Body Block block = ast.newBlock(); decl.setBody(block); addAssertionError(block); // Add to type scopeBody.add(decl); generatedMethods.add(decl); }