Example usage for org.eclipse.jdt.core.dom AST newPrimitiveType

List of usage examples for org.eclipse.jdt.core.dom AST newPrimitiveType

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom AST newPrimitiveType.

Prototype

public PrimitiveType newPrimitiveType(PrimitiveType.Code typeCode) 

Source Link

Document

Creates and returns a new unparented primitive type node with the given type code.

Usage

From source file:ac.at.tuwien.dsg.uml.statemachine.export.transformation.engines.AbstractStateMachineTestStrategy.java

License:Open Source License

/**
 * Creates abstract methods which return true   
 * @param javadoc/*from   ww w  . j  ava 2s . c  o m*/
 * @param methodName
 * @param ast
 * @return an AST method declaration
 */
protected MethodDeclaration createAbstractAssertMethod(Javadoc javadoc, String methodName, AST ast) {

    MethodDeclaration method = ast.newMethodDeclaration();

    method.setJavadoc(javadoc);

    method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    method.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD));
    method.setName(ast.newSimpleName(methodName)); //escape all spaces in state name

    /**
     * add to method generic arguments  Object... arguments
     */
    SingleVariableDeclaration param = ast.newSingleVariableDeclaration();
    param.setName(ast.newSimpleName("arguments"));
    param.setType(ast.newSimpleType(ast.newName("Object")));
    param.setStructuralProperty(SingleVariableDeclaration.VARARGS_PROPERTY, true);

    method.setReturnType2(ast.newPrimitiveType(PrimitiveType.BOOLEAN));

    return method;
}

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.  j a v a2  s . co 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 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 w  w w .j a va  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 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: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  a v a2  s  .  c o  m*/
    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.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

/**
 * Creates a {@link Type} from the given name, owned by the given AST.
 *//*w  w w.ja v  a 2  s. c o  m*/
protected Type getTypeFromString(AST ast, String name) {
    if (name == null) {
        return ast.newPrimitiveType(PrimitiveType.VOID);
    }
    PrimitiveType.Code primitiveTypeCode = PrimitiveType.toCode(name);
    if (primitiveTypeCode != null) {
        return ast.newPrimitiveType(primitiveTypeCode);
    }

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_STATEMENTS);
    parser.setSource((name + " a;").toCharArray());

    Block block = (Block) parser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType());
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Creates a new appropriate {@link Type} from the given <code>value</code>.
 * <p>//from   w ww.  ja  v a  2 s.c o  m
 * Note that if <code>value</code> is <code>null</code> returns
 * {@link PrimitiveType#VOID}.
 * 
 * @param ast
 *            {@link AST} of the {@link ASTNode ASTElement} needing a new
 *            Type
 * @param value
 *            the name of the {@link Type} to be created.
 * @param canBePrimitiveType
 *            if <code>true</code> try to create a primitive from the
 *            given <code>value</code> if possible, otherwise create a new
 *            Type without checking primitives
 * @author Luiza
 * 
 * @flowerModelElementId _zVs8hZiOEd6aNMdNFvR5WQ
 */
public static Type getJavaTypeFromString(AST ast, String value, boolean canBePrimitiveType) {
    if (canBePrimitiveType) {
        PrimitiveType.Code primitiveTypeCode = null;
        if (value == null)
            primitiveTypeCode = PrimitiveType.VOID;
        else {
            primitiveTypeCode = PrimitiveType.toCode(value);
        }
        if (primitiveTypeCode != null)
            return ast.newPrimitiveType(primitiveTypeCode);
    }

    // not a primitive
    ASTParser statementParser = ASTParser.newParser(AST.JLS3);
    statementParser.setKind(ASTParser.K_STATEMENTS);
    statementParser.setSource((value + " a;").toCharArray()); // try to parse a variable declaration

    Block block = (Block) statementParser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType()); // detach the type from the parent node
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Create a new Type for the given type binding.  If the binding
 * represents a parameterized type reference, the returned Type
 * is a ParameterizedType with the same type parameters.  Otherwise
 * the returned Type is a SimpleType.//  w ww .  j a va2s .  com
 */
@SuppressWarnings("unchecked")
private Type createType(AST ast, ITypeBinding scope, ITypeBinding type) {
    Type newType;
    if (type.isArray()) {
        newType = ast.newArrayType(createType(ast, scope, type.getElementType()), type.getDimensions());
    } else if (type.isPrimitive()) {
        newType = ast.newPrimitiveType(PrimitiveType.toCode(type.getName()));
    } else if (type.isWildcardType()) {
        WildcardType wildType = ast.newWildcardType();
        ITypeBinding bound = type.getBound();
        if (bound != null) {
            wildType.setBound(createType(ast, scope, bound), type.isUpperbound());
        }
        newType = wildType;
    } else if (!type.isParameterizedType()) {
        String name = inScope(type, scope) ? type.getName() : type.getQualifiedName();
        newType = ast.newSimpleType(ast.newName(name));
    } else {
        ITypeBinding erasure = type.getErasure();
        String name = inScope(type, scope) ? erasure.getName() : erasure.getQualifiedName();
        Type rawType = ast.newSimpleType(ast.newName(name));
        ParameterizedType paramType = ast.newParameterizedType(rawType);
        ITypeBinding[] typeArgs = type.getTypeArguments();
        for (ITypeBinding param : typeArgs) {
            paramType.typeArguments().add(createType(ast, scope, param));
        }
        newType = paramType;
    }
    generatedTypes.put(newType, type);
    return newType;
}

From source file:com.google.devtools.j2cpp.translate.DestructorGenerator.java

License:Open Source License

private MethodDeclaration buildFinalizeMethod(AST ast, ITypeBinding declaringClass,
        List<IVariableBinding> fields) {
    ITypeBinding voidType = Types.mapTypeName("void");
    GeneratedMethodBinding binding = new GeneratedMethodBinding(destructorName, Modifier.PUBLIC, voidType,
            declaringClass, false, false, true);
    MethodDeclaration method = ast.newMethodDeclaration();
    Types.addBinding(method, binding);
    method.setName(ast.newSimpleName(destructorName));
    Types.addBinding(method.getName(), binding);
    @SuppressWarnings("unchecked")
    List<Modifier> modifiers = method.modifiers();
    modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    method.setBody(ast.newBlock());/*from w  ww .ja v a2 s  .  co  m*/
    addReleaseStatements(method, fields);
    Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
    Types.addBinding(returnType, ast.resolveWellKnownType("void"));
    method.setReturnType2(returnType);
    return method;
}

From source file:com.google.devtools.j2cpp.translate.InitializationNormalizer.java

License:Open Source License

@SuppressWarnings("unchecked")
private void addMethod(String name, int modifiers, ITypeBinding type, List<Statement> initStatements,
        List<BodyDeclaration> members, AST ast, boolean isConstructor) {
    Block body = ast.newBlock();//from w  w w.  j  a  v a 2  s.co  m
    List<Statement> stmts = body.statements(); // safe by definition
    for (Statement stmt : initStatements) {
        Statement newStmt = NodeCopier.copySubtree(ast, stmt);
        stmts.add(newStmt);
    }
    MethodDeclaration method = ast.newMethodDeclaration();
    GeneratedMethodBinding binding = new GeneratedMethodBinding(name, modifiers, null, type, isConstructor,
            false, true);
    Types.addBinding(method, binding);
    Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
    Types.addBinding(returnType, ast.resolveWellKnownType("void"));
    method.setReturnType2(returnType);
    method.setBody(body);
    method.setConstructor(isConstructor);
    method.modifiers().addAll(ast.newModifiers(modifiers));
    SimpleName nameNode = NameTable.unsafeSimpleName(name, ast);
    Types.addBinding(nameNode, binding);
    method.setName(nameNode);
    members.add(method);
    Symbols.resolve(method, binding);
}

From source file:com.google.devtools.j2cpp.translate.Rewriter.java

License:Open Source License

/**
 * Add a static write accessor method for a specified variable.
 *//*from  w w w  .j  av a  2  s.co  m*/
private MethodDeclaration makeStaticWriter(VariableDeclarationFragment var, String paramName, Type type,
        int modifiers) {
    AST ast = var.getAST();
    String varName = var.getName().getIdentifier();
    IVariableBinding varBinding = Types.getVariableBinding(var);

    Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
    Types.addBinding(returnType, ast.resolveWellKnownType("void"));
    String methodName = "set" + NameTable.capitalize(varName);
    MethodDeclaration accessor = createBlankAccessor(var, methodName, modifiers, returnType);
    GeneratedMethodBinding binding = new GeneratedMethodBinding(accessor, varBinding.getDeclaringClass(),
            false);
    Types.addBinding(accessor, binding);
    Types.addBinding(accessor.getName(), binding);

    SingleVariableDeclaration param = ast.newSingleVariableDeclaration();
    param.setName(ast.newSimpleName(paramName));
    Type paramType = NodeCopier.copySubtree(ast, type);
    param.setType(paramType);
    Types.addBinding(paramType, type.resolveBinding());
    @SuppressWarnings("unchecked")
    List<SingleVariableDeclaration> parameters = accessor.parameters(); // safe by definition
    GeneratedVariableBinding paramBinding = new GeneratedVariableBinding(paramName, 0, type.resolveBinding(),
            false, true, varBinding.getDeclaringClass(), binding);
    Types.addBinding(param, paramBinding);
    Types.addBinding(param.getName(), paramBinding);
    parameters.add(param);
    binding.addParameter(paramBinding);

    Assignment assign = ast.newAssignment();
    SimpleName sn = ast.newSimpleName(NameTable.getName(varBinding));
    assign.setLeftHandSide(sn);
    Types.addBinding(sn, varBinding);
    assign.setRightHandSide(NodeCopier.copySubtree(ast, param.getName()));
    Types.addBinding(assign, varBinding.getType());
    ExpressionStatement assignStmt = ast.newExpressionStatement(assign);

    @SuppressWarnings("unchecked")
    List<Statement> stmts = accessor.getBody().statements(); // safe by definition
    stmts.add(assignStmt);
    Symbols.scanAST(accessor);
    return accessor;
}