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

The following examples show how to use javax.lang.model.util.Types. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: buck   Source File: ClassVisitorDriverFromElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param targetVersion the class file version to target, expressed as the corresponding Java
 *     source version
 * @param messager
 * @param types
 * @param includeParameterMetadata
 */
ClassVisitorDriverFromElement(
    SourceVersion targetVersion,
    ElementsExtended elements,
    Messager messager,
    Types types,
    boolean includeParameterMetadata) {
  this.targetVersion = targetVersion;
  this.elements = elements;
  descriptorFactory = new DescriptorFactory(elements);
  this.messager = messager;
  this.types = types;
  this.includeParameterMetadata = includeParameterMetadata;
  signatureFactory = new SignatureFactory(descriptorFactory);
  accessFlagsUtils = new AccessFlags(elements);
}
 
Example 2
Source Project: turbine   Source File: TurbineProcessingEnvironment.java    License: Apache License 2.0 6 votes vote down vote up
public TurbineProcessingEnvironment(
    Filer filer,
    Types types,
    Elements elements,
    Messager messager,
    Map<String, String> processorOptions,
    SourceVersion sourceVersion,
    @Nullable ClassLoader processorLoader,
    Map<String, byte[]> statistics) {
  this.filer = filer;
  this.types = types;
  this.processorOptions = processorOptions;
  this.sourceVersion = sourceVersion;
  this.elements = elements;
  this.statistics = statistics;
  this.messager = messager;
  this.processorLoader = processorLoader;
}
 
Example 3
Source Project: netbeans   Source File: RenameConstructor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo compilationInfo, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    if (treePath.getLeaf().getKind() == Kind.METHOD) {
        MethodTree mt = (MethodTree) treePath.getLeaf();
        TreePath parentPath = treePath.getParentPath();
        ClassTree ct = (ClassTree) parentPath.getLeaf();
        Trees trees = compilationInfo.getTrees();
        Types types = compilationInfo.getTypes();
        TreeUtilities tu = compilationInfo.getTreeUtilities();
        TypeMirror type = types.erasure(trees.getTypeMirror(treePath));
        if (!Utilities.isValidType(type)) {
            return null;
        }
        for (Tree member : ct.getMembers()) {
            TreePath memberPath = new TreePath(parentPath, member);
            if (member.getKind() == Kind.METHOD && "<init>".contentEquals(((MethodTree)member).getName()) //NOI18N
                    && !tu.isSynthetic(memberPath) && types.isSameType(types.erasure(trees.getTypeMirror(memberPath)), type)) {
                return null;
            }
        }
        RenameConstructorFix fix = new RenameConstructorFix(compilationInfo.getSnapshot().getSource(), TreePathHandle.create(treePath, compilationInfo), offset, mt.getName(), ct.getSimpleName());
        return Collections.<Fix>singletonList(fix);
    }
    return null;
}
 
Example 4
Source Project: FreeBuilder   Source File: ModelUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean signatureMatches(
    ExecutableElement method, Types types, String name, TypeMirror... params) {
  if (!method.getSimpleName().contentEquals(name)) {
    return false;
  }
  if (method.getParameters().size() != params.length) {
    return false;
  }
  for (int i = 0; i < params.length; ++i) {
    TypeMirror expected = types.erasure(params[i]);
    TypeMirror actual = types.erasure(method.getParameters().get(i).asType());
    if (!types.isSameType(expected, actual)) {
      return false;
    }
  }
  return true;
}
 
Example 5
Source Project: netbeans   Source File: ImportAnalysisTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testAddImport3() 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);
            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.List");
            TypeElement collection = workingCopy.getElements().getTypeElement("java.util.Collection");
            Types types = workingCopy.getTypes();
            TypeMirror tm = types.getDeclaredType(list, types.erasure(collection.asType()));
            stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "utilList", make.Type(tm), null));
            workingCopy.rewrite(body, make.Block(stats, false));
        }
    };
    src.runModificationTask(task).commit();
    assertFiles("testAddImport3.pass");
}
 
Example 6
Source Project: netbeans   Source File: PullUpTransformer.java    License: Apache License 2.0 6 votes vote down vote up
private boolean deepSearchTypes(DeclaredType currentElement, TypeMirror orig, TypeMirror something, Map<TypeMirror, TypeParameterElement> mappings) {
    Types types = workingCopy.getTypes();
    List<? extends TypeMirror> directSupertypes = types.directSupertypes(currentElement);
    for (TypeMirror superType : directSupertypes) {
        DeclaredType type = (DeclaredType) superType;
        List<? extends TypeMirror> typeArguments = type.getTypeArguments();
        for (int i = 0; i < typeArguments.size(); i++) {
            TypeMirror typeArgument = typeArguments.get(i);
            if (something.equals(typeArgument)) {
                TypeElement asElement = (TypeElement) type.asElement();
                mappings.put(orig, asElement.getTypeParameters().get(i));
                if (types.erasure(targetType.asType()).equals(types.erasure(superType))) {
                    return true;
                }
                if(deepSearchTypes(type, orig, typeArgument, mappings)) {
                    break;
                }
            }
        }
        if (types.erasure(targetType.asType()).equals(types.erasure(superType))) {
            mappings.remove(orig);
            return true;
        }
    }
    return false;
}
 
Example 7
Source Project: netbeans   Source File: JpaControllerUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static TypeMirror stripCollection(TypeMirror passedType, Types types) {
    if (TypeKind.DECLARED != passedType.getKind() || !(passedType instanceof DeclaredType)) {
        return passedType;
    }
    TypeElement passedTypeElement = (TypeElement) types.asElement(passedType);
    String passedTypeQualifiedName = passedTypeElement.getQualifiedName().toString();   //does not include type parameter info
    Class passedTypeClass = null;
    try {
        passedTypeClass = Class.forName(passedTypeQualifiedName);
    } catch (ClassNotFoundException e) {
        //just let passedTypeClass be null
    }
    if (passedTypeClass != null && Collection.class.isAssignableFrom(passedTypeClass)) {
        List<? extends TypeMirror> passedTypeArgs = ((DeclaredType)passedType).getTypeArguments();
        if (passedTypeArgs.isEmpty()) {
            return passedType;
        }
        return passedTypeArgs.get(0);
    }
    return passedType;
}
 
Example 8
Source Project: netbeans   Source File: DelegateAssignabilityChecker.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean handleBothTypeVars( TypeMirror argType,
        TypeMirror varTypeArg, Types types )
{
    /*
     * Implementation of spec item :
     * the delegate type parameter and the bean type parameter are both 
     * type variables and the upper bound of the bean type
     * parameter is assignable to the upper bound, 
     * if any, of the delegate type parameter
     */
    TypeMirror upper = ((TypeVariable)argType).getUpperBound();
    TypeMirror upperVar = ((TypeVariable)varTypeArg).getUpperBound();
    
    if ( upperVar == null || upperVar.getKind() == TypeKind.NULL ){
        return true;
    }
    if ( upper == null || upper.getKind() == TypeKind.NULL ){
        return false;
    }
    
    return checkIsAssignable(types, upper, upperVar);
}
 
Example 9
Source Project: immutables   Source File: AttributeBuilderReflection.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if there's a public way to build the value type with an instance no-arg method.
 *
 * @param attribute value attribute to check.
 * @param possibleBuildMethod method which matches {@link StyleMirror#attributeBuilder()}
 * @return true if this is the possibleBuildMethod can build the value type.
 */
private static boolean isPossibleBuildMethod(ValueAttribute attribute, Element possibleBuildMethod) {
  if (possibleBuildMethod.getKind() != ElementKind.METHOD) {
    return false;
  }

  if (!attribute.containingType.names().possibleAttributeBuilder(possibleBuildMethod.getSimpleName())) {
    return false;
  }

  Types typeUtils = attribute.containingType.constitution.protoclass()
      .environment()
      .processing()
      .getTypeUtils();

  ExecutableElement candidateBuildMethod = (ExecutableElement) possibleBuildMethod;
  return !candidateBuildMethod.getModifiers().contains(Modifier.STATIC)
      && candidateBuildMethod.getModifiers().contains(Modifier.PUBLIC)
      && candidateBuildMethod.getTypeParameters().isEmpty()
      && candidateBuildMethod.getReturnType().getKind() == TypeKind.DECLARED
      && typeUtils.isSameType(candidateBuildMethod.getReturnType(), attribute.containedTypeElement.asType());
}
 
Example 10
Source Project: auto-parcel   Source File: MoreTypes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Resolves a {@link VariableElement} parameter to a method or constructor based on the given
 * container, or a member of a class. For parameters to a method or constructor, the variable's
 * enclosing element must be a supertype of the container type. For example, given a
 * {@code container} of type {@code Set<String>}, and a variable corresponding to the {@code E e}
 * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}.
 */
public static TypeMirror asMemberOf(Types types, DeclaredType container,
                                    VariableElement variable) {
    if (variable.getKind().equals(ElementKind.PARAMETER)) {
        ExecutableElement methodOrConstructor =
                MoreElements.asExecutable(variable.getEnclosingElement());
        ExecutableType resolvedMethodOrConstructor = MoreTypes.asExecutable(
                types.asMemberOf(container, methodOrConstructor));
        List<? extends VariableElement> parameters = methodOrConstructor.getParameters();
        List<? extends TypeMirror> parameterTypes =
                resolvedMethodOrConstructor.getParameterTypes();
        checkState(parameters.size() == parameterTypes.size());
        for (int i = 0; i < parameters.size(); i++) {
            // We need to capture the parameter type of the variable we're concerned about,
            // for later printing.  This is the only way to do it since we can't use
            // types.asMemberOf on variables of methods.
            if (parameters.get(i).equals(variable)) {
                return parameterTypes.get(i);
            }
        }
        throw new IllegalStateException("Could not find variable: " + variable);
    } else {
        return types.asMemberOf(container, variable);
    }
}
 
Example 11
Source Project: RetroFacebook   Source File: RetroFacebookProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private String getSerialVersionUID(TypeElement type) {
  Types typeUtils = processingEnv.getTypeUtils();
  TypeMirror serializable = getTypeMirror(Serializable.class);
  if (typeUtils.isAssignable(type.asType(), serializable)) {
    List<VariableElement> fields = ElementFilter.fieldsIn(type.getEnclosedElements());
    for (VariableElement field : fields) {
      if (field.getSimpleName().toString().equals("serialVersionUID")) {
        Object value = field.getConstantValue();
        if (field.getModifiers().containsAll(Arrays.asList(Modifier.STATIC, Modifier.FINAL))
            && field.asType().getKind() == TypeKind.LONG
            && value != null) {
          return value + "L";
        } else {
          errorReporter.reportError(
              "serialVersionUID must be a static final long compile-time constant", field);
          break;
        }
      }
    }
  }
  return "";
}
 
Example 12
Source Project: requery   Source File: AttributeMember.java    License: Apache License 2.0 6 votes vote down vote up
private ElementValidator validateCollectionType(ProcessingEnvironment processingEnvironment) {
    Types types = processingEnvironment.getTypeUtils();
    TypeElement collectionElement = (TypeElement) types.asElement(typeMirror());
    if (collectionElement != null) {
        ElementValidator validator = new ElementValidator(collectionElement, processingEnvironment);
        if (Mirrors.isInstance(types, collectionElement, List.class)) {
            builderClass = ListAttributeBuilder.class;
        } else if (Mirrors.isInstance(types, collectionElement, Set.class)) {
            builderClass = SetAttributeBuilder.class;
        } else if (Mirrors.isInstance(types, collectionElement, Iterable.class)) {
            builderClass = ResultAttributeBuilder.class;
        } else {
            validator.error("Invalid collection type, must be Set, List or Iterable");
        }
        return validator;
    }
    return null;
}
 
Example 13
Source Project: jackdaw   Source File: ProcessorUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static TypeElement getWrappedType(final TypeMirror mirror) {
    final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment();
    final Types typeUtils = env.getTypeUtils();

    final TypeKind kind = mirror.getKind();
    final boolean primitive = kind.isPrimitive();

    if (primitive) {
        return typeUtils.boxedClass((PrimitiveType) mirror);
    }
    return (TypeElement) typeUtils.asElement(mirror);
}
 
Example 14
Source Project: litho   Source File: TagExtractorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  Elements elements = mCompilationRule.getElements();
  Types types = mCompilationRule.getTypes();

  mTagModels =
      TagExtractor.extractTagsFromSpecClass(
          types, elements.getTypeElement(TestClass.class.getCanonicalName()), RunMode.normal());

  mTagModelsInAbiMode =
      TagExtractor.extractTagsFromSpecClass(
          types,
          elements.getTypeElement(TestClass.class.getCanonicalName()),
          EnumSet.of(RunMode.ABI));
}
 
Example 15
Source Project: netbeans   Source File: TreeFactory.java    License: Apache License 2.0 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 ERROR:
            if (t.hasTag(TypeTag.ERROR)) {
                tp = make.at(NOPOS).Ident(((ErrorType) type).tsym.name);
                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;
        default:
            return make.at(NOPOS).Type((Type)type);
    }

    return tp.setType(t);
}
 
Example 16
Source Project: sqlitemagic   Source File: ColumnElement.java    License: Apache License 2.0 5 votes vote down vote up
public static TypeName findEquivalentType(ExtendedTypeElement serializedType,
                                          Environment environment) {
  final Types typeUtils = environment.getTypeUtils();
  TypeMirror typeMirror = serializedType.getTypeMirror();
  if (typeMirror instanceof PrimitiveType) {
    typeMirror = typeUtils.boxedClass((PrimitiveType) typeMirror).asType();
  }
  if (typeUtils.isSubtype(typeMirror, NUMBER_TYPE)) {
    return NUMBER;
  }
  if (typeUtils.isSubtype(typeMirror, CHAR_SEQUENCE_TYPE)) {
    return CHAR_SEQUENCE;
  }
  return typeNameForGenerics(serializedType);
}
 
Example 17
Source Project: paperparcel   Source File: PaperParcelAutoValueExtension.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec constructor(Context context) {
  Types types = context.processingEnvironment().getTypeUtils();
  DeclaredType declaredValueType = MoreTypes.asDeclared(context.autoValueClass().asType());

  ImmutableList.Builder<ParameterSpec> parameterBuilder = ImmutableList.builder();
  for (Map.Entry<String, ExecutableElement> entry : context.properties().entrySet()) {
    ExecutableType resolvedExecutableType =
        MoreTypes.asExecutable(types.asMemberOf(declaredValueType, entry.getValue()));
    TypeName typeName = TypeName.get(resolvedExecutableType.getReturnType());
    ParameterSpec.Builder spec = ParameterSpec.builder(typeName, entry.getKey());
    AnnotationMirror nullableAnnotation =
        Utils.getAnnotationWithSimpleName(entry.getValue(), NULLABLE_ANNOTATION_NAME);
    if (nullableAnnotation != null) {
      spec.addAnnotation(AnnotationSpec.get(nullableAnnotation));
    }
    parameterBuilder.add(spec.build());
  }

  ImmutableList<ParameterSpec> parameters = parameterBuilder.build();
  CodeBlock parameterList = CodeBlocks.join(FluentIterable.from(parameters)
      .transform(new Function<ParameterSpec, CodeBlock>() {
        @Override public CodeBlock apply(ParameterSpec parameterSpec) {
          return CodeBlock.of("$N", parameterSpec.name);
        }
      }), ", ");

  return MethodSpec.constructorBuilder()
      .addParameters(parameters)
      .addStatement("super($L)", parameterList)
      .build();
}
 
Example 18
Source Project: buck   Source File: BuckModuleVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private static TypeElement convertAnnotationValueToTypeElement(
    Types types, AnnotationValue annotationValue) {
  if (!(annotationValue.getValue() instanceof TypeMirror)) {
    throw new RuntimeException(
        "Invalid type of " + annotationValue + ". Need to be a TypeMirror");
  }
  Element element = types.asElement((TypeMirror) annotationValue.getValue());
  if (!(element instanceof TypeElement)) {
    throw new RuntimeException("Invalid type of " + element + ". Need to be a TypeElement");
  }
  return (TypeElement) element;
}
 
Example 19
Source Project: auto   Source File: AutoServiceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies {@link ServiceProvider} constraints on the concrete provider class.
 * Note that these constraints are enforced at runtime via the ServiceLoader,
 * we're just checking them at compile time to be extra nice to our users.
 */
private boolean checkImplementer(TypeElement providerImplementer, TypeElement providerType) {

  String verify = processingEnv.getOptions().get("verify");
  if (verify == null || !Boolean.valueOf(verify)) {
    return true;
  }

  // TODO: We're currently only enforcing the subtype relationship
  // constraint. It would be nice to enforce them all.

  Types types = processingEnv.getTypeUtils();

  return types.isSubtype(providerImplementer.asType(), providerType.asType());
}
 
Example 20
Source Project: auto   Source File: BuilderSpec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds any methods in the set that return the builder type. If the builder has type parameters
 * {@code <A, B>}, then the return type of the method must be {@code Builder<A, B>} with the
 * same parameter names. We enforce elsewhere that the names and bounds of the builder
 * parameters must be the same as those of the @AutoValue class. Here's a correct example:
 *
 * <pre>
 * {@code @AutoValue abstract class Foo<A extends Number, B> {
 *   abstract int someProperty();
 *
 *   abstract Builder<A, B> toBuilder();
 *
 *   interface Builder<A extends Number, B> {...}
 * }}
 * </pre>
 *
 * <p>We currently impose that there cannot be more than one such method.
 */
ImmutableSet<ExecutableElement> toBuilderMethods(
    Types typeUtils, Set<ExecutableElement> abstractMethods) {

  List<String> builderTypeParamNames =
      builderTypeElement.getTypeParameters().stream()
          .map(e -> e.getSimpleName().toString())
          .collect(toList());

  ImmutableSet.Builder<ExecutableElement> methods = ImmutableSet.builder();
  for (ExecutableElement method : abstractMethods) {
    if (builderTypeElement.equals(typeUtils.asElement(method.getReturnType()))) {
      methods.add(method);
      DeclaredType returnType = MoreTypes.asDeclared(method.getReturnType());
      List<String> typeArguments =
          returnType.getTypeArguments().stream()
              .filter(t -> t.getKind().equals(TypeKind.TYPEVAR))
              .map(t -> typeUtils.asElement(t).getSimpleName().toString())
              .collect(toList());
      if (!builderTypeParamNames.equals(typeArguments)) {
        errorReporter.reportError(
            method,
            "Builder converter method should return %s%s",
            builderTypeElement,
            TypeSimplifier.actualTypeParametersString(builderTypeElement));
      }
    }
  }
  ImmutableSet<ExecutableElement> builderMethods = methods.build();
  if (builderMethods.size() > 1) {
    errorReporter.reportError(
        builderMethods.iterator().next(), "There can be at most one builder converter method");
  }
  this.toBuilderMethods = builderMethods;
  return builderMethods;
}
 
Example 21
Source Project: auto   Source File: MoreTypes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the superclass of {@code type}, with any type parameters bound by {@code type}, or
 * {@link Optional#absent()} if {@code type} is an interface or {@link Object} or its superclass
 * is {@link Object}.
 */
// TODO(user): Remove unused parameter Elements?
public static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements,
    DeclaredType type) {
  checkNotNull(types);
  checkNotNull(elements);  // This is no longer used, but here to avoid changing the API.
  checkNotNull(type);

  TypeMirror superclassType = asTypeElement(type).getSuperclass();
  if (!isType(superclassType)) { // type is Object or an interface
    return Optional.absent();
  }

  DeclaredType superclass =  asDeclared(superclassType);
  if (isObjectType(superclass)) {
    return Optional.absent();
  }

  if (superclass.getTypeArguments().isEmpty()) {
    return Optional.of(superclass);
  }

  // In the case where the super class has type parameters, TypeElement#getSuperclass gives
  // SuperClass<T> rather than SuperClass<Foo>, so use Types#directSupertypes instead. The javadoc
  // for Types#directSupertypes guarantees that a super class, if it exists, comes before any
  // interfaces. Thus, we can just get the first element in the list.
  return Optional.of(asDeclared(types.directSupertypes(type).get(0)));
}
 
Example 22
/**
 * Verifies {@link java.util.spi.LocaleServiceProvider} constraints on the concrete provider class.
 * Note that these constraints are enforced at runtime via the ServiceLoader,
 * we're just checking them at compile time to be extra nice to our users.
 */
private boolean checkImplementer(TypeElement providerImplementer, TypeMirror providerType) {
	// TODO: We're currently only enforcing the subtype relationship
	// constraint. It would be nice to enforce them all.
	Types types = processingEnv.getTypeUtils();

	return types.isSubtype(providerImplementer.asType(), providerType);
}
 
Example 23
Source Project: TencentKona-8   Source File: JavahTask.java    License: GNU General Public License v2.0 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 24
Source Project: dagger2-sample   Source File: MembersInjectionBinding.java    License: Apache License 2.0 5 votes vote down vote up
Factory(Elements elements, Types types, Key.Factory keyFactory,
    DependencyRequest.Factory dependencyRequestFactory) {
  this.elements = checkNotNull(elements);
  this.types = checkNotNull(types);
  this.keyFactory = checkNotNull(keyFactory);
  this.dependencyRequestFactory = checkNotNull(dependencyRequestFactory);
}
 
Example 25
Source Project: netbeans   Source File: AST2Bytecode.java    License: Apache License 2.0 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 26
Source Project: SimpleWeibo   Source File: TypeSimplifier.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<String> ambiguousNames(Types typeUtils, Set<TypeMirror> types) {
  Set<String> ambiguous = new HashSet<String>();
  Set<String> simpleNames = new HashSet<String>();
  for (TypeMirror type : types) {
    if (type.getKind() == TypeKind.ERROR) {
      throw new MissingTypeException();
    }
    String simpleName = typeUtils.asElement(type).getSimpleName().toString();
    if (!simpleNames.add(simpleName)) {
      ambiguous.add(simpleName);
    }
  }
  return ambiguous;
}
 
Example 27
Source Project: netbeans   Source File: ElementsService.java    License: Apache License 2.0 5 votes vote down vote up
protected ElementsService(Context context) {
    context.put(KEY, this);
    jctypes = com.sun.tools.javac.code.Types.instance(context);
    names = Names.instance(context);
    types = JavacTypes.instance(context);
    allowDefaultMethods = SourceLevelUtils.allowDefaultMethods(Source.instance(context));
}
 
Example 28
Source Project: jdk8u60   Source File: Env.java    License: GNU General Public License v2.0 5 votes vote down vote up
void init(DocTrees trees, Elements elements, Types types) {
    this.trees = trees;
    this.elements = elements;
    this.types = types;
    java_lang_Error = elements.getTypeElement("java.lang.Error").asType();
    java_lang_RuntimeException = elements.getTypeElement("java.lang.RuntimeException").asType();
    java_lang_Throwable = elements.getTypeElement("java.lang.Throwable").asType();
    java_lang_Void = elements.getTypeElement("java.lang.Void").asType();
}
 
Example 29
Source Project: netbeans   Source File: JavadocCompletionQuery.java    License: Apache License 2.0 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 30
Source Project: netbeans   Source File: ToolTipAnnotation.java    License: Apache License 2.0 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;
}