/** */ private List<VariableTree> generateParamVariables( WorkingCopy workingCopy, ExecutableType srcMethod, String[] varNames) { TreeMaker maker = workingCopy.getTreeMaker(); List<? extends TypeMirror> params = srcMethod.getParameterTypes(); if ((params == null) || params.isEmpty()) { return Collections.<VariableTree>emptyList(); } Set<Modifier> noModifiers = Collections.<Modifier>emptySet(); List<VariableTree> paramVariables = new ArrayList<VariableTree>(params.size()); int index = 0; for (TypeMirror param : params) { if (param.getKind() == TypeKind.TYPEVAR){ param = getSuperType(workingCopy, param); } paramVariables.add( maker.Variable(maker.Modifiers(noModifiers), varNames[index++], maker.Type(param), getDefaultValue(maker, param))); } return paramVariables; }
private boolean isHidden(Element member, List<? extends Element> members, Elements elements, Types types) { for (ListIterator<? extends Element> it = members.listIterator(); it.hasNext();) { Element hider = it.next(); if (hider == member) return true; if (hider.getSimpleName().contentEquals(member.getSimpleName())) { if (elements.hides(member, hider)) { it.remove(); } else { if (member instanceof VariableElement && hider instanceof VariableElement && (!member.getKind().isField() || hider.getKind().isField())) return true; TypeMirror memberType = member.asType(); TypeMirror hiderType = hider.asType(); if (memberType.getKind() == TypeKind.EXECUTABLE && hiderType.getKind() == TypeKind.EXECUTABLE) { if (types.isSubsignature((ExecutableType)hiderType, (ExecutableType)memberType)) return true; } else { return false; } } } } return false; }
@Override public List<? extends TypeMirror> visitNewClass(NewClassTree node, Object p) { TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath()); if (tm == null || tm.getKind() != TypeKind.DECLARED) { return null; } Element el = info.getTrees().getElement(getCurrentPath()); if (el == null) { return null; } if (theExpression.getLeaf() != node.getEnclosingExpression()) { ExecutableType execType = (ExecutableType)info.getTypes().asMemberOf((DeclaredType)tm, el); return visitMethodOrNew(node, p, node.getArguments(), execType); } else { DeclaredType dt = (DeclaredType)tm; if (dt.getEnclosingType() == null) { return null; } return Collections.singletonList(dt.getEnclosingType()); } }
private ExecutableElement findExecutableMember(TypeElement clazz, String methodName, List<TypeMirror> paramTypes, Types types) { List<ExecutableElement> members = methodName.contentEquals(clazz.getSimpleName()) ? ElementFilter.constructorsIn(clazz.getEnclosedElements()) : ElementFilter.methodsIn(clazz.getEnclosedElements()); outer: for (ExecutableElement ee : members) { if (ee.getKind() == ElementKind.CONSTRUCTOR || methodName.contentEquals(ee.getSimpleName())) { List<? extends TypeMirror> memberParamTypes = ((ExecutableType) ee.asType()).getParameterTypes(); if (memberParamTypes.size() == paramTypes.size()) { Iterator<TypeMirror> it = paramTypes.iterator(); for (TypeMirror memberParamType : memberParamTypes) { TypeMirror type = it.next(); if (types.isSameType(type, memberParamType)) { continue outer; } } return ee; } } } return null; }
private static void enumerateMethods( @Nonnull final TypeElement scope, @Nonnull final Types typeUtils, @Nonnull final TypeElement element, @Nonnull final Map<String, ExecutableElement> methods ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { enumerateMethods( scope, typeUtils, (TypeElement) ( (DeclaredType) superclass ).asElement(), methods ); } for ( final TypeMirror interfaceType : element.getInterfaces() ) { final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement(); enumerateMethods( scope, typeUtils, interfaceElement, methods ); } for ( final Element member : element.getEnclosedElements() ) { if ( member.getKind() == ElementKind.METHOD ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) scope.asType(), member ); methods.put( member.getSimpleName() + methodType.toString(), (ExecutableElement) member ); } } }
private void addAutorun( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotReturnAnyValue( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); final String name = deriveAutorunName( method, annotation ); checkNameUnique( name, method, Constants.AUTORUN_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final AutorunDescriptor autorun = new AutorunDescriptor( this, name, mutation, method, methodType ); _autoruns.put( autorun.getName(), autorun ); }
private void determineLifecycleMethods( @Nonnull final TypeElement typeElement, @Nonnull final ComponentDescriptor descriptor ) { /* * Get the list of lifecycle methods that have been overridden by typeElement * a parent class, or by a default method method implemented by typeElement or * a parent class. */ final Collection<ExecutableElement> lifecycleMethods = getComponentLifecycleMethods().values(); final Elements elementUtils = processingEnv.getElementUtils(); final Types typeUtils = processingEnv.getTypeUtils(); final TypeElement componentType = elementUtils.getTypeElement( Constants.COMPONENT_CLASSNAME ); final List<MethodDescriptor> overriddenLifecycleMethods = // Get all methods on type parent classes, and default methods from interfaces ProcessorUtil.getMethods( typeElement, processingEnv.getTypeUtils() ).stream() // Only keep methods that override the lifecycle methods .filter( m -> lifecycleMethods.stream().anyMatch( l -> elementUtils.overrides( m, l, typeElement ) ) ) //Remove those that come from the base classes .filter( m -> m.getEnclosingElement() != componentType ) .map( m -> new MethodDescriptor( m, (ExecutableType) typeUtils.asMemberOf( descriptor.getDeclaredType(), m ) ) ) .collect( Collectors.toList() ); descriptor.setLifecycleMethods( overriddenLifecycleMethods ); }
public ExposedMethod(Element element) { ExecutableType method = (ExecutableType) element.asType(); TypeElement declaringClass = (TypeElement) element.getEnclosingElement(); this.name = element.getSimpleName().toString(); this.originalMethod = declaringClass.getQualifiedName().toString() + "." + element.getSimpleName(); this.returnType = method.getReturnType().toString(); this.params = new ArrayList<>(); int count = 0; for (TypeMirror param : method.getParameterTypes()) { this.params.add(param.toString()); String[] components = param.toString().toLowerCase().split("\\."); String paramName = components[components.length - 1]; if (paramName.endsWith(">")) { paramName = paramName.substring(0, paramName.length() - 1); } this.params.add(paramName + count); count++; } this.thrown = Stream.of(method.getThrownTypes()).map(new Function<TypeMirror, String>() { @Override public String apply(TypeMirror typeMirror) { return typeMirror.toString(); } }).toList(); }
@Override protected ExecutableElement doGet(ProcessingEnvironment env) { TypeElement typeElt = env.getElementUtils().getTypeElement(fqn.getName()); if (typeElt != null) { next: for (ExecutableElement executableElement : ElementFilter.methodsIn(typeElt.getEnclosedElements())) { if (executableElement.getSimpleName().toString().equals(name)) { List<? extends TypeMirror> parameterTypes = ((ExecutableType)executableElement.asType()).getParameterTypes(); int len = parameterTypes.size(); if (len == this.parameterTypes.size()) { for (int i = 0;i < len;i++) { if (!parameterTypes.get(i).toString().equals(this.parameterTypes.get(i))) { continue next; } } return executableElement; } } } } return null; }
private List<Pair<ExecutableElement, ExecutableType>> filterExecutableTypesByArguments(AnalyzeTask at, Iterable<Pair<ExecutableElement, ExecutableType>> candidateMethods, List<TypeMirror> precedingActualTypes) { List<Pair<ExecutableElement, ExecutableType>> candidate = new ArrayList<>(); int paramIndex = precedingActualTypes.size(); OUTER: for (Pair<ExecutableElement, ExecutableType> method : candidateMethods) { boolean varargInvocation = paramIndex >= method.snd.getParameterTypes().size(); for (int i = 0; i < paramIndex; i++) { TypeMirror actual = precedingActualTypes.get(i); if (this.parameterType(method.fst, method.snd, i, !varargInvocation) .noneMatch(formal -> at.getTypes().isAssignable(actual, formal))) { continue OUTER; } } candidate.add(method); } return candidate; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!ran) { ran = true; ExecutableElement m = getFirstMethodIn("C"); System.err.println("method: " + m); TypeMirror type = (DeclaredType)m.getParameters().get(0).asType(); System.err.println("parameters[0]: " + type); if (!isParameterized(type)) throw new AssertionError(type); type = ((ExecutableType)m.asType()).getParameterTypes().get(0); System.err.println("parameterTypes[0]: " + type); if (!isParameterized(type)) throw new AssertionError(type); System.err.println(); } return true; }
private static boolean equal(TypeMirror a, TypeMirror b, Set<ComparedElements> visiting) { // TypeMirror.equals is not guaranteed to return true for types that are equal, but we can // assume that if it does return true then the types are equal. This check also avoids getting // stuck in infinite recursion when Eclipse decrees that the upper bound of the second K in // <K extends Comparable<K>> is a distinct but equal K. // The javac implementation of ExecutableType, at least in some versions, does not take thrown // exceptions into account in its equals implementation, so avoid this optimization for // ExecutableType. if (Objects.equal(a, b) && !(a instanceof ExecutableType)) { return true; } EqualVisitorParam p = new EqualVisitorParam(); p.type = b; p.visiting = visiting; if (INTERSECTION_TYPE != null) { if (isIntersectionType(a)) { return equalIntersectionTypes(a, b, visiting); } else if (isIntersectionType(b)) { return false; } } return (a == b) || (a != null && b != null && a.accept(EQUAL_VISITOR, p)); }
/** * 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); } }
void setRefMethod( @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeSubclassCallable( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); if ( null != _refMethod ) { throw new ArezProcessorException( "@ComputedValueRef target duplicates existing method named " + _refMethod.getSimpleName(), method ); } else { _refMethod = Objects.requireNonNull( method ); _refMethodType = Objects.requireNonNull( methodType ); } }
void setTrackedMethod( final boolean mutation, final boolean reportParameters, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType trackedMethodType ) { MethodChecks.mustBeOverridable( Constants.TRACK_ANNOTATION_CLASSNAME, method ); if ( null != _trackedMethod ) { throw new ArezProcessorException( "@Track target duplicates existing method named " + _trackedMethod.getSimpleName(), method ); } else { _mutation = mutation; _reportParameters = reportParameters; _trackedMethod = Objects.requireNonNull( method ); _trackedMethodType = Objects.requireNonNull( trackedMethodType ); } }
static TypeMirror asInheritedMemberReturnType( ProcessingEnvironment processing, TypeElement typeElement, ExecutableElement method) { ExecutableType asMethodOfType = (ExecutableType) processing.getTypeUtils() .asMemberOf((DeclaredType) typeElement.asType(), method); return asMethodOfType.getReturnType(); }
/** * Find the type of the method descriptor associated to the functional interface. * * @param origin functional interface type * @return associated method descriptor type or <code>null</code> if the <code>origin</code> is not a functional interface. * @since 0.112 */ public ExecutableType getDescriptorType(DeclaredType origin) { Types types = Types.instance(info.impl.getJavacTask().getContext()); if (types.isFunctionalInterface(((Type)origin).tsym)) { Type dt = types.findDescriptorType((Type)origin); if (dt != null && dt.getKind() == TypeKind.EXECUTABLE) { return (ExecutableType)dt; } } return null; }
private void addComputedValueRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = methodType.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !toRawType( returnType ).toString().equals( "arez.ComputedValue" ) ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef must return an instance of " + "arez.ComputedValue", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, COMPUTED_VALUE_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef should specify name or be " + "named according to the convention get[Name]ComputedValue", method ); } } else { name = declaredName; if ( !ProcessorUtil.isJavaIdentifier( name ) ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef specified invalid name " + name, method ); } } findOrCreateComputed( name ).setRefMethod( method, methodType ); }
/** */ private List<VariableTree> generateParamVariables( WorkingCopy workingCopy, ExecutableType srcMethod, String[] varNames) { TreeMaker maker = workingCopy.getTreeMaker(); List<? extends TypeMirror> params = srcMethod.getParameterTypes(); if ((params == null) || params.isEmpty()) { return Collections.<VariableTree>emptyList(); } Set<Modifier> noModifiers = Collections.<Modifier>emptySet(); List<VariableTree> paramVariables = new ArrayList<VariableTree>(params.size()); int index = 0; for (TypeMirror param : params) { if (param.getKind() == TypeKind.TYPEVAR){ param = getSuperType(workingCopy, param); } if (param.getKind() == TypeKind.DECLARED) { boolean typeVar = containsTypeVar((DeclaredType) param, false); if (typeVar) { return null; } } param = getTypeMirror(workingCopy, param); paramVariables.add( maker.Variable(maker.Modifiers(noModifiers), varNames[index++], maker.Type(param), getDefaultValue(maker, param))); } return paramVariables; }
/** * * @param info context {@link CompilationInfo} * @param iterable tested {@link TreePath} * @return generic type of an {@link Iterable} or {@link ArrayType} at a TreePath */ public static TypeMirror getIterableGenericType(CompilationInfo info, TreePath iterable) { TypeElement iterableElement = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N if (iterableElement == null) { return null; } TypeMirror iterableType = info.getTrees().getTypeMirror(iterable); if (iterableType == null) { return null; } TypeMirror designedType = null; if (iterableType.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) iterableType; if (!info.getTypes().isSubtype(info.getTypes().erasure(declaredType), info.getTypes().erasure(iterableElement.asType()))) { return null; } ExecutableElement iteratorMethod = (ExecutableElement) iterableElement.getEnclosedElements().get(0); ExecutableType iteratorMethodType = (ExecutableType) info.getTypes().asMemberOf(declaredType, iteratorMethod); List<? extends TypeMirror> typeArguments = ((DeclaredType) iteratorMethodType.getReturnType()).getTypeArguments(); if (!typeArguments.isEmpty()) { designedType = typeArguments.get(0); } else { TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object"); if (jlObject != null) { designedType = jlObject.asType(); } } } else if (iterableType.getKind() == TypeKind.ARRAY) { designedType = ((ArrayType) iterableType).getComponentType(); } if (designedType == null) { return null; } return JavaPluginUtils.resolveCapturedType(info, designedType); }
private static List<? extends TypeMirror> computeAssignment(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { AssignmentTree at = (AssignmentTree) parent.getLeaf(); TypeMirror type = null; if (at.getVariable() == error) { type = info.getTrees().getTypeMirror(new TreePath(parent, at.getExpression())); if (type != null) { //anonymous class? type = JavaPluginUtils.convertIfAnonymous(type); if (type.getKind() == TypeKind.EXECUTABLE) { //TODO: does not actualy work, attempt to solve situations like: //t = Collections.emptyList() //t = Collections.<String>emptyList(); //see also testCreateFieldMethod1 and testCreateFieldMethod2 tests: type = ((ExecutableType) type).getReturnType(); } } } if (at.getExpression() == error) { type = info.getTrees().getTypeMirror(new TreePath(parent, at.getVariable())); } //class or field: if (type == null) { return null; } types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(type); }
private ExecutableType findMapGetMethod(DeclaredType inType) { TypeElement mapClass = compilationInfo.getElements().getTypeElement(MAP_CLASS); if (mapGetMethod == null) { for (ExecutableElement mm : ElementFilter.methodsIn(mapClass.getEnclosedElements())) { if (mm.getSimpleName().toString().equals("get")) { // NOI18N mapGetMethod = mm; } } } return (ExecutableType)compilationInfo.getTypes().asMemberOf(inType, mapGetMethod); }
/** * Build all constructors as they appear on the ArezComponent class. * Arez Observable fields are populated as required and parameters are passed up to superclass. */ private void buildConstructors( @Nonnull final TypeSpec.Builder builder, @Nonnull final Types typeUtils ) { final boolean requiresDeprecatedSuppress = hasDeprecatedElements(); for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( getElement() ) ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor ); builder.addMethod( buildConstructor( constructor, methodType, requiresDeprecatedSuppress ) ); } }
private void addMapProperty(ExecutableElement m, String propName) { FxProperty pi = new FxProperty(propName, FxDefinitionKind.MAP); pi.setSimple(false); pi.setAccessor(ElementHandle.create(m)); // must extract type arguments; assume there's a DeclaredType DeclaredType t = ((DeclaredType)m.getReturnType()); ExecutableType getterType = findMapGetMethod(t); pi.setType(TypeMirrorHandle.create(getterType.getReturnType())); pi.setObservableAccessors(pi.getAccessor()); registerProperty(pi); }
private void addListProperty(ExecutableElement m, String propName) { FxProperty pi = new FxProperty(propName, FxDefinitionKind.LIST); pi.setSimple(false); pi.setAccessor(ElementHandle.create(m)); // must extract type arguments; assume there's a DeclaredType DeclaredType t = ((DeclaredType)m.getReturnType()); ExecutableType getterType = findListGetMethod(t); pi.setType(TypeMirrorHandle.create(getterType.getReturnType())); pi.setObservableAccessors(pi.getAccessor()); registerProperty(pi); }
@Override public CI createParametersItem(CompilationInfo info, ExecutableElement elem, ExecutableType type, int substitutionOffset, boolean isDeprecated, int activeParamIndex, String name) { String simpleName = name != null ? name : elem.getKind() == ElementKind.CONSTRUCTOR ? elem.getEnclosingElement().getSimpleName().toString() : elem.getSimpleName().toString(); StringBuilder sb = new StringBuilder(); StringBuilder sortParams = new StringBuilder(); int cnt = 0; sb.append(info.getTypeUtilities().getTypeName(type.getReturnType())); sb.append(' '); sb.append(simpleName); sb.append('('); sortParams.append('('); Iterator<? extends VariableElement> it = elem.getParameters().iterator(); Iterator<? extends TypeMirror> tIt = type.getParameterTypes().iterator(); while(it.hasNext() && tIt.hasNext()) { TypeMirror tm = tIt.next(); if (tm == null) { break; } Set<TypeUtilities.TypeNameOptions> options = EnumSet.noneOf(TypeUtilities.TypeNameOptions.class); if (elem.isVarArgs() && !tIt.hasNext()) { options.add(TypeUtilities.TypeNameOptions.PRINT_AS_VARARG); } String typeName = info.getTypeUtilities().getTypeName(tm, options.toArray(new TypeUtilities.TypeNameOptions[0])).toString(); sb.append(typeName); sb.append(' '); sb.append(it.next().getSimpleName()); sortParams.append(typeName); if (it.hasNext()) { sb.append(", "); //NOI18N sortParams.append(','); } cnt++; } sb.append(") - parameters"); //NOI18N sortParams.append(')'); return new CI(sb.toString(), 100 - SMART_TYPE, "#" + ((cnt < 10 ? "0" : "") + cnt) + "#" + sortParams.toString()); }
/** * Checks whether an ambiguous overload exists. Javacs prior to JDK9 use imperfect * inference for type parameters, which causes more overloads to match the invocation, * therefore causing an error during compilation. If the diamond hint was applied * in such a case, the result would not be error-highlighted in editor, but would * fail to compile using JDK < 9. * <p/> * The check is very rough, so it should not be used to generate errors as older * javacs do. * <p/> * See defect #248162 */ private static boolean checkAmbiguousOverload(CompilationInfo info, TreePath newPath) { if (info.getSourceVersion().compareTo(SourceVersion.RELEASE_8) > 0) { return false; } Element el = info.getTrees().getElement(newPath); if (el == null || el.getKind() != ElementKind.CONSTRUCTOR) { return false; } ExecutableElement ctor = (ExecutableElement)el; DeclaredType resolvedType = (DeclaredType)info.getTrees().getTypeMirror(newPath); ExecutableType ctorType = (ExecutableType)info.getTypes().asMemberOf(resolvedType, el); for (ExecutableElement ee : ElementFilter.constructorsIn(el.getEnclosingElement().getEnclosedElements())) { if (ee == el) { continue; } if (ee.getParameters().size() != ctor.getParameters().size()) { continue; } TypeMirror t = info.getTypes().asMemberOf(resolvedType, ee); if (!Utilities.isValidType(t) || t.getKind() != TypeKind.EXECUTABLE) { continue; } ExecutableType et = (ExecutableType)t; for (int i = 0; i < ee.getParameters().size(); i++) { TypeMirror earg = et.getParameterTypes().get(i); TypeMirror carg = ctorType.getParameterTypes().get(i); if (!earg.getKind().isPrimitive() && !carg.getKind().isPrimitive()) { TypeMirror erasedC = info.getTypes().erasure(carg); TypeMirror erasedE = info.getTypes().erasure(earg); if (info.getTypes().isAssignable(erasedC, earg) && !info.getTypes().isSameType(erasedC, erasedE)) { // invalid hint here! return true; } } } } return false; }
AutorunDescriptor( @Nonnull final ComponentDescriptor componentDescriptor, @Nonnull final String name, final boolean mutation, @Nonnull final ExecutableElement autorun, @Nonnull final ExecutableType autorunType ) { _componentDescriptor = Objects.requireNonNull( componentDescriptor ); _name = Objects.requireNonNull( name ); _mutation = mutation; _autorun = Objects.requireNonNull( autorun ); _autorunType = Objects.requireNonNull( autorunType ); }
private static List<? extends TypeMirror> computeMethodInvocation(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { MethodInvocationTree nat = (MethodInvocationTree) parent.getLeaf(); int realArgumentError = -1; int i = 0; for (Tree param : nat.getArguments()) { if (param == error) { realArgumentError = i; break; } i++; } if (realArgumentError != (-1)) { List<TypeMirror> proposedTypes = new ArrayList<TypeMirror>(); int[] proposedIndex = new int[1]; List<ExecutableElement> ee = org.netbeans.modules.editor.java.Utilities.fuzzyResolveMethodInvocation(info, parent, proposedTypes, proposedIndex); if (ee.isEmpty()) { //cannot be resolved TypeMirror executable = info.getTrees().getTypeMirror(new TreePath(parent, nat.getMethodSelect())); if (executable == null || executable.getKind() != TypeKind.EXECUTABLE) return null; ExecutableType et = (ExecutableType) executable; if (realArgumentError >= et.getParameterTypes().size()) { return null; } proposedTypes.add(et.getParameterTypes().get(realArgumentError)); } types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return proposedTypes; } return null; }
/** * * @param info context {@link CompilationInfo} * @param iterable tested {@link TreePath} * @return generic type of an {@link Iterable} or {@link ArrayType} at a TreePath */ public static TypeMirror getIterableGenericType(CompilationInfo info, TreePath iterable) { TypeElement iterableElement = info.getElements().getTypeElement("java.lang.Iterable"); //NOI18N if (iterableElement == null) { return null; } TypeMirror iterableType = info.getTrees().getTypeMirror(iterable); if (iterableType == null) { return null; } TypeMirror designedType = null; if (iterableType.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) iterableType; if (!info.getTypes().isSubtype(info.getTypes().erasure(declaredType), info.getTypes().erasure(iterableElement.asType()))) { return null; } ExecutableElement iteratorMethod = (ExecutableElement) iterableElement.getEnclosedElements().get(0); ExecutableType iteratorMethodType = (ExecutableType) info.getTypes().asMemberOf(declaredType, iteratorMethod); List<? extends TypeMirror> typeArguments = ((DeclaredType) iteratorMethodType.getReturnType()).getTypeArguments(); if (!typeArguments.isEmpty()) { designedType = typeArguments.get(0); } else { TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object"); if (jlObject != null) { designedType = jlObject.asType(); } } } else if (iterableType.getKind() == TypeKind.ARRAY) { designedType = ((ArrayType) iterableType).getComponentType(); } if (designedType == null) { return null; } return resolveTypeForDeclaration(info, designedType); }
@Override public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) { if (!TreeUtilities.CLASS_TREE_KINDS.contains(treePath.getLeaf().getKind())) return Collections.emptyList(); Element el = info.getTrees().getElement(treePath); if (el == null || !el.getKind().isClass()) return Collections.emptyList(); TypeElement clazz = (TypeElement) el; TypeMirror superType = clazz.getSuperclass(); if (superType.getKind() != TypeKind.DECLARED) return Collections.emptyList(); TypeElement superClazz = (TypeElement) info.getTypes().asElement(superType); DeclaredType targetType = (DeclaredType) clazz.asType(); Scope classScope = info.getTrees().getScope(treePath); List<Fix> result = new ArrayList<Fix>(); for (ExecutableElement constr : ElementFilter.constructorsIn(superClazz.getEnclosedElements())) { if (!info.getTrees().isAccessible(classScope, constr, (DeclaredType) superType)) continue; StringBuilder name = new StringBuilder(); name.append(clazz.getSimpleName()).append("("); ExecutableType target = (ExecutableType) info.getTypes().asMemberOf(targetType, constr); boolean firstParam = true; for (TypeMirror p : target.getParameterTypes()) { if (!firstParam) name.append(", "); firstParam = false; name.append(info.getTypeUtilities().getTypeName(p)); } name.append(")"); result.add(new FixImpl(info, treePath, constr, StringEscapeUtils.escapeHtml(name.toString())).toEditorFix()); } return result; }
@Override public List<? extends TypeMirror> visitMethodInvocation(MethodInvocationTree node, Object p) { TypeMirror execType = info.getTrees().getTypeMirror( new TreePath(getCurrentPath(), node.getMethodSelect())); if (execType == null || execType.getKind() != TypeKind.EXECUTABLE) { return null; } return visitMethodOrNew(node, p, node.getArguments(), (ExecutableType)execType); }
public static CompletionItem createExecutableItem(CompilationInfo info, ExecutableElement e, ExecutableType et, int startOffset, boolean isInherited, boolean isDeprecated) { CompletionItem delegate = JavaCompletionItem.createExecutableItem( info, e, et, null, startOffset, null, isInherited, isDeprecated, false, false, false, -1, false, null); return new JavadocExecutableItem(delegate, e, startOffset); }
Void printExecutable(ExecutableElement e, DeclaredType dt, Boolean highlightName) { switch (e.getKind()) { case CONSTRUCTOR: modifier(e.getModifiers()); dumpTypeArguments(e.getTypeParameters()); result.append(' '); boldStartCheck(highlightName); result.append(e.getEnclosingElement().getSimpleName()); boldStopCheck(highlightName); TypeMirror memberType = null; if (dt != null) { dumpRealTypeArguments(dt.getTypeArguments()); try { memberType = info.getTypes().asMemberOf(dt, e); } catch (IllegalStateException ise) {} } if (memberType instanceof ExecutableType) { dumpArguments(e.getParameters(), ((ExecutableType) memberType).getParameterTypes()); } else { dumpArguments(e.getParameters(), null); } dumpThrows(e.getThrownTypes()); break; case METHOD: modifier(e.getModifiers()); dumpTypeArguments(e.getTypeParameters()); result.append(getTypeName(info, e.getReturnType(), true)); result.append(' '); boldStartCheck(highlightName); result.append(e.getSimpleName()); boldStopCheck(highlightName); dumpArguments(e.getParameters(), null); dumpThrows(e.getThrownTypes()); break; case INSTANCE_INIT: case STATIC_INIT: //these two cannot be referenced anyway... } return null; }
private Description findInfo(Element e) throws LayerGenerationException { Element type; switch (e.asType().getKind()) { case DECLARED: type = e; break; case EXECUTABLE: type = ((DeclaredType)((ExecutableType)e.asType()).getReturnType()).asElement(); break; default: throw new LayerGenerationException("" + e.asType().getKind(), e); } TopComponent.Description info = type.getAnnotation(TopComponent.Description.class); return info; }
private TypeMirror adjustTypeMirror(TypeMirror tm) { if (tm.getKind() == TypeKind.EXECUTABLE) { tm = ((ExecutableType) tm).getReturnType(); tm = adjustTypeMirror(tm); } else if (tm.getKind() == TypeKind.ARRAY) { tm = ((ArrayType) tm).getComponentType(); tm = adjustTypeMirror(tm); } return tm; }
private void determineDefaultPropsMethod( @Nonnull final ComponentDescriptor descriptor ) { final List<ExecutableElement> defaultPropsMethods = ProcessorUtil.getMethods( descriptor.getElement(), processingEnv.getTypeUtils() ).stream() .filter( m -> m.getSimpleName().toString().equals( "getInitialProps" ) ) .collect( Collectors.toList() ); if ( !defaultPropsMethods.isEmpty() ) { for ( final ExecutableElement method : defaultPropsMethods ) { final ExecutableType methodType = (ExecutableType) processingEnv.getTypeUtils().asMemberOf( descriptor.getDeclaredType(), method ); if ( methodType.getThrownTypes().isEmpty() && methodType.getParameterTypes().isEmpty() && method.getModifiers().contains( Modifier.STATIC ) && !method.getModifiers().contains( Modifier.PRIVATE ) && processingEnv.getTypeUtils() .isAssignable( methodType.getReturnType(), descriptor.getPropsType().asType() ) ) { descriptor.setDefaultPropsMethod( method ); return; } } throw new ReactProcessorException( "The getInitialProps method does not satisfy constraints. The method must " + "be static, non-private, have no parameters, throw no exceptions and must " + "return a value that is compatible with the prop type for the component.", descriptor.getElement() ); } }
private void determineRenderMethod( @Nonnull final TypeElement typeElement, @Nonnull final ComponentDescriptor descriptor ) { /* * Get the render method that has been overridden by the typeElement, a parent class, or by a default * method method implemented by the typeElement or a parent class. */ final ExecutableElement renderMethod = getComponentRenderMethod(); final Elements elementUtils = processingEnv.getElementUtils(); final Types typeUtils = processingEnv.getTypeUtils(); final TypeElement componentType = elementUtils.getTypeElement( Constants.COMPONENT_CLASSNAME ); final MethodDescriptor overriddenRenderMethod = // Get all methods on type parent classes, and default methods from interfaces ProcessorUtil.getMethods( typeElement, processingEnv.getTypeUtils() ).stream() // Only keep method if they override the render method .filter( m -> elementUtils.overrides( m, renderMethod, typeElement ) ) //Remove those that come from the base classes .filter( m -> m.getEnclosingElement() != componentType ) .map( m -> new MethodDescriptor( m, (ExecutableType) typeUtils.asMemberOf( descriptor.getDeclaredType(), m ) ) ) .findAny(). orElse( null ); if ( null == overriddenRenderMethod ) { throw new ReactProcessorException( "The react component does not override any render methods.", typeElement ); } else { descriptor.setRenderMethod( overriddenRenderMethod ); } }
EventHandlerDescriptor( @Nonnull final String name, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType, @Nonnull final TypeElement eventHandlerType, @Nonnull final ExecutableElement eventHandlerMethod ) { _name = Objects.requireNonNull( name ); _method = Objects.requireNonNull( method ); _methodType = Objects.requireNonNull( methodType ); _eventHandlerType = Objects.requireNonNull( eventHandlerType ); _eventHandlerMethod = Objects.requireNonNull( eventHandlerMethod ); }
public TypeMirror getType(Element element) throws WitchException { if (element.getKind().isField()) { return element.asType(); } else if (element.getKind() == ElementKind.METHOD) { ExecutableType ext = (ExecutableType) element.asType(); return ext.getReturnType(); } return null; }