use of javax.lang.model.element.ElementKind in project GitTest by xiaoxige.
the class AnontationProcessor method process.
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (set == null || set.size() <= 0) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "It's TypeElement is null or empty");
return false;
}
for (TypeElement element : set) {
mMessager.printMessage(Diagnostic.Kind.NOTE, element.toString());
}
Set<? extends Element> elementsAnnotatedWith = roundEnvironment.getElementsAnnotatedWith(ClassAnontation.class);
for (Element element : elementsAnnotatedWith) {
// 得到注解标识的是什么玩意(Em. 类,方法, 成员变量...)
ElementKind kind = element.getKind();
mMessager.printMessage(Diagnostic.Kind.NOTE, "kind " + kind.toString());
// 得到注解标识的权限是什么(Em. public, private, static, final ...)
Set<Modifier> modifiers = element.getModifiers();
mMessager.printMessage(Diagnostic.Kind.NOTE, "--> modifiers " + element.getEnclosingElement().toString());
// 得到注释的注解内容(比如获取的值)
ClassAnontation annotation = element.getAnnotation(ClassAnontation.class);
// 表示java编程语中的类型(用这个去判断是int?String?...)
TypeMirror typeMirror = element.asType();
mMessager.printMessage(Diagnostic.Kind.NOTE, "--> typeMirror " + typeMirror.toString());
if (element.getKind().isClass()) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "==>> It's a Class " + element.getSimpleName());
}
if (element.getKind().isField()) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "==> It's a Field ");
}
}
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(MethodAnontation.class);
for (Element element : elements) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "simpleName " + element.getSimpleName());
mMessager.printMessage(Diagnostic.Kind.NOTE, "--> modifiers " + element.getEnclosingElement().toString());
// 参数
TypeMirror typeMirror = element.asType();
mMessager.printMessage(Diagnostic.Kind.NOTE, "--> typeMirror " + typeMirror.toString());
// 方法
ExecutableElement executableElement = (ExecutableElement) element;
TypeElement enclosingElement = (TypeElement) executableElement.getEnclosingElement();
String qualifiedName = enclosingElement.getQualifiedName().toString();
if (element.getKind() == ElementKind.METHOD) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "==> It's a method ");
}
}
mMessager.printMessage(Diagnostic.Kind.NOTE, "-------------------------------------------");
Set<? extends Element> annotatedWith = roundEnvironment.getElementsAnnotatedWith(Method2Anontation.class);
for (Element element : annotatedWith) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "simpleName " + element.getSimpleName());
mMessager.printMessage(Diagnostic.Kind.NOTE, "--> modifiers " + element.getEnclosingElement().toString());
// 参数
TypeMirror typeMirror = element.asType();
mMessager.printMessage(Diagnostic.Kind.NOTE, "--> typeMirror " + typeMirror.toString());
// 方法
ExecutableElement executableElement = (ExecutableElement) element;
TypeElement enclosingElement = (TypeElement) executableElement.getEnclosingElement();
String qualifiedName = enclosingElement.getQualifiedName().toString();
if (element.getKind() == ElementKind.METHOD) {
mMessager.printMessage(Diagnostic.Kind.NOTE, "==> It's a method ");
}
}
return true;
}
use of javax.lang.model.element.ElementKind in project graal by oracle.
the class NodeParser method importPublicStaticMembers.
@SuppressWarnings("unchecked")
private List<Element> importPublicStaticMembers(TypeElement importGuardClass, boolean includeConstructors) {
// hack to reload type is necessary for incremental compiling in eclipse.
// otherwise methods inside of import guard types are just not found.
TypeElement typeElement = ElementUtils.fromTypeMirror(context.reloadType(importGuardClass.asType()));
List<Element> members = new ArrayList<>();
List<Element> typeElementMembers = (List<Element>) processingEnv.getElementUtils().getAllMembers(typeElement);
// add default constructor
if (typeElement.getModifiers().contains(Modifier.PUBLIC) && ElementFilter.constructorsIn(typeElementMembers).isEmpty()) {
typeElementMembers = new ArrayList<>(typeElementMembers);
typeElementMembers.add(new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), typeElement.asType(), null));
}
for (Element importElement : typeElementMembers) {
if (!importElement.getModifiers().contains(Modifier.PUBLIC)) {
continue;
}
if (includeConstructors && importElement.getKind() == ElementKind.CONSTRUCTOR) {
members.add(importElement);
}
if (!importElement.getModifiers().contains(Modifier.STATIC)) {
continue;
}
ElementKind kind = importElement.getKind();
if (kind.isField() || kind == ElementKind.METHOD) {
members.add(importElement);
}
}
/*
* Sort elements by enclosing type to ensure that duplicate static methods are used from the
* most concrete subtype.
*/
Collections.sort(members, new Comparator<Element>() {
Map<TypeMirror, Set<String>> cachedQualifiedNames = new HashMap<>();
public int compare(Element o1, Element o2) {
TypeMirror e1 = o1.getEnclosingElement() != null ? o1.getEnclosingElement().asType() : null;
TypeMirror e2 = o2.getEnclosingElement() != null ? o2.getEnclosingElement().asType() : null;
Set<String> e1SuperTypes = getCachedSuperTypes(e1);
Set<String> e2SuperTypes = getCachedSuperTypes(e2);
return ElementUtils.compareByTypeHierarchy(e1, e1SuperTypes, e2, e2SuperTypes);
}
private Set<String> getCachedSuperTypes(TypeMirror e) {
if (e == null) {
return Collections.emptySet();
}
Set<String> superTypes = cachedQualifiedNames.get(e);
if (superTypes == null) {
superTypes = new HashSet<>(ElementUtils.getQualifiedSuperTypeNames(ElementUtils.fromTypeMirror(e)));
cachedQualifiedNames.put(e, superTypes);
}
return superTypes;
}
});
return members;
}
use of javax.lang.model.element.ElementKind in project meghanada-server by mopemope.
the class TreeAnalyzer method analyzeFieldAccess.
private static void analyzeFieldAccess(SourceContext context, JCTree.JCFieldAccess fieldAccess, int preferredPos, int endPos) throws IOException {
Source src = context.getSource();
Symbol sym = fieldAccess.sym;
JCTree.JCExpression selected = fieldAccess.getExpression();
analyzeParsedTree(context, selected);
String selectScope = selected.toString();
Name identifier = fieldAccess.getIdentifier();
Range range = Range.create(src, preferredPos + 1, endPos);
if (isNull(sym)) {
if (src.isReportUnknown()) {
log.warn("unknown fieldAccess sym is null fieldAccess:{} {}", fieldAccess, src.filePath);
}
return;
}
ElementKind kind = sym.getKind();
if (kind.equals(ElementKind.FIELD)) {
//
FieldAccess fa = new FieldAccess(identifier.toString(), preferredPos + 1, range);
fa.scope = getFieldScope(fa, selectScope);
Symbol owner = sym.owner;
if (nonNull(owner) && nonNull(owner.type)) {
getTypeString(src, owner.type).ifPresent(fqcn -> {
fa.declaringClass = TreeAnalyzer.markFQCN(src, fqcn);
if (selected instanceof JCTree.JCIdent) {
JCTree.JCIdent ident = (JCTree.JCIdent) selected;
int vStart = ident.getStartPosition();
int vEnd = ident.getEndPosition(context.getEndPosTable());
Range vRange = Range.create(src, vStart, vEnd);
Variable variable = new Variable(selectScope, ident.pos, vRange);
variable.fqcn = fqcn;
src.getCurrentScope().ifPresent(s -> s.addVariable(variable));
}
});
}
if (nonNull(sym.type)) {
setReturnTypeAndArgType(context, src, sym.type, fa);
}
src.getCurrentScope().ifPresent(scope -> scope.addFieldAccess(fa));
} else if (kind.equals(ElementKind.METHOD)) {
MethodCall methodCall = new MethodCall(selectScope, identifier.toString(), preferredPos + 1, range, range);
Symbol owner = sym.owner;
if (nonNull(owner) && nonNull(owner.type)) {
getTypeString(src, owner.type).ifPresent(fqcn -> methodCall.declaringClass = TreeAnalyzer.markFQCN(src, fqcn));
}
if (nonNull(sym.type)) {
setReturnTypeAndArgType(context, src, sym.type, methodCall);
}
src.getCurrentScope().ifPresent(scope -> scope.addMethodCall(methodCall));
} else if (kind.equals(ElementKind.ENUM)) {
if (nonNull(sym.type)) {
getTypeString(src, sym.type).ifPresent(fqcn -> {
String ignore = TreeAnalyzer.markFQCN(src, fqcn);
});
}
} else if (kind.equals(ElementKind.ENUM_CONSTANT)) {
FieldAccess fa = new FieldAccess(identifier.toString(), preferredPos + 1, range);
fa.scope = getFieldScope(fa, selectScope);
fa.isEnum = true;
Symbol owner = sym.owner;
if (nonNull(owner) && nonNull(owner.type)) {
getTypeString(src, owner.type).ifPresent(fqcn -> fa.declaringClass = TreeAnalyzer.markFQCN(src, fqcn));
}
if (nonNull(sym.type)) {
setReturnTypeAndArgType(context, src, sym.type, fa);
}
src.getCurrentScope().ifPresent(scope -> scope.addFieldAccess(fa));
} else if (kind.equals(ElementKind.PACKAGE)) {
// skip
} else if (kind.equals(ElementKind.CLASS)) {
if (nonNull(sym.type)) {
getTypeString(src, sym.type).ifPresent(fqcn -> {
String ignore = TreeAnalyzer.markFQCN(src, fqcn);
});
}
} else if (kind.equals(ElementKind.INTERFACE)) {
if (nonNull(sym.type)) {
getTypeString(src, sym.type).ifPresent(fqcn -> {
String ignore = TreeAnalyzer.markFQCN(src, fqcn);
});
}
} else if (kind.equals(ElementKind.ANNOTATION_TYPE)) {
if (nonNull(sym.type)) {
getTypeString(src, sym.type).ifPresent(fqcn -> {
String ignore = TreeAnalyzer.markFQCN(src, fqcn);
});
}
} else {
log.warn("other kind:{}", kind);
}
}
use of javax.lang.model.element.ElementKind in project checker-framework by typetools.
the class BaseTypeVisitor method warnAboutTypeAnnotationsTooEarly.
/**
* Warn if a type annotation is written before a modifier such as "public" or before a declaration
* annotation.
*
* @param node a VariableTree or a MethodTree
* @param modifiersTree the modifiers sub-tree of node
*/
private void warnAboutTypeAnnotationsTooEarly(Tree node, ModifiersTree modifiersTree) {
// the effort to do so.
if (node.getKind() == Tree.Kind.VARIABLE) {
ElementKind varKind = TreeUtils.elementFromDeclaration((VariableTree) node).getKind();
switch(varKind) {
case ENUM_CONSTANT:
// appears to be before "public".
return;
case RESOURCE_VARIABLE:
// appears to be before "final".
return;
default:
if (TreeUtils.isAutoGeneratedRecordMember(node)) {
// a warning about those.
return;
}
}
}
Set<Modifier> modifierSet = modifiersTree.getFlags();
List<? extends AnnotationTree> annotations = modifiersTree.getAnnotations();
if (annotations.isEmpty()) {
return;
}
// Warn about type annotations written before modifiers such as "public". javac retains no
// information about modifier locations. So, this is a very partial check: Issue a warning if
// a type annotation is at the very beginning of the VariableTree, and a modifier follows it.
// Check if a type annotation precedes a declaration annotation.
int lastDeclAnnoIndex = -1;
for (int i = annotations.size() - 1; i > 0; i--) {
// no need to check index 0
if (!isTypeAnnotation(annotations.get(i))) {
lastDeclAnnoIndex = i;
break;
}
}
if (lastDeclAnnoIndex != -1) {
List<AnnotationTree> badTypeAnnos = new ArrayList<>();
for (int i = 0; i < lastDeclAnnoIndex; i++) {
AnnotationTree anno = annotations.get(i);
if (isTypeAnnotation(anno)) {
badTypeAnnos.add(anno);
}
}
if (!badTypeAnnos.isEmpty()) {
checker.reportWarning(node, "type.anno.before.decl.anno", badTypeAnnos, annotations.get(lastDeclAnnoIndex));
}
}
// Determine the length of the text that ought to precede the first type annotation.
// If the type annotation appears before that text could appear, then warn that a
// modifier appears after the type annotation.
// TODO: in the future, account for the lengths of declaration annotations. Length of toString
// of the annotation isn't useful, as it might be different length than original input. Can use
// JCTree.getEndPosition(EndPosTable) and com.sun.tools.javac.tree.EndPosTable, but it requires
// -Xjcov.
AnnotationTree firstAnno = annotations.get(0);
if (!modifierSet.isEmpty() && isTypeAnnotation(firstAnno)) {
int precedingTextLength = 0;
for (Modifier m : modifierSet) {
// +1 for the space
precedingTextLength += m.toString().length() + 1;
}
int annoStartPos = ((JCTree) firstAnno).getStartPosition();
int varStartPos = ((JCTree) node).getStartPosition();
if (annoStartPos < varStartPos + precedingTextLength) {
checker.reportWarning(node, "type.anno.before.modifier", firstAnno, modifierSet);
}
}
}
use of javax.lang.model.element.ElementKind in project checker-framework by typetools.
the class DependentTypesHelper method atVariableDeclaration.
/**
* Standardize the Java expressions in annotations in a variable declaration. Converts the
* parameter syntax, e.g "#1", to the parameter name.
*
* @param type the type of the variable declaration; is side-effected by this method
* @param declarationTree the variable declaration
* @param variableElt the element of the variable declaration
*/
public void atVariableDeclaration(AnnotatedTypeMirror type, Tree declarationTree, VariableElement variableElt) {
if (!hasDependentType(type)) {
return;
}
TreePath pathToVariableDecl = factory.getPath(declarationTree);
if (pathToVariableDecl == null) {
// If this is a synthetic created by dataflow, the path will be null.
return;
}
ElementKind variableKind = variableElt.getKind();
if (ElementUtils.isBindingVariable(variableElt)) {
// Treat binding variables the same as local variables.
variableKind = ElementKind.LOCAL_VARIABLE;
}
switch(variableKind) {
case PARAMETER:
TreePath pathTillEnclTree = TreePathUtil.pathTillOfKind(pathToVariableDecl, METHOD_OR_LAMBDA);
if (pathTillEnclTree == null) {
throw new BugInCF("no enclosing method or lambda found for " + variableElt);
}
Tree enclTree = pathTillEnclTree.getLeaf();
if (enclTree.getKind() == Tree.Kind.METHOD) {
MethodTree methodDeclTree = (MethodTree) enclTree;
StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atMethodBody(stringExpr, methodDeclTree, factory.getChecker());
if (debugStringToJavaExpression) {
System.out.printf("atVariableDeclaration(%s, %s, %s) 1 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExpr);
}
convertAnnotatedTypeMirror(stringToJavaExpr, type);
} else {
// Lambdas can use local variables defined in the enclosing method, so allow
// identifiers to be locals in scope at the location of the lambda.
StringToJavaExpression stringToJavaExpr = stringExpr -> StringToJavaExpression.atLambdaParameter(stringExpr, (LambdaExpressionTree) enclTree, pathToVariableDecl.getParentPath(), factory.getChecker());
if (debugStringToJavaExpression) {
System.out.printf("atVariableDeclaration(%s, %s, %s) 2 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExpr);
}
convertAnnotatedTypeMirror(stringToJavaExpr, type);
}
break;
case LOCAL_VARIABLE:
case RESOURCE_VARIABLE:
case EXCEPTION_PARAMETER:
StringToJavaExpression stringToJavaExprVar = stringExpr -> StringToJavaExpression.atPath(stringExpr, pathToVariableDecl, factory.getChecker());
if (debugStringToJavaExpression) {
System.out.printf("atVariableDeclaration(%s, %s, %s) 3 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExprVar);
}
convertAnnotatedTypeMirror(stringToJavaExprVar, type);
break;
case FIELD:
case ENUM_CONSTANT:
StringToJavaExpression stringToJavaExprField = stringExpr -> StringToJavaExpression.atFieldDecl(stringExpr, variableElt, factory.getChecker());
if (debugStringToJavaExpression) {
System.out.printf("atVariableDeclaration(%s, %s, %s) 4 created %s%n", type, TreeUtils.toStringTruncated(declarationTree, 65), variableElt, stringToJavaExprField);
}
convertAnnotatedTypeMirror(stringToJavaExprField, type);
break;
default:
throw new BugInCF("unexpected element kind " + variableElt.getKind() + " for " + variableElt);
}
}
Aggregations