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

The following are top voted examples for showing how to use javax.lang.model.type.TypeMirror. 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: incubator-netbeans   File: SuspiciousToArray.java   Source Code and License 7 votes vote down vote up
private void rewriteNewArrayTree(WorkingCopy copy, TreeMaker mk, TreePath natPath, TypeMirror compType) {
    NewArrayTree nat = (NewArrayTree)natPath.getLeaf();
    TypeMirror existing = copy.getTrees().getTypeMirror(natPath);
    int existingDim = numberOfDimensions(existing);
    int newDim = numberOfDimensions(compType);
    
    if (existingDim == newDim + 1 /* newDim is counted from component type, lacks the enclosing array */) {
        // simple, number of dimensions does not change
        copy.rewrite(nat.getType(), mk.Type(compType));
        return;
    }
    List<ExpressionTree> l = new ArrayList<ExpressionTree>(nat.getDimensions().subList(
            0, Math.min(newDim + 1, nat.getDimensions().size())));
    Tree replacement = mk.NewArray(mk.Type(compType), l, null);
    GeneratorUtilities.get(copy).copyComments(nat, replacement, true);
    GeneratorUtilities.get(copy).copyComments(nat, replacement, false);
    
    copy.rewrite(nat, replacement);
}
 
Example 2
Project: java-code-templates   File: AstSubstitutionProcessor.java   Source Code and License 7 votes vote down vote up
private void handleVarDef(final JCVariableDecl node, final boolean endStatement) {
	final TreePath path = trees.getPath(compilationUnit, node);
	final TypeMirror typeMirror = trees.getElement(path).asType();

	printExpr(node.mods);
	print(substitutionInventory.applyTypeSubstitution(typeMirror));
	print(" ");
	print(node.name); // variable name
	if (node.init != null) {
		print(" = ");
		printExpr(node.init);
	}
	if (endStatement) {
		print(";");
	}
}
 
Example 3
Project: incubator-netbeans   File: MethodExitDetector.java   Source Code and License 7 votes vote down vote up
@Override
public Boolean visitMethodInvocation(MethodInvocationTree tree, Stack<Tree> d) {
    Element el = info.getTrees().getElement(new TreePath(getCurrentPath(), tree.getMethodSelect()));
    
    if (el == null) {
        System.err.println("Warning: decl == null");
        System.err.println("tree=" + tree);
    }
    
    if (el != null && el.getKind() == ElementKind.METHOD) {
        for (TypeMirror m : ((ExecutableElement) el).getThrownTypes()) {
            addToExceptionsMap(m, tree);
        }
    }
    
    super.visitMethodInvocation(tree, d);
    return null;
}
 
Example 4
Project: incubator-netbeans   File: MethodExitDetector.java   Source Code and License 6 votes vote down vote up
private void addToExceptionsMap(TypeMirror key, Tree value) {
    if (key == null || value == null)
        return ;
    
    Map<TypeMirror, List<Tree>> map = exceptions2HighlightsStack.peek();
    
    if (map == null) {
        map = new HashMap<TypeMirror, List<Tree>>();
        exceptions2HighlightsStack.pop();
        exceptions2HighlightsStack.push(map);
    }
    
    List<Tree> l = map.get(key);
    
    if (l == null) {
        map.put(key, l = new ArrayList<Tree>());
    }
    
    l.add(value);
}
 
Example 5
Project: incubator-netbeans   File: BeanModelBuilder.java   Source Code and License 6 votes vote down vote up
private void processGetters() {
    // Check presence !
    TypeMirror listType = compilationInfo.getElements().getTypeElement(LIST_CLASS).asType();
    TypeMirror mapType = compilationInfo.getElements().getTypeElement(MAP_CLASS).asType();
    for (ExecutableElement m : getters) {
        String n = getPropertyName(m.getSimpleName().toString());
        if (allProperties.containsKey(n)) {
            continue;
        }
        TypeMirror retType = m.getReturnType();
        TypeMirror erasure = compilationInfo.getTypes().erasure(retType);
        if (compilationInfo.getTypes().isAssignable(erasure, listType)) {
            addListProperty(m, n);
        } else if (compilationInfo.getTypes().isAssignable(erasure, mapType)) {
            addMapProperty(m, n);
        }
    }
}
 
Example 6
Project: javaide   File: PrintingProcessor.java   Source Code and License 6 votes vote down vote up
private void printInterfaces(TypeElement e) {
    ElementKind kind = e.getKind();

    if(kind != ANNOTATION_TYPE) {
        List<? extends TypeMirror> interfaces = e.getInterfaces();
        if (interfaces.size() > 0) {
            writer.print((kind.isClass() ? " implements" : " extends"));

            boolean first = true;
            for(TypeMirror interf: interfaces) {
                if (!first)
                    writer.print(",");
                writer.print(" ");
                writer.print(interf.toString());
                first = false;
            }
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: EnumValueCompleter.java   Source Code and License 6 votes vote down vote up
@Override
public Completer createCompleter(CompletionContext ctx) {
    FxProperty p = ctx.getEnclosingProperty();
    if (p == null || p.getType() == null) {
        return null;
    }
    TypeMirror m = p.getType().resolve(ctx.getCompilationInfo());
    if (m.getKind() == TypeKind.BOOLEAN) {
        return new EnumValueCompleter(ctx);
    }
    if (m.getKind() != TypeKind.DECLARED) {
        return null;
    }
    DeclaredType t = (DeclaredType)m;
    TypeElement tel = (TypeElement)t.asElement();
    if (tel.getQualifiedName().contentEquals("java.lang.Boolean")) {
        return new EnumValueCompleter(ctx);
    }
    if (tel.getKind() == ElementKind.ENUM) {
        return new EnumValueCompleter(ctx, tel);
    } else {
        return null;
    }
}
 
Example 8
Project: incubator-netbeans   File: BeanModelBuilder.java   Source Code and License 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 9
Project: annotation-processor-toolkit   File: TypeUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Checks whether passed typeElement is assignable to passed genericType.
 *
 * @param typeMirror  the type element to check
 * @param genericType the genric type to check
 * @return true if typeElement is assignable to genericType otherwise false.
 */
public boolean genericIsAssignableTo(TypeMirror typeMirror, GenericType genericType) {

    if (typeMirror == null || genericType == null) {
        return false;
    }

    TypeMirror typeMirrorToCompareWith = genericType.getRawType();
    if (typeMirrorToCompareWith == null) {
        return false;
    }

    // Compare raw types - this will not work for super wildcard type since it has Object as raw type
    if (!typeComparison.isAssignableTo(getTypes().erasure(typeMirror), getTypes().erasure(typeMirrorToCompareWith))) {
        return false;
    }

    return isAssignableToGenericTypeRecursively(typeMirror, genericType);
}
 
Example 10
Project: incubator-netbeans   File: MethodExitDetector.java   Source Code and License 6 votes vote down vote up
@Override
public Boolean visitCatch(CatchTree tree, Stack<Tree> d) {
    TypeMirror type1 = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), tree.getParameter()), tree.getParameter().getType()));
    Types t = info.getTypes();
    
    if (type1 != null) {
        Set<TypeMirror> toRemove = new HashSet<TypeMirror>();
        Map<TypeMirror, List<Tree>> exceptions2Highlights = exceptions2HighlightsStack.peek();
        
        if (exceptions2Highlights != null) {
            for (TypeMirror type2 : exceptions2Highlights.keySet()) {
                if (t.isAssignable(type2, type1)) {
                    toRemove.add(type2);
                }
            }
            
            for (TypeMirror type : toRemove) {
                exceptions2Highlights.remove(type);
            }
        }
        
    }
    
    scan(tree.getParameter(), d);
    return scan(tree.getBlock(), d);
}
 
Example 11
Project: GitHub   File: ButterKnifeProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a method name from the {@link android.content.res.Resources} class for array resource
 * binding, null if the element type is not supported.
 */
private static FieldResourceBinding.Type getArrayResourceMethodName(Element element) {
  TypeMirror typeMirror = element.asType();
  if (TYPED_ARRAY_TYPE.equals(typeMirror.toString())) {
    return FieldResourceBinding.Type.TYPED_ARRAY;
  }
  if (TypeKind.ARRAY.equals(typeMirror.getKind())) {
    ArrayType arrayType = (ArrayType) typeMirror;
    String componentType = arrayType.getComponentType().toString();
    if (STRING_TYPE.equals(componentType)) {
      return FieldResourceBinding.Type.STRING_ARRAY;
    } else if ("int".equals(componentType)) {
      return FieldResourceBinding.Type.INT_ARRAY;
    } else if ("java.lang.CharSequence".equals(componentType)) {
      return FieldResourceBinding.Type.TEXT_ARRAY;
    }
  }
  return null;
}
 
Example 12
Project: android-auto-mapper   File: MoreTypes.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the non-object superclass of the type with the proper type parameters.
 * An absent Optional is returned if there is no non-Object superclass.
 */
public static Optional<DeclaredType> nonObjectSuperclass(final Types types, Elements elements,
                                                         DeclaredType type) {
    checkNotNull(types);
    checkNotNull(elements);
    checkNotNull(type);

    final TypeMirror objectType =
            elements.getTypeElement(Object.class.getCanonicalName()).asType();
    // It's guaranteed there's only a single CLASS superclass because java doesn't have multiple
    // class inheritance.
    TypeMirror superclass = getOnlyElement(FluentIterable.from(types.directSupertypes(type))
            .filter(new Predicate<TypeMirror>() {
                @Override
                public boolean apply(TypeMirror input) {
                    return input.getKind().equals(TypeKind.DECLARED)
                            && (MoreElements.asType(
                            MoreTypes.asDeclared(input).asElement())).getKind().equals(ElementKind.CLASS)
                            && !types.isSameType(objectType, input);
                }
            }), null);
    return superclass != null
            ? Optional.of(MoreTypes.asDeclared(superclass))
            : Optional.<DeclaredType>absent();
}
 
Example 13
Project: incubator-netbeans   File: CreateElementUtilities.java   Source Code and License 6 votes vote down vote up
private static List<? extends TypeMirror> computeMethodInvocation(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    MethodInvocationTree nat = (MethodInvocationTree) parent.getLeaf();
    boolean errorInRealArguments = false;
    
    for (Tree param : nat.getArguments()) {
        errorInRealArguments |= param == error;
    }
    
    if (errorInRealArguments) {
        List<TypeMirror> proposedTypes = new ArrayList<TypeMirror>();
        int[] proposedIndex = new int[1];
        List<ExecutableElement> ee = fuzzyResolveMethodInvocation(info, parent, proposedTypes, proposedIndex);
        
        if (ee.isEmpty()) { //cannot be resolved
            return null;
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return proposedTypes;
    }
    
    return null;
}
 
Example 14
Project: GitHub   File: Proto.java   Source Code and License 6 votes vote down vote up
@Value.Lazy
List<TypeElement> builderIncludedTypes() {
  Optional<FIncludeMirror> includes = builderInclude();

  ImmutableList<TypeMirror> typeMirrors = includes.isPresent()
      ? ImmutableList.copyOf(includes.get().valueMirror())
      : ImmutableList.<TypeMirror>of();

  FluentIterable<TypeElement> typeElements = FluentIterable.from(typeMirrors)
      .filter(DeclaredType.class)
      .transform(DeclatedTypeToElement.FUNCTION);

  ImmutableSet<String> uniqueTypeNames = typeElements
      .filter(IsPublic.PREDICATE)
      .transform(ElementToName.FUNCTION)
      .toSet();

  if (uniqueTypeNames.size() != typeMirrors.size()) {
    report().annotationNamed(IncludeMirror.simpleName())
        .warning("Some types were ignored, non-supported for inclusion: duplicates,"
            + " non declared reference types, non-public");
  }

  return typeElements.toList();
}
 
Example 15
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 16
Project: incubator-netbeans   File: ControllerGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public TypeMirror visitDeclared(DeclaredType t, CompilationInfo p) {
    if (t.getTypeArguments().isEmpty()) {
        return t;
    }
    List<TypeMirror> newArgs = new ArrayList<TypeMirror>(t.getTypeArguments().size());
    for (TypeMirror tm : t.getTypeArguments()) {
        newArgs.add(visit(tm, p));
    }
    
    TypeMirror enclosing = t.getEnclosingType();
    if (enclosing != null) {
        enclosing = visit(enclosing, p);
    }
    
    return p.getTypes().getDeclaredType(
        (DeclaredType)enclosing,
        (TypeElement)t.asElement(), 
        newArgs.toArray(new TypeMirror[newArgs.size()]));
}
 
Example 17
Project: OpenJSharp   File: TypeModeler.java   Source Code and License 6 votes vote down vote up
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {

        TypeElement retClass = null;
        if (theClass.getKind().equals(ElementKind.CLASS)) {
            TypeMirror superClass = theClass.getSuperclass();
            if (!superClass.getKind().equals(TypeKind.NONE))
                retClass = getDeclaringClassMethod(superClass, methodName, args);
        }
        if (retClass == null) {
            for (TypeMirror interfaceType : theClass.getInterfaces()) {
                retClass = getDeclaringClassMethod(interfaceType, methodName, args);
            }
        }
        if (retClass == null) {
            Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
            for (ExecutableElement method : methods) {
                if (method.getSimpleName().toString().equals(methodName)) {
                    retClass = theClass;
                    break;
                }
            }
        }
        return retClass;
    }
 
Example 18
Project: GitHub   File: ViewStateProviderClassGenerator.java   Source Code and License 6 votes vote down vote up
private String getViewClassFromAnnotationParams(TypeElement typeElement) {
	InjectViewState annotation = typeElement.getAnnotation(InjectViewState.class);
	String mvpViewClassName = "";

	if (annotation != null) {
		TypeMirror value = null;
		try {
			annotation.view();
		} catch (MirroredTypeException mte) {
			value = mte.getTypeMirror();
		}

		mvpViewClassName = Util.getFullClassName(value);
	}

	if (mvpViewClassName.isEmpty() || DefaultView.class.getName().equals(mvpViewClassName)) {
		return null;
	}

	return mvpViewClassName;
}
 
Example 19
Project: GitHub   File: ViewStateProviderClassGenerator.java   Source Code and License 6 votes vote down vote up
private String getViewStateClassFromAnnotationParams(TypeElement typeElement) {
	InjectViewState annotation = typeElement.getAnnotation(InjectViewState.class);
	String mvpViewStateClassName = "";

	if (annotation != null) {
		TypeMirror value;
		try {
			annotation.value();
		} catch (MirroredTypeException mte) {
			value = mte.getTypeMirror();
			mvpViewStateClassName = value.toString();
		}
	}

	if (mvpViewStateClassName.isEmpty() || DefaultViewState.class.getName().equals(mvpViewStateClassName)) {
		return null;
	}

	return mvpViewStateClassName;
}
 
Example 20
Project: inspector   File: InspectorFactoryProcessor.java   Source Code and License 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 21
Project: butterknife-parent   File: ButterKnifeProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a method name from the {@link android.content.res.Resources} class for array resource
 * binding, null if the element type is not supported.
 */
private static FieldResourceBinding.Type getArrayResourceMethodName(Element element) {
  TypeMirror typeMirror = element.asType();
  if (TYPED_ARRAY_TYPE.equals(typeMirror.toString())) {
    return FieldResourceBinding.Type.TYPED_ARRAY;
  }
  if (TypeKind.ARRAY.equals(typeMirror.getKind())) {
    ArrayType arrayType = (ArrayType) typeMirror;
    String componentType = arrayType.getComponentType().toString();
    if (STRING_TYPE.equals(componentType)) {
      return FieldResourceBinding.Type.STRING_ARRAY;
    } else if ("int".equals(componentType)) {
      return FieldResourceBinding.Type.INT_ARRAY;
    } else if ("java.lang.CharSequence".equals(componentType)) {
      return FieldResourceBinding.Type.TEXT_ARRAY;
    }
  }
  return null;
}
 
Example 22
Project: GitHub   File: PresenterInjectorRules.java   Source Code and License 6 votes vote down vote up
private void checkEnvironment(final Element annotatedField) {
	if (!(annotatedField.asType() instanceof DeclaredType)) {
		return;
	}

	TypeElement typeElement = (TypeElement) ((DeclaredType) annotatedField.asType()).asElement();
	String viewClassFromGeneric = getViewClassFromGeneric(typeElement, (DeclaredType) annotatedField.asType());

	Collection<TypeMirror> viewsType = getViewsType((TypeElement) ((DeclaredType) annotatedField.getEnclosingElement().asType()).asElement());

	boolean result = false;

	for (TypeMirror typeMirror : viewsType) {
		if (Util.getFullClassName(typeMirror).equals(viewClassFromGeneric) || Util.fillGenerics(Collections.<String, String>emptyMap(), typeMirror).equals(viewClassFromGeneric)) {
			result = true;
			break;
		}
	}
	if (!result) {
		MvpCompiler.getMessager().printMessage(Diagnostic.Kind.ERROR, "You can not use @InjectPresenter in classes that are not View, which is typified target Presenter", annotatedField);
	}
}
 
Example 23
Project: easyprefs   File: ExposedMethod.java   Source Code and License 6 votes vote down vote up
public ExposedMethod(Element element) {
    ExecutableType method = (ExecutableType) element.asType();
    TypeElement declaringClass = (TypeElement) element.getEnclosingElement();
    this.name = element.getSimpleName().toString();
    this.originalMethod = declaringClass.getQualifiedName().toString() + "." + element.getSimpleName();
    this.returnType = method.getReturnType().toString();
    this.params = new ArrayList<>();
    int count = 0;
    for (TypeMirror param : method.getParameterTypes()) {
        this.params.add(param.toString());
        String[] components = param.toString().toLowerCase().split("\\.");
        String paramName = components[components.length - 1];
        if (paramName.endsWith(">")) {
            paramName = paramName.substring(0, paramName.length() - 1);
        }
        this.params.add(paramName + count);
        count++;
    }
    this.thrown = Stream.of(method.getThrownTypes()).map(new Function<TypeMirror, String>() {
        @Override
        public String apply(TypeMirror typeMirror) {
            return typeMirror.toString();
        }
    }).toList();
}
 
Example 24
Project: GitHub   File: PresenterInjectorRules.java   Source Code and License 6 votes vote down vote up
private Collection<TypeMirror> getViewsType(TypeElement typeElement) {
	TypeMirror superclass = typeElement.asType();

	List<TypeMirror> result = new ArrayList<>();

	while (superclass.getKind() != TypeKind.NONE) {
		TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();
		Collection<? extends TypeMirror> interfaces = new HashSet<>(superclassElement.getInterfaces());
		for (TypeMirror typeMirror : interfaces) {
			if (typeMirror instanceof DeclaredType) {
				result.addAll(getViewsType((TypeElement) ((DeclaredType) typeMirror).asElement()));
			}
		}
		result.addAll(interfaces);
		result.add(superclass);

		superclass = superclassElement.getSuperclass();
	}

	return result;
}
 
Example 25
Project: domino   File: RequestFactorySourceWriter.java   Source Code and License 6 votes vote down vote up
private TypeSpec makeRequestClass(ExecutableElement method) {

        TypeName requestTypeName = getRequestClassName(method);
        DeclaredType responseReturnType = (DeclaredType) method.getReturnType();
        TypeMirror responseBean = responseReturnType.getTypeArguments().get(0);


        TypeSpec.Builder requestBuilder = TypeSpec.classBuilder(processorElement.simpleName() + "_" + method.getSimpleName())
                .addModifiers(Modifier.PUBLIC)
                .superclass(ParameterizedTypeName.get(ClassName.get(ServerRequest.class),
                        requestTypeName,
                        ClassName.get(responseBean)))
                .addMethod(constructor(requestTypeName));

        requestBuilder.addAnnotation(AnnotationSpec.builder(Request.class).build());
        requestBuilder.addAnnotation(pathAnnotation(method.getAnnotation(Path.class)));

        return requestBuilder.build();
    }
 
Example 26
Project: affinechecker   File: AffinePointerValue.java   Source Code and License 5 votes vote down vote up
private AnnotatedTypeVariable getEffectTypeVar(TypeMirror typeMirror) {
    if (typeMirror == null) {
        return null;
    } else if (typeMirror.getKind() == TypeKind.WILDCARD) {
        return getEffectTypeVar(((WildcardType) typeMirror).getExtendsBound());

    } else if (typeMirror.getKind() == TypeKind.TYPEVAR) {
        TypeVariable typevar = ((TypeVariable) typeMirror);
        AnnotatedTypeMirror atm =
                analysis.getTypeFactory().getAnnotatedType(typevar.asElement());
        return (AnnotatedTypeVariable) atm;
    } else {
        return null;
    }
}
 
Example 27
Project: incubator-netbeans   File: JDIWrappersTest.java   Source Code and License 5 votes vote down vote up
private TypeMirror adjustTypeMirror(TypeMirror tm) {
    if (tm.getKind() == TypeKind.EXECUTABLE) {
        tm = ((ExecutableType) tm).getReturnType();
        tm = adjustTypeMirror(tm);
    } else if (tm.getKind() == TypeKind.ARRAY) {
        tm = ((ArrayType) tm).getComponentType();
        tm = adjustTypeMirror(tm);
    }
    return tm;
}
 
Example 28
Project: data-mediator   File: ElementHandle.java   Source Code and License 5 votes vote down vote up
public static Method create(ExecutableElement elt) { 
  TypeElement typeElt = (TypeElement)elt.getEnclosingElement(); 
  String name = elt.getSimpleName().toString(); 
  FQN fqn = new FQN(typeElt.getQualifiedName().toString()); 
  ArrayList<String> parameterTypes = new ArrayList<String>(); 
  for (TypeMirror parameterType : ((ExecutableType)elt.asType()).getParameterTypes()) {
    parameterTypes.add(parameterType.toString()); 
  } 
 
  return new Method(fqn, name, parameterTypes); 
}
 
Example 29
Project: incubator-netbeans   File: ExpectedTypeResolver.java   Source Code and License 5 votes vote down vote up
@Override
public List<? extends TypeMirror> visitDoWhileLoop(DoWhileLoopTree node, Object p) {
    if (theExpression == null) {
        initExpression(node.getCondition());
    } else if (theExpression.getLeaf() != node.getCondition()) {
        return null;
    }
    return booleanType();
}
 
Example 30
Project: Witch-Android   File: AnnotationUtils.java   Source Code and License 5 votes vote down vote up
public static TypeMirror getOnBindTypeMirror(Element action) {
    TypeMirror bindClass;
    try {
        action.getAnnotation(se.snylt.witch.annotations.OnBind.class).value();
        return null;
    } catch (MirroredTypeException mte) {
        bindClass = mte.getTypeMirror();
    }
    return bindClass;
}
 
Example 31
Project: OpenJSharp   File: JavacTrees.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the original type from the ErrorType object.
 * @param errorType The errorType for which we want to get the original type.
 * @returns TypeMirror corresponding to the original type, replaced by the ErrorType.
 *          noType (type.tag == NONE) is returned if there is no original type.
 */
public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
    if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
        return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
    }

    return com.sun.tools.javac.code.Type.noType;
}
 
Example 32
Project: incubator-netbeans   File: ExtractSuperclassRefactoringPlugin.java   Source Code and License 5 votes vote down vote up
private static MethodTree removeRuntimeExceptions(final WorkingCopy javac, ExecutableElement superclassConstr, final TreeMaker make, MethodTree newConstr) {
    int i = 0;
    TypeMirror rte = javac.getElements().getTypeElement("java.lang.RuntimeException").asType(); //NOI18N
    ArrayList<Integer> rtes = new ArrayList<Integer>();
    for (TypeMirror throwz : superclassConstr.getThrownTypes()) {
        if (javac.getTypes().isSubtype(throwz, rte)) {
            rtes.add(i);
        }
        i++;
    }
    for (int j = rtes.size()-1; j >= 0; j--) {
        newConstr = make.removeMethodThrows(newConstr, rtes.get(j));
    }
    return newConstr;
}
 
Example 33
Project: openjdk-jdk10   File: JavacTrees.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the original type from the ErrorType object.
 * @param errorType The errorType for which we want to get the original type.
 * @return TypeMirror corresponding to the original type, replaced by the ErrorType.
 *         noType (type.tag == NONE) is returned if there is no original type.
 */
@Override @DefinedBy(Api.COMPILER_TREE)
public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
    if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
        return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
    }

    return com.sun.tools.javac.code.Type.noType;
}
 
Example 34
Project: incubator-netbeans   File: ResourceStringFoldProvider.java   Source Code and License 5 votes vote down vote up
private void processGetBundleCall(MethodInvocationTree node) {
    TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());
    if (resourceBundleType == null ||tm == null || tm.getKind() != TypeKind.DECLARED) {
        return;
    }
    if (!info.getTypes().isAssignable(tm, resourceBundleType)) {
        return;
    }
    
    // OK, get the parameter said to describe the bundle name
    exprBundleName = getBundleName(node, messageMethod.getBundleParam(), messageMethod.getBundleFile());
}
 
Example 35
Project: incubator-netbeans   File: LookupProviderAnnotationProcessor.java   Source Code and License 5 votes vote down vote up
private List<TypeMirror> findServiceAnnotation(Element e) throws LayerGenerationException {
    for (AnnotationMirror ann : e.getAnnotationMirrors()) {
        if (!ProjectServiceProvider.class.getName().equals(ann.getAnnotationType().toString())) {
            continue;
        }
        for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> attr : ann.getElementValues().entrySet()) {
            if (!attr.getKey().getSimpleName().contentEquals("service")) {
                continue;
            }
            List<TypeMirror> r = new ArrayList<TypeMirror>();
            for (Object item : (List<?>) attr.getValue().getValue()) {
                TypeMirror type = (TypeMirror) ((AnnotationValue) item).getValue();
                Types typeUtils = processingEnv.getTypeUtils();
                for (TypeMirror otherType : r) {
                    for (boolean swap : new boolean[] {false, true}) {
                        TypeMirror t1 = swap ? type : otherType;
                        TypeMirror t2 = swap ? otherType : type;
                        if (typeUtils.isSubtype(t1, t2)) {
                            processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "registering under both " + typeUtils.asElement(t2).getSimpleName() + " and its subtype " + typeUtils.asElement(t1).getSimpleName() + " will not work if LookupMerger<" + typeUtils.asElement(t2).getSimpleName() + "> is used (#205151)", e, ann, attr.getValue());
                        }
                    }
                }
                r.add(type);
            }
            return r;
        }
        throw new LayerGenerationException("No service attr found", e);
    }
    throw new LayerGenerationException("No @ProjectServiceProvider found", e);
}
 
Example 36
Project: incubator-netbeans   File: MethodExitDetector.java   Source Code and License 5 votes vote down vote up
private void doPopup() {
    Map<TypeMirror, List<Tree>> top = exceptions2HighlightsStack.pop();
    
    if (top == null)
        return ;
    
    Map<TypeMirror, List<Tree>> result = exceptions2HighlightsStack.pop();
    
    if (result == null) {
        exceptions2HighlightsStack.push(top);
        return ;
    }
    
    for (TypeMirror key : top.keySet()) {
        List<Tree> topKey    = top.get(key);
        List<Tree> resultKey = result.get(key);
        
        if (topKey == null)
            continue;
        
        if (resultKey == null) {
            result.put(key, topKey);
            continue;
        }
        
        resultKey.addAll(topKey);
    }
    
    exceptions2HighlightsStack.push(result);
}
 
Example 37
Project: RapidRouter   File: RouterProcessor.java   Source Code and License 5 votes vote down vote up
private static TypeMirror getParamTypeMirror(RRParam rrParam) {
    try {
        rrParam.type();
    } catch (MirroredTypeException mte) {
        return mte.getTypeMirror();
    }
    return null;
}
 
Example 38
Project: incubator-netbeans   File: TransformationSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Performs transformation described by transformationJackpotPattern on all occurences described by inputJackpotPattern.
 * @param inputJackpotPattern
 * @param transformationJackpotPattern
 * @param cancel 
 * @return
 */
private static Collection<? extends ModificationResult> performTransformation(String inputJackpotPattern, final String transformationJackpotPattern, AtomicBoolean cancel) {
    return performTransformation(inputJackpotPattern, new Transformer() {

        @Override
        public void transform(WorkingCopy copy, Occurrence occurrence) {
            try {
                Fix toFix = TransformationSupport.rewriteFix(copy, "whatever", occurrence.getOccurrenceRoot(), transformationJackpotPattern, occurrence.getVariables(), occurrence.getMultiVariables(), occurrence.getVariables2Names(), Collections.<String, TypeMirror>emptyMap(), Collections.<String, String>emptyMap());
                TransformationSupport.process(((JavaFixImpl) toFix).jf, copy, false, null, new ArrayList<RefactoringElementImplementation>());
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }, cancel);
}
 
Example 39
Project: dataenum   File: ValueParser.java   Source Code and License 5 votes vote down vote up
private static boolean isValueSpecMarker(
    TypeMirror returnType, ProcessingEnvironment processingEnvironment) {
  Types types = processingEnvironment.getTypeUtils();
  Elements elements = processingEnvironment.getElementUtils();

  return types.isSameType(
      returnType, elements.getTypeElement(dataenum_case.class.getCanonicalName()).asType());
}
 
Example 40
Project: incubator-netbeans   File: TypeUtilitiesTest.java   Source Code and License 5 votes vote down vote up
public void testSubstitute() throws Exception {
    JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0])), ClassPathSupport.createClassPath(new URL[0]), ClassPathSupport.createClassPath(new URL[0])));
    
    js.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController info)  {
            TypeElement jlStringElement = info.getElements().getTypeElement("java.lang.String");
            TypeMirror jlString = info.getTypes().getDeclaredType(jlStringElement);
            TypeElement juListElement = info.getElements().getTypeElement("java.util.List");
            TypeMirror juListString = info.getTypes().getDeclaredType(juListElement, jlString);
            
            DeclaredType juListType = (DeclaredType) juListElement.asType();
            TypeMirror substituted = info.getTypeUtilities().substitute(juListType, juListType.getTypeArguments(), Collections.singletonList(jlString));
            
            assertTrue(info.getTypes().isSameType(juListString, substituted));
            
            boolean wasThrown = false;
            
            try {
                info.getTypeUtilities().substitute(juListType, juListType.getTypeArguments(), Collections.<TypeMirror>emptyList());
            } catch (IllegalArgumentException ex) {
                wasThrown = true;
            }
            
            assertTrue(wasThrown);
        }
    }, true);
    
}
 
Example 41
Project: incubator-netbeans   File: TreeUtilitiesTest.java   Source Code and License 5 votes vote down vote up
public void testUncaughtExceptionHandler() throws Exception {
    String code = "package test;\n" +
                  "public class Test {\n" +
                  "    public static void test() {\n" +
                  "        t(ne|w Runnable() {\n" +
                  "            public void run() {\n" +
                  "                throw new UnsupportedOperationException();\n" +
                  "            }\n" +
                  "        });\n"+
                  "    }\n" +
                  "    private static void t(Runnable r) {}\n" +
                  "}\n";
    int pos = code.indexOf('|');

    prepareTest("Test", code.replaceAll(Pattern.quote("|"), ""));

    TreePath tp = info.getTreeUtilities().pathFor(pos);
    Set<TypeMirror> uncaughtExceptions = info.getTreeUtilities().getUncaughtExceptions(tp);
    Set<String> uncaughtExceptionStrings = new HashSet<String>();

    for (TypeMirror tm : uncaughtExceptions) {
        uncaughtExceptionStrings.add(tm.toString());
    }

    Set<String> golden = new HashSet<String>();

    assertEquals(golden, uncaughtExceptionStrings);
}
 
Example 42
Project: DUnit   File: DUnitModelUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取DUnit的group字段的TypeMirror
 */
public TypeMirror getUnitModelGroupTypeMirror(DUnit dUnit){
	try {
		dUnit.group();
	}catch (MirroredTypeException e){
		TypeMirror typeMirror = e.getTypeMirror();
		return typeMirror;
	}
	return null;
}
 
Example 43
Project: openjdk-jdk10   File: ReturnTaglet.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Content getTagletOutput(Element holder, TagletWriter writer) {
    Messages messages = writer.configuration().getMessages();
    Utils utils = writer.configuration().utils;
    TypeMirror returnType = utils.getReturnType((ExecutableElement)holder);
    List<? extends DocTree> tags = utils.getBlockTags(holder, name);

    //Make sure we are not using @return tag on method with void return type.
    if (returnType != null && utils.isVoid(returnType)) {
        if (!tags.isEmpty()) {
            messages.warning(holder, "doclet.Return_tag_on_void_method");
        }
        return null;
    }
    if (!tags.isEmpty())
        return writer.returnTagOutput(holder, tags.get(0));
    //Inherit @return tag if necessary.
    List<DocTree> ntags = new ArrayList<>();
    Input input = new DocFinder.Input(utils, holder, this);
    DocFinder.Output inheritedDoc = DocFinder.search(writer.configuration(), input);
    if (inheritedDoc.holderTag != null) {
        CommentHelper ch = utils.getCommentHelper(input.element);
        ch.setOverrideElement(inheritedDoc.holder);
        ntags.add(inheritedDoc.holderTag);
    }
    return !ntags.isEmpty() ? writer.returnTagOutput(holder, ntags.get(0)) : null;
}
 
Example 44
Project: GeneratorX   File: AnnotatedClass.java   Source Code and License 5 votes vote down vote up
public AnnotatedClass(TypeElement typeElement, List<String> variableNames,
        HashMap<String, TypeMirror> map, boolean isParce) {

    this.annotatedClassName = typeElement.getSimpleName().toString();
    generatorClassName = annotatedClassName + "X";
    this.variableNames = variableNames;
    this.typeElement = typeElement;
    this.variableMap = map;
    this.isParcelable = isParce;
}
 
Example 45
Project: openjdk-jdk10   File: MethodSubstitutionVerifier.java   Source Code and License 5 votes vote down vote up
/**
 * Tests whether one type is a subtype of another. Any type is considered to be a subtype of
 * itself.
 *
 * @param t1 the first type
 * @param t2 the second type
 * @return {@code true} if and only if the first type is a subtype of the second
 */
private boolean isSubtype(TypeMirror t1, TypeMirror t2) {
    TypeMirror t1Erased = t1;
    TypeMirror t2Erased = t2;
    if (needsErasure(t1Erased)) {
        t1Erased = env.getTypeUtils().erasure(t1Erased);
    }
    if (needsErasure(t2Erased)) {
        t2Erased = env.getTypeUtils().erasure(t2Erased);
    }
    return env.getTypeUtils().isSubtype(t1Erased, t2Erased);
}
 
Example 46
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 47
Project: incubator-netbeans   File: EqualsHashCodeGenerator.java   Source Code and License 5 votes vote down vote up
private static String choosePattern(CompilationInfo info, TypeMirror tm, Map<Acceptor, String> patterns) {
    for (Entry<Acceptor, String> e : patterns.entrySet()) {
        if (e.getKey().accept(info, tm)) {
            return e.getValue();
        }
    }

    throw new IllegalStateException();
}
 
Example 48
Project: remoter   File: IntParamBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public void readResultsFromProxy(TypeMirror resultType, MethodSpec.Builder methodBuilder) {
    if (resultType.getKind() == TypeKind.ARRAY) {
        methodBuilder.addStatement("result = reply.createIntArray()");
    } else {
        methodBuilder.addStatement("result = reply.readInt()");
    }
}
 
Example 49
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 50
Project: incubator-netbeans   File: UtilitiesTest.java   Source Code and License 5 votes vote down vote up
public void testParseAndAttributeMethodDeclarationWithMultiparameters() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "public void t($params$) {}", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.METHOD);

    String golden = " public void t($params$) { }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
}
 
Example 51
Project: incubator-netbeans   File: Flow.java   Source Code and License 5 votes vote down vote up
private void recordResumeOnExceptionHandler(ExecutableElement invoked) {
            for (TypeMirror tt : invoked.getThrownTypes()) {
                recordResumeOnExceptionHandler(tt);
            }

//            recordResumeOnExceptionHandler(runtimeExceptionType);
//            recordResumeOnExceptionHandler(errorType);
        }
 
Example 52
Project: GitHub   File: TypeResolver.java   Source Code and License 5 votes vote down vote up
TypeMirror resolve(Trees.TypeDeclaration type) {
  TypeMirror resolved = knife.imports.get(type.type().value());
  if (resolved == null) {
    throw new TypingException(String.format("Could not resolve %s simple type", type));
  }
  if (type.kind() == Trees.TypeDeclaration.Kind.ITERABLE) {
    resolved = makeIterableTypeOf(resolved);
  }
  return resolved;
}
 
Example 53
Project: openjdk-jdk10   File: Utils.java   Source Code and License 5 votes vote down vote up
public TypeElement getFirstVisibleSuperClassAsTypeElement(TypeElement te) {
    if (isAnnotationType(te) || isInterface(te) ||
            te.asType().equals(getObjectType())) {
        return null;
    }
    TypeMirror firstVisibleSuperClass = getFirstVisibleSuperClass(te);
    return firstVisibleSuperClass == null ? null : asTypeElement(firstVisibleSuperClass);
}
 
Example 54
Project: remoter   File: DoubleParamBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public void readResultsFromStub(TypeMirror resultType, MethodSpec.Builder methodBuilder) {
    if (resultType.getKind() == TypeKind.ARRAY) {
        methodBuilder.addStatement("reply.writeDoubleArray(result)");
    } else {
        methodBuilder.addStatement("reply.writeDouble(result)");
    }
}
 
Example 55
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 56
Project: incubator-netbeans   File: CreateElementUtilities.java   Source Code and License 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 57
Project: incubator-netbeans   File: ControllerGenerator.java   Source Code and License 5 votes vote down vote up
private boolean isGenerated(String name, TypeMirror paramType) {
    Collection<TypeMirror> param = generatedMethods.get(name);
    if (param == null) {
        return false;
    }
    for (TypeMirror tm : param) {
        if (wcopy.getTypes().isSameType(tm, paramType)) {
            return true;
        }
    }
    return false;
}
 
Example 58
Project: incubator-netbeans   File: ExpectedTypeResolver.java   Source Code and License 4 votes vote down vote up
@Override
public List<? extends TypeMirror> visitModifiers(ModifiersTree node, Object p) {
    return null;
}
 
Example 59
Project: Spyglass   File: TestTypeMirrorHelper.java   Source Code and License 4 votes vote down vote up
@Test
public void testIsPrimitive_typeMirrorForBoxedFloat() {
	final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType();

	assertThat(helper.isPrimitive(typeMirror), is(false));
}
 
Example 60
Project: Spyglass   File: TestTypeMirrorHelper.java   Source Code and License 4 votes vote down vote up
@Test
public void testIsCharacter_typeMirrorForBoxedLong() {
	final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType();

	assertThat(helper.isCharacter(typeMirror), is(false));
}