Search in sources :

Example 1 with FieldDeclaration

use of org.eclipse.jdt.internal.compiler.ast.FieldDeclaration in project che by eclipse.

the class HandleFactory method createElement.

/**
	 * Create handle by adding child to parent obtained by recursing into parent scopes.
	 */
public IJavaElement createElement(Scope scope, int elementPosition, ICompilationUnit unit, HashSet existingElements, HashMap knownScopes) {
    IJavaElement newElement = (IJavaElement) knownScopes.get(scope);
    if (newElement != null)
        return newElement;
    switch(scope.kind) {
        case Scope.COMPILATION_UNIT_SCOPE:
            newElement = unit;
            break;
        case Scope.CLASS_SCOPE:
            IJavaElement parentElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
            switch(parentElement.getElementType()) {
                case IJavaElement.COMPILATION_UNIT:
                    newElement = ((ICompilationUnit) parentElement).getType(new String(scope.enclosingSourceType().sourceName));
                    break;
                case IJavaElement.TYPE:
                    newElement = ((IType) parentElement).getType(new String(scope.enclosingSourceType().sourceName));
                    break;
                case IJavaElement.FIELD:
                case IJavaElement.INITIALIZER:
                case IJavaElement.METHOD:
                    IMember member = (IMember) parentElement;
                    if (member.isBinary()) {
                        return null;
                    } else {
                        newElement = member.getType(new String(scope.enclosingSourceType().sourceName), 1);
                        // increment occurrence count if collision is detected
                        if (newElement != null) {
                            while (!existingElements.add(newElement)) ((SourceRefElement) newElement).occurrenceCount++;
                        }
                    }
                    break;
            }
            if (newElement != null) {
                knownScopes.put(scope, newElement);
            }
            break;
        case Scope.METHOD_SCOPE:
            if (scope.isLambdaScope()) {
                parentElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
                LambdaExpression expression = (LambdaExpression) scope.originalReferenceContext();
                if (expression.resolvedType != null && expression.resolvedType.isValidBinding() && !(expression.descriptor instanceof ProblemMethodBinding)) {
                    // chain in lambda element only if resolved properly.
                    //newElement = new org.eclipse.jdt.internal.core.SourceLambdaExpression((JavaElement) parentElement, expression).getMethod();
                    newElement = LambdaFactory.createLambdaExpression((JavaElement) parentElement, expression).getMethod();
                    knownScopes.put(scope, newElement);
                    return newElement;
                }
                return parentElement;
            }
            IType parentType = (IType) createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
            MethodScope methodScope = (MethodScope) scope;
            if (methodScope.isInsideInitializer()) {
                // inside field or initializer, must find proper one
                TypeDeclaration type = methodScope.referenceType();
                int occurenceCount = 1;
                int length = type.fields == null ? 0 : type.fields.length;
                for (int i = 0; i < length; i++) {
                    FieldDeclaration field = type.fields[i];
                    if (field.declarationSourceStart <= elementPosition && elementPosition <= field.declarationSourceEnd) {
                        switch(field.getKind()) {
                            case AbstractVariableDeclaration.FIELD:
                            case AbstractVariableDeclaration.ENUM_CONSTANT:
                                newElement = parentType.getField(new String(field.name));
                                break;
                            case AbstractVariableDeclaration.INITIALIZER:
                                newElement = parentType.getInitializer(occurenceCount);
                                break;
                        }
                        break;
                    } else if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
                        occurenceCount++;
                    }
                }
            } else {
                // method element
                AbstractMethodDeclaration method = methodScope.referenceMethod();
                newElement = parentType.getMethod(new String(method.selector), Util.typeParameterSignatures(method));
                if (newElement != null) {
                    knownScopes.put(scope, newElement);
                }
            }
            break;
        case Scope.BLOCK_SCOPE:
            // standard block, no element per se
            newElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
            break;
    }
    return newElement;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ProblemMethodBinding(org.eclipse.jdt.internal.compiler.lookup.ProblemMethodBinding) MethodScope(org.eclipse.jdt.internal.compiler.lookup.MethodScope) IMember(org.eclipse.jdt.core.IMember) LambdaExpression(org.eclipse.jdt.internal.compiler.ast.LambdaExpression) TypeDeclaration(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) AbstractMethodDeclaration(org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration) FieldDeclaration(org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) SourceRefElement(org.eclipse.jdt.internal.core.SourceRefElement) IType(org.eclipse.jdt.core.IType)

Example 2 with FieldDeclaration

use of org.eclipse.jdt.internal.compiler.ast.FieldDeclaration in project che by eclipse.

the class SourceTypeConverter method convert.

/*
	 * Convert a field source element into a parsed field declaration
	 */
private FieldDeclaration convert(SourceField fieldHandle, TypeDeclaration type, CompilationResult compilationResult) throws JavaModelException {
    SourceFieldElementInfo fieldInfo = (SourceFieldElementInfo) fieldHandle.getElementInfo();
    FieldDeclaration field = new FieldDeclaration();
    int start = fieldInfo.getNameSourceStart();
    int end = fieldInfo.getNameSourceEnd();
    field.name = fieldHandle.getElementName().toCharArray();
    field.sourceStart = start;
    field.sourceEnd = end;
    field.declarationSourceStart = fieldInfo.getDeclarationSourceStart();
    field.declarationSourceEnd = fieldInfo.getDeclarationSourceEnd();
    int modifiers = fieldInfo.getModifiers();
    boolean isEnumConstant = (modifiers & ClassFileConstants.AccEnum) != 0;
    if (isEnumConstant) {
        // clear AccEnum bit onto AST (binding will add it)
        field.modifiers = modifiers & ~ClassFileConstants.AccEnum;
    } else {
        field.modifiers = modifiers;
        field.type = createTypeReference(fieldInfo.getTypeName(), start, end);
    }
    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert annotations */
        field.annotations = convertAnnotations(fieldHandle);
    }
    /* conversion of field constant */
    if ((this.flags & FIELD_INITIALIZATION) != 0) {
        char[] initializationSource = fieldInfo.getInitializationSource();
        if (initializationSource != null) {
            if (this.parser == null) {
                this.parser = new Parser(this.problemReporter, true);
            }
            this.parser.parse(field, type, this.unit, initializationSource);
        }
    }
    /* conversion of local and anonymous types */
    if ((this.flags & LOCAL_TYPE) != 0) {
        IJavaElement[] children = fieldInfo.getChildren();
        int childrenLength = children.length;
        if (childrenLength == 1) {
            field.initialization = convert(children[0], isEnumConstant ? field : null, compilationResult);
        } else if (childrenLength > 1) {
            ArrayInitializer initializer = new ArrayInitializer();
            field.initialization = initializer;
            Expression[] expressions = new Expression[childrenLength];
            initializer.expressions = expressions;
            for (int i = 0; i < childrenLength; i++) {
                expressions[i] = convert(children[i], isEnumConstant ? field : null, compilationResult);
            }
        }
    }
    return field;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) SourceFieldElementInfo(org.eclipse.jdt.internal.core.SourceFieldElementInfo) FieldDeclaration(org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) Parser(org.eclipse.jdt.internal.compiler.parser.Parser) ArrayInitializer(org.eclipse.jdt.internal.compiler.ast.ArrayInitializer)

Example 3 with FieldDeclaration

use of org.eclipse.jdt.internal.compiler.ast.FieldDeclaration in project lombok by rzwitserloot.

the class PatchDelegate method fillMethodBindingsForFields.

private static void fillMethodBindingsForFields(CompilationUnitDeclaration cud, ClassScope scope, List<BindingTuple> methodsToDelegate) {
    TypeDeclaration decl = scope.referenceContext;
    if (decl == null)
        return;
    if (decl.fields != null)
        for (FieldDeclaration field : decl.fields) {
            if (field.annotations == null)
                continue;
            for (Annotation ann : field.annotations) {
                if (!isDelegate(ann, decl))
                    continue;
                if (Annotation_applied.getAndSet(ann, true))
                    continue;
                if ((field.modifiers & ClassFileConstants.AccStatic) != 0) {
                    EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true);
                    eclipseAst.get(ann).addError(LEGALITY_OF_DELEGATE);
                    break;
                }
                List<ClassLiteralAccess> rawTypes = rawTypes(ann, "types");
                List<ClassLiteralAccess> excludedRawTypes = rawTypes(ann, "excludes");
                List<BindingTuple> methodsToExclude = new ArrayList<BindingTuple>();
                List<BindingTuple> methodsToDelegateForThisAnn = new ArrayList<BindingTuple>();
                try {
                    for (ClassLiteralAccess cla : excludedRawTypes) {
                        addAllMethodBindings(methodsToExclude, cla.type.resolveType(decl.initializerScope), new HashSet<String>(), field.name, ann);
                    }
                    Set<String> banList = new HashSet<String>();
                    for (BindingTuple excluded : methodsToExclude) banList.add(printSig(excluded.parameterized));
                    if (rawTypes.isEmpty()) {
                        addAllMethodBindings(methodsToDelegateForThisAnn, field.type.resolveType(decl.initializerScope), banList, field.name, ann);
                    } else {
                        for (ClassLiteralAccess cla : rawTypes) {
                            addAllMethodBindings(methodsToDelegateForThisAnn, cla.type.resolveType(decl.initializerScope), banList, field.name, ann);
                        }
                    }
                } catch (DelegateRecursion e) {
                    EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true);
                    eclipseAst.get(ann).addError(String.format(RECURSION_NOT_ALLOWED, new String(e.member), new String(e.type)));
                    break;
                }
                // Not doing this right now because of problems - see commented-out-method for info.
                // removeExistingMethods(methodsToDelegate, decl, scope);
                String dupe = containsDuplicates(methodsToDelegateForThisAnn);
                if (dupe != null) {
                    EclipseAST eclipseAst = TransformEclipseAST.getAST(cud, true);
                    eclipseAst.get(ann).addError("The method '" + dupe + "' is being delegated by more than one specified type.");
                } else {
                    methodsToDelegate.addAll(methodsToDelegateForThisAnn);
                }
            }
        }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) EclipseAST(lombok.eclipse.EclipseAST) TransformEclipseAST(lombok.eclipse.TransformEclipseAST) FieldDeclaration(org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) Annotation(org.eclipse.jdt.internal.compiler.ast.Annotation) List(java.util.List) ArrayList(java.util.ArrayList) TypeDeclaration(org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) ClassLiteralAccess(org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess) HashSet(java.util.HashSet)

Example 4 with FieldDeclaration

use of org.eclipse.jdt.internal.compiler.ast.FieldDeclaration in project lombok by rzwitserloot.

the class HandleSetter method createSetter.

static MethodDeclaration createSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, boolean shouldReturnThis, int modifier, EclipseNode sourceNode, List<Annotation> onMethod, List<Annotation> onParam) {
    FieldDeclaration field = (FieldDeclaration) fieldNode.get();
    ASTNode source = sourceNode.get();
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;
    MethodDeclaration method = new MethodDeclaration(parent.compilationResult);
    method.modifiers = modifier;
    if (shouldReturnThis) {
        method.returnType = cloneSelfType(fieldNode, source);
    }
    if (method.returnType == null) {
        method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
        method.returnType.sourceStart = pS;
        method.returnType.sourceEnd = pE;
        shouldReturnThis = false;
    }
    Annotation[] deprecated = null;
    if (isFieldDeprecated(fieldNode)) {
        deprecated = new Annotation[] { generateDeprecatedAnnotation(source) };
    }
    method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated);
    Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL);
    param.sourceStart = pS;
    param.sourceEnd = pE;
    method.arguments = new Argument[] { param };
    method.selector = name.toCharArray();
    method.binding = null;
    method.thrownExceptions = null;
    method.typeParameters = null;
    method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
    NameReference fieldNameRef = new SingleNameReference(field.name, p);
    Assignment assignment = new Assignment(fieldRef, fieldNameRef, (int) p);
    assignment.sourceStart = pS;
    assignment.sourceEnd = assignment.statementEnd = pE;
    method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
    method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
    Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN);
    Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN);
    List<Statement> statements = new ArrayList<Statement>(5);
    if (nonNulls.length == 0) {
        statements.add(assignment);
    } else {
        Statement nullCheck = generateNullCheck(field, sourceNode);
        if (nullCheck != null)
            statements.add(nullCheck);
        statements.add(assignment);
    }
    if (shouldReturnThis) {
        ThisReference thisRef = new ThisReference(pS, pE);
        ReturnStatement returnThis = new ReturnStatement(thisRef, pS, pE);
        statements.add(returnThis);
    }
    method.statements = statements.toArray(new Statement[0]);
    param.annotations = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0]));
    method.traverse(new SetGeneratedByVisitor(source), parent.scope);
    return method;
}
Also used : NameReference(org.eclipse.jdt.internal.compiler.ast.NameReference) SingleNameReference(org.eclipse.jdt.internal.compiler.ast.SingleNameReference) Argument(org.eclipse.jdt.internal.compiler.ast.Argument) MethodDeclaration(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration) ReturnStatement(org.eclipse.jdt.internal.compiler.ast.ReturnStatement) Statement(org.eclipse.jdt.internal.compiler.ast.Statement) ArrayList(java.util.ArrayList) ThisReference(org.eclipse.jdt.internal.compiler.ast.ThisReference) SingleNameReference(org.eclipse.jdt.internal.compiler.ast.SingleNameReference) FieldDeclaration(org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) Annotation(org.eclipse.jdt.internal.compiler.ast.Annotation) Assignment(org.eclipse.jdt.internal.compiler.ast.Assignment) Expression(org.eclipse.jdt.internal.compiler.ast.Expression) ASTNode(org.eclipse.jdt.internal.compiler.ast.ASTNode) ReturnStatement(org.eclipse.jdt.internal.compiler.ast.ReturnStatement)

Example 5 with FieldDeclaration

use of org.eclipse.jdt.internal.compiler.ast.FieldDeclaration in project lombok by rzwitserloot.

the class HandleToString method createToString.

public static MethodDeclaration createToString(EclipseNode type, Collection<EclipseNode> fields, boolean includeFieldNames, boolean callSuper, ASTNode source, FieldAccess fieldAccess) {
    String typeName = getTypeName(type);
    char[] suffix = ")".toCharArray();
    String infixS = ", ";
    char[] infix = infixS.toCharArray();
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;
    final int PLUS = OperatorIds.PLUS;
    char[] prefix;
    if (callSuper) {
        prefix = (typeName + "(super=").toCharArray();
    } else if (fields.isEmpty()) {
        prefix = (typeName + "()").toCharArray();
    } else if (includeFieldNames) {
        prefix = (typeName + "(" + new String(((FieldDeclaration) fields.iterator().next().get()).name) + "=").toCharArray();
    } else {
        prefix = (typeName + "(").toCharArray();
    }
    boolean first = true;
    Expression current = new StringLiteral(prefix, pS, pE, 0);
    setGeneratedBy(current, source);
    if (callSuper) {
        MessageSend callToSuper = new MessageSend();
        callToSuper.sourceStart = pS;
        callToSuper.sourceEnd = pE;
        setGeneratedBy(callToSuper, source);
        callToSuper.receiver = new SuperReference(pS, pE);
        setGeneratedBy(callToSuper, source);
        callToSuper.selector = "toString".toCharArray();
        current = new BinaryExpression(current, callToSuper, PLUS);
        setGeneratedBy(current, source);
        first = false;
    }
    for (EclipseNode field : fields) {
        TypeReference fieldType = getFieldType(field, fieldAccess);
        Expression fieldAccessor = createFieldAccessor(field, fieldAccess, source);
        // The distinction between primitive and object will be useful if we ever add a 'hideNulls' option.
        boolean fieldBaseTypeIsPrimitive = BUILT_IN_TYPES.contains(new String(fieldType.getLastToken()));
        boolean fieldIsPrimitive = fieldType.dimensions() == 0 && fieldBaseTypeIsPrimitive;
        boolean fieldIsPrimitiveArray = fieldType.dimensions() == 1 && fieldBaseTypeIsPrimitive;
        boolean fieldIsObjectArray = fieldType.dimensions() > 0 && !fieldIsPrimitiveArray;
        @SuppressWarnings("unused") boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray;
        Expression ex;
        if (fieldIsPrimitiveArray || fieldIsObjectArray) {
            MessageSend arrayToString = new MessageSend();
            arrayToString.sourceStart = pS;
            arrayToString.sourceEnd = pE;
            arrayToString.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray());
            arrayToString.arguments = new Expression[] { fieldAccessor };
            setGeneratedBy(arrayToString.arguments[0], source);
            arrayToString.selector = (fieldIsObjectArray ? "deepToString" : "toString").toCharArray();
            ex = arrayToString;
        } else {
            ex = fieldAccessor;
        }
        setGeneratedBy(ex, source);
        if (first) {
            current = new BinaryExpression(current, ex, PLUS);
            current.sourceStart = pS;
            current.sourceEnd = pE;
            setGeneratedBy(current, source);
            first = false;
            continue;
        }
        StringLiteral fieldNameLiteral;
        if (includeFieldNames) {
            char[] namePlusEqualsSign = (infixS + field.getName() + "=").toCharArray();
            fieldNameLiteral = new StringLiteral(namePlusEqualsSign, pS, pE, 0);
        } else {
            fieldNameLiteral = new StringLiteral(infix, pS, pE, 0);
        }
        setGeneratedBy(fieldNameLiteral, source);
        current = new BinaryExpression(current, fieldNameLiteral, PLUS);
        setGeneratedBy(current, source);
        current = new BinaryExpression(current, ex, PLUS);
        setGeneratedBy(current, source);
    }
    if (!first) {
        StringLiteral suffixLiteral = new StringLiteral(suffix, pS, pE, 0);
        setGeneratedBy(suffixLiteral, source);
        current = new BinaryExpression(current, suffixLiteral, PLUS);
        setGeneratedBy(current, source);
    }
    ReturnStatement returnStatement = new ReturnStatement(current, pS, pE);
    setGeneratedBy(returnStatement, source);
    MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
    setGeneratedBy(method, source);
    method.modifiers = toEclipseModifier(AccessLevel.PUBLIC);
    method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] { p, p, p });
    setGeneratedBy(method.returnType, source);
    method.annotations = new Annotation[] { makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source) };
    method.arguments = null;
    method.selector = "toString".toCharArray();
    method.thrownExceptions = null;
    method.typeParameters = null;
    method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
    method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
    method.statements = new Statement[] { returnStatement };
    return method;
}
Also used : MethodDeclaration(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration) ToString(lombok.ToString) FieldDeclaration(org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) SuperReference(org.eclipse.jdt.internal.compiler.ast.SuperReference) MessageSend(org.eclipse.jdt.internal.compiler.ast.MessageSend) StringLiteral(org.eclipse.jdt.internal.compiler.ast.StringLiteral) BinaryExpression(org.eclipse.jdt.internal.compiler.ast.BinaryExpression) Expression(org.eclipse.jdt.internal.compiler.ast.Expression) BinaryExpression(org.eclipse.jdt.internal.compiler.ast.BinaryExpression) QualifiedTypeReference(org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) ReturnStatement(org.eclipse.jdt.internal.compiler.ast.ReturnStatement) EclipseNode(lombok.eclipse.EclipseNode) TypeReference(org.eclipse.jdt.internal.compiler.ast.TypeReference) QualifiedTypeReference(org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference)

Aggregations

FieldDeclaration (org.eclipse.jdt.internal.compiler.ast.FieldDeclaration)40 EclipseNode (lombok.eclipse.EclipseNode)21 MethodDeclaration (org.eclipse.jdt.internal.compiler.ast.MethodDeclaration)17 TypeDeclaration (org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)17 ArrayList (java.util.ArrayList)15 TypeReference (org.eclipse.jdt.internal.compiler.ast.TypeReference)11 Expression (org.eclipse.jdt.internal.compiler.ast.Expression)10 QualifiedTypeReference (org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference)10 ReturnStatement (org.eclipse.jdt.internal.compiler.ast.ReturnStatement)10 AbstractMethodDeclaration (org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration)7 Annotation (org.eclipse.jdt.internal.compiler.ast.Annotation)7 SingleNameReference (org.eclipse.jdt.internal.compiler.ast.SingleNameReference)7 Statement (org.eclipse.jdt.internal.compiler.ast.Statement)7 ASTNode (org.eclipse.jdt.internal.compiler.ast.ASTNode)6 AllocationExpression (org.eclipse.jdt.internal.compiler.ast.AllocationExpression)6 Argument (org.eclipse.jdt.internal.compiler.ast.Argument)6 ArrayTypeReference (org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference)4 Assignment (org.eclipse.jdt.internal.compiler.ast.Assignment)4 EqualExpression (org.eclipse.jdt.internal.compiler.ast.EqualExpression)4 MessageSend (org.eclipse.jdt.internal.compiler.ast.MessageSend)4