Java Code Examples for javax.lang.model.type.TypeKind

The following are top voted examples for showing how to use javax.lang.model.type.TypeKind. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: inspector   File: InspectorFactoryProcessor.java   View source code 6 votes vote down vote up
private boolean searchInterfacesAncestry(TypeMirror rootIface, TypeMirror target) {
  TypeElement rootIfaceElement = (TypeElement) typeUtils.asElement(rootIface);
  // check if it implements valid interfaces
  for (TypeMirror iface : rootIfaceElement.getInterfaces()) {
    TypeElement ifaceElement = (TypeElement) typeUtils.asElement(rootIface);
    while (iface.getKind() != TypeKind.NONE) {
      if (typeUtils.isSameType(iface, target)) {
        return true;
      }
      // go up
      if (searchInterfacesAncestry(iface, target)) {
        return true;
      }
      // then move on
      iface = ifaceElement.getSuperclass();
    }
  }
  return false;
}
 
Example 2
Project: incubator-netbeans   File: CheckReturnValueHint.java   View source code 6 votes vote down vote up
@TriggerPattern("$method($params$);")
public static ErrorDescription hint(HintContext ctx) {
    Element invoked = ctx.getInfo().getTrees().getElement(new TreePath(ctx.getPath(), ((ExpressionStatementTree) ctx.getPath().getLeaf()).getExpression()));

    if (invoked == null || invoked.getKind() != ElementKind.METHOD || ((ExecutableElement) invoked).getReturnType().getKind() == TypeKind.VOID) return null;

    boolean found = false;

    for (AnnotationMirror am : invoked.getAnnotationMirrors()) {
        String simpleName = am.getAnnotationType().asElement().getSimpleName().toString();

        if ("CheckReturnValue".equals(simpleName)) {
            found = true;
            break;
        }
    }

    if (!found && !checkReturnValueForJDKMethods((ExecutableElement) invoked)) return null;

    String displayName = NbBundle.getMessage(CheckReturnValueHint.class, "ERR_org.netbeans.modules.java.hints.bugs.CheckReturnValueHint");
    
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName);
}
 
Example 3
Project: remoter   File: ParcelerParamBuilder.java   View source code 6 votes vote down vote up
@Override
public void readOutResultsFromStub(VariableElement param, ParamType paramType, String paramName, MethodSpec.Builder methodBuilder) {
    if (param.asType().getKind() == TypeKind.ARRAY) {
        methodBuilder.beginControlFlow("if (" + paramName + " != null)");
        methodBuilder.addStatement("reply.writeInt(" + paramName + ".length)");
        methodBuilder.beginControlFlow("for($T item:" + paramName + " )", ((ArrayType) param.asType()).getComponentType());
        methodBuilder.addStatement("Class pClass = getParcelerClass(item)");
        methodBuilder.addStatement("reply.writeString(pClass.getName())");
        methodBuilder.addStatement("org.parceler.Parcels.wrap(pClass, item).writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE)");
        methodBuilder.endControlFlow();
        methodBuilder.endControlFlow();
        methodBuilder.beginControlFlow("else");
        methodBuilder.addStatement("reply.writeInt(-1)");
        methodBuilder.endControlFlow();
    }
}
 
Example 4
Project: react4j   File: ProcessorUtil.java   View source code 6 votes vote down vote up
private static void enumerateFields( @Nonnull final TypeElement scope,
                                     @Nonnull final Types typeUtils,
                                     @Nonnull final TypeElement element,
                                     @Nonnull final Map<String, TypeMirror> fields )
{
  final TypeMirror superclass = element.getSuperclass();
  if ( TypeKind.NONE != superclass.getKind() )
  {
    enumerateFields( scope, typeUtils, (TypeElement) ( (DeclaredType) superclass ).asElement(), fields );
  }
  for ( final Element member : element.getEnclosedElements() )
  {
    if ( member.getKind() == ElementKind.FIELD )
    {
      final TypeMirror fieldType = typeUtils.asMemberOf( (DeclaredType) scope.asType(), member );
      fields.put( member.getSimpleName().toString(), fieldType );
    }
  }
}
 
Example 5
Project: incubator-netbeans   File: JUnit3TestGenerator.java   View source code 6 votes vote down vote up
/**
 */
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            maker.Modifiers(createModifierSet(PUBLIC)),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
 
Example 6
Project: incubator-netbeans   File: MemberAdditionTest.java   View source code 6 votes vote down vote up
public Void visitClass(ClassTree node, Boolean p) {
    TypeElement te = (TypeElement)model.getElement(node);
    if (te != null) {
        List<Tree> members = new ArrayList<Tree>();
        for(Tree m : node.getMembers())
            members.add(m);
        members.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", make.PrimitiveType(TypeKind.INT), null));
        ClassTree decl = make.Class(node.getModifiers(), node.getSimpleName(), node.getTypeParameters(), node.getExtendsClause(), (List<ExpressionTree>)node.getImplementsClause(), members);
        model.setElement(decl, te);
        model.setType(decl, model.getType(node));
        model.setPos(decl, model.getPos(node));
        copy.rewrite(node, decl);
    }
    
    return null;
}
 
Example 7
Project: incubator-netbeans   File: ConvertToLambdaPreconditionChecker.java   View source code 6 votes vote down vote up
private void verifyTargetType() {

        TypeMirror expectedType = findExpectedType(pathToNewClassTree);
        if (!Utilities.isValidType(expectedType)) {
            foundErroneousTargetType = true;
            return;
        }

        TypeMirror erasedExpectedType = info.getTypes().erasure(expectedType);

        TreePath pathForClassIdentifier = new TreePath(pathToNewClassTree, newClassTree.getIdentifier());
        TypeMirror lambdaType = info.getTrees().getTypeMirror(pathForClassIdentifier);
        lambdaType = info.getTypes().erasure(lambdaType);

        foundAssignmentToSupertype = !info.getTypes().isSameType(erasedExpectedType, lambdaType);
        
        if (erasedExpectedType.getKind() == TypeKind.DECLARED) {
            TypeElement te = (TypeElement)((DeclaredType)erasedExpectedType).asElement();
            TypeMirror tt = (DeclaredType)te.asType();
            if (tt.getKind() == TypeKind.DECLARED && !((DeclaredType)tt).getTypeArguments().isEmpty()) {
                foundAssignmentToRawType =  info.getTypes().isSameType(erasedExpectedType, expectedType);
            }
        }
    }
 
Example 8
Project: remoter   File: ParcellableParamBuilder.java   View source code 6 votes vote down vote up
@Override
public void writeParamsToProxy(VariableElement param, ParamType paramType, MethodSpec.Builder methodBuilder) {
    if (param.asType().getKind() == TypeKind.ARRAY) {
        if (paramType == ParamType.OUT) {
            writeArrayOutParamsToProxy(param, methodBuilder);
        } else {
            methodBuilder.addStatement("data.writeTypedArray(" + param.getSimpleName() + ", 0)");
        }
    } else {
        if (paramType != ParamType.OUT) {
            methodBuilder.beginControlFlow("if (" + param.getSimpleName() + " != null)");
            methodBuilder.addStatement("data.writeInt(1)");
            methodBuilder.addStatement(param.getSimpleName() + ".writeToParcel(data, 0)");
            methodBuilder.endControlFlow();
            methodBuilder.beginControlFlow("else");
            methodBuilder.addStatement("data.writeInt(0)");
            methodBuilder.endControlFlow();
        }
    }
}
 
Example 9
Project: openjdk-jdk10   File: ApiExtraction.java   View source code 6 votes vote down vote up
private static PubType getDummyInner1() {
    PubMethod init = new PubMethod(setOf(),
                                   emptyList(),
                                   new PrimitiveTypeDesc(TypeKind.VOID),
                                   "<init>",
                                   emptyList(),
                                   emptyList());

    PubMethod run = new PubMethod(setOf(PUBLIC),
                                  emptyList(),
                                  new PrimitiveTypeDesc(TypeKind.VOID),
                                  "run",
                                  emptyList(),
                                  emptyList());

    PubVar field = new PubVar(setOf(PROTECTED),
                              new PrimitiveTypeDesc(TypeKind.INT),
                              "field",
                              null);

    return new PubType(setOf(STATIC),
                       "TestClass$DummyInner1",
                       new PubApi(emptyList(),
                                  asList(field),
                                  asList(init, run)));
}
 
Example 10
Project: openjdk-jdk10   File: TestTypeKind.java   View source code 6 votes vote down vote up
static int testIsPrimitive() {
    int failures = 0;
    // The eight primitive types
    Set<TypeKind> primitives = EnumSet.of(BOOLEAN,  // 1
                                          BYTE,     // 2
                                          CHAR,     // 3
                                          DOUBLE,   // 4
                                          FLOAT,    // 5
                                          INT,      // 6
                                          LONG,     // 7
                                          SHORT);   // 8

    for(TypeKind tk : TypeKind.values()) {
        boolean primitiveness;
        if ((primitiveness=tk.isPrimitive()) != primitives.contains(tk) ) {
            failures++;
            System.err.println("Unexpected isPrimitive value " + primitiveness +
                               "for " + tk);
        }
    }
    return failures;
}
 
Example 11
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 6 votes vote down vote up
private static List<? extends TypeMirror> computeConditionalExpression(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ConditionalExpressionTree cet = (ConditionalExpressionTree) parent.getLeaf();
    
    if (cet.getCondition() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.BOOLEAN));
    }
    
    if (cet.getTrueExpression() == error || cet.getFalseExpression() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return resolveType(types, info, parent.getParentPath(), cet, offset, null, null);
    }
    
    return null;
}
 
Example 12
Project: GitHub   File: TypeHierarchyCollector.java   View source code 6 votes vote down vote up
private void collectInterfacesMirrors(TypeMirror typeMirror, TypevarContext context) {
  if (typeMirror.getKind() != TypeKind.DECLARED) {
    return;
  }
  DeclaredType declaredType = toDeclaredType(typeMirror);
  TypeElement e = toTypeElement(declaredType);

  if (e.getKind().isInterface()) {
    implementedInterfaces.add(e);
    String stringified = stringify(declaredType, context);
    TypevarContext nestedContext = new TypevarContext(e, stringified);
    implementedInterfaceNames.add(stringified);
    for (TypeMirror m : e.getInterfaces()) {
      collectInterfacesMirrors(m, nestedContext);
    }
  }
}
 
Example 13
Project: openjdk-jdk10   File: TypeMonikerFactory.java   View source code 6 votes vote down vote up
public static TypeMoniker getTypeMoniker(TypeMirror typeMirror) {
    if (typeMirror == null)
        throw new NullPointerException();

    if (typeMirror.getKind().isPrimitive())
        return new PrimitiveTypeMoniker((PrimitiveType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.ARRAY))
        return new ArrayTypeMoniker((ArrayType) typeMirror);
    else if (typeMirror.getKind().equals(TypeKind.DECLARED))
        return new DeclaredTypeMoniker((DeclaredType) typeMirror);
    return getTypeMoniker(typeMirror.toString());
}
 
Example 14
Project: incubator-netbeans   File: InvertBooleanRefactoringPlugin.java   View source code 6 votes vote down vote up
/**
 * Copy from JavaRefactoringPlugin.
 */
private Problem isElementAvail(TreePathHandle e, CompilationInfo info) {
    if (e==null) {
        //element is null or is not valid.
        return new Problem(true, NbBundle.getMessage(FindVisitor.class, "DSC_ElNotAvail")); // NOI18N
    } else {
        Element el = e.resolveElement(info);
        String elName = el != null ? el.getSimpleName().toString() : null;
        if (el == null || el.asType().getKind() == TypeKind.ERROR || "<error>".equals(elName)) { // NOI18N
            return new Problem(true, NbBundle.getMessage(FindVisitor.class, "DSC_ElementNotResolved"));
        }
        
        if ("this".equals(elName) || "super".equals(elName)) { // NOI18N
            return new Problem(true, NbBundle.getMessage(FindVisitor.class, "ERR_CannotRefactorThis", el.getSimpleName()));
        }
        
        // element is still available
        return null;
    }
}
 
Example 15
Project: incubator-netbeans   File: SpringXMLConfigCompletionItem.java   View source code 6 votes vote down vote up
@Override
public StringBuilder visitWildcard(WildcardType t, Boolean p) {
    DEFAULT_VALUE.append("?"); //NOI18N
    TypeMirror bound = t.getSuperBound();
    if (bound == null) {
        bound = t.getExtendsBound();
        if (bound != null) {
            DEFAULT_VALUE.append(" extends "); //NOI18N
            if (bound.getKind() == TypeKind.WILDCARD)
                bound = ((WildcardType)bound).getSuperBound();
            visit(bound, p);
        } else {
            bound = SourceUtils.getBound(t);
            if (bound != null && (bound.getKind() != TypeKind.DECLARED || !((TypeElement)((DeclaredType)bound).asElement()).getQualifiedName().contentEquals("java.lang.Object"))) { //NOI18N
                DEFAULT_VALUE.append(" extends "); //NOI18N
                visit(bound, p);
            }
        }
    } else {
        DEFAULT_VALUE.append(" super "); //NOI18N
        visit(bound, p);
    }
    return DEFAULT_VALUE;
}
 
Example 16
Project: react4j   File: ProcessorUtil.java   View source code 6 votes vote down vote up
private static void enumerateFieldElements( @Nonnull final TypeElement element,
                                            @Nonnull final Map<String, VariableElement> fields )
{
  final TypeMirror superclass = element.getSuperclass();
  if ( TypeKind.NONE != superclass.getKind() )
  {
    enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields );
  }
  for ( final Element member : element.getEnclosedElements() )
  {
    if ( member.getKind() == ElementKind.FIELD )
    {
      fields.put( member.getSimpleName().toString(), (VariableElement) member );
    }
  }
}
 
Example 17
Project: incubator-netbeans   File: GeneratorUtilities.java   View source code 6 votes vote down vote up
private static String[] correspondingGSNames(Tree member) {
    if (isSetter(member)) {
        String name = name(member);
        VariableTree param = ((MethodTree)member).getParameters().get(0);
        if (param.getType().getKind() == Tree.Kind.PRIMITIVE_TYPE && ((PrimitiveTypeTree)param.getType()).getPrimitiveTypeKind() == TypeKind.BOOLEAN) {
            return new String[] {'g' + name.substring(1), "is" + name.substring(3)};
        }
        return new String[] {'g' + name.substring(1)};
    }
    if (isGetter(member)) {
        return new String[] {'s' + name(member).substring(1)};
    }
    if (isBooleanGetter(member)) {
        return new String[] {"set" + name(member).substring(2)}; //NOI18N
    }
    return null;
}
 
Example 18
Project: incubator-netbeans   File: ElementUtilities.java   View source code 6 votes vote down vote up
/**
 * Checks whether 'e' contains error or is missing. If the passed element is null
 * it's assumed the element could not be resolved and this method returns true. Otherwise,
 * the element's type kind is checked against error constants and finally the erroneous
 * state of the element is checked. 
 * 
 * @param e Element to check or {@code null}
 * @return true, if the element is missing (is {@code null}) or contains errors.
 */
public boolean isErroneous(@NullAllowed Element e) {
    if (e == null) {
        return true;
    }
    if (e.getKind() == ElementKind.MODULE && ((Symbol)e).kind == Kinds.Kind.ERR) {
        return true;
    }
    final TypeMirror type = e.asType();
    if (type == null) {
        return false;
    }
    if (type.getKind() == TypeKind.ERROR || type.getKind() == TypeKind.OTHER) {
        return true;
    }
    if (type instanceof Type) {
        if (((Type)type).isErroneous()) {
            return true;
        }
    }
    return false;
}
 
Example 19
Project: incubator-netbeans   File: ExpressionVisitor.java   View source code 6 votes vote down vote up
/**
 * In the numeric case, accept both primitives and boxed types. Each boxed type is
 * convertible to the appropriate primitive, and all primitive types are assignable to double.
 */
private boolean isCorrectType(ExpressionTree t) {
    if (currentMatches) {
        return true;
    }
    TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());
    switch (tm.getKind()) {
        case BOOLEAN:
            return logical;
        case BYTE:
        case DOUBLE:
        case FLOAT:
        case INT:
        case LONG:
        case SHORT:
            return !logical;
        case DECLARED:
            // can be converted to primitive
            return info.getTypes().isAssignable(tm, info.getTypes().getPrimitiveType(TypeKind.DOUBLE));
        default:
            return false;
    }
}
 
Example 20
Project: incubator-netbeans   File: EncapsulateFieldRefactoringPlugin.java   View source code 6 votes vote down vote up
public static ExecutableElement findMethod(CompilationInfo javac, TypeElement clazz, String name, List<? extends VariableElement> params, boolean includeSupertypes) {
    if (name == null || name.length() == 0) {
        return null;
    }

    TypeElement c = clazz;
    while (true) {
        for (Element elm : c.getEnclosedElements()) {
            if (ElementKind.METHOD == elm.getKind()) {
                ExecutableElement m = (ExecutableElement) elm;
                if (name.contentEquals(m.getSimpleName())
                        && compareParams(javac, params, m.getParameters())
                        && isAccessible(javac, clazz, m)) {
                    return m;
                }
            }
        }

        TypeMirror superType = c.getSuperclass();
        if (!includeSupertypes || superType.getKind() == TypeKind.NONE) {
            return null;
        }
        c = (TypeElement) ((DeclaredType) superType).asElement();
    }
}
 
Example 21
Project: incubator-netbeans   File: Constructor.java   View source code 6 votes vote down vote up
private TypeDeclaration typeToTypeDeclaration(TypeMirror tMirror){
    int dimension = 0;
    TypeMirror aType =  tMirror;
    ITypeDeclaration[] generics = null;
    if(tMirror.getKind() == TypeKind.ARRAY){
        for(;aType.getKind() == TypeKind.ARRAY; aType =  ((ArrayType)tMirror).getComponentType()) {
            dimension++;
        }
    }
    if(aType.getKind() == TypeKind.DECLARED){
        DeclaredType dType = (DeclaredType) aType;
        List<? extends TypeMirror> parameters = dType.getTypeArguments();
        if( parameters!=null && parameters.size()>0){
            generics = new ITypeDeclaration[parameters.size()];
            int i=0;
            for(TypeMirror gType: parameters){
                generics[i] = typeToTypeDeclaration(gType);
                i++;
            }
        }
    }
    return new TypeDeclaration(owner, generics, dimension);
}
 
Example 22
Project: incubator-netbeans   File: GetterSetterGenerator.java   View source code 6 votes vote down vote up
private void createGetterSetterLists(CompilationController cc, List<ElementHandle<? extends Element>> variables, List<? super TreePathHandle> handles, List<String> getters, List<String> setters, CodeStyle codestyle) {
    for (ElementHandle handle:variables) {
        final Element el = handle.resolve(cc);
        handles.add(TreePathHandle.create(el, cc));
        boolean isStatic = el.getModifiers().contains(Modifier.STATIC);
        if (type!=GeneratorUtils.GETTERS_ONLY) {
            setters.add(CodeStyleUtils.computeSetterName(el.getSimpleName(), isStatic, codestyle));
        } else {
            setters.add(null);
        }
        if (type!=GeneratorUtils.SETTERS_ONLY) {
            getters.add(CodeStyleUtils.computeGetterName(el.getSimpleName(), el.asType().getKind() == TypeKind.BOOLEAN, isStatic, codestyle));
        } else {
            getters.add(null);
        }
    }
}
 
Example 23
Project: incubator-netbeans   File: BeanModelBuilder.java   View source code 6 votes vote down vote up
private void addDependency(TypeMirror tm) {
    if (tm.getKind() == TypeKind.ARRAY) {
        addDependency(((ArrayType)tm).getComponentType());
    } else if (tm.getKind() == TypeKind.WILDCARD) {
        WildcardType wt = (WildcardType)tm;
        TypeMirror bound = wt.getSuperBound();
        if (bound == null) {
            bound = wt.getExtendsBound();
        }
        addDependency(bound);
    } else if (tm.getKind() == TypeKind.DECLARED) {
        addDependency(
            ((TypeElement)compilationInfo.getTypes().asElement(tm)).getQualifiedName().toString()
        );
    }
}
 
Example 24
Project: incubator-netbeans   File: RenameTestClassRefactoringPlugin.java   View source code 5 votes vote down vote up
private void addIfMatchMethod(final LocationResult location, final TestLocator testLocator, final List<RenameRefactoring> renameRefactoringsList) {
       if(location.getFileObject() != null && testLocator.getFileType(location.getFileObject()).equals(TestLocator.FileType.TEST)) {
    try {
	JavaSource.forFileObject(location.getFileObject()).runUserActionTask(new Task<CompilationController>() {
	    @Override
	    public void run(CompilationController javac) throws Exception {
		final Element methodElement = treePathHandle.resolveElement(javac);
		String methodName = methodElement.getSimpleName().toString();
		String testMethodName = RefactoringUtils.getTestMethodName(methodName);
		javac.toPhase(JavaSource.Phase.RESOLVED);
		CompilationUnitTree cut = javac.getCompilationUnit();
		Tree classTree = cut.getTypeDecls().get(0);
		List<? extends Tree> members = ((ClassTree) classTree).getMembers();
		for (int i = 0; i < members.size(); i++) {
                           Tree member = members.get(i);
                           if(member.getKind() != Tree.Kind.METHOD) {
                               continue;
                           }
                           MethodTree methodTree = (MethodTree) member;
		    if (methodTree.getName().contentEquals(testMethodName)
                                   && methodTree.getReturnType().getKind() == Tree.Kind.PRIMITIVE_TYPE
                                   && ((PrimitiveTypeTree) methodTree.getReturnType()).getPrimitiveTypeKind() == TypeKind.VOID) {
                                // test method should at least be void
                               classTree = ((ClassTree) classTree).getMembers().get(i);
                               TreePath tp = TreePath.getPath(cut, classTree);
                               RenameRefactoring renameRefactoring = new RenameRefactoring(Lookups.singleton(TreePathHandle.create(tp, javac)));
                               renameRefactoring.setNewName(RefactoringUtils.getTestMethodName(refactoring.getNewName()));
                               renameRefactoring.setSearchInComments(true);
                               renameRefactoringsList.add(renameRefactoring);
                               break;
                           }
		}
	    }
	}, true);
    } catch (IOException ex) {
	Exceptions.printStackTrace(ex);
    }
}
   }
 
Example 25
Project: openjdk-jdk10   File: LLNI.java   View source code 5 votes vote down vote up
private int doTwoWordFields(FieldDefsRes res, TypeElement clazz,
                            int offset, String cname, boolean padWord) {
    boolean first = true;
    List<VariableElement> fields = ElementFilter.fieldsIn(clazz.getEnclosedElements());

    for (VariableElement field: fields) {
        TypeKind tk = field.asType().getKind();
        boolean twoWords = (tk == TypeKind.LONG || tk == TypeKind.DOUBLE);
        if (twoWords && doField(res, field, cname, first && padWord)) {
            offset += 8; first = false;
        }
    }
    return offset;
}
 
Example 26
Project: openjdk-jdk10   File: NestedTypeVars.java   View source code 5 votes vote down vote up
String toString(TypeMirror bound) {
    if (bound.getKind() == TypeKind.TYPEVAR) {
        TypeVariable var = (TypeVariable) bound;
        return toString(var.asElement());
    }
    return bound.toString();
}
 
Example 27
Project: remoter   File: ByteParamBuilder.java   View source code 5 votes vote down vote up
@Override
public void writeParamsToProxy(VariableElement param, ParamType paramType, MethodSpec.Builder methodBuilder) {
    if (param.asType().getKind() == TypeKind.ARRAY) {
        if (paramType == ParamType.OUT) {
            writeArrayOutParamsToProxy(param, methodBuilder);
        } else {
            methodBuilder.addStatement("data.writeByteArray(" + param.getSimpleName() + ")");
        }
    } else {
        methodBuilder.addStatement("data.writeByte(" + param.getSimpleName() + ")");
    }
}
 
Example 28
Project: incubator-netbeans   File: Utilities.java   View source code 5 votes vote down vote up
@Override
public Boolean visitSwitch(SwitchTree node, Void p) {
    boolean lastCaseExit = false;
    boolean defaultSeen = false;
    Set<Element> enumValues = null;
    
    if (node.getExpression() != null) {
        TypeMirror exprType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
        if (isValidType(exprType) && exprType.getKind() == TypeKind.DECLARED) {
            Element el = ((DeclaredType)exprType).asElement();
            enumValues = new HashSet<>();
            for (Element f : el.getEnclosedElements()) {
                if (f.getKind() == ElementKind.ENUM_CONSTANT) {
                    enumValues.add(f);
                }
            }
        }
    }
    for (CaseTree ct : node.getCases()) {
        Boolean res = scan(ct, null);
        if (res == Boolean.FALSE) {
            return res;
        }
        lastCaseExit = res == Boolean.TRUE;
        if (ct.getExpression() == null) {
            defaultSeen = true;
        } else if (enumValues != null ) {
            TreePath casePath = new TreePath(getCurrentPath(), ct);
            Element v = info.getTrees().getElement(new TreePath(
                    casePath, ct.getExpression()));
            if (v != null) {
                enumValues.remove(v);
            }
        }
    }
    if (enumValues != null && enumValues.isEmpty()) {
        defaultSeen = true;
    }
    return lastCaseExit == Boolean.TRUE && defaultSeen;
}
 
Example 29
Project: dependency-injection-checks   File: DuplicateInjectionInHierarchyCheck.java   View source code 5 votes vote down vote up
/**
 * Return the type parameter of a class that extends {@code Lazy} or {@code Provider}.
 *
 * <ul>
 *   <li>Return parameter type Foo for, Lazy&lt;Foo&gt;.
 *   <li>Return FooProvider if no parameter type.
 *   <li>Return null, if we are unable to determine any type/kind of element.
 * </ul>
 *
 * @param element
 * @return the TypeElement for declared type.
 */
@Nullable
private TypeElement getKindParameter(Element element) {
  final TypeMirror type = element.asType();
  if (TypeKind.DECLARED == type.getKind()) {
    final List<? extends TypeMirror> typeMirrors = ((DeclaredType) type).getTypeArguments();
    if (typeMirrors.size() == 1) {
      return (TypeElement) typeUtils.asElement(typeUtils.erasure(typeMirrors.get(0)));
    } else {
      return (TypeElement) typeUtils.asElement(element.asType());
    }
  }
  return null;
}
 
Example 30
Project: incubator-netbeans   File: AbstractTestGenerator.java   View source code 5 votes vote down vote up
private boolean containsTypeVar(DeclaredType dt, boolean typeVar) {
    List<? extends TypeMirror> args = dt.getTypeArguments();
    for (TypeMirror arg : args) {
        if (arg.getKind() == TypeKind.TYPEVAR) {
            typeVar = true;
        }
        if (arg.getKind() == TypeKind.DECLARED) {
            typeVar = typeVar || containsTypeVar((DeclaredType) arg, typeVar);
        }
    }
    return typeVar;
}
 
Example 31
Project: incubator-netbeans   File: InstanceRefFinder.java   View source code 5 votes vote down vote up
@Override
public Object visitIdentifier(IdentifierTree node, Object p) {
    Element el = ci.getTrees().getElement(getCurrentPath());
    if (el == null || el.asType() == null || el.asType().getKind() == TypeKind.ERROR) {
        return null;
    }
    switch (el.getKind()) {
        case LOCAL_VARIABLE:
            addLocalClassVariable(el);
            addUsedMember(el, enclosingType);
            break;
        case TYPE_PARAMETER:
            addInstanceOfTypeParameter(el);
            break;
        case FIELD:
        case METHOD:
            addInstanceForMemberOf(el);
            break;
        case CLASS:
        case ENUM:
        case INTERFACE:
            if (node.getName().contentEquals("this") || node.getName().contentEquals("super")) {
                addInstanceForType(enclosingType);
            }
            break;
        case EXCEPTION_PARAMETER:
        case RESOURCE_VARIABLE:
            addLocalClassVariable(el);
            // fall through
        case PARAMETER:
            addInstanceOfParameterOwner(el);
            break;
        case PACKAGE:
            break;
        default:
            addUsedMember(el, enclosingType);
    }
    return super.visitIdentifier(node, p);
}
 
Example 32
Project: arez   File: MethodChecks.java   View source code 5 votes vote down vote up
static void mustNotReturnAnyValue( @Nonnull final String annotationName,
                                   @Nonnull final ExecutableElement method )
  throws ArezProcessorException
{
  if ( TypeKind.VOID != method.getReturnType().getKind() )
  {
    throw new ArezProcessorException( "@" + ProcessorUtil.toSimpleName( annotationName ) + " target must not return a value", method );
  }
}
 
Example 33
Project: GitHub   File: ButterKnifeProcessor.java   View source code 5 votes vote down vote up
private void parseResourceColor(Element element,
    Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) {
  boolean hasError = false;
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify that the target type is int or ColorStateList.
  boolean isColorStateList = false;
  TypeMirror elementType = element.asType();
  if (COLOR_STATE_LIST_TYPE.equals(elementType.toString())) {
    isColorStateList = true;
  } else if (elementType.getKind() != TypeKind.INT) {
    error(element, "@%s field type must be 'int' or 'ColorStateList'. (%s.%s)",
        BindColor.class.getSimpleName(), enclosingElement.getQualifiedName(),
        element.getSimpleName());
    hasError = true;
  }

  // Verify common generated code restrictions.
  hasError |= isInaccessibleViaGeneratedCode(BindColor.class, "fields", element);
  hasError |= isBindingInWrongPackage(BindColor.class, element);

  if (hasError) {
    return;
  }

  // Assemble information on the field.
  String name = element.getSimpleName().toString();
  int id = element.getAnnotation(BindColor.class).value();
  QualifiedId qualifiedId = elementToQualifiedId(element, id);
  BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
  builder.addResource(new FieldResourceBinding(getId(qualifiedId), name,
      isColorStateList ? FieldResourceBinding.Type.COLOR_STATE_LIST
          : FieldResourceBinding.Type.COLOR));

  erasedTargetNames.add(enclosingElement);
}
 
Example 34
Project: incubator-netbeans   File: JavaUtils.java   View source code 5 votes vote down vote up
public static boolean isGetter(ExecutableElement ee) {
    String methodName = ee.getSimpleName().toString();
    TypeMirror retType = ee.getReturnType();

    // discard private and static methods
    if (ee.getModifiers().contains(Modifier.PRIVATE) || ee.getModifiers().contains(Modifier.STATIC)) {
        return false;
    }
    
    
    boolean retVal = methodName.startsWith(GET_PREFIX) && methodName.length() > GET_PREFIX.length() && retType.getKind() != TypeKind.VOID;
    retVal = retVal || methodName.startsWith(IS_PREFIX) && methodName.length() > IS_PREFIX.length() && retType.getKind() == TypeKind.BOOLEAN;
    
    return retVal;
}
 
Example 35
Project: incubator-netbeans   File: CodeGenerator.java   View source code 5 votes vote down vote up
private Tree computeSuper(TypeMirror superClass) {
    if (superClass == null) return null;
    if (superClass.getKind() == TypeKind.NONE) return null; //for j.l.Object
    TypeElement jlObject = wc.getElements().getTypeElement("java.lang.Object"); //NOI18N
    if (jlObject != null && wc.getTypes().isSameType(superClass, jlObject.asType())) return null; //for extends j.l.Object

    return make.Type(superClass);
}
 
Example 36
Project: OpenJSharp   File: ApNavigator.java   View source code 5 votes vote down vote up
public TypeMirror erasure(TypeMirror t) {
    Types tu = env.getTypeUtils();
    t = tu.erasure(t);
    if (t.getKind().equals(TypeKind.DECLARED)) {
        DeclaredType dt = (DeclaredType)t;
        if (!dt.getTypeArguments().isEmpty())
            return tu.getDeclaredType((TypeElement) dt.asElement());
    }
    return t;
}
 
Example 37
Project: incubator-netbeans   File: TestGenerator.java   View source code 5 votes vote down vote up
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 */
private MethodTree generateInitMethod(String methodName,
                                      String annotationClassName,
                                      boolean isStatic,
                                      WorkingCopy workingCopy) {
    Set<Modifier> methodModifiers
            = isStatic ? createModifierSet(PUBLIC, STATIC)
                       : Collections.<Modifier>singleton(PUBLIC);
    ModifiersTree modifiers = createModifiersTree(annotationClassName,
                                                  methodModifiers,
                                                  workingCopy);
    TreeMaker maker = workingCopy.getTreeMaker();
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>emptyList(),
            false);
    MethodTree method = maker.Method(
            modifiers,              // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
 
Example 38
Project: GitHub   File: GlideExtensionValidator.java   View source code 5 votes vote down vote up
private static void validateStaticVoid(ExecutableElement executableElement, Class<?> clazz) {
  if (!executableElement.getModifiers().contains(Modifier.STATIC)) {
    throw new IllegalArgumentException("@" + clazz.getSimpleName() + " methods must be static");
  }
  TypeMirror returnType = executableElement.getReturnType();
  if (returnType.getKind() != TypeKind.VOID) {
    throw new IllegalArgumentException("@" + clazz.getSimpleName() + " methods must return void");
  }
}
 
Example 39
Project: incubator-netbeans   File: CreateElementUtilities.java   View source code 5 votes vote down vote up
private static List<? extends TypeMirror> computeNewArray(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    NewArrayTree nat = (NewArrayTree) parent.getLeaf();
    
    if (nat.getType() == error) {
        types.add(ElementKind.CLASS);
        types.add(ElementKind.ENUM);
        types.add(ElementKind.INTERFACE);
        
        return null;
    }
    
    for (Tree dimension : nat.getDimensions()) {
        if (dimension == error) {
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);
            
            return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.INT));
        }
    }
    
    for (Tree init : nat.getInitializers()) {
        if (init == error) {
            TypeMirror whole = info.getTrees().getTypeMirror(parent);
            
            if (whole == null || whole.getKind() != TypeKind.ARRAY)
                return null;
            
            types.add(ElementKind.PARAMETER);
            types.add(ElementKind.LOCAL_VARIABLE);
            types.add(ElementKind.FIELD);
            
            return Collections.singletonList(((ArrayType) whole).getComponentType());
        }
    }
    
    return null;
}
 
Example 40
Project: remoter   File: CharParamBuilder.java   View source code 5 votes vote down vote up
@Override
public void readResultsFromStub(TypeMirror resultType, MethodSpec.Builder methodBuilder) {
    if (resultType.getKind() == TypeKind.ARRAY) {
        methodBuilder.addStatement("reply.writeCharArray(result)");
    } else {
        methodBuilder.addStatement("reply.writeInt((int)result)");
    }
}