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

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

Introduction

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

Prototype

public TypeParameter newTypeParameter() 

Source Link

Document

Creates and returns a new unparented type parameter type node with an unspecified type variable name and an empty list of type bounds.

Usage

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);/*  w w  w.  ja v  a  2s.  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: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.
 *//*from w  ww.j  av  a 2s  .  c o  m*/
@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);
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.InterfaceGenerator.java

License:Apache License

/**
 * Generate the Generics for this Interface.
 * // w ww . jav a  2 s  . c o m
 * @param clazz
 *            the UML class
 * @param ast
 *            the JDT Java AST
 * @param td
 *            TypeDeclaration JDT
 */
@SuppressWarnings("unchecked")
public void generateClassTemplateParams(Classifier clazz, AST ast, TypeDeclaration td) {
    TemplateSignature templateSignature = clazz.getOwnedTemplateSignature();
    if (templateSignature != null) {
        EList<TemplateParameter> templateParameters = templateSignature.getParameters();
        for (TemplateParameter templateParameter : templateParameters) {
            Classifier classifier = (Classifier) templateParameter.getOwnedParameteredElement();
            String typeName = classifier.getLabel();
            TypeParameter typeParameter = ast.newTypeParameter();
            typeParameter.setName(ast.newSimpleName(typeName));
            td.typeParameters().add(typeParameter);
        }
    }
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.InterfaceGenerator.java

License:Apache License

/**
 * Generate the template parameter for the given method - Generic Method.
 * /*from w w w . jav  a  2 s. c  o  m*/
 * @param ast
 *            AST tree JDT
 * @param operation
 *            UML2 Operation
 * @param md
 *            MethodDeclaration JDT
 */
@SuppressWarnings("unchecked")
public void generateMethodTemplateParams(AST ast, Operation operation, MethodDeclaration md) {
    TemplateSignature templateSignature = operation.getOwnedTemplateSignature();
    if (templateSignature != null) {
        EList<TemplateParameter> templateParameters = templateSignature.getParameters();
        for (TemplateParameter templateParameter : templateParameters) {
            Classifier classifier = (Classifier) templateParameter.getOwnedParameteredElement();
            String typeName = classifier.getLabel();
            TypeParameter typeParameter = ast.newTypeParameter();
            typeParameter.setName(ast.newSimpleName(typeName));
            md.typeParameters().add(typeParameter);
        }
    }
}

From source file:de.dentrassi.varlink.generator.JdtGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
private void createImplFactory(final AST ast, final TypeDeclaration td) {

    final TypeDeclaration ftd = ast.newTypeDeclaration();
    td.bodyDeclarations().add(ftd);//  www  .  j  a  v  a2  s  . co m
    ftd.setName(ast.newSimpleName("Factory"));
    make(ftd, PUBLIC_KEYWORD, STATIC_KEYWORD);

    ftd.superInterfaceTypes().add(ast.newSimpleType(ast.newName("de.dentrassi.varlink.spi.Factory")));

    /*
     *
     * @Override public <T> T create(final VarlinkImpl varlink, final Class<T>
     * clazz, final Connection connection)
     */

    final MethodDeclaration md = ast.newMethodDeclaration();
    ftd.bodyDeclarations().add(md);
    md.setName(ast.newSimpleName("create"));
    md.setReturnType2(ast.newSimpleType(ast.newName("T")));
    make(md, PUBLIC_KEYWORD);
    addSimpleAnnotation(md, "Override");

    final TypeParameter tp = ast.newTypeParameter();
    tp.setName(ast.newSimpleName("T"));
    md.typeParameters().add(tp);

    final ParameterizedType clazz = ast.newParameterizedType(ast.newSimpleType(ast.newName("Class")));

    clazz.typeArguments().add(ast.newSimpleType(ast.newName("T")));

    createParameter(md, "de.dentrassi.varlink.internal.VarlinkImpl", "varlink", FINAL_KEYWORD);
    createParameter(md, clazz, "clazz", FINAL_KEYWORD);
    createParameter(md, "de.dentrassi.varlink.spi.Connection", "connection", FINAL_KEYWORD);

    final Block body = ast.newBlock();
    md.setBody(body);

    // return clazz.cast(new Impl(varlink,connection));

    final ReturnStatement ret = ast.newReturnStatement();
    body.statements().add(ret);

    final MethodInvocation cast = ast.newMethodInvocation();
    cast.setName(ast.newSimpleName("cast"));
    cast.setExpression(ast.newSimpleName("clazz"));

    ret.setExpression(cast);

    final ClassInstanceCreation newImpl = ast.newClassInstanceCreation();
    newImpl.setType(ast.newSimpleType(ast.newName(td.getName().getIdentifier())));
    cast.arguments().add(newImpl);

    newImpl.arguments().add(ast.newSimpleName("connection"));
    newImpl.arguments().add(ast.newSimpleName("varlink"));
}

From source file:nz.ac.massey.cs.care.refactoring.executers.IntroduceFactoryRefactoring.java

License:Open Source License

/**
 * Copies the constructor's parent type's type parameters, if any, as
 * method type parameters of the new static factory method. (Recall
 * that static methods can't refer to type arguments of the enclosing
 * class, since they have no instance to serve as a context.)<br>
 * Makes sure to copy the bounds from the owning type, to ensure that the
 * return type of the factory method satisfies the bounds of the type
 * being instantiated.<br>//ww w  . ja  v a 2s  .co  m
 * E.g., for ctor Foo() in the type Foo<T extends Number>, be sure that
 * the factory method is declared as<br>
 * <code>static <T extends Number> Foo<T> createFoo()</code><br>
 * and not simply<br>
 * <code>static <T> Foo<T> createFoo()</code><br>
 * or the compiler will bark.
 * @param ast utility object needed to create ASTNode's for the new method
 * @param newMethod the method onto which to copy the type parameters
 */
private void copyTypeParameters(AST ast, MethodDeclaration newMethod) {
    ITypeBinding[] ctorOwnerTypeParms = fCtorBinding.getDeclaringClass().getTypeParameters();
    List<TypeParameter> factoryMethodTypeParms = newMethod.typeParameters();
    for (int i = 0; i < ctorOwnerTypeParms.length; i++) {
        TypeParameter newParm = ast.newTypeParameter();
        ITypeBinding[] parmTypeBounds = ctorOwnerTypeParms[i].getTypeBounds();
        List<Type> newParmBounds = newParm.typeBounds();

        newParm.setName(ast.newSimpleName(ctorOwnerTypeParms[i].getName()));
        for (int b = 0; b < parmTypeBounds.length; b++) {
            if (parmTypeBounds[b].isClass() && parmTypeBounds[b].getSuperclass() == null)
                continue;

            Type newBound = fImportRewriter.addImport(parmTypeBounds[b], ast);

            newParmBounds.add(newBound);
        }
        factoryMethodTypeParms.add(newParm);
    }
}

From source file:org.decojer.cavaj.transformers.TrOutline.java

License:Open Source License

/**
 * Decompile Type Parameters./*from w ww . j ava2s. c o  m*/
 *
 * @param typeParams
 *            Type Parameters
 * @param typeParameters
 *            AST Type Parameters
 * @param contextT
 *            Type Declaration
 */
private static void decompileTypeParams(@Nonnull final T[] typeParams, final List<TypeParameter> typeParameters,
        @Nonnull final T contextT) {
    final AST ast = contextT.getCu().getAst();
    for (final T typeParam : typeParams) {
        final TypeParameter typeParameter = ast.newTypeParameter();
        typeParameter.setName(newSimpleName(typeParam.getName(), ast));
        final List<IExtendedModifier> modifiers = typeParameter.modifiers();
        assert modifiers != null;
        Annotations.decompileAnnotations(typeParam, modifiers, contextT);
        final T superT = typeParam.getSuperT();
        if (superT != null && !superT.isObject()) {
            typeParameter.typeBounds().add(newType(superT, contextT));
        }
        for (final T interfaceT : typeParam.getInterfaceTs()) {
            assert interfaceT != null;
            typeParameter.typeBounds().add(newType(interfaceT, contextT));
        }
        typeParameters.add(typeParameter);
    }
}

From source file:org.eclipse.objectteams.otdt.internal.ui.text.correction.AddMethodMappingSignaturesProposal.java

License:Open Source License

@SuppressWarnings("unchecked")
private void convertTypeParameters(final AST ast, IMethodBinding roleMethod, MethodSpec destMethodSpec) {
    for (ITypeBinding typeParameter : roleMethod.getTypeParameters()) {
        TypeParameter newTypeParameter = ast.newTypeParameter();
        newTypeParameter.setName(ast.newSimpleName(typeParameter.getName()));
        for (ITypeBinding typeBound : typeParameter.getTypeBounds())
            newTypeParameter.typeBounds().add(convertType(ast, typeBound));
        destMethodSpec.typeParameters().add(newTypeParameter);
    }//  w w w  .ja  v  a  2  s .  com
}

From source file:org.eclipse.objectteams.otdt.internal.ui.text.correction.MappingProposalSubProcessor.java

License:Open Source License

@SuppressWarnings("unchecked") // handling AST-Lists 
public static ICommandAccess addTypeParameterToCallin(ICompilationUnit cu, ASTNode selectedNode,
        TypeDeclaration enclosingType) {
    final String TYPE_VAR_NAME = "E"; //$NON-NLS-1$

    if (selectedNode instanceof Name) {
        MethodSpec roleSpec = (MethodSpec) ASTNodes.getParent(selectedNode, ASTNode.METHOD_SPEC);
        ASTNode oldType = selectedNode.getParent();

        // find the role method to perform the same change on it, too.
        IMethodBinding roleMethod = roleSpec.resolveBinding();
        MethodDeclaration roleMethodDecl = null;
        for (MethodDeclaration method : enclosingType.getMethods()) {
            if (method.resolveBinding() == roleMethod) {
                Type returnType = method.getReturnType2();
                if (returnType == null)
                    break;
                if (returnType.isSimpleType()) {
                    Name typeName = ((SimpleType) returnType).getName();
                    if ("void".equals(typeName.getFullyQualifiedName())) //$NON-NLS-1$
                        break;
                }/*from  w  ww .ja  v a2  s  .c o  m*/
                roleMethodDecl = method;
                break;
            }
        }

        AST ast = enclosingType.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        TextEditGroup group = new TextEditGroup("adding parameter"); //$NON-NLS-1$
        // create type parameter <E extends OriginalType>
        TypeParameter typeParameter = ast.newTypeParameter();
        typeParameter.setName(ast.newSimpleName(TYPE_VAR_NAME));
        typeParameter.typeBounds().add(ASTNode.copySubtree(ast, oldType));
        // add type parameter to role method spec
        rewrite.getListRewrite(roleSpec, MethodSpec.TYPE_PARAMETERS_PROPERTY).insertFirst(typeParameter, group);
        // change return type to type variable
        rewrite.set(roleSpec, MethodSpec.RETURN_TYPE2_PROPERTY,
                ast.newSimpleType(ast.newSimpleName(TYPE_VAR_NAME)), group);

        // the same changes also against the method declaration:
        if (roleMethodDecl != null) {
            rewrite.getListRewrite(roleMethodDecl, MethodDeclaration.TYPE_PARAMETERS_PROPERTY)
                    .insertFirst(ASTNode.copySubtree(ast, typeParameter), group);
            rewrite.set(roleMethodDecl, MethodDeclaration.RETURN_TYPE2_PROPERTY,
                    ast.newSimpleType(ast.newSimpleName(TYPE_VAR_NAME)), group);
        }

        return new ASTRewriteCorrectionProposal(CorrectionMessages.OTQuickfix_addtypeparametertocallin_label,
                cu, rewrite, 10000, // TODO(SH)
                JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
    }
    return null;
}

From source file:org.eclipse.objectteams.otdt.ui.tests.dom.rewrite.ASTRewritingModifyingCallinMappingDeclarationTest.java

License:Open Source License

/**
 * add signatures, 1 base method, type parameter
 *//*from   www  .ja  v  a2  s  .c  o  m*/
public void test0013() throws MalformedTreeException, JavaModelException, BadLocationException {
    IPackageFragment pack1 = sourceFolder.createPackageFragment("test0013", false, null);
    StringBuffer buf = new StringBuffer();

    buf.append("package test0013;\n");
    buf.append("public team class Team {\n");
    buf.append("   public class Role playedBy Base {\n");
    buf.append("        roleMethod <- before baseMethod;\n");
    buf.append("    }\n");
    buf.append("}\n");

    ICompilationUnit cu = pack1.createCompilationUnit("Team.java", buf.toString(), false, null);

    CompilationUnit astRoot = createCU(cu, false);
    AST ast = astRoot.getAST();

    astRoot.recordModifications();

    TypeDeclaration aTeam = (TypeDeclaration) astRoot.types().get(0);
    RoleTypeDeclaration role = (RoleTypeDeclaration) aTeam.bodyDeclarations().get(0);
    CallinMappingDeclaration callin = (CallinMappingDeclaration) role.bodyDeclarations().get(0);
    MethodSpec roleMethodSpec = (MethodSpec) callin.getRoleMappingElement();
    TypeParameter typeParameter = ast.newTypeParameter();
    typeParameter.setName(ast.newSimpleName("E"));
    roleMethodSpec.typeParameters().add(typeParameter);
    addSignature(ast, roleMethodSpec, "E", new String[] { "String" }, new String[] { "s1" });
    addSignature(ast, (MethodSpec) callin.getBaseMappingElements().get(0), "E", new String[] { "String" },
            new String[] { "s2" });

    String preview = evaluateRewrite(cu.getSource(), astRoot);

    buf = new StringBuffer();
    buf.append("package test0013;\n");
    buf.append("public team class Team {\n");
    buf.append("   public class Role playedBy Base {\n");
    buf.append("        <E> E roleMethod(String s1) <- before E baseMethod(String s2);\n");
    buf.append("    }\n");
    buf.append("}\n");

    assertEqualString(preview, buf.toString());
}