javax.lang.model.element.QualifiedNameable Java Examples

The following examples show how to use javax.lang.model.element.QualifiedNameable. 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 check out the related API usage on the sidebar.
Example #1
Source File: TypeSimplifier.java    From auto with Apache License 2.0 6 votes vote down vote up
private static Set<String> ambiguousNames(Types typeUtils, Set<TypeMirror> types) {
  Set<String> ambiguous = new HashSet<>();
  Map<String, Name> simpleNamesToQualifiedNames = new HashMap<>();
  for (TypeMirror type : types) {
    if (type.getKind() == TypeKind.ERROR) {
      throw new MissingTypeException(MoreTypes.asError(type));
    }
    String simpleName = typeUtils.asElement(type).getSimpleName().toString();
    /*
     * Compare by qualified names, because in Eclipse JDT, if Java 8 type annotations are used,
     * the same (unannotated) type may appear multiple times in the Set<TypeMirror>.
     * TODO(emcmanus): investigate further, because this might cause problems elsewhere.
     */
    Name qualifiedName = ((QualifiedNameable) typeUtils.asElement(type)).getQualifiedName();
    Name previous = simpleNamesToQualifiedNames.put(simpleName, qualifiedName);
    if (previous != null && !previous.equals(qualifiedName)) {
      ambiguous.add(simpleName);
    }
  }
  return ambiguous;
}
 
Example #2
Source File: ImmutableTreeTranslator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Tree visitMemberSelect(MemberSelectTree tree, Object p) {
    if (tree instanceof QualIdentTree) {
        QualIdentTree qit = (QualIdentTree) tree;
        Element el = qit.sym;

        if (el == null) {
            el = overlay.resolve(model, elements, qit.getFQN());
        } else {
            if (el.getKind().isClass() || el.getKind().isInterface() || el.getKind() == ElementKind.PACKAGE) {
                el = overlay.resolve(model, elements, ((QualifiedNameable) el).getQualifiedName().toString(), el, elements.getModuleOf(el));
            }
        }

        return importAnalysis.resolveImport(tree, el);
    } else {
        return rewriteChildren(tree);
    }
}
 
Example #3
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String fqnFor(Tree t) {
    Element el = ASTService.getElementImpl(t);

    if (el != null) {
        if (el.getKind().isClass() || el.getKind().isInterface() || el.getKind() == ElementKind.PACKAGE) {
            return ((QualifiedNameable) el).getQualifiedName().toString();
        } else {
            Logger.getLogger(ElementOverlay.class.getName()).log(Level.SEVERE, "Not a QualifiedNameable: {0}", el);
            return null;
        }
    } else if (t instanceof QualIdentTree) {
        return ((QualIdentTree) t).getFQN();
    } else if (t.getKind() == Kind.PARAMETERIZED_TYPE) {
        return fqnFor(((ParameterizedTypeTree) t).getType());
    } else {
        Logger.getLogger(ElementOverlay.class.getName()).log(Level.FINE, "No element and no QualIdent");
        return null;
    }
}
 
Example #4
Source File: InterfaceScannerTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public void onImport(
    boolean isStatic,
    boolean isStarImport,
    TreePath leafmostElementPath,
    QualifiedNameable leafmostElement,
    Name memberName) {
  if (!isStatic) {
    if (isStarImport) {
      starImportedElements.add(leafmostElement);
    } else {
      importedTypes.add((TypeElement) leafmostElement);
    }
  } else if (!isStarImport) {
    staticImportOwners.put(memberName.toString(), (TypeElement) leafmostElement);
  } else {
    staticStarImports.add((TypeElement) leafmostElement);
  }
}
 
Example #5
Source File: TreeBackedTypeResolutionSimulator.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
protected TreeBackedResolvedType resolvePackage(
    TreePath referencingPath,
    PackageElement referencedPackage,
    QualifiedNameable canonicalPackage) {
  // PackageElements are not considered to be enclosed by their parent elements, but
  // our logic is a lot simpler if we can pretend they are.
  TreeBackedResolvedType enclosingElement = null;
  String qualifiedName = canonicalPackage.getQualifiedName().toString();
  int lastDot = qualifiedName.lastIndexOf('.');
  if (lastDot > 0) {
    String enclosingPackageQualifiedName = qualifiedName.substring(0, lastDot);
    PackageElement enclosingPackage =
        Objects.requireNonNull(
            MoreElements.getPackageElementEvenIfEmpty(elements, enclosingPackageQualifiedName));
    enclosingElement = resolveEnclosingElement(enclosingPackage);
  }

  return new TreeBackedResolvedType(referencingPath, canonicalPackage, enclosingElement);
}
 
Example #6
Source File: ByteCodePatchingAnnotationProcessor.java    From arvo2parquet with MIT License 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (roundEnv.processingOver()) return true;

  // looking for at least one class annotated with @InvokeByteCodePatching
  final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(InvokeByteCodePatching.class);
  if (elements.size() <= 0) return false;

  //noinspection LoopStatementThatDoesntLoop
  for (final Element elem : elements) {
    // is invalid to apply this annotation to anything other than a class type
    if (!elem.getKind().isClass() || !(elem instanceof QualifiedNameable)) {
      throw new AnnotationFormatError(elem.toString() + " Java type not supported by " + InvokeByteCodePatching.class);
    }

    InvokeByteCodePatching annotation = elem.getAnnotation(InvokeByteCodePatching.class);
    if (annotation == null) {
      throw new AnnotationFormatError("invalid annotation " + InvokeByteCodePatching.class);
    }

    break; // found a class marked by the @InvokeByteCodePatching annotation
  }

  try {
    final String classesBldDir = System.getProperty("maven.build.classes.dir", "target/classes");
    ValidateAvroSchema.bytecodePatchAvroSchemaClass(new File(classesBldDir));
  } catch (ClassNotFoundException|IOException e) {
    uncheckedExceptionThrow(e);
  }

  return true; // no further processing of this annotation type
}
 
Example #7
Source File: MemoizeExtension.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the fully-qualified name of an annotation-mirror, e.g.
 * "com.google.auto.value.AutoValue".
 */
// TODO(b/122509249): Move code copied from com.google.auto.value.processor to auto-common.
private static String getAnnotationFqName(AnnotationMirror annotation) {
  return ((QualifiedNameable) annotation.getAnnotationType().asElement())
      .getQualifiedName()
      .toString();
}
 
Example #8
Source File: ImportsTrackerTestHelper.java    From buck with Apache License 2.0 5 votes vote down vote up
private static void handleImport(Trees trees, ImportsTracker imports, TreePath importTreePath) {
  ImportTree importTree = (ImportTree) importTreePath.getLeaf();
  MemberSelectTree importedExpression = (MemberSelectTree) importTree.getQualifiedIdentifier();
  TreePath importedExpressionPath = new TreePath(importTreePath, importedExpression);
  Name simpleName = importedExpression.getIdentifier();
  boolean isStarImport = simpleName.contentEquals("*");

  if (!isStarImport && !importTree.isStatic()) {
    TypeElement importedType = (TypeElement) trees.getElement(importedExpressionPath);
    imports.importType(importedType, importedExpressionPath);
  } else {
    ExpressionTree containingElementExpression = importedExpression.getExpression();
    TreePath containingElementExpressionPath =
        new TreePath(importedExpressionPath, containingElementExpression);
    QualifiedNameable containingElement =
        (QualifiedNameable) trees.getElement(containingElementExpressionPath);

    if (importTree.isStatic()) {
      TypeElement containingType = (TypeElement) containingElement;
      if (isStarImport) {
        imports.importStaticMembers((TypeElement) containingElement);
      } else {
        imports.importStatic(containingType, simpleName);
      }
    } else {
      // Normal star import
      imports.importMembers(containingElement, containingElementExpressionPath);
    }
  }
}
 
Example #9
Source File: TreeBackedTypeResolutionSimulator.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
protected TreeBackedResolvedType resolveType(
    TreePath referencingPath, TypeElement referencedType, QualifiedNameable canonicalType) {
  if (canonicalType == null) {
    canonicalType = referencedType;
  }
  return new TreeBackedResolvedType(
      referencingPath,
      canonicalType,
      resolveEnclosingElement((QualifiedNameable) canonicalType.getEnclosingElement()));
}
 
Example #10
Source File: TreeBackedElements.java    From buck with Apache License 2.0 5 votes vote down vote up
private Name getFullyQualifiedName(
    @Nullable QualifiedNameable enclosingElement, Name simpleName) {
  for (int i = 0; i < simpleName.length(); i++) {
    if (simpleName.charAt(i) == '.') {
      throw new IllegalArgumentException(String.format("%s is not a simple name", simpleName));
    }
  }

  if (enclosingElement == null || enclosingElement.getQualifiedName().length() == 0) {
    return simpleName;
  } else {
    return getName(String.format("%s.%s", enclosingElement.getQualifiedName(), simpleName));
  }
}
 
Example #11
Source File: AutoValueOrOneOfProcessor.java    From auto with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the fully-qualified name of an annotation-mirror, e.g.
 * "com.google.auto.value.AutoValue".
 */
private static String getAnnotationFqName(AnnotationMirror annotation) {
  return ((QualifiedNameable) annotation.getAnnotationType().asElement())
      .getQualifiedName()
      .toString();
}
 
Example #12
Source File: TypeHelper.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private String getQualifiedName(Element element) {
	if (element instanceof QualifiedNameable) {
		return ((QualifiedNameable) element).getQualifiedName().toString();
	}
	return element.toString();
}
 
Example #13
Source File: ImportsTracker.java    From buck with Apache License 2.0 4 votes vote down vote up
public void importMembers(QualifiedNameable typeOrPackage, @Nullable TreePath location) {
  importedOwners.put(typeOrPackage, location);
}
 
Example #14
Source File: InterfaceValidator.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void onImport(
    boolean isStatic,
    boolean isStarImport,
    TreePath leafmostElementPath,
    QualifiedNameable leafmostElement,
    @Nullable Name memberName) {
  if (leafmostElement.getKind() != ElementKind.PACKAGE) {
    if (isStatic) {
      CompletedType completedType = completer.complete(leafmostElement, true);
      if (completedType != null
          && (completedType.kind == CompletedTypeKind.CRASH
              || completedType.kind == CompletedTypeKind.PARTIALLY_COMPLETED_TYPE)) {
        reportMissingDeps(completedType, leafmostElementPath);
      }
    } else {
      ResolvedType compilerResolvedType = compilerResolver.resolve(leafmostElementPath);
      if (compilerResolvedType != null) {
        switch (compilerResolvedType.kind) {
          case CRASH:
            reportMissingDeps(compilerResolvedType, leafmostElementPath);
            break;
          case RESOLVED_TYPE:
            // Nothing to do; it would resolve fine
            break;
            // $CASES-OMITTED$
          default:
            {
              TreeBackedResolvedType treeBackedResolvedType =
                  treeBackedResolver.resolve(leafmostElementPath);
              if (!treeBackedResolvedType.isCorrect()) {
                if (treeBackedResolvedType.isCorrectable()) {
                  treeBackedResolvedType.reportErrors(messageKind);
                } else {
                  reportMissingDeps(compilerResolvedType, leafmostElementPath);
                }
              }
            }
            break;
        }
      }
    }
  }

  if (!isStatic) {
    if (!isStarImport) {
      imports.importType((TypeElement) leafmostElement, leafmostElementPath);
    } else {
      imports.importMembers(leafmostElement, leafmostElementPath);
    }
  } else if (!isStarImport) {
    imports.importStatic((TypeElement) leafmostElement, Objects.requireNonNull(memberName));
  } else {
    imports.importStaticMembers((TypeElement) leafmostElement);
  }
}
 
Example #15
Source File: PropertyProcessor.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected CompiledPropertyMetadata toPropertyMetadata(VariableElement element, AnnotationMirror propertyAnnotation)
{
	Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues = processingEnv.getElementUtils().getElementValuesWithDefaults(propertyAnnotation);
	
	CompiledPropertyMetadata property = new CompiledPropertyMetadata();
	
	String propName = (String) annotationValue(annotationValues, "name").getValue();
	if (propName == null || propName.isEmpty())
	{
		propName = (String) element.getConstantValue();
		if (propName == null)
		{
			processingEnv.getMessager().printMessage(Kind.WARNING, "Failed to read constant value for " + element, 
					element);
			return null;
		}
	}
	property.setName(propName);
	
	boolean deprecated = processingEnv.getElementUtils().isDeprecated(element);
	property.setDeprecated(deprecated);
	
	QualifiedNameable enclosingElement = (QualifiedNameable) element.getEnclosingElement();
	property.setConstantDeclarationClass(enclosingElement.getQualifiedName().toString());
	property.setConstantFieldName(element.getSimpleName().toString());
	
	property.setCategory((String) annotationValue(annotationValues, "category").getValue());
	property.setDefaultValue((String) annotationValue(annotationValues, "defaultValue").getValue());
	property.setSinceVersion((String) annotationValue(annotationValues, "sinceVersion").getValue());
	property.setValueType(((TypeMirror) annotationValue(annotationValues, "valueType").getValue()).toString());
	
	@SuppressWarnings("unchecked")
	List<? extends AnnotationValue> scopeValues = (List<? extends AnnotationValue>) annotationValue(annotationValues, "scopes").getValue();
	List<PropertyScope> propertyScopes = new ArrayList<>(scopeValues.size());
	for (AnnotationValue scopeValue : scopeValues)
	{
		PropertyScope scope = Enum.valueOf(PropertyScope.class, ((VariableElement) scopeValue.getValue()).getSimpleName().toString());
		propertyScopes.add(scope); 
	}
	
	//automatically adding Global if Context is present
	int contextIndex = propertyScopes.indexOf(PropertyScope.CONTEXT);
	if (contextIndex >= 0 && !propertyScopes.contains(PropertyScope.GLOBAL))
	{
		propertyScopes.add(contextIndex, PropertyScope.GLOBAL);
	}
	
	//automatically adding Report if Dataset is present
	int datasetIndex = propertyScopes.indexOf(PropertyScope.DATASET);
	if (datasetIndex >= 0 && !propertyScopes.contains(PropertyScope.REPORT))
	{
		propertyScopes.add(datasetIndex, PropertyScope.REPORT);
	}
	
	property.setScopes(propertyScopes);
	
	@SuppressWarnings("unchecked")
	List<? extends AnnotationValue> scopeQualificationValues = (List<? extends AnnotationValue>) annotationValue(annotationValues, "scopeQualifications").getValue();
	List<String> scopeQualifications = new ArrayList<>(scopeValues.size());
	for (AnnotationValue qualificationValue : scopeQualificationValues)
	{
		String qualification = (String) qualificationValue.getValue();
		scopeQualifications.add(qualification);
	}
	property.setScopeQualifications(scopeQualifications);
	
	return property;
}
 
Example #16
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Element getEnclosingElement() {
    return ElementOverlay.this.resolve(ast, elements, ((QualifiedNameable/*XXX*/) delegateTo.getEnclosingElement()).getQualifiedName().toString(), moduleOf(elements, delegateTo));
}
 
Example #17
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void registerClass(String parent, String clazz, ClassTree tree, boolean modified) {
    if (clazz == null) return;
    
    Element myself = ASTService.getElementImpl(tree);

    boolean newOrModified =    myself == null
                            || (!myself.getKind().isClass() && !myself.getKind().isInterface())
                            || !((QualifiedNameable) myself).getQualifiedName().contentEquals(clazz);

    if (newOrModified || class2Enclosed.containsKey(parent)) {
        List<String> c = class2Enclosed.get(parent);

        if (c == null) {
            class2Enclosed.put(parent, c = new ArrayList<String>());
        }

        c.add(clazz);
    }

    if (modified) {
        class2Enclosed.put(clazz, new ArrayList<String>());
    }

    Set<String> superFQNs = superFQNs(tree);

    boolean hadObject = superFQNs.remove("java.lang.Object");

    Set<String> original;

    if (!newOrModified) {
        original = new LinkedHashSet<String>();

        TypeElement tel = (TypeElement) myself;

        if (tel.getSuperclass() != null && tel.getSuperclass().getKind() == TypeKind.DECLARED) {
            original.add(((TypeElement) ((DeclaredType) tel.getSuperclass()).asElement()).getQualifiedName().toString());
        }

        for (TypeMirror intf : tel.getInterfaces()) {
            original.add(((TypeElement) ((DeclaredType) intf).asElement()).getQualifiedName().toString());
        }

        original.remove("java.lang.Object");
    } else {
        original = null;
    }

    if (!superFQNs.equals(original)) {
        if (hadObject) superFQNs.add("java.lang.Object");
        
        Set<Modifier> mods = EnumSet.noneOf(Modifier.class);

        mods.addAll(tree.getModifiers().getFlags());
        classes.put(clazz, mods);
        class2SuperElementTrees.put(clazz, superFQNs);
    }
}
 
Example #18
Source File: TypeHelper.java    From java-technology-stack with MIT License 4 votes vote down vote up
private String getQualifiedName(Element element) {
	if (element instanceof QualifiedNameable) {
		return ((QualifiedNameable) element).getQualifiedName().toString();
	}
	return element.toString();
}
 
Example #19
Source File: TypeHelper.java    From magic-starter with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String getQualifiedName(Element element) {
	if (element instanceof QualifiedNameable) {
		return ((QualifiedNameable) element).getQualifiedName().toString();
	}
	return element.toString();
}
 
Example #20
Source File: InterfaceScanner.java    From buck with Apache License 2.0 3 votes vote down vote up
/**
 * An import statement was encountered.
 *
 * @param isStatic true for static imports
 * @param isStarImport true for star imports
 * @param leafmostElementPath the path of the leafmost known element in the imported type
 *     expression
 * @param leafmostElement the leafmost known element in the imported type expression. For
 *     single-type imports, this is the imported type. For the rest, this is the type or package
 *     enclosing the imported element(s).
 * @param memberName for named static imports, the name of the static members to import.
 *     Otherwise null.
 */
void onImport(
    boolean isStatic,
    boolean isStarImport,
    TreePath leafmostElementPath,
    QualifiedNameable leafmostElement,
    @Nullable Name memberName);