private static String getFieldAddress(RestActionClass actionClass, Element element) { String address; if (actionClass.getTypeElement().equals(element.getEnclosingElement())) { address = "action.$L"; } else { address = String.format("((%s)action).$L", element.getEnclosingElement()); } return address; }
private void parseBindExtra( Element element, Map<TypeElement, IntentBindingAdapterGenerator> targetClassMap, Set<String> erasedTargetNames) throws InvalidTypeException { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target has all the appropriate information for type TypeMirror type = element.asType(); if (type instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) type; type = typeVariable.getUpperBound(); } validateNotRequiredArguments(element); validateForCodeGeneration(BindExtra.class, element); validateBindingPackage(BindExtra.class, element); // Assemble information on the bind point String name = element.getSimpleName().toString(); String intentType = typeUtil.getIntentType(type); KeySpec key = getKey(element); boolean required = element.getAnnotation(NotRequired.class) == null; boolean hasDefault = typeUtil.isPrimitive(type); boolean needsToBeCast = typeUtil.needToCastIntentType(type); IntentBindingAdapterGenerator intentBindingAdapterGenerator = getOrCreateTargetClass(targetClassMap, enclosingElement); IntentFieldBinding binding = new IntentFieldBinding(name, type, intentType, key, needsToBeCast, hasDefault, required); intentBindingAdapterGenerator.addField(binding); // Add the type-erased version to the valid targets set. erasedTargetNames.add(enclosingElement.toString()); }
private void parseBind( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { // Verify common generated code restrictions. if (isInaccessibleViaGeneratedCode(Bind.class, "fields", element) || isBindingInWrongPackage(Bind.class, element)) { return; } TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.ARRAY) { parseBindMany(element, targetClassMap, erasedTargetNames); } else if (LIST_TYPE.equals(doubleErasure(elementType))) { parseBindMany(element, targetClassMap, erasedTargetNames); } else if (isSubtypeOfType(elementType, ITERABLE_TYPE)) { error( element, "@%s must be a List or array. (%s.%s)", Bind.class.getSimpleName(), ((TypeElement) element.getEnclosingElement()).getQualifiedName(), element.getSimpleName()); } else { parseBindOne(element, targetClassMap, erasedTargetNames); } }
/** super(args) -> SuperType.call(this, args) */ private JS callToSuperConstructor( WriterVisitor<JS> visitor, MethodInvocationTree tree, GenerationContext<JS> context) { Element methodElement = TreeUtils.elementFromUse(tree); TypeElement typeElement = (TypeElement) methodElement.getEnclosingElement(); String methodName = MethodInvocationWriter.buildMethodName(tree); // avoid useless call to super() when the super class is Object if (GeneratorConstants.SUPER.equals(methodName) && JavaNodes.sameRawType(typeElement.asType(), Object.class)) { return null; } // avoid call to super for synthetic types if (GeneratorConstants.SUPER.equals(methodName) && context.getCurrentWrapper().getEnclosingType().isSyntheticType()) { return null; } // transform it into superType.[prototype.method].call(this, args..); String typeName = context.getNames().getTypeName(context, typeElement, DependencyType.STATIC); JS superType = context .js() .name( GeneratorConstants.SUPER.equals(methodName) ? typeName : typeName + ".prototype." + methodName); List<JS> arguments = MethodInvocationWriter.buildArguments(visitor, tree, context); arguments.add(0, context.js().keyword(Keyword.THIS)); return context.js().functionCall(context.js().property(superType, "call"), arguments); }
private void parseOnChanged( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames, Class annotationClass) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); TypeMirror mirror = element.asType(); if (!(mirror.getKind() == TypeKind.EXECUTABLE)) return; String method = element.toString().trim(); String methodName = method.substring(0, method.indexOf("(")); Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(method); if (m.find()) { String[] methodTypes = m.group(1).split(","); String key = null; if (annotationClass.equals(OnKStringChanged.class)) { KStringBinding binding = new KStringBinding(methodName, methodTypes); key = element.getAnnotation(OnKStringChanged.class).value(); bindingClass.putGeneric(key, binding); } else if (annotationClass.equals(OnKBooleanChanged.class)) { KBooleanBinding binding = new KBooleanBinding(methodName, methodTypes); key = element.getAnnotation(OnKBooleanChanged.class).value(); bindingClass.putGeneric(key, binding); } else { error(element, "unknow annotation class type @%s", annotationClass.getSimpleName()); } } erasedTargetNames.add(enclosingElement.toString()); }
private TypeElement getAnnotatedType(Element element) { List<TypeElement> types = ImmutableList.of(); while (types.isEmpty()) { types = ElementFilter.typesIn(Arrays.asList(element)); element = element.getEnclosingElement(); } return Iterables.getOnlyElement(types); }
@Override public Boolean call(Element element) { if (ElementKind.PACKAGE != element.getEnclosingElement().getKind()) { mProcessingEnv.printMessage( Diagnostic.Kind.ERROR, element, "Annotation not supported for nested class"); return false; } return true; }
private boolean isDeprecated(Element element) { if (isElementDeprecated(element)) { return true; } if (element != null && (element instanceof VariableElement || element instanceof ExecutableElement)) { return isElementDeprecated(element.getEnclosingElement()); } return false; }
private PackageElement getPackage(final Element serviceElement) { if (serviceElement == null) { return null; } Element enclosing = serviceElement.getEnclosingElement(); if (enclosing instanceof PackageElement) { return (PackageElement) enclosing; } else { return getPackage(enclosing); } }
public static Collection<TypeElement> foldToTypeElements( final Set<? extends Element> allElements) { final Collection<TypeElement> elements = Sets.newHashSet(); for (final Element element : allElements) { if (element instanceof TypeElement) { elements.add((TypeElement) element); } else if (element instanceof VariableElement || element instanceof ExecutableElement) { final Element enclosingElement = element.getEnclosingElement(); if (enclosingElement instanceof TypeElement) { elements.add((TypeElement) enclosingElement); } else if (enclosingElement instanceof ExecutableElement) { elements.add((TypeElement) enclosingElement.getEnclosingElement()); } } else { throw new UnsupportedOperationException("Unknown type of element"); } } return elements; }
private void processProjectionTypes(Set<TypeElement> elements) { Set<Element> visited = new HashSet<Element>(); for (Element element : getElements(QueryProjection.class)) { Element parent = element.getEnclosingElement(); if (!elements.contains(parent) && !visited.contains(parent)) { EntityType model = elementHandler.handleProjectionType((TypeElement) parent); registerTypeElement(model.getFullName(), (TypeElement) parent); context.projectionTypes.put(model.getFullName(), model); visited.add(parent); } } }
// TODO(sgoldfed): better format for other types of elements? static String elementToString(Element element) { switch (element.getKind()) { case FIELD: // fall through case CONSTRUCTOR: // fall through case METHOD: return element.getEnclosingElement() + "." + element; default: return element.toString(); } }
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; }
@Override @Value.Derived @Value.Auxiliary public DeclaringPackage packageOf() { Element e = element(); for (; e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) {} return interner() .forPackage( ImmutableProto.DeclaringPackage.builder() .environment(environment()) .interner(interner()) .element((PackageElement) e) .build()); }
String getElementKeyString(Element element) { JsonKey key = element.getAnnotation(JsonKey.class); JsonModel model = element.getEnclosingElement().getAnnotation(JsonModel.class); String keyStr; if (!"".equals(key.value())) { keyStr = key.value(); } else if ("".equals(key.value()) && key.decamelize()) { keyStr = decamelize(element.toString()); } else if ("".equals(key.value()) && model.decamelize()) { keyStr = decamelize(element.toString()); } else { keyStr = element.toString(); } return keyStr; }
private List<String> pointsOfTestCase(Element method) { List<String> pointNames = new ArrayList<>(); Optional<String> classAnnotation = getPointsAnnotationValueIfAny(method.getEnclosingElement()); if (classAnnotation.isPresent()) { String annotation = classAnnotation.get(); pointNames.addAll(Arrays.asList(annotation.split(" +"))); } Optional<String> methodAnnotation = getPointsAnnotationValueIfAny(method); if (methodAnnotation.isPresent()) { String annotation = methodAnnotation.get(); pointNames.addAll(Arrays.asList(annotation.split(" +"))); } return pointNames; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(Test.class)) { if (element.getKind() == ElementKind.METHOD) { String methodName = element.getSimpleName().toString(); String className = ((TypeElement) (element.getEnclosingElement())).getQualifiedName().toString(); List<String> points = pointsOfTestCase(element); if (!points.isEmpty()) { String testName = className + " " + methodName; testDescs.add(new TestDesc(testName, ImmutableList.copyOf(points))); } } } return false; }
private void parseBindText( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) elementType; elementType = typeVariable.getUpperBound(); } // Assemble information on the field. int[] ids = element.getAnnotation(BindText.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); for (int id : ids) { if (bindingClass != null) { KBindings bindings = bindingClass.getKBindings(String.valueOf(id)); if (bindings != null) { Iterator<FieldViewBinding> iterator = bindings.getFieldBindings().iterator(); if (iterator.hasNext()) { FieldViewBinding existingBinding = iterator.next(); error( element, "Attempt to use @%s for an already bound ID %s on '%s'. (%s.%s)", BindText.class.getSimpleName(), id, existingBinding.getName(), enclosingElement.getQualifiedName(), element.getSimpleName()); return; } } } else { bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); } String name = element.getSimpleName().toString(); TypeName type = TypeName.get(elementType); boolean required = isRequiredBinding(element); FieldViewBinding binding = new FieldViewBinding(name, type, required); bindingClass.addField(String.valueOf(id), binding); } // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement.toString()); }
@Override public boolean process( Set<? extends TypeElement> typeElements, RoundEnvironment roundEnvironment) { logger = new Logger(processingEnv.getMessager()); // Get holding class for (TypeElement typeElement : typeElements) { Set<? extends Element> annotatedElements = roundEnvironment.getElementsAnnotatedWith(typeElement); for (Element annotatedElement : annotatedElements) { TypeElement enclosingElement = (TypeElement) annotatedElement.getEnclosingElement(); manageType(enclosingElement, logger); } } return true; }
public TableEndpointDefinition(Element typeElement, ProcessorManager processorManager) { super(typeElement, processorManager); TableEndpoint endpoint = typeElement.getAnnotation(TableEndpoint.class); tableName = endpoint.name(); contentProviderName = endpoint.contentProviderName(); isTopLevel = typeElement.getEnclosingElement() instanceof PackageElement; List<? extends Element> elements = processorManager.getElements().getAllMembers((TypeElement) typeElement); for (Element innerElement : elements) { if (innerElement.getAnnotation(ContentUri.class) != null) { ContentUriDefinition contentUriDefinition = new ContentUriDefinition(innerElement, processorManager); if (!pathValidationMap.containsKey(contentUriDefinition.path)) { contentUriDefinitions.add(contentUriDefinition); } else { processorManager.logError( "There must be unique paths for the specified @ContentUri" + " %1s from %1s", contentUriDefinition.name, contentProviderName); } } else if (innerElement.getAnnotation(Notify.class) != null) { NotifyDefinition notifyDefinition = new NotifyDefinition(innerElement, processorManager); for (String path : notifyDefinition.paths) { Map<Notify.Method, List<NotifyDefinition>> methodListMap = notifyDefinitionPathMap.get(path); if (methodListMap == null) { methodListMap = Maps.newHashMap(); notifyDefinitionPathMap.put(path, methodListMap); } List<NotifyDefinition> notifyDefinitionList = methodListMap.get(notifyDefinition.method); if (notifyDefinitionList == null) { notifyDefinitionList = Lists.newArrayList(); methodListMap.put(notifyDefinition.method, notifyDefinitionList); } notifyDefinitionList.add(notifyDefinition); } } } }
@Value.Lazy public Optional<DeclaringType> enclosingTopLevel() { TypeElement top = element(); for (Element e = top; e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) { top = (TypeElement) e; } if (top == element()) { return Optional.absent(); } return Optional.of( interner() .forType( ImmutableProto.DeclaringType.builder() .environment(environment()) .interner(interner()) .element(top) .build())); }
private boolean isInaccessibleViaGeneratedCode( Class<? extends Annotation> annotationClass, String targetThing, Element element) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify method modifiers. Set<Modifier> modifiers = element.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) { error( element, "@%s %s must not be private or static. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify containing type. if (enclosingElement.getKind() != CLASS) { error( enclosingElement, "@%s %s may only be contained in classes. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify containing class visibility is not private. if (enclosingElement.getModifiers().contains(PRIVATE)) { error( enclosingElement, "@%s %s may not be contained in private classes. (%s.%s)", annotationClass.getSimpleName(), targetThing, enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } return hasError; }
/** * Determine the type of a field access (implicit or explicit) based on the receiver type and the * declared annotations for the field. * * @param type Type of the field access expression * @param declaredFieldAnnotations Annotations on the element. * @param receiverType Inferred annotations of the receiver */ private void computeFieldAccessType( AnnotatedTypeMirror type, Collection<? extends AnnotationMirror> declaredFieldAnnotations, AnnotatedTypeMirror receiverType, AnnotatedTypeMirror fieldAnnotations, Element element) { // not necessary for primitive fields if (TypesUtils.isPrimitive(type.getUnderlyingType())) { return; } // not necessary if there is an explicit UnknownInitialization // annotation on the field if (AnnotationUtils.containsSameIgnoringValues( fieldAnnotations.getAnnotations(), UNCLASSIFIED)) { return; } if (isUnclassified(receiverType) || isFree(receiverType)) { TypeMirror fieldDeclarationType = element.getEnclosingElement().asType(); boolean isInitializedForFrame = isInitializedForFrame(receiverType, fieldDeclarationType); if (isInitializedForFrame) { // The receiver is initialized for this frame. // Change the type of the field to @UnknownInitialization or @Raw so that // anything can be assigned to this field. type.replaceAnnotation(UNCLASSIFIED); } else if (computingAnnotatedTypeMirrorOfLHS) { // The receiver is not initialized for this frame, but the type of a lhs is being computed. // Change the type of the field to @UnknownInitialization or @Raw so that // anything can be assigned to this field. type.replaceAnnotation(UNCLASSIFIED); } else { // The receiver is not initialized for this frame and the type being computed is not a LHS. // Replace all annotations with the top annotation for that hierarchy. type.clearAnnotations(); type.addAnnotations(qualHierarchy.getTopAnnotations()); } if (!AnnotationUtils.containsSame(declaredFieldAnnotations, NOT_ONLY_COMMITTED) || !useFbc) { // add root annotation for all other hierarchies, and // Committed for the commitment hierarchy type.replaceAnnotation(COMMITTED); } } }
private void parseOnKStringUpdate( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); TypeMirror mirror = element.asType(); if (!(mirror.getKind() == TypeKind.EXECUTABLE)) return; String method = element.toString().trim(); String methodName = method.substring(0, method.indexOf("(")); Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(method); if (m.find()) { String[] methodTypes = m.group(1).split(","); UpdateKStringBinding binding = new UpdateKStringBinding(methodName, methodTypes); String kstring = element.getAnnotation(OnKStringChanged.class).value(); bindingClass.addKStringUpdateBinding(kstring, binding); } erasedTargetNames.add(enclosingElement.toString()); }
private void parseResourceDimen( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is int or ColorStateList. boolean isInt = false; TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.INT) { isInt = true; } else if (elementType.getKind() != TypeKind.FLOAT) { error( element, "@%s field type must be 'int' or 'float'. (%s.%s)", BindDimen.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindDimen.class, "fields", element); hasError |= isBindingInWrongPackage(BindDimen.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindDimen.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(id, name, isInt ? "getDimensionPixelSize" : "getDimension"); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement.toString()); }
static boolean checkAbstractValueType(Element element, Collection<String> violations) { boolean ofSupportedKind = false || element.getKind() == ElementKind.INTERFACE || element.getKind() == ElementKind.ANNOTATION_TYPE || element.getKind() == ElementKind.CLASS; boolean staticOrTopLevel = false || element.getEnclosingElement().getKind() == ElementKind.PACKAGE || element.getModifiers().contains(Modifier.STATIC); boolean nonFinal = !element.getModifiers().contains(Modifier.FINAL); boolean hasNoTypeParameters = ((TypeElement) element).getTypeParameters().isEmpty(); boolean publicOrPackageVisible = !element.getModifiers().contains(Modifier.PRIVATE) && !element.getModifiers().contains(Modifier.PROTECTED); if (!ofSupportedKind) { violations.add("must be class or interface or annotation type"); } if (!nonFinal) { violations.add("must be non-final"); } if (!hasNoTypeParameters) { violations.add("should have no type parameters"); } if (!publicOrPackageVisible) { violations.add("should be public or package-visible"); } if (!staticOrTopLevel) { violations.add("should be top-level or static inner class"); } return violations.isEmpty(); }
private OutputModel processOutput(Element outputElement) { OutputModel outputModel = new OutputModel(); if (elementTools.isField(outputElement)) { System.out.println("Processing element : " + elementTools.getFieldName(outputElement)); System.out.println( "Parent class name : " + elementTools.getParentElementClassName(outputElement)); outputModel.setParentClassName(elementTools.getParentElementClassName(outputElement)); outputModel.setFieldName(elementTools.getFieldName(outputElement)); List<? extends Element> presenterElements = outputElement.getEnclosingElement().getEnclosedElements(); for (Element element : presenterElements) { if (element.getKind() == ElementKind.METHOD) { System.out.println("Processing enclosing: " + element); processOnResult(outputModel, outputElement, element); processOnError(outputModel, outputElement, element); processOnCancel(outputModel, outputElement, element); } } } return outputModel; }
private void processAnnotation( final Element element, final HashMap<String, String> values, final Messager msg) { // Get the Option annotation on the member final Option option = element.getAnnotation(Option.class); // Get the class name of the option bean className = element.getEnclosingElement().toString(); // Check if the type in the member is a String. If not we ignore it // We are currently only supporting String type if (!element.asType().toString().equals(String.class.getName())) { msg.printMessage( Diagnostic.Kind.WARNING, element.asType() + " not supported. " + option.name() + " not processed"); return; } // Save the option switch and the member's name in a hash set // e.g. -filename (option switch) mapped to fileName (member) values.put(option.name(), element.getSimpleName().toString()); }
private void parseResourceString( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { boolean hasError = false; TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target type is String. if (!"java.lang.String".equals(element.asType().toString())) { error( element, "@%s field type must be 'String'. (%s.%s)", BindString.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName()); hasError = true; } // Verify common generated code restrictions. hasError |= isInaccessibleViaGeneratedCode(BindString.class, "fields", element); hasError |= isBindingInWrongPackage(BindString.class, element); if (hasError) { return; } // Assemble information on the field. String name = element.getSimpleName().toString(); int id = element.getAnnotation(BindString.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement); FieldResourceBinding binding = new FieldResourceBinding(id, name, "getString"); bindingClass.addResource(binding); erasedTargetNames.add(enclosingElement.toString()); }
private boolean isBindingInWrongPackage( Class<? extends Annotation> annotationClass, Element element) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); String qualifiedName = enclosingElement.getQualifiedName().toString(); if (qualifiedName.startsWith(ANDROID_PREFIX)) { error( element, "@%s-annotated class incorrectly in Android framework package. (%s)", annotationClass.getSimpleName(), qualifiedName); return true; } if (qualifiedName.startsWith(JAVA_PREFIX)) { error( element, "@%s-annotated class incorrectly in Java framework package. (%s)", annotationClass.getSimpleName(), qualifiedName); return true; } return false; }