Search in sources :

Example 41 with Types

use of javax.lang.model.util.Types in project checker-framework by typetools.

the class DefaultTypeArgumentInference method addConstraintsBetweenTargets.

/**
 * Declarations of the form: {@code <A, B extends A>} implies a TUConstraint of {@code B <: A}.
 * Add these to the constraint list.
 */
public void addConstraintsBetweenTargets(Set<TUConstraint> constraints, Set<TypeVariable> targets, boolean asSubtype, AnnotatedTypeFactory typeFactory) {
    final Types types = typeFactory.getProcessingEnv().getTypeUtils();
    final List<TypeVariable> targetList = new ArrayList<>(targets);
    final Map<TypeVariable, AnnotatedTypeVariable> paramDeclarations = new HashMap<>();
    for (int i = 0; i < targetList.size(); i++) {
        final TypeVariable earlierTarget = targetList.get(i);
        for (int j = i + 1; j < targetList.size(); j++) {
            final TypeVariable laterTarget = targetList.get(j);
            if (types.isSameType(earlierTarget.getUpperBound(), laterTarget)) {
                final AnnotatedTypeVariable headDecl = addOrGetDeclarations(earlierTarget, typeFactory, paramDeclarations);
                final AnnotatedTypeVariable nextDecl = addOrGetDeclarations(laterTarget, typeFactory, paramDeclarations);
                if (asSubtype) {
                    constraints.add(new TSubU(headDecl, nextDecl));
                } else {
                    constraints.add(new TSuperU(nextDecl, headDecl));
                }
            } else if (types.isSameType(laterTarget.getUpperBound(), earlierTarget)) {
                final AnnotatedTypeVariable headDecl = addOrGetDeclarations(earlierTarget, typeFactory, paramDeclarations);
                final AnnotatedTypeVariable nextDecl = addOrGetDeclarations(laterTarget, typeFactory, paramDeclarations);
                if (asSubtype) {
                    constraints.add(new TSubU(nextDecl, headDecl));
                } else {
                    constraints.add(new TSuperU(headDecl, nextDecl));
                }
            }
        }
    }
}
Also used : Types(javax.lang.model.util.Types) AnnotatedTypes(org.checkerframework.framework.util.AnnotatedTypes) TypeVariable(javax.lang.model.type.TypeVariable) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) TSuperU(org.checkerframework.framework.util.typeinference.constraint.TSuperU) AnnotatedTypeVariable(org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable) AFConstraint(org.checkerframework.framework.util.typeinference.constraint.AFConstraint) TUConstraint(org.checkerframework.framework.util.typeinference.constraint.TUConstraint) TSubU(org.checkerframework.framework.util.typeinference.constraint.TSubU)

Example 42 with Types

use of javax.lang.model.util.Types in project checker-framework by typetools.

the class SubtypesSolver method glbSubtypes.

public InferenceResult glbSubtypes(final Set<TypeVariable> remainingTargets, final ConstraintMap constraints, final AnnotatedTypeFactory typeFactory) {
    final InferenceResult inferenceResult = new InferenceResult();
    final QualifierHierarchy qualifierHierarchy = typeFactory.getQualifierHierarchy();
    final Types types = typeFactory.getProcessingEnv().getTypeUtils();
    List<TypeVariable> targetsSubtypesLast = new ArrayList<>(remainingTargets);
    // If we have two type variables <A, A extends B> order them A then B
    // this is required because we will use the fact that B must be below A
    // when determining the glb of B
    Collections.sort(targetsSubtypesLast, new Comparator<TypeVariable>() {

        @Override
        public int compare(TypeVariable o1, TypeVariable o2) {
            if (types.isSubtype(o1, o2)) {
                return 1;
            } else if (types.isSubtype(o2, o1)) {
                return -1;
            }
            return 0;
        }
    });
    for (final TypeVariable target : targetsSubtypesLast) {
        Subtypes subtypes = constraints.getConstraints(target).subtypes;
        if (subtypes.types.isEmpty()) {
            continue;
        }
        propagatePreviousGlbs(subtypes, inferenceResult, subtypes.types);
        // if the subtypes size is only 1 then we need not do any GLBing on the underlying types
        // but we may have primary annotations that need to be GLBed
        AnnotationMirrorMap<AnnotationMirrorSet> primaries = subtypes.primaries;
        if (subtypes.types.size() == 1) {
            final Map.Entry<AnnotatedTypeMirror, AnnotationMirrorSet> entry = subtypes.types.entrySet().iterator().next();
            AnnotatedTypeMirror supertype = entry.getKey().deepCopy();
            for (AnnotationMirror top : entry.getValue()) {
                final AnnotationMirrorSet superAnnos = primaries.get(top);
                // if it is null we're just going to use the anno already on supertype
                if (superAnnos != null) {
                    final AnnotationMirror supertypeAnno = supertype.getAnnotationInHierarchy(top);
                    superAnnos.add(supertypeAnno);
                }
            }
            if (!primaries.isEmpty()) {
                for (AnnotationMirror top : qualifierHierarchy.getTopAnnotations()) {
                    final AnnotationMirror glb = greatestLowerBound(subtypes.primaries.get(top), qualifierHierarchy);
                    supertype.replaceAnnotation(glb);
                }
            }
            inferenceResult.put(target, new InferredType(supertype));
        } else {
            // GLB all of the types than combine this with the GLB of primary annotation constraints
            final AnnotatedTypeMirror glbType = GlbUtil.glbAll(subtypes.types, typeFactory);
            if (glbType != null) {
                if (!primaries.isEmpty()) {
                    for (AnnotationMirror top : qualifierHierarchy.getTopAnnotations()) {
                        final AnnotationMirror glb = greatestLowerBound(subtypes.primaries.get(top), qualifierHierarchy);
                        final AnnotationMirror currentAnno = glbType.getAnnotationInHierarchy(top);
                        if (currentAnno == null) {
                            glbType.addAnnotation(glb);
                        } else if (glb != null) {
                            glbType.replaceAnnotation(qualifierHierarchy.greatestLowerBound(glb, currentAnno));
                        }
                    }
                }
                inferenceResult.put(target, new InferredType(glbType));
            }
        }
    }
    return inferenceResult;
}
Also used : Types(javax.lang.model.util.Types) InferredType(org.checkerframework.framework.util.typeinference.solver.InferredValue.InferredType) ArrayList(java.util.ArrayList) Subtypes(org.checkerframework.framework.util.typeinference.solver.TargetConstraints.Subtypes) AnnotatedTypeMirror(org.checkerframework.framework.type.AnnotatedTypeMirror) AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeVariable(javax.lang.model.type.TypeVariable) QualifierHierarchy(org.checkerframework.framework.type.QualifierHierarchy) AnnotationMirrorSet(org.checkerframework.framework.util.AnnotationMirrorSet) AnnotationMirrorMap(org.checkerframework.framework.util.AnnotationMirrorMap) Map(java.util.Map)

Example 43 with Types

use of javax.lang.model.util.Types in project checker-framework by typetools.

the class TypesIntoElements method store.

/**
 * The entry point.
 *
 * @param processingEnv the environment
 * @param atypeFactory the type factory
 * @param tree the ClassTree to process
 */
public static void store(ProcessingEnvironment processingEnv, AnnotatedTypeFactory atypeFactory, ClassTree tree) {
    Symbol.ClassSymbol csym = (Symbol.ClassSymbol) TreeUtils.elementFromDeclaration(tree);
    Types types = processingEnv.getTypeUtils();
    storeTypeParameters(processingEnv, types, atypeFactory, tree.getTypeParameters(), csym);
    for (Tree mem : tree.getMembers()) {
        if (mem.getKind() == Tree.Kind.METHOD) {
            storeMethod(processingEnv, types, atypeFactory, (MethodTree) mem);
        } else if (mem.getKind() == Tree.Kind.VARIABLE) {
            storeVariable(processingEnv, types, atypeFactory, (VariableTree) mem);
        } else {
        // System.out.println("Unhandled member tree: " + mem);
        }
    }
}
Also used : Types(javax.lang.model.util.Types) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) Symbol(com.sun.tools.javac.code.Symbol) VariableTree(com.sun.source.tree.VariableTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) TypeParameterTree(com.sun.source.tree.TypeParameterTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) JCTree(com.sun.tools.javac.tree.JCTree)

Example 44 with Types

use of javax.lang.model.util.Types in project kie-wb-common by kiegroup.

the class FormDefinitionGenerator method extracFormFields.

private List<FormDefinitionFieldData> extracFormFields(TypeElement type, FieldPolicy policy, I18nSettings i18nSettings, Map<String, String> defaultParams) throws Exception {
    final Types typeUtils = context.getProcessingEnvironment().getTypeUtils();
    Collection<FieldInfo> fieldInfos = FormGenerationUtils.extractFieldInfos(type, fieldElement -> filter(fieldElement, policy));
    List<FormDefinitionFieldData> fieldSettings = new ArrayList<>();
    for (FieldInfo fieldInfo : fieldInfos) {
        if (fieldInfo.getSetter() != null && fieldInfo.getGetter() != null) {
            String fieldName = fieldInfo.getFieldElement().getSimpleName().toString();
            FormDefinitionFieldData fieldData = new FormDefinitionFieldData(type.getQualifiedName().toString(), fieldName);
            fieldData.setLabel(fieldName);
            fieldData.setBinding(fieldName);
            fieldData.setMethodName("getFormElement_" + fieldName);
            boolean isList = false;
            org.kie.workbench.common.forms.model.TypeKind typeKind = org.kie.workbench.common.forms.model.TypeKind.BASE;
            boolean overrideI18n = false;
            TypeMirror finalType = fieldInfo.getFieldElement().asType();
            TypeElement finalTypeElement = (TypeElement) typeUtils.asElement(finalType);
            String fieldModifier = "";
            if (finalTypeElement.getKind().equals(ElementKind.CLASS)) {
                FieldDefinition fieldDefinitionAnnotation = finalTypeElement.getAnnotation(FieldDefinition.class);
                if (fieldDefinitionAnnotation != null) {
                    // Override the using the i18n mechanism
                    if (fieldDefinitionAnnotation.i18nMode().equals(I18nMode.OVERRIDE_I18N_KEY)) {
                        fieldData.setLabel(finalType.toString() + i18nSettings.separator() + fieldDefinitionAnnotation.labelKeySuffix());
                        Collection<FieldInfo> labelInfos = FormGenerationUtils.extractFieldInfos(finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null);
                        if (labelInfos != null && labelInfos.size() == 1) {
                            FieldInfo labelInfo = labelInfos.iterator().next();
                            fieldData.setLabel(finalType.toString() + i18nSettings.separator() + labelInfo.getFieldElement().getSimpleName());
                        }
                        fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + fieldDefinitionAnnotation.helpMessageKeySuffix());
                        Collection<FieldInfo> helpMessages = FormGenerationUtils.extractFieldInfos(finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldHelp.class) != null);
                        if (helpMessages != null && helpMessages.size() == 1) {
                            FieldInfo helpInfo = helpMessages.iterator().next();
                            fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + helpInfo.getFieldElement().getSimpleName());
                        }
                    }
                    Collection<FieldInfo> fieldValue = FormGenerationUtils.extractFieldInfos(finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldValue.class) != null);
                    if (fieldValue == null || fieldValue.size() != 1) {
                        throw new Exception("Problem processing FieldDefinition [" + finalType + "]: it should have one field marked as @FieldValue");
                    }
                    FieldInfo valueInfo = fieldValue.iterator().next();
                    fieldData.setBinding(fieldData.getBinding() + "." + valueInfo.getFieldElement().getSimpleName());
                    fieldModifier = FormGenerationUtils.fixClassName(finalType.toString()) + "_FieldStatusModifier";
                    finalType = valueInfo.getFieldElement().asType();
                    finalTypeElement = (TypeElement) typeUtils.asElement(finalType);
                    overrideI18n = !fieldDefinitionAnnotation.i18nMode().equals(I18nMode.DONT_OVERRIDE);
                } else {
                    FormDefinition formDefinitionAnnotation = finalTypeElement.getAnnotation(FormDefinition.class);
                    if (formDefinitionAnnotation != null) {
                        fieldData.setLabel(finalType.toString() + i18nSettings.separator() + FieldDefinition.LABEL);
                        Collection<FieldInfo> labelInfos = FormGenerationUtils.extractFieldInfos(finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null);
                        if (labelInfos != null && labelInfos.size() == 1) {
                            FieldInfo labelInfo = labelInfos.iterator().next();
                            fieldData.setLabel(finalType.toString() + i18nSettings.separator() + labelInfo.getFieldElement().getSimpleName());
                            overrideI18n = true;
                        }
                        fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + FieldDefinition.HELP_MESSAGE);
                        Collection<FieldInfo> helpMessages = FormGenerationUtils.extractFieldInfos(finalTypeElement, fieldElement -> fieldElement.getAnnotation(FieldHelp.class) != null);
                        if (helpMessages != null && helpMessages.size() == 1) {
                            FieldInfo helpInfo = helpMessages.iterator().next();
                            fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator() + helpInfo.getFieldElement().getSimpleName());
                            overrideI18n = true;
                        }
                        typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT;
                    }
                }
            }
            DeclaredType fieldType = (DeclaredType) finalType;
            if (typeUtils.isAssignable(finalTypeElement.asType(), listType)) {
                if (fieldType.getTypeArguments().size() != 1) {
                    throw new IllegalArgumentException("Impossible to generate a field for type " + fieldType.toString() + ". Type should have one and only one Type arguments.");
                }
                isList = true;
                finalType = fieldType.getTypeArguments().get(0);
                finalTypeElement = (TypeElement) typeUtils.asElement(finalType);
                if (FormModelPropertiesUtil.isBaseType(finalTypeElement.getQualifiedName().toString())) {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.BASE;
                } else if (typeUtils.isAssignable(finalTypeElement.asType(), enumType)) {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM;
                } else {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT;
                }
            } else if (typeUtils.isAssignable(finalTypeElement.asType(), enumType)) {
                typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM;
            }
            fieldData.setType(typeKind.toString());
            fieldData.setClassName(finalTypeElement.getQualifiedName().toString());
            fieldData.setList(String.valueOf(isList));
            fieldData.setFieldModifier(fieldModifier);
            fieldData.getParams().putAll(defaultParams);
            FormField settings = fieldInfo.getFieldElement().getAnnotation(FormField.class);
            if (settings != null) {
                try {
                    fieldData.setPreferredType(settings.type().getName());
                } catch (MirroredTypeException exception) {
                    fieldData.setPreferredType(exception.getTypeMirror().toString());
                }
                fieldData.setAfterElement(settings.afterElement());
                if (!overrideI18n && !isEmpty(settings.labelKey())) {
                    fieldData.setLabel(settings.labelKey());
                }
                if (!overrideI18n && !isEmpty(settings.helpMessageKey())) {
                    fieldData.setHelpMessage(settings.helpMessageKey());
                }
                fieldData.setRequired(Boolean.valueOf(settings.required()).toString());
                fieldData.setReadOnly(Boolean.valueOf(settings.readonly()).toString());
                for (FieldParam fieldParam : settings.settings()) {
                    fieldData.getParams().put(fieldParam.name(), fieldParam.value());
                }
                fieldData.setWrap(Boolean.valueOf(settings.layoutSettings().wrap()).toString());
                fieldData.setHorizontalSpan(String.valueOf(settings.layoutSettings().horizontalSpan()));
                fieldData.setVerticalSpan(String.valueOf(settings.layoutSettings().verticalSpan()));
            }
            if (!overrideI18n) {
                if (!isEmpty(i18nSettings.keyPreffix())) {
                    fieldData.setLabel(i18nSettings.keyPreffix() + i18nSettings.separator() + fieldData.getLabel());
                    if (!isEmpty(fieldData.getHelpMessage())) {
                        fieldData.setHelpMessage(i18nSettings.keyPreffix() + i18nSettings.separator() + fieldData.getHelpMessage());
                    }
                }
            }
            extractFieldExtraSettings(fieldData, fieldInfo.getFieldElement());
            fieldSettings.add(fieldData);
        }
    }
    return fieldSettings;
}
Also used : Types(javax.lang.model.util.Types) FieldParam(org.kie.workbench.common.forms.adf.definitions.annotations.FieldParam) TypeElement(javax.lang.model.element.TypeElement) FieldDefinition(org.kie.workbench.common.forms.adf.definitions.annotations.metaModel.FieldDefinition) ArrayList(java.util.ArrayList) MirroredTypeException(javax.lang.model.type.MirroredTypeException) MirroredTypeException(javax.lang.model.type.MirroredTypeException) TypeMirror(javax.lang.model.type.TypeMirror) FormDefinition(org.kie.workbench.common.forms.adf.definitions.annotations.FormDefinition) FormField(org.kie.workbench.common.forms.adf.definitions.annotations.FormField) SkipFormField(org.kie.workbench.common.forms.adf.definitions.annotations.SkipFormField) FieldInfo(org.kie.workbench.common.forms.adf.processors.util.FieldInfo) DeclaredType(javax.lang.model.type.DeclaredType)

Example 45 with Types

use of javax.lang.model.util.Types in project kie-wb-common by kiegroup.

the class GeneratorUtils method getAnnotatedMethods.

public static List<ExecutableElement> getAnnotatedMethods(final TypeElement originalClassElement, final ProcessingEnvironment processingEnvironment, final String annotationName, final TypeMirror requiredReturnType, final String[] requiredParameterTypes) {
    final Types typeUtils = processingEnvironment.getTypeUtils();
    final Elements elementUtils = processingEnvironment.getElementUtils();
    TypeElement classElement = originalClassElement;
    while (true) {
        final List<ExecutableElement> methods = ElementFilter.methodsIn(classElement.getEnclosedElements());
        List<ExecutableElement> matches = new ArrayList<ExecutableElement>();
        for (ExecutableElement e : methods) {
            final TypeMirror actualReturnType = e.getReturnType();
            if (getAnnotation(elementUtils, e, annotationName) == null) {
                continue;
            }
            List<String> problems = new ArrayList<String>();
            if (!typeUtils.isAssignable(actualReturnType, requiredReturnType)) {
                problems.add("return " + requiredReturnType);
            }
            if (!doParametersMatch(typeUtils, elementUtils, e, requiredParameterTypes)) {
                if (requiredParameterTypes.length == 0) {
                    problems.add("take no parameters");
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append("take ").append(requiredParameterTypes.length).append(" parameters of type (");
                    boolean first = true;
                    for (String p : requiredParameterTypes) {
                        if (!first) {
                            sb.append(", ");
                        }
                        sb.append(p);
                        first = false;
                    }
                    sb.append(")");
                    problems.add(sb.toString());
                }
            }
            if (e.getModifiers().contains(Modifier.STATIC)) {
                problems.add("be non-static");
            }
            if (e.getModifiers().contains(Modifier.PRIVATE)) {
                problems.add("be non-private");
            }
            if (problems.isEmpty()) {
                matches.add(e);
            } else {
                processingEnvironment.getMessager().printMessage(Diagnostic.Kind.ERROR, formatProblemsList(annotationName, problems), e);
            }
        }
        if (!matches.isEmpty()) {
            return matches;
        }
        TypeMirror superclass = classElement.getSuperclass();
        if (superclass instanceof DeclaredType) {
            classElement = (TypeElement) ((DeclaredType) superclass).asElement();
        } else {
            break;
        }
    }
    return Collections.emptyList();
}
Also used : Types(javax.lang.model.util.Types) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) Elements(javax.lang.model.util.Elements) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

Types (javax.lang.model.util.Types)113 TypeMirror (javax.lang.model.type.TypeMirror)77 TypeElement (javax.lang.model.element.TypeElement)52 Elements (javax.lang.model.util.Elements)48 ExecutableElement (javax.lang.model.element.ExecutableElement)34 Element (javax.lang.model.element.Element)30 SupportedAnnotationTypes (javax.annotation.processing.SupportedAnnotationTypes)27 DeclaredType (javax.lang.model.type.DeclaredType)26 ArrayList (java.util.ArrayList)25 Map (java.util.Map)24 VariableElement (javax.lang.model.element.VariableElement)24 List (java.util.List)21 AnnotationMirror (javax.lang.model.element.AnnotationMirror)20 TypeKind (javax.lang.model.type.TypeKind)18 Set (java.util.Set)16 Collection (java.util.Collection)15 HashMap (java.util.HashMap)13 ElementKind (javax.lang.model.element.ElementKind)13 Modifier (javax.lang.model.element.Modifier)13 IOException (java.io.IOException)12