/** INTERNAL: Visit an executable and create a MetadataMethod object. */ @Override public MetadataMethod visitExecutable( ExecutableElement executableElement, MetadataClass metadataClass) { MetadataMethod method = new MetadataMethod(metadataClass.getMetadataFactory(), metadataClass); // Set the name. method.setName(executableElement.getSimpleName().toString()); // Set the attribute name. method.setAttributeName(Helper.getAttributeNameFromMethodName(method.getName())); // Set the modifiers. method.setModifiers(getModifiers(executableElement.getModifiers())); // Visit executable element for the parameters, return type and generic type. executableElement.asType().accept(typeVisitor, method); // Set the annotations. buildMetadataAnnotations(method, executableElement.getAnnotationMirrors()); // Handle multiple methods with the same name. MetadataMethod existing = metadataClass.getMethods().get(method.getName()); if (existing == null) { metadataClass.addMethod(method); } else { while (existing.getNext() != null) { existing = existing.getNext(); } existing.setNext(method); } return method; }
private void processExecutableElement(String prefix, ExecutableElement element) { if (element.getModifiers().contains(Modifier.PUBLIC) && (TypeKind.VOID != element.getReturnType().getKind())) { Element returns = this.processingEnv.getTypeUtils().asElement(element.getReturnType()); if (returns instanceof TypeElement) { ItemMetadata group = ItemMetadata.newGroup( prefix, this.typeUtils.getType(returns), this.typeUtils.getType(element.getEnclosingElement()), element.toString()); if (this.metadataCollector.hasSimilarGroup(group)) { this.processingEnv .getMessager() .printMessage( Kind.ERROR, "Duplicate `@ConfigurationProperties` definition for prefix '" + prefix + "'", element); } else { this.metadataCollector.add(group); processTypeElement(prefix, (TypeElement) returns, element); } } } }
private void parseMethod(Api api, ExecutableElement executableElement) throws IOException { Element actionElement = generator .getProcessingEnvironment() .getElementUtils() .getTypeElement(ApiMethodDoc.class.getName()); TypeMirror apiMethodDocType = actionElement.asType(); for (AnnotationMirror am : executableElement.getAnnotationMirrors()) { if (am.getAnnotationType().equals(apiMethodDocType)) { api.apiMethodDoc = Maps.newHashMap(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> ee : am.getElementValues().entrySet()) { api.apiMethodDoc.put(ee.getKey().getSimpleName().toString(), ee.getValue()); } break; } } // generator.log("apiMethodDoc: " + api.apiMethodDoc); if (null == api.apiMethodDoc) { generator.log("Method miss @ApiMethodDoc. " + executableElement); return; } api.methodName = executableElement.getSimpleName().toString(); api.methodMapping = executableElement.getAnnotation(RequestMapping.class); api.parameters = Lists.newArrayList(); for (VariableElement var : executableElement.getParameters()) { api.parameters.add(var); } }
private void processSimpleTypes( String prefix, TypeElement element, ExecutableElement source, TypeElementMembers members, Map<String, Object> fieldValues) { for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters().entrySet()) { String name = entry.getKey(); ExecutableElement getter = entry.getValue(); TypeMirror returnType = getter.getReturnType(); ExecutableElement setter = members.getPublicSetter(name, returnType); VariableElement field = members.getFields().get(name); Element returnTypeElement = this.processingEnv.getTypeUtils().asElement(returnType); boolean isExcluded = this.typeExcludeFilter.isExcluded(returnType); boolean isNested = isNested(returnTypeElement, field, element); boolean isCollection = this.typeUtils.isCollectionOrMap(returnType); if (!isExcluded && !isNested && (setter != null || isCollection)) { String dataType = this.typeUtils.getType(returnType); String sourceType = this.typeUtils.getType(element); String description = this.typeUtils.getJavaDoc(field); Object defaultValue = fieldValues.get(name); boolean deprecated = isDeprecated(getter) || isDeprecated(setter) || isDeprecated(source); this.metadataCollector.add( ItemMetadata.newProperty( prefix, name, dataType, sourceType, null, description, defaultValue, (deprecated ? getItemDeprecation(getter) : null))); } } }
private void createConstructorAndBuilder() { List<ExecutableElement> constructors = new ArrayList<ExecutableElement>(); for (Element e : annotatedElement.getEnclosedElements()) { if (e.getKind() == CONSTRUCTOR) { constructors.add((ExecutableElement) e); } } for (ExecutableElement userConstructor : constructors) { JMethod copyConstructor = generatedClass.constructor(PUBLIC); JMethod staticHelper = generatedClass.method(PUBLIC | STATIC, generatedClass._extends(), "build"); codeModelHelper.generifyStaticHelper(this, staticHelper, getAnnotatedElement()); JBlock body = copyConstructor.body(); JInvocation superCall = body.invoke("super"); JInvocation newInvocation = JExpr._new(generatedClass); for (VariableElement param : userConstructor.getParameters()) { String paramName = param.getSimpleName().toString(); JClass paramType = codeModelHelper.typeMirrorToJClass(param.asType(), this); copyConstructor.param(paramType, paramName); staticHelper.param(paramType, paramName); superCall.arg(JExpr.ref(paramName)); newInvocation.arg(JExpr.ref(paramName)); } JVar newCall = staticHelper.body().decl(generatedClass, "instance", newInvocation); staticHelper.body().invoke(newCall, getOnFinishInflate()); staticHelper.body()._return(newCall); body.invoke(getInit()); } }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { // System.out.println("supported options: "+ // Arrays.toString(getSupportedOptions().toArray())); if (!roundEnv.processingOver()) { for (TypeElement currAnno : annotations) { // System.out.println("Found " + currAnno.getQualifiedName()); if (currAnno.getQualifiedName().contentEquals(GENERATE_POJO_BUILDER_CLASS.getName())) { Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(currAnno); // System.out.println("[GenerateBuilder] annotatedElements="+ // Arrays.toString(annotatedElements.toArray())); for (Element elem : annotatedElements) { if (elem.getKind() == ElementKind.CLASS) { TypeElement typeElem = (TypeElement) elem; GeneratePojoBuilder annotation = typeElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS); generatePojoBuilderProcessor.process(typeElem, annotation); } else if (elem.getKind() == ElementKind.METHOD) { ExecutableElement execElem = (ExecutableElement) elem; GeneratePojoBuilder annotation = execElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS); generatePojoBuilderProcessor.process(execElem, annotation); } } } } } return false; }
String getConverterClassName(Element el) { AnnotationValue converter = null; for (AnnotationMirror am : el.getAnnotationMirrors()) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = am.getElementValues(); for (ExecutableElement e : elementValues.keySet()) { if ("converter".equals(e.getSimpleName().toString())) { converter = elementValues.get(e); } } } String result = null; if (converter != null && !TokenConverter.class.getCanonicalName().equals(converter)) { String tmp = converter.toString(); if (tmp.endsWith(".class")) { int i = tmp.lastIndexOf('.'); result = tmp.substring(0, i); } else { result = tmp; } } return result; }
/** * Returns true if {@code annotation} has a single element named "value", letting us drop the * 'value=' prefix in the source code. */ private static boolean hasSingleValueWithDefaultKey(AnnotationMirror annotation) { if (annotation.getElementValues().size() != 1) { return false; } ExecutableElement key = getOnlyElement(annotation.getElementValues().keySet()); return key.getSimpleName().contentEquals("value"); }
/** * Tests whether a method invocation is an invocation of {@link Comparable#compareTo}. * * <p> * * @param node a method invocation node * @return true iff {@code node} is a invocation of {@code compareTo()} */ private boolean isInvocationOfCompareTo(MethodInvocationTree node) { ExecutableElement method = TreeUtils.elementFromUse(node); return (method.getParameters().size() == 1 && method.getReturnType().getKind() == TypeKind.INT // method symbols only have simple names && method.getSimpleName().contentEquals("compareTo")); }
@Override public void process(Element element, EBeanHolder holder) { final ExecutableElement afterPutMethod = (ExecutableElement) element; final UseModelHolder useModelHolder = holder.getPluginHolder(new UseModelHolder(holder)); useModelHolder.setAfterPutMethod(afterPutMethod); List<Class<? extends Annotation>> annotations = Arrays.asList(UseModel.class, LocalDBModel.class, ServerModel.class); for (Class<? extends Annotation> annotation : annotations) { if (element.getAnnotation(annotation) != null) return; } List<? extends VariableElement> parameters = afterPutMethod.getParameters(); JInvocation invocation = useModelHolder .getPutModelInitBlock() ._if(ref("result").ne(_null())) ._then() .invoke(afterPutMethod.getSimpleName().toString()); for (VariableElement param : parameters) { final String paramName = param.getSimpleName().toString(); ParamUtils.injectParam(paramName, invocation); } }
private void processFromProperties(TypeElement type, Set<TypeElement> types) { List<? extends Element> children = type.getEnclosedElements(); VisitorConfig config = conf.getConfig(type, children); // fields if (config.visitFieldProperties()) { for (VariableElement field : ElementFilter.fieldsIn(children)) { TypeElement typeElement = typeExtractor.visit(field.asType()); if (typeElement != null) { types.add(typeElement); } } } // getters if (config.visitMethodProperties()) { for (ExecutableElement method : ElementFilter.methodsIn(children)) { String name = method.getSimpleName().toString(); if ((name.startsWith("get") || name.startsWith("is")) && method.getParameters().isEmpty()) { TypeElement typeElement = typeExtractor.visit(method.getReturnType()); if (typeElement != null) { types.add(typeElement); } } } } }
@Override public void printErrorCheckMethod( final PrintWriter writer, final ExecutableElement method, final String tabs) { final Check check = method.getAnnotation(Check.class); if (check != null) // Get the error code from an IntBuffer output parameter writer.println( tabs + "Util.checkCLError(" + check.value() + ".get(" + check.value() + ".position()));"); else { final Class return_type = Utils.getJavaType(method.getReturnType()); if (return_type == int.class) writer.println(tabs + "Util.checkCLError(__result);"); else { boolean hasErrCodeParam = false; for (final VariableElement param : method.getParameters()) { if ("errcode_ret".equals(param.getSimpleName().toString()) && Utils.getJavaType(param.asType()) == IntBuffer.class) { hasErrCodeParam = true; break; } } if (hasErrCodeParam) throw new RuntimeException( "A method is missing the @Check annotation: " + method.toString()); } } }
/** * Returns true if generated code can invoke {@code constructor}. That is, if the constructor is * non-private and its enclosing class is either a top-level class or a static nested class. */ public static boolean isCallableConstructor(ExecutableElement constructor) { if (constructor.getModifiers().contains(Modifier.PRIVATE)) { return false; } TypeElement type = (TypeElement) constructor.getEnclosingElement(); return type.getEnclosingElement().getKind() == ElementKind.PACKAGE || type.getModifiers().contains(Modifier.STATIC); }
private boolean checkForDependencies(List<ExecutableElement> providerMethods) { for (ExecutableElement element : providerMethods) { if (!element.getParameters().isEmpty()) { return true; } } return false; }
private void hasConstructor(TypeElement type) { for (ExecutableElement cons : ElementFilter.constructorsIn(type.getEnclosedElements())) { if (cons.getParameters().isEmpty()) { return; } } error("missing default (no-args) constructor", type); }
private boolean checkForMultibindings(List<ExecutableElement> providerMethods) { for (ExecutableElement element : providerMethods) { if (element.getAnnotation(Provides.class).type() == Provides.Type.SET) { return true; } } return false; }
public static boolean isSimpleMethod(final Element element) { if (element instanceof ExecutableElement) { final ExecutableElement ee = (ExecutableElement) element; final List<? extends VariableElement> parameters = ee.getParameters(); return !hasAnyModifier(ee, Modifier.STATIC) && parameters.isEmpty(); } return false; }
private static Set<TypeElement> nestedAnnotationElements( TypeElement annotationElement, Set<TypeElement> annotationElements) { if (annotationElements.add(annotationElement)) { for (ExecutableElement method : methodsIn(annotationElement.getEnclosedElements())) { TRAVERSE_NESTED_ANNOTATIONS.visit(method.getReturnType(), annotationElements); } } return annotationElements; }
private static String getResultType(ExecutableElement method, boolean native_stub) { if (native_stub && method.getAnnotation(PointerWrapper.class) != null) { return "long"; } else if (!native_stub && method.getAnnotation(GLreturn.class) != null) { return Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false); } else { return Utils.getJavaType(Utils.getMethodReturnType(method)).getSimpleName(); } }
private void processNestedTypes( String prefix, TypeElement element, ExecutableElement source, TypeElementMembers members) { for (Map.Entry<String, ExecutableElement> entry : members.getPublicGetters().entrySet()) { String name = entry.getKey(); ExecutableElement getter = entry.getValue(); VariableElement field = members.getFields().get(name); processNestedType(prefix, element, source, name, getter, field, getter.getReturnType()); } }
/** * @param executable the executable to check * @return {@code true}, iff the executable does not represent {@link * java.lang.Object#equals(Object)} or an overridden version of it */ private static boolean isNotObjectEquals(ExecutableElement executable) { if (executable.getSimpleName().contentEquals("equals") && executable.getParameters().size() == 1 && asTypeElement(executable.getParameters().get(0).asType()) .getQualifiedName() .contentEquals("java.lang.Object")) { return false; } return true; }
// 4942232: // check that classes exist for all the parameters of native methods private void checkMethodParameters(Set<TypeElement> classes) { Types types = processingEnv.getTypeUtils(); for (TypeElement te : classes) { for (ExecutableElement ee : ElementFilter.methodsIn(te.getEnclosedElements())) { for (VariableElement ve : ee.getParameters()) { TypeMirror tm = ve.asType(); checkMethodParametersVisitor.visit(tm, types); } } } }
private AutoValueExtension.Context createContext(TypeElement type) { String packageName = MoreElements.getPackage(type).getQualifiedName().toString(); Set<ExecutableElement> allMethods = MoreElements.getLocalAndInheritedMethods(type, elements); Set<ExecutableElement> methods = methodsToImplement(type, allMethods); Map<String, ExecutableElement> properties = new LinkedHashMap<String, ExecutableElement>(); for (ExecutableElement e : methods) { properties.put(e.getSimpleName().toString(), e); } return new TestContext(processingEnvironment, packageName, type, properties); }
private void setConstructor() { constructor = generatedClass.constructor(PRIVATE); JVar constructorContextParam = constructor.param(getClasses().CONTEXT, "context"); JBlock constructorBody = constructor.body(); List<ExecutableElement> constructors = ElementFilter.constructorsIn(annotatedElement.getEnclosedElements()); ExecutableElement superConstructor = constructors.get(0); if (superConstructor.getParameters().size() == 1) { constructorBody.invoke("super").arg(constructorContextParam); } constructorBody.assign(getContextField(), constructorContextParam); }
private void printMethod(ExecutableElement executableElement) { StringBuilder s = new StringBuilder(256); s.append("method: " + executableElement).append("\n\t"); s.append("annotations: " + executableElement.getAnnotationMirrors()).append("\n\t"); s.append("return: " + executableElement.getReturnType()).append("\n\t"); for (VariableElement var : executableElement.getParameters()) { s.append("parameter: " + var + ", " + var.getAnnotation(ApiParameterDoc.class)) .append("\n\t"); } generator.log(s.toString()); }
/** Returns the no-args constructor for {@code type}, or null if no such constructor exists. */ public static ExecutableElement getNoArgsConstructor(TypeElement type) { for (Element enclosed : type.getEnclosedElements()) { if (enclosed.getKind() != ElementKind.CONSTRUCTOR) { continue; } ExecutableElement constructor = (ExecutableElement) enclosed; if (constructor.getParameters().isEmpty()) { return constructor; } } return null; }
/** * Build the comments for the method. Do nothing if {@link Configuration#nocomment} is set to * true. * * @param node the XML element that specifies which components to document * @param methodDocTree the content tree to which the documentation will be added */ public void buildMethodComments(XMLNode node, Content methodDocTree) { if (!configuration.nocomment) { ExecutableElement method = currentMethod; if (utils.getBody(currentMethod).isEmpty()) { DocFinder.Output docs = DocFinder.search(configuration, new DocFinder.Input(utils, currentMethod)); if (docs.inlineTags != null && !docs.inlineTags.isEmpty()) method = (ExecutableElement) docs.holder; } TypeMirror containingType = method.getEnclosingElement().asType(); writer.addComments(containingType, method, methodDocTree); } }
/** * Determines whether or not the given element overrides the named method in the named class. * * @param e an element for a method * @param clazz the class * @param method the name of a method * @return true if the method given by {@code e} overrides the named method in the named class; * false otherwise */ private boolean overrides(ExecutableElement e, Class<?> clazz, String method) { // Get the element named by "clazz". TypeElement clazzElt = elements.getTypeElement(clazz.getCanonicalName()); assert clazzElt != null; // Check all of the methods in the class for name matches and overriding. for (ExecutableElement elt : methodsIn(clazzElt.getEnclosedElements())) if (elt.getSimpleName().contentEquals(method) && elements.overrides(e, elt, clazzElt)) return true; return false; }
private boolean hasParcelableConstructor(TypeElement typeElement) { for (Element e : typeElement.getEnclosedElements()) { if (e.getKind() == ElementKind.CONSTRUCTOR && hasSomeModifier(e, Modifier.PUBLIC)) { ExecutableElement c = (ExecutableElement) e; List<? extends VariableElement> params = c.getParameters(); if (params.size() == 1 && ClassName.get(params.get(0).asType()).equals(ClassName.get(Parcel.class))) { return true; } } } return false; }
private Set<TypeElement> processDelegateMethods() { Set<Element> delegateMethods = (Set) getElements(QueryDelegate.class); Set<TypeElement> typeElements = new HashSet<TypeElement>(); for (Element delegateMethod : delegateMethods) { ExecutableElement method = (ExecutableElement) delegateMethod; Element element = delegateMethod.getEnclosingElement(); String name = method.getSimpleName().toString(); Type delegateType = typeFactory.getType(element.asType(), true); Type returnType = typeFactory.getType(method.getReturnType(), true); List<Parameter> parameters = elementHandler.transformParams(method.getParameters()); // remove first element parameters = parameters.subList(1, parameters.size()); EntityType entityType = null; for (AnnotationMirror annotation : delegateMethod.getAnnotationMirrors()) { if (TypeUtils.isAnnotationMirrorOfType(annotation, QueryDelegate.class)) { TypeMirror type = TypeUtils.getAnnotationValueAsTypeMirror(annotation, "value"); if (type != null) { entityType = typeFactory.getEntityType(type, true); } } } if (entityType != null) { registerTypeElement(entityType.getFullName(), (TypeElement) element); entityType.addDelegate( new Delegate(entityType, delegateType, name, parameters, returnType)); TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(entityType.getFullName()); boolean isAnnotated = false; for (Class<? extends Annotation> ann : conf.getEntityAnnotations()) { if (typeElement.getAnnotation(ann) != null) { isAnnotated = true; } } if (isAnnotated) { // handle also properties of entity type typeElements.add( processingEnv.getElementUtils().getTypeElement(entityType.getFullName())); } else { // skip handling properties context.extensionTypes.put(entityType.getFullName(), entityType); context.allTypes.put(entityType.getFullName(), entityType); } } } return typeElements; }