Java Code Examples for javax.lang.model.util.Types

The following are top voted examples for showing how to use javax.lang.model.util.Types. 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: GitHub   File: JsonObjectProcessor.java   Source Code and License 6 votes vote down vote up
private void createOrUpdateFieldHolder(Element element, Elements elements, Types types, JsonObjectHolder objectHolder) {
    JsonIgnore ignoreAnnotation = element.getAnnotation(JsonIgnore.class);
    boolean shouldParse = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.SERIALIZE_ONLY;
    boolean shouldSerialize = ignoreAnnotation == null || ignoreAnnotation.ignorePolicy() == IgnorePolicy.PARSE_ONLY;

    if (shouldParse || shouldSerialize) {
        JsonFieldHolder fieldHolder = objectHolder.fieldMap.get(element.getSimpleName().toString());
        if (fieldHolder == null) {
            fieldHolder = new JsonFieldHolder();
            objectHolder.fieldMap.put(element.getSimpleName().toString(), fieldHolder);
        }

        String error = fieldHolder.fill(element, elements, types, null, null, objectHolder, shouldParse, shouldSerialize);
        if (!TextUtils.isEmpty(error)) {
            error(element, error);
        }
    }
}
 
Example 2
Project: incubator-netbeans   File: JavadocCompletionQuery.java   Source Code and License 6 votes vote down vote up
private boolean isOfKindAndType(TypeMirror type, Element e, EnumSet<ElementKind> kinds, TypeMirror base, Scope scope, Trees trees, Types types) {
    if (type.getKind() != TypeKind.ERROR && kinds.contains(e.getKind())) {
        if (base == null)
            return true;
        if (types.isSubtype(type, base))
            return true;
    }
    if ((e.getKind().isClass() || e.getKind().isInterface()) && 
        (kinds.contains(ANNOTATION_TYPE) || kinds.contains(CLASS) || kinds.contains(ENUM) || kinds.contains(INTERFACE))) {
        DeclaredType dt = (DeclaredType)e.asType();
        for (Element ee : e.getEnclosedElements())
            if (trees.isAccessible(scope, ee, dt) && isOfKindAndType(ee.asType(), ee, kinds, base, scope, trees, types))
                return true;
    }
    return false;
}
 
Example 3
Project: easy-plugins   File: MarkerAnnotation.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a statement creating a new MarkerAnnotation instance to builder.
 * Returns the name of the instance.
 * @param builder The builder to add to.
 * @param annotation The service annotation to gather info from.
 * @return The name of the new instance.
 */
public static String addMarkerAnnotationInstance(MethodSpec.Builder builder,
                                                 UserMarkerAnnotation annotation,
                                                 Types types,
                                                 Elements elements) {

    String siName =
            ((TypeElement)types.asElement(annotation.getServiceInterfaceType())).getQualifiedName().toString();
    builder.addComment("The following values were gathered from the original @Service annotation parameters,");
    builder.addComment("and included here for this specialized service processor.");
    builder.addStatement("$T marker = new $T($S, $S, $S, $S)",
            MARKER_ANNOTATION_CLASS_NAME,
            MARKER_ANNOTATION_CLASS_NAME,
            siName,
            annotation.getServiceInterfaceName(),
            annotation.getIndividualNameKey(),
            annotation.getOutputPackage(elements));

    return "marker";
}
 
Example 4
Project: incubator-netbeans   File: EqualsHashCodeGenerator.java   Source Code and License 6 votes vote down vote up
private static KindOfType detectKind(CompilationInfo info, TypeMirror tm) {
    if (tm.getKind().isPrimitive()) {
        return KindOfType.valueOf(tm.getKind().name());
    }

    if (tm.getKind() == TypeKind.ARRAY) {
        return ((ArrayType) tm).getComponentType().getKind().isPrimitive() ? KindOfType.ARRAY_PRIMITIVE : KindOfType.ARRAY;
    }

    if (tm.getKind() == TypeKind.DECLARED) {
        Types t = info.getTypes();
        TypeElement en = info.getElements().getTypeElement("java.lang.Enum");

        if (en != null) {
            if (t.isSubtype(tm, t.erasure(en.asType()))) {
                return KindOfType.ENUM;
            }
        }

        if (((DeclaredType)tm).asElement().getKind().isClass() && ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().contentEquals("java.lang.String")) {
            return KindOfType.STRING;
        }
    }

    return KindOfType.OTHER;
}
 
Example 5
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 6 votes vote down vote up
public void testAddImport14() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest3.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("java.util.Map.Entry");
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getArrayType(types.erasure(list.asType()));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "entry", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImport14.pass");
}
 
Example 6
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 6 votes vote down vote up
public void testAddImportOrder1() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest7.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("java.util.LinkedList");
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getArrayType(types.erasure(list.asType()));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "s", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImportOrder1.pass");
}
 
Example 7
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 6 votes vote down vote up
private boolean isOfKindAndType(TypeMirror type, Element e, EnumSet<ElementKind> kinds, TypeMirror base, Scope scope, Trees trees, Types types) {
    if (type.getKind() != TypeKind.ERROR && kinds.contains(e.getKind())) {
        if (base == null) {
            return true;
        }
        if (types.isSubtype(type, base)) {
            return true;
        }
    }
    if ((e.getKind().isClass() || e.getKind().isInterface())
            && (kinds.contains(ANNOTATION_TYPE) || kinds.contains(CLASS) || kinds.contains(ENUM) || kinds.contains(INTERFACE))) {
        DeclaredType dt = (DeclaredType) e.asType();
        for (Element ee : e.getEnclosedElements()) {
            if (trees.isAccessible(scope, ee, dt) && isOfKindAndType(ee.asType(), ee, kinds, base, scope, trees, types)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 8
Project: incubator-netbeans   File: EntityMappingsUtilitiesTest.java   Source Code and License 6 votes vote down vote up
public void testGetFirstTypeArgument() throws Exception {
    ClasspathInfo cpi = ClasspathInfo.create(srcFO);
    final AnnotationModelHelper helper = AnnotationModelHelper.create(cpi);
    helper.runJavaSourceTask(new Runnable() {
        public void run() {
            Elements elements = helper.getCompilationController().getElements();
            Types types = helper.getCompilationController().getTypes();
            TypeElement typeElement = elements.getTypeElement("java.util.Collection");
            // Collection<E>
            assertNull(EntityMappingsUtilities.getFirstTypeArgument(typeElement.asType()));
            // Collection
            assertNull(EntityMappingsUtilities.getFirstTypeArgument(types.erasure(typeElement.asType())));
            // Collection<String>
            TypeMirror stringType = elements.getTypeElement("java.lang.String").asType();
            TypeElement argTypeElement = EntityMappingsUtilities.getFirstTypeArgument(types.getDeclaredType(typeElement, stringType));
            assertTrue(argTypeElement.getQualifiedName().contentEquals("java.lang.String"));
        }
    });
}
 
Example 9
Project: incubator-netbeans   File: MoveMembersTransformer.java   Source Code and License 6 votes vote down vote up
private void checkForUsagesOutsideOfType(final Element target, TreePath currentPath, TreePathHandle elementBeingMoved) {
    final Types types = workingCopy.getTypes();
    TypeMirror targetType = target.asType();
    TreePath enclosingPath = JavaRefactoringUtils.findEnclosingClass(workingCopy, currentPath, true, true, true, true, false);
    Element enclosingEl = null;
    if(enclosingPath != null) {
        enclosingEl = workingCopy.getTrees().getElement(enclosingPath);
    }
    if(enclosingEl != null) {
        TypeMirror enclosingType = enclosingEl.asType();
        if(!(enclosedBy(targetType, enclosingType) || enclosedBy(enclosingType, targetType)) && !types.isSameType(enclosingType, targetType)) {
            usageOutsideOfType.put(elementBeingMoved, Boolean.TRUE);
        }
    } else {
        usageOutsideOfType.put(elementBeingMoved, Boolean.TRUE);
    }
}
 
Example 10
Project: incubator-netbeans   File: JavaReference.java   Source Code and License 6 votes vote down vote up
private ExecutableElement findExecutableMember(TypeElement clazz, String methodName, List<TypeMirror> paramTypes, Types types) {
    List<ExecutableElement> members = methodName.contentEquals(clazz.getSimpleName())
            ? ElementFilter.constructorsIn(clazz.getEnclosedElements())
            : ElementFilter.methodsIn(clazz.getEnclosedElements());
    outer: for (ExecutableElement ee : members) {
        if (ee.getKind() == ElementKind.CONSTRUCTOR || methodName.contentEquals(ee.getSimpleName())) {
            List<? extends TypeMirror> memberParamTypes = ((ExecutableType) ee.asType()).getParameterTypes();
            if (memberParamTypes.size() == paramTypes.size()) {
                Iterator<TypeMirror> it = paramTypes.iterator();
                for (TypeMirror memberParamType : memberParamTypes) {
                    TypeMirror type = it.next();
                    if (types.isSameType(type, memberParamType)) {
                        continue outer;
                    }
                }
                return ee;
            }
        }
    }
    return null;
}
 
Example 11
Project: incubator-netbeans   File: UseSuperTypeRefactoringPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public Tree visitTypeCast(TypeCastTree castTree, Element elementToMatch) {
    TreePath path = getCurrentPath();
    Types types = workingCopy.getTypes();
    TypeMirror castTypeErasure = types.erasure(workingCopy.getTrees().getTypeMirror(path));
    TypeMirror elToMatchErasure = types.erasure(subTypeElement.asType());
    path = path.getParentPath();
    Element element = workingCopy.getTrees().getElement(path);
    if (element instanceof VariableElement && types.isSameType(castTypeErasure, elToMatchErasure)) {
        VariableElement varElement = (VariableElement)element;
        TypeMirror varTypeErasure = types.erasure(varElement.asType());
        if (types.isSameType(varTypeErasure, elToMatchErasure) && isReplaceCandidate(varElement)) {
            TypeCastTree newTree = make.TypeCast(
                make.Identifier(superTypeElement), castTree.getExpression());
            rewrite(castTree, newTree);
        }
    }
    return super.visitTypeCast(castTree, elementToMatch);
}
 
Example 12
Project: data-mediator   File: ElementHelper.java   Source Code and License 6 votes vote down vote up
public static boolean processGlobalSetting(Types mTypes, List<? extends AnnotationMirror> annoMirrors, ProcessorPrinter pp) {
    for (AnnotationMirror am : annoMirrors) {
        //if not my want. ignore
        if (!isValidAnnotation(am, pp)) {
            continue;
        }
        Map<? extends ExecutableElement, ? extends AnnotationValue> methodMap = am.getElementValues();
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> en : methodMap.entrySet()) {
            ExecutableElement key = en.getKey();//the method of annotation
            switch (key.getSimpleName().toString()) {
                case KEY_GSON_CONFIG: {
                    Object value = en.getValue().getValue(); //@GsonConfig
                    AnnotationMirror am2 = (AnnotationMirror) value;
                    handleGsonConfig(am2, pp);
                }

                default:
                    //next to do
                    break;
            }
        }
    }
    return true;
}
 
Example 13
Project: incubator-netbeans   File: AST2Bytecode.java   Source Code and License 5 votes vote down vote up
private static boolean isInTypes(Types types, TypeMirror tm, List<TypeMirror>[] sTypes, int from) {
    if (from >= sTypes.length) {
        return true;
    }
    for (TypeMirror testTM : sTypes[from]) {
        if (types.isSameType(tm, testTM)) {
            return isInTypes(types, tm, sTypes, from + 1);
        }
    }
    return false;
}
 
Example 14
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 5 votes vote down vote up
private void addEffectivelyFinalAutoCloseables(final Env env) throws IOException {
    final CompilationController controller = env.getController();
    final Elements elements = controller.getElements();
    final TypeElement te = elements.getTypeElement("java.lang.AutoCloseable"); //NOI18N
    if (te != null) {
        final Types types = controller.getTypes();
        final ElementUtilities eu = controller.getElementUtilities();
        final Scope scope = env.getScope();
        final Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env);
        final TypeElement enclClass = scope.getEnclosingClass();
        for (Element e : getLocalMembersAndVars(env)) {
            switch (e.getKind()) {
                case EXCEPTION_PARAMETER:
                case LOCAL_VARIABLE:
                case RESOURCE_VARIABLE:
                case PARAMETER:
                    if (types.isSubtype(e.asType(), te.asType()) && eu.isEffectivelyFinal((VariableElement) e)) {
                        results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, e.asType(), anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, e.asType(), smartTypes), env.assignToVarPos()));
                    }
                    break;
                case FIELD:
                    if (types.isSubtype(e.asType(), te.asType())) {
                        String name = e.getSimpleName().toString();
                        if (THIS_KEYWORD.equals(name) || SUPER_KEYWORD.equals(name)) {
                            results.add(itemFactory.createKeywordItem(name, null, anchorOffset, isOfSmartType(env, e.asType(), smartTypes)));
                        } else {
                            TypeMirror tm = asMemberOf(e, enclClass != null ? enclClass.asType() : null, types);
                            results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, tm, anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, tm, smartTypes), env.assignToVarPos()));
                        }
                    }
                    break;
            }
        }
    }
}
 
Example 15
Project: MRouter   File: ProcessorUtils.java   Source Code and License 5 votes vote down vote up
public static TargetTypeKind getTargetTypeKind(Elements elements, Types types, TypeElement enclosingElement) {
    if (isInActivity(elements, types, enclosingElement)) {
        return TargetTypeKind.ACTIVITY;
    }
    if (isInFragment(elements, types, enclosingElement)) {
        return TargetTypeKind.FRAGMENT;
    }

    if (isInProvider(elements, types, enclosingElement)) {
        return TargetTypeKind.PROVIDER;
    }

    return TargetTypeKind.UNKNOWN;
}
 
Example 16
Project: SyncGenerator   File: AnnotatedType.java   Source Code and License 5 votes vote down vote up
private Set<MethodSpec> getMethods(Types typeUtils) {
    Set<MethodSpec> methods = new HashSet<>();

    MethodSpec constructor = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(classTypeName, MEMBER_FIELD_NAME)
            .addStatement("this.$N = $N", MEMBER_FIELD_NAME, MEMBER_FIELD_NAME)
            .build();

    methods.add(constructor);

    Set<Element> allElements = new HashSet<>();
    allElements.addAll(element.getEnclosedElements());
    for (TypeMirror typeMirror : element.getInterfaces()) {
        allElements.addAll(typeUtils.asElement(typeMirror).getEnclosedElements());
    }

    for (Element e : allElements) {
        if (!(e instanceof ExecutableElement)) {
            continue;
        }
        ExecutableElement method = (ExecutableElement) e;
        String methodName = method.getSimpleName().toString();
        if ("<init>".equals(methodName)) { // skip constructors
            continue;
        }
        Set<Modifier> modifiers = new HashSet<>(method.getModifiers());
        if (modifiers.contains(Modifier.PRIVATE)
                || modifiers.contains(Modifier.STATIC)
                || modifiers.contains(Modifier.FINAL)) {
            continue;
        }
        modifiers.remove(Modifier.ABSTRACT);
        modifiers.add(Modifier.SYNCHRONIZED);

        MethodSpec.Builder spec = MethodSpec.methodBuilder(methodName)
                .addModifiers(modifiers);

        List<? extends TypeMirror> thrownTypes = method.getThrownTypes();
        for (TypeMirror throwable : thrownTypes) {
            spec = spec.addException(TypeName.get(throwable));
        }

        String arguments = "";
        List<? extends VariableElement> parameters = method.getParameters();
        for (VariableElement parameter : parameters) {
            arguments += parameter.getSimpleName().toString();
            if (parameters.indexOf(parameter) != parameters.size() - 1) {
                arguments += ", ";
            }
            spec.addParameter(ParameterSpec.get(parameter));
        }

        if (method.getReturnType() instanceof NoType) {
            spec = spec.addStatement("$N.$N($L)", MEMBER_FIELD_NAME, methodName, arguments);
        } else {
            spec = spec.addStatement("return $N.$N($L)", MEMBER_FIELD_NAME, methodName, arguments)
                    .returns(TypeName.get(method.getReturnType()));
        }

        methods.add(spec.build());
    }
    return methods;
}
 
Example 17
Project: react4j   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
@Nonnull
static List<ExecutableElement> getMethods( @Nonnull final TypeElement element,
                                           @Nonnull final Types typeUtils )
{
  final Map<String, ExecutableElement> methodMap = new LinkedHashMap<>();
  enumerateMethods( element, typeUtils, element, methodMap );
  return new ArrayList<>( methodMap.values() );
}
 
Example 18
Project: incubator-netbeans   File: JavaOperationsImpl.java   Source Code and License 5 votes vote down vote up
@Override
@NonNull
public Collection<? extends String> getFieldNames(
        @NonNull final String clz,
        final boolean rt,
        @NullAllowed final String type) throws QueryException {
    final TypeElement te = findClass(clz);
    if (te == null) {
        return Collections.<String>emptyList();
    }
    final Types types = control.getTypes();
    TypeMirror tm = null;
    if (type != null) {
        final List<? extends TypeElement> topLevels = control.getTopLevelElements();
        tm = topLevels.isEmpty() ?
            null :
            control.getTreeUtilities().parseType(type, topLevels.get(0));
        if (tm == null) {
            return Collections.<String>emptyList();
        } else if (rt) {
            tm = types.erasure(tm);
        }
    }
    final Collection<String> result = new ArrayList<String>();
    for (VariableElement ve : ElementFilter.fieldsIn(te.getEnclosedElements())) {
        if (isSameType(types,tm,ve.asType(),rt)) {
            result.add(ve.getSimpleName().toString());
        }
    }
    return Collections.unmodifiableCollection(result);
}
 
Example 19
Project: incubator-netbeans   File: BaseTask.java   Source Code and License 5 votes vote down vote up
TypeMirror asMemberOf(Element element, TypeMirror type, Types types) {
    TypeMirror ret = element.asType();
    TypeMirror enclType = element.getEnclosingElement().asType();
    if (enclType.getKind() == TypeKind.DECLARED) {
        enclType = types.erasure(enclType);
    }
    while (type != null && type.getKind() == TypeKind.DECLARED) {
        if ((enclType.getKind() != TypeKind.DECLARED || ((DeclaredType) enclType).asElement().getSimpleName().length() > 0) && types.isSubtype(type, enclType)) {
            ret = types.asMemberOf((DeclaredType) type, element);
            break;
        }
        type = ((DeclaredType) type).getEnclosingType();
    }
    return ret;
}
 
Example 20
Project: incubator-netbeans   File: MethodModelSupportTest.java   Source Code and License 5 votes vote down vote up
public void testGetTypeName() throws Exception {
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "}");
    runUserActionTask(testFO, new Task<CompilationController>() {
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Elements elements = controller.getElements();
            Types types = controller.getTypes();
            
            String typeName = String.class.getName();
            String resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType());
            assertEquals(typeName, resolvedTypeName);
            
            typeName = InputStream.class.getName();
            resolvedTypeName = MethodModelSupport.getTypeName(elements.getTypeElement(typeName).asType());
            assertEquals(typeName, resolvedTypeName);
            
            resolvedTypeName = MethodModelSupport.getTypeName(types.getPrimitiveType(TypeKind.INT));
            assertEquals("int", resolvedTypeName);

            typeName = String.class.getName();
            resolvedTypeName = MethodModelSupport.getTypeName(types.getArrayType(elements.getTypeElement(typeName).asType()));
            assertEquals("java.lang.String[]", resolvedTypeName);
            
            PrimitiveType primitiveType = types.getPrimitiveType(TypeKind.BYTE);
            ArrayType arrayType = types.getArrayType(primitiveType);
            resolvedTypeName = MethodModelSupport.getTypeName(arrayType);
            assertEquals("byte[]", resolvedTypeName);
        }
    });
}
 
Example 21
Project: domino   File: ProcessorElement.java   Source Code and License 5 votes vote down vote up
public ProcessorElement(Element element, Elements elementUtils, Types typeUtils,
                        Messager messager) {
    this.element = element;
    this.elementUtils = elementUtils;
    this.typeUtils = typeUtils;
    this.messager = messager;
}
 
Example 22
Project: openjdk-jdk10   File: ApNavigator.java   Source Code and License 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 23
Project: incubator-netbeans   File: TestGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Checks that the given annotation is of type
 * <code>{@value #ANN_SUITE}.{@value #ANN_SUITE_MEMBERS}</code>
 * and contains the given list of classes as (the only) argument,
 * in the same order.
 * 
 * @param  annMirror  annotation to be checked
 * @param  suiteMembers  list of fully qualified class names denoting
 *                       content of the test suite
 * @return  {@code true} if the annotation meets the described criteria,
 *          {@code false} otherwise
 */
private boolean checkSuiteMembersAnnotation(AnnotationMirror annMirror,
                                            List<String> suiteMembers,
                                            WorkingCopy workingCopy) {
    Map<? extends ExecutableElement,? extends AnnotationValue> annParams
            = annMirror.getElementValues();
    
    if (annParams.size() != 1) {
        return false;
    }
    
    AnnotationValue annValue = annParams.values().iterator().next();
    Object value = annValue.getValue();
    if (value instanceof java.util.List) {
        List<? extends AnnotationValue> items
                = (List<? extends AnnotationValue>) value;
        
        if (items.size() != suiteMembers.size()) {
            return false;
        }
        
        Types types = workingCopy.getTypes();
        Iterator<String> suiteMembersIt = suiteMembers.iterator();
        for (AnnotationValue item : items) {
            Name suiteMemberName = getAnnotationValueClassName(item, types);
            if (suiteMemberName == null) {
                return false;
            }
            if (!suiteMemberName.contentEquals(suiteMembersIt.next())) {
                return false;
            }
        }
        return true;
    }
    
    return false;
}
 
Example 24
Project: incubator-netbeans   File: TestGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Returns fully qualified class name of a class given to an annotation
 * as (the only) argument.
 * 
 * @param  annValue  annotation value
 * @return  fully qualified name of a class represented by the given
 *          annotation value, or {@code null} if the annotation value
 *          does not represent a class
 */
private Name getAnnotationValueClassName(AnnotationValue annValue,
                                         Types types) {
    Object value = annValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror typeMirror = (TypeMirror) value;
        Element typeElement = types.asElement(typeMirror);
        if (typeElement.getKind() == ElementKind.CLASS) {
            return ((TypeElement) typeElement).getQualifiedName();
        }
    }
    return null;
}
 
Example 25
Project: incubator-netbeans   File: TreeFactory.java   Source Code and License 5 votes vote down vote up
public ExpressionTree Type(TypeMirror type) {
    Type t = (Type) type;
    JCExpression tp;
    switch (type.getKind()) {
        case WILDCARD: {
            WildcardType a = ((WildcardType) type);
            tp = make.at(NOPOS).Wildcard(make.at(NOPOS).TypeBoundKind(a.kind), (JCExpression) Type(a.type));
            break;
        }
        case DECLARED:
            JCExpression clazz = (JCExpression) QualIdent(t.tsym);
            tp = t.getTypeArguments().isEmpty()
            ? clazz
                    : make.at(NOPOS).TypeApply(clazz, Types(t.getTypeArguments()));
            break;
        case ARRAY:
            
            tp = make.at(NOPOS).TypeArray((JCExpression) Type(((ArrayType) type).getComponentType()));
            break;
        case NULL:
            tp = make.at(NOPOS).Literal(TypeTag.BOT, null);
            break;
        case ERROR:
            tp = make.at(NOPOS).Ident(((ErrorType) type).tsym.name);
            break;
        default:
            return make.at(NOPOS).Type((Type)type);
    }

    return tp.setType(t);
}
 
Example 26
Project: react4j   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
@Nonnull
static Map<String, TypeMirror> getFields( @Nonnull final TypeElement element,
                                          @Nonnull final Types typeUtils )
{
  final Map<String, TypeMirror> methodMap = new LinkedHashMap<>();
  enumerateFields( element, typeUtils, element, methodMap );
  return methodMap;
}
 
Example 27
Project: data-mediator   File: ImplInfoDelegate.java   Source Code and License 5 votes vote down vote up
private static boolean parseImplClass(Types types, ProcessorPrinter pp, AnnotationMirror am, ImplInfo info) {
    Map<? extends ExecutableElement, ? extends AnnotationValue> map = am.getElementValues();
    pp.note(TAG, "parseImplClass", "am.getElementValues() = map . is " + map);
    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> en : map.entrySet()) {
        ExecutableElement key = en.getKey();
        if (key.getSimpleName().toString().equals("value")) {
            TypeMirror tm = (TypeMirror) en.getValue().getValue();
            if (!verifyClassName(tm, pp)) {
                return false;
            }
            info.setImplClass(new FieldData.TypeCompat(types, tm));
        }
    }
    return true;
}
 
Example 28
Project: incubator-netbeans   File: JavadocCompletionQuery.java   Source Code and License 5 votes vote down vote up
private DeclaredType getDeclaredType(TypeElement e, HashMap<? extends Element, ? extends TypeMirror> map, Types types) {
    List<? extends TypeParameterElement> tpes = e.getTypeParameters();
    TypeMirror[] targs = new TypeMirror[tpes.size()];
    int i = 0;
    for (Iterator<? extends TypeParameterElement> it = tpes.iterator(); it.hasNext();) {
        TypeParameterElement tpe = it.next();
        TypeMirror t = map.get(tpe);
        targs[i++] = t != null ? t : tpe.asType();
    }
    Element encl = e.getEnclosingElement();
    if ((encl.getKind().isClass() || encl.getKind().isInterface()) && !((TypeElement)encl).getTypeParameters().isEmpty())
            return types.getDeclaredType(getDeclaredType((TypeElement)encl, map, types), e, targs);
    return types.getDeclaredType(e, targs);
}
 
Example 29
Project: vulture   File: TypeUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isParcelableArray(Types typeUtils, Elements elementUtils, Element element) {
    if (element.asType().getKind() != TypeKind.ARRAY) {
        return false;
    }

    ArrayType arrayType = (ArrayType) element.asType();
    TypeMirror componentType = arrayType.getComponentType();

    TypeElement typeParcelable = elementUtils.getTypeElement(Parcelable.class.getName());
    return typeUtils.isSubtype(componentType, typeParcelable.asType());
}
 
Example 30
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 5 votes vote down vote up
private List<Pair<ExecutableElement, ExecutableType>> getMatchingExecutables(TypeMirror type, Iterable<? extends Element> elements, String name, TypeMirror[] argTypes, Types types) {
    List<Pair<ExecutableElement, ExecutableType>> ret = new ArrayList<>();
    for (Element e : elements) {
        if ((e.getKind() == CONSTRUCTOR || e.getKind() == METHOD) && name.contentEquals(e.getSimpleName())) {
            List<? extends VariableElement> params = ((ExecutableElement) e).getParameters();
            int parSize = params.size();
            boolean varArgs = ((ExecutableElement) e).isVarArgs();
            if (!varArgs && (parSize < argTypes.length)) {
                continue;
            }
            ExecutableType eType = (ExecutableType) asMemberOf(e, type, types);
            if (parSize == 0) {
                ret.add(Pair.of((ExecutableElement) e, eType));
            } else {
                Iterator<? extends TypeMirror> parIt = eType.getParameterTypes().iterator();
                TypeMirror param = null;
                for (int i = 0; i <= argTypes.length; i++) {
                    if (parIt.hasNext()) {
                        param = parIt.next();
                        if (!parIt.hasNext() && param.getKind() == TypeKind.ARRAY) {
                            param = ((ArrayType) param).getComponentType();
                        }
                    } else if (!varArgs) {
                        break;
                    }
                    if (i == argTypes.length) {
                        ret.add(Pair.of((ExecutableElement) e, eType));
                        break;
                    }
                    if (argTypes[i] == null || !types.isAssignable(argTypes[i], param)) {
                        break;
                    }
                }
            }
        }
    }
    return ret;
}
 
Example 31
Project: SyncGenerator   File: AnnotatedType.java   Source Code and License 5 votes vote down vote up
private TypeSpec generateCode(Types typeUtils) {
    Modifier[] modifiers = getModifiers();
    return TypeSpec.classBuilder(TypeUtils.simpleNameOf(decoratorClassName))
            .addModifiers(modifiers)
            .addField(getMemberField())
            .addMethods(getMethods(typeUtils))
            .superclass(getSuperclass())
            .addSuperinterfaces(getSuperInterfaces())
            .build();
}
 
Example 32
Project: java-code-templates   File: ProcessorModule.java   Source Code and License 5 votes vote down vote up
@Provides @Singleton @Named(DESCRIPTOR_KEY)
static Inventory provideDescriptorInventory(@Named(DESCRIPTOR_KEY) final TypeElement descriptorElement,
		final ClassName outputClassName, final Types types, final Elements elements, final Trees trees,
		final Messager messager, @Named(TEMPLATE_KEY) Inventory templateInventory,
		final ImmutableSet<TypeElement> typesToReceiveAnnotations) {
	return new Inventory(descriptorElement, outputClassName, types, elements, trees, messager, true,
			templateInventory.rawTypeNameSubstitutions(), typesToReceiveAnnotations);
}
 
Example 33
Project: incubator-netbeans   File: ElementUtilities.java   Source Code and License 5 votes vote down vote up
private DeclaredType findCommonSubtype(DeclaredType type1, DeclaredType type2, Env<AttrContext> env) {
    List<DeclaredType> subtypes1 = getSubtypes(type1, env);
    List<DeclaredType> subtypes2 = getSubtypes(type2, env);
    if (subtypes1 == null || subtypes2 == null) return null;
    Types types = info.getTypes();
    for (DeclaredType subtype1 : subtypes1) {
        for (DeclaredType subtype2 : subtypes2) {
            if (types.isSubtype(subtype1, subtype2))
                return subtype1;
            if (types.isSubtype(subtype2, subtype1))
                return subtype2;
        }
    }
    return null;
}
 
Example 34
Project: OpenJSharp   File: ApNavigator.java   Source Code and License 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 35
Project: incubator-netbeans   File: AnnotationProcessors.java   Source Code and License 5 votes vote down vote up
@Hint(displayName="#DN_AnnotationProcessors.overridingGetSupportedAnnotations",
      description="#DESC_AnnotationProcessors.overridingGetSupportedAnnotations",
      category="rules15")
@Messages({/*"DN_AnnotationProcessors.overridingGetSupportedAnnotations=AbstractProcessor.getSupportedAnnotations() is overridden",
           "DESC_AnnotationProcessors.overridingGetSupportedAnnotations=Overriding Processor.getSupportedAnnotations() may lead to " +
                                                                       "unnecessary classloading during development, and may prevent important optimalizations. " +
                                                                       "consider using @javax.annotation.processing.SupportedAnnotationTypes",*/
           "ERR_AnnotationProcessors.overridingGetSupportedAnnotations=AbstractProcessor.getSupportedAnnotationTypes() overridden, may cause performance problems during development"})
@TriggerTreeKind(Kind.CLASS)
public static ErrorDescription oGSA(HintContext ctx) {
    Element clazz = ctx.getInfo().getTrees().getElement(ctx.getPath());

    if (clazz == null || !clazz.getKind().isClass()) return null;

    TypeElement ap = ctx.getInfo().getElements().getTypeElement("javax.annotation.processing.AbstractProcessor");

    if (ap == null) return null;

    Types types = ctx.getInfo().getTypes();

    if (!types.isSubtype(types.erasure(clazz.asType()), types.erasure(ap.asType()))) return null;

    for (ExecutableElement ee : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
        if (ee.getSimpleName().contentEquals("getSupportedAnnotationTypes") && ee.getParameters().isEmpty()) {
            Tree t = ctx.getInfo().getTrees().getTree(ee);

            if (t != null) {
                return ErrorDescriptionFactory.forName(ctx, t, Bundle.ERR_AnnotationProcessors_overridingGetSupportedAnnotations());
            }
        }
    }

    return null;
}
 
Example 36
Project: DUnit   File: ElementUtil.java   Source Code and License 5 votes vote down vote up
public static TypeElement getSuperElement(Types types,Element element){
	if (element instanceof TypeElement){
		TypeElement typeElement = (TypeElement) element;
		Element superElement = types.asElement(typeElement.getSuperclass());
		return (TypeElement) superElement;
	}
	return null;
}
 
Example 37
Project: incubator-netbeans   File: JavaOperationsImpl.java   Source Code and License 5 votes vote down vote up
private static boolean isSameType (
        @NonNull Types types,
        @NullAllowed final TypeMirror t1,
        @NonNull final TypeMirror t2,
        final boolean rawType) {
    return t1 == null ||
        types.isSameType(
            t1,
            rawType ? types.erasure(t2) : t2);
}
 
Example 38
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 5 votes vote down vote up
private TypeMirror getCorrectedReturnType(Env env, ExecutableType et, ExecutableElement el, TypeMirror site) {
    TypeMirror type = et.getReturnType();
    if (site != null && site.getKind() == TypeKind.DECLARED) {
        if ("getClass".contentEquals(el.getSimpleName()) && et.getParameterTypes().isEmpty() //NOI18N
                && type.getKind() == TypeKind.DECLARED
                && JAVA_LANG_CLASS.contentEquals(((TypeElement) ((DeclaredType) type).asElement()).getQualifiedName())
                && ((TypeElement) ((DeclaredType) type).asElement()).getTypeParameters().size() == 1) {
            Types types = env.getController().getTypes();
            type = types.getDeclaredType((TypeElement) ((DeclaredType) type).asElement(), types.getWildcardType(site, null));
        }
    }
    return type;
}
 
Example 39
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 5 votes vote down vote up
public void testAddImport12() throws IOException {
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            TypeElement map = workingCopy.getElements().getTypeElement("java.util.Map");
            ClassTree nue = make.addClassImplementsClause(clazz, make.QualIdent(map));
            workingCopy.rewrite(clazz, nue);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("java.util.Map.Entry");
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getArrayType(types.erasure(list.asType()));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "entry", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImport12.pass");
}
 
Example 40
Project: incubator-netbeans   File: AST2Bytecode.java   Source Code and License 5 votes vote down vote up
private static TypeMirror findUnion(Types types, List<TypeMirror>[] sTypes) {
    for (TypeMirror tm : sTypes[0]) {
        if (isInTypes(types, tm, sTypes, 1)) {
            return tm;
        }
    }
    return null;
}
 
Example 41
Project: incubator-netbeans   File: JavadocCompletionQuery.java   Source Code and License 5 votes vote down vote up
private static TypeMirror asMemberOf(Element element, TypeMirror type, Types types) {
    TypeMirror ret = element.asType();
    TypeMirror enclType = element.getEnclosingElement().asType();
    if (enclType.getKind() == TypeKind.DECLARED)
        enclType = types.erasure(enclType);
    while(type != null && type.getKind() == TypeKind.DECLARED) {
        if (types.isSubtype(type, enclType)) {
            ret = types.asMemberOf((DeclaredType)type, element);
            break;
        }
        type = ((DeclaredType)type).getEnclosingType();
    }
    return ret;
}
 
Example 42
Project: incubator-netbeans   File: ImportAnalysisTest.java   Source Code and License 5 votes vote down vote up
public void testAddImportSamePackage() throws IOException {
    testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest7.java");
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree node = (MethodTree) clazz.getMembers().get(0);
            BlockTree body = node.getBody();
            List<StatementTree> stats = new ArrayList<StatementTree>();
            for (StatementTree st : body.getStatements()) {
                stats.add(st);
            }
            TypeElement list = workingCopy.getElements().getTypeElement("org.netbeans.test.codegen.ImportsTest6");
            assertNotNull(list);
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getArrayType(types.erasure(list.asType()));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "s", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImportSamePackage.pass");
}
 
Example 43
Project: incubator-netbeans   File: JUnit4TestGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Returns fully qualified class name of a class given to an annotation
 * as (the only) argument.
 * 
 * @param  annValue  annotation value
 * @return  fully qualified name of a class represented by the given
 *          annotation value, or {@code null} if the annotation value
 *          does not represent a class
 */
private Name getAnnotationValueClassName(AnnotationValue annValue,
                                         Types types) {
    Object value = annValue.getValue();
    if (value instanceof TypeMirror) {
        TypeMirror typeMirror = (TypeMirror) value;
        Element typeElement = types.asElement(typeMirror);
        if (typeElement.getKind() == ElementKind.CLASS) {
            return ((TypeElement) typeElement).getQualifiedName();
        }
    }
    return null;
}
 
Example 44
Project: data-mediator   File: OutInterfaceManager.java   Source Code and License 5 votes vote down vote up
public static List<MethodSpec.Builder> getProxyClassMethodBuilders(TargetClassInfo info, TypeElement te,
                                                                   Types types, ProcessorPrinter pp){

    //the method builders for super interface.
    final List<MethodSpec.Builder> methodBuilders =  new ArrayList<>();
    final ClassName cn_inter = ClassName.get(info.getPackageName(), info.getDirectParentInterfaceName());

    List<? extends TypeMirror> interfaces = getAttentionInterfaces(te, types, pp);
    pp.note(TAG, "getProxyClassMethodBuilders", "te : " + te + " ,superinterfaces = " + interfaces);
    for(TypeMirror tm : interfaces){
        FieldData.TypeCompat tc = new FieldData.TypeCompat(types, tm);
        TypeElement type = tc.getElementAsType();
        String interfaceName = type.getQualifiedName().toString();
        final TypeInterfaceFiller filler = sFillerMap.get(interfaceName);
        //for proxy .method build is in ProxyGenerator.
        if(filler instanceof TypeSelectableFiller){
            continue;
        }

        //get all method element
        final List<? extends Element> list = type.getEnclosedElements();
        for(Element e : list){
            if (!(e instanceof ExecutableElement)) {
                continue;
            }
            ExecutableElement ee = (ExecutableElement) e;
            MethodSpec.Builder builder = overriding(info, interfaceName, ee, pp, cn_inter)
                    .addModifiers(Modifier.PUBLIC);
            if(filler != null){
                filler.buildProxyMethod(builder, ee, cn_inter);
                methodBuilders.add(builder);
            }
        }
    }
    return methodBuilders;
}
 
Example 45
Project: incubator-netbeans   File: AbstractTestGenerator.java   Source Code and License 5 votes vote down vote up
/**
 */
private static boolean throwsNonRuntimeExceptions(CompilationInfo compInfo,
                                                  ExecutableElement method) {
    List<? extends TypeMirror> thrownTypes = method.getThrownTypes();
    if (thrownTypes.isEmpty()) {
        return false;
    }

    String runtimeExcName = "java.lang.RuntimeException";           //NOI18N
    TypeElement runtimeExcElement = compInfo.getElements()
                                    .getTypeElement(runtimeExcName);
    if (runtimeExcElement == null) {
        Logger.getLogger("junit").log(                              //NOI18N
                Level.WARNING,
                "Could not find TypeElement for "                   //NOI18N
                        + runtimeExcName);
        return true;
    }

    Types types = compInfo.getTypes();
    TypeMirror runtimeExcType = runtimeExcElement.asType();
    for (TypeMirror exceptionType : thrownTypes) {
        if (!types.isSubtype(exceptionType, runtimeExcType)) {
            return true;
        }
    }

    return false;
}
 
Example 46
Project: incubator-netbeans   File: JavacClassInfo.java   Source Code and License 5 votes vote down vote up
@Override
public Set<SourceClassInfo> getInterfaces() {
    final Set<SourceClassInfo> ifcs = new HashSet<SourceClassInfo>();
    if (handle != null) {
        try {
            JavaSource s = getSource(false);
            if (s != null) {
                s.runUserActionTask(new Task<CompilationController>() {
                    public void run(CompilationController cc) throws Exception {
                        cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                        TypeElement te = handle.resolve(cc);

                        Types t = cc.getTypes();
                        if (te != null) {
                            for(TypeMirror ifc : te.getInterfaces()) {
                                TypeElement ife = (TypeElement)t.asElement(ifc);
                                ifcs.add(new JavacClassInfo(ElementHandle.create(ife), cc));
                            }
                        }
                    }
                }, true);
            }
        } catch (IOException e) {
            LOG.log(Level.WARNING, null, e);
        }    
    }
    return ifcs;
}
 
Example 47
Project: incubator-netbeans   File: JavaCompletionTask.java   Source Code and License 5 votes vote down vote up
private void addLocalFieldsAndVars(final Env env) throws IOException {
    final CompilationController controller = env.getController();
    final Elements elements = controller.getElements();
    final Types types = controller.getTypes();
    final Scope scope = env.getScope();
    Set<? extends TypeMirror> smartTypes = options.contains(Options.ALL_COMPLETION) ? null : getSmartTypes(env);
    final TypeElement enclClass = scope.getEnclosingClass();
    for (Element e : getLocalMembersAndVars(env)) {
        switch (e.getKind()) {
            case ENUM_CONSTANT:
            case EXCEPTION_PARAMETER:
            case LOCAL_VARIABLE:
            case RESOURCE_VARIABLE:
            case PARAMETER:
                results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, e.asType(), anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, e.asType(), smartTypes), env.assignToVarPos()));
                break;
            case FIELD:
                String name = e.getSimpleName().toString();
                if (THIS_KEYWORD.equals(name) || SUPER_KEYWORD.equals(name)) {
                    results.add(itemFactory.createKeywordItem(name, null, anchorOffset, isOfSmartType(env, e.asType(), smartTypes)));
                } else {
                    TypeMirror tm = asMemberOf(e, enclClass != null ? enclClass.asType() : null, types);
                    results.add(itemFactory.createVariableItem(env.getController(), (VariableElement) e, tm, anchorOffset, null, env.getScope().getEnclosingClass() != e.getEnclosingElement(), elements.isDeprecated(e), isOfSmartType(env, tm, smartTypes), env.assignToVarPos()));
                }
                break;
        }
    }
}
 
Example 48
Project: openjdk-jdk10   File: SourceCodeAnalysisImpl.java   Source Code and License 5 votes vote down vote up
private List<? extends Element> primitivesOrVoid(AnalyzeTask at) {
    Types types = at.getTypes();
    return Stream.of(
            TypeKind.BOOLEAN, TypeKind.BYTE, TypeKind.CHAR,
            TypeKind.DOUBLE, TypeKind.FLOAT, TypeKind.INT,
            TypeKind.LONG, TypeKind.SHORT, TypeKind.VOID)
            .map(tk -> (Type)(tk == TypeKind.VOID ? types.getNoType(tk) : types.getPrimitiveType(tk)))
            .map(Type::asElement)
            .collect(toList());
}
 
Example 49
Project: incubator-netbeans   File: PushDownTransformer.java   Source Code and License 5 votes vote down vote up
@Override
public Tree visitClass(ClassTree node, Element source) {
    final GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy);
    final TreePath classPath = getCurrentPath();
    
    ClassTree classTree = node;
    translateQueue.addLast(new HashMap<Tree, Tree>());
    
    Element el = workingCopy.getTrees().getElement(getCurrentPath());
    inSuperClass = el.equals(source);

    Tree value = super.visitClass(classTree, source);
    
    if (inSuperClass) {
        classTree = rewriteSuperClass(el, classTree, genUtils);
    } else {
        TypeMirror tm = el.asType();
        Types types = workingCopy.getTypes();
        Trees trees = workingCopy.getTrees();
        if (types.isSubtype(types.erasure(tm), types.erasure(source.asType()))) {
            classTree = rewriteSubClass(el, source, genUtils, trees, node);
        }
    }
    Map<Tree, Tree> original2Translated = translateQueue.pollLast();
    classTree = (ClassTree) workingCopy.getTreeUtilities().translate(classTree, original2Translated);
    if (/* final boolean notTopLevel = classPath.getParentPath().getLeaf().getKind() != Tree.Kind.COMPILATION_UNIT; */
        !translateQueue.isEmpty()) {
        translateQueue.getLast().put(node, classTree);
    } else {        
        rewrite(node, classTree);
    }
    return value;
}
 
Example 50
Project: openjdk-jdk10   File: JavahTask.java   Source Code and License 5 votes vote down vote up
private void checkMethodParameters(Set<TypeElement> classes) {
    Types types = processingEnv.getTypeUtils();
    for (TypeElement te: classes) {
        for (ExecutableElement ee: ElementFilter.methodsIn(te.getEnclosedElements())) {
            for (VariableElement ve: ee.getParameters()) {
                TypeMirror tm = ve.asType();
                checkMethodParametersVisitor.visit(tm, types);
            }
        }
    }
}
 
Example 51
Project: incubator-netbeans   File: FindSubtypesVisitor.java   Source Code and License 5 votes vote down vote up
private boolean containsType(List<? extends TypeMirror> list, TypeMirror t) {
    Types types = workingCopy.getTypes();
    for (TypeMirror m:list) {
        if (types.isSameType(t, types.erasure(m))) {
            return true;
        }
    }
    return false;
}
 
Example 52
Project: OpenJSharp   File: JavahTask.java   Source Code and License 5 votes vote down vote up
@Override
public Void visitDeclared(DeclaredType t, Types types) {
    t.asElement().getKind(); // ensure class exists
    for (TypeMirror st: types.directSupertypes(t))
        visit(st, types);
    return null;
}
 
Example 53
Project: incubator-netbeans   File: CastVSInstanceOf.java   Source Code and License 5 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value="if ($var instanceof $instanceofClass) {" +
                          "$type $name = ($castClass) $var;" +
                          "$stmts$;" +
                          "}"),
    @TriggerPattern(value="if ($var instanceof $instanceofClass) {" +
                          "final $type $name = ($castClass) $var;" +
                          "$stmts$;" +
                          "}"),
    @TriggerPattern(value="if ($var instanceof $instanceofClass) {" +
                          "$name = ($castClass) $var;" +
                          "$stmts$;" +
                          "}")
})
public static ErrorDescription hint(HintContext ctx) {
    TypeMirror tm1 = ctx.getInfo().getTrees().getTypeMirror(ctx.getVariables().get("$instanceofClass"));
    TreePath castClass = ctx.getVariables().get("$castClass");
    TypeMirror tm2 = ctx.getInfo().getTrees().getTypeMirror(castClass);
    Types t = ctx.getInfo().getTypes();

    if (!(Utilities.isValidType(tm1) && Utilities.isValidType(tm2))) {
        return null;
    }

    tm1 = t.erasure(tm1);
    tm2 = t.erasure(tm2);

    if (t.isSubtype(tm1, tm2)) {
        return null;
    }

    if (t.isSubtype(tm2, tm1)) {
        return null;
    }

    return ErrorDescriptionFactory.forTree(ctx, castClass, NbBundle.getMessage(CastVSInstanceOf.class,"ERR_CastVSInstanceOf"));
}
 
Example 54
Project: incubator-netbeans   File: ExpandEnhancedForLoop.java   Source Code and License 5 votes vote down vote up
@TriggerPattern("for ($type $varName : $expression) { $stmts$; }")
public static ErrorDescription run(HintContext ctx) {
    TreePath tp = ctx.getPath();
    EnhancedForLoopTree efl = (EnhancedForLoopTree) tp.getLeaf();
    long statementStart = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), efl.getStatement());
    int caret = ctx.getCaretLocation();

    if (caret >= statementStart) {
        return null;
    }
    
    TypeMirror expressionType = ctx.getInfo().getTrees().getTypeMirror(new TreePath(tp, efl.getExpression()));

    if (expressionType == null || expressionType.getKind() != TypeKind.DECLARED) {
        return null;
    }

    ExecutableElement iterator = findIterable(ctx.getInfo());
    Types t = ctx.getInfo().getTypes();
    if (iterator == null || !t.isSubtype(((DeclaredType) expressionType), t.erasure(iterator.getEnclosingElement().asType()))) {
        return null;
    }

    FixImpl fix = new FixImpl(TreePathHandle.create(tp, ctx.getInfo()));
    List<Fix> fixes = Collections.<Fix>singletonList(fix.toEditorFix());
    return ErrorDescriptionFactory.createErrorDescription(ctx.getSeverity(),
                                                          NbBundle.getMessage(ExpandEnhancedForLoop.class, "ERR_ExpandEhancedForLoop"),
                                                          fixes,
                                                          ctx.getInfo().getFileObject(),
                                                          caret,
                                                          caret);
    
}
 
Example 55
Project: incubator-netbeans   File: ToolTipAnnotation.java   Source Code and License 5 votes vote down vote up
/**
 * Test if typeElement is a parent of currentElement.
 */
private static boolean testParentOf(Types types, TypeMirror currentElement, TypeMirror typeMirror) {
    List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement);
    for (TypeMirror superType : directSupertypes) {
        if (superType.equals(typeMirror)) {
            return true;
        } else {
            boolean isParent = testParentOf(types, superType, typeMirror);
            if (isParent) {
                return true;
            }
        }
    }
    return false;
}
 
Example 56
Project: r-parser   File: RParser.java   Source Code and License 4 votes vote down vote up
public static Builder builder(Trees trees, Types typesUtils, Elements elementUtils) {
    return new Builder(trees, typesUtils, elementUtils);
}
 
Example 57
Project: datapipelines-java   File: PutManyProcessor.java   Source Code and License 4 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment environment) {
    for(final Element element : environment.getElementsAnnotatedWith(PutMany.class)) {
        final PutMany annotation = element.getAnnotation(PutMany.class);

        if(ElementKind.METHOD != element.getKind()) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not a method.");
        }

        final Set<Modifier> modifiers = element.getModifiers();
        if(!modifiers.contains(Modifier.PUBLIC)) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with public methods only! Tried to use with " + element.getSimpleName()
                    + ", which is not public.");
        }
        if(modifiers.contains(Modifier.STATIC)) {
            throw new DataSinkDefinitionException(
                "Must use @PutMany with non-static methods only! Tried to use with " + element.getSimpleName()
                    + ", which is static.");
        }

        final ExecutableType method = (ExecutableType)element.asType();
        final Types types = processingEnv.getTypeUtils();
        final Elements elements = processingEnv.getElementUtils();

        // annotation.value() will throw the exception because it doesn't have compiled class information yet, and is of type Class<?>.
        TypeMirror annotatedType = null;
        try {
            annotation.value();
        } catch(final MirroredTypeException e) {
            annotatedType = e.getTypeMirror();
        }

        if(TypeKind.VOID != method.getReturnType().getKind()) {
            throw new DataSinkDefinitionException("@PutMany method must have void return! Tried to use with " + element.getSimpleName() + ", which returns "
                + method.getReturnType() + ".");
        }
        if(method.getParameterTypes().size() != 2) {
            throw new DataSinkDefinitionException("@PutMany methods must take 2 arguments: Iterable<T> items, PipelineContext context. Tried to use with "
                + element.getSimpleName() + ", which has a different signature.");
        }

        final TypeElement iterableType = elements.getTypeElement(Iterable.class.getName());
        final TypeMirror[] genericType = new TypeMirror[] {annotatedType};
        final DeclaredType itemsType = types.getDeclaredType(iterableType, genericType);
        final TypeMirror contextType = elements.getTypeElement(PipelineContext.class.getName()).asType();

        if(!types.isAssignable(itemsType, method.getParameterTypes().get(0))) {
            throw new DataSinkDefinitionException(
                "@PutMany method annotated value must be assignable from the generic type of the method's first argument . Tried to use with "
                    + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(0) + ".");
        }
        if(!types.isAssignable(method.getParameterTypes().get(1), contextType)) {
            throw new DataSinkDefinitionException("@PutMany method second argument must be assignable from " + contextType + ". Tried to use with "
                + element.getSimpleName() + ", which takes " + method.getParameterTypes().get(1) + ".");
        }
    }

    return true;
}
 
Example 58
Project: data-mediator   File: OutInterfaceManager.java   Source Code and License 4 votes vote down vote up
/**
 * @see #getAttentionInterfaces(TypeElement, Types, List, ProcessorPrinter)
 */
public static List<? extends TypeMirror> getAttentionInterfaces(TypeElement te,
                                                                Types types, ProcessorPrinter pp){
    return getAttentionInterfaces(te, types , new ArrayList<String>(), pp);
}
 
Example 59
Project: LifecycleAware   File: MethodWrapperGenerator.java   Source Code and License 4 votes vote down vote up
public MethodWrapperGenerator(ClassNameProducer producer, Elements elementUtils, Types typeUtils, Messager messager) {
    super(producer, elementUtils, typeUtils, messager);
}
 
Example 60
Project: android-auto-mapper   File: TypeUtil.java   Source Code and License 4 votes vote down vote up
public static boolean isClassOfType(Types typeUtils, TypeMirror type, TypeMirror cls) {
    return type != null && typeUtils.isAssignable(cls, type);
}