Example usage for org.eclipse.jdt.internal.compiler.ast FieldDeclaration getKind

List of usage examples for org.eclipse.jdt.internal.compiler.ast FieldDeclaration getKind

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast FieldDeclaration getKind.

Prototype

@Override
public int getKind() 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.FieldLocator.java

License:Open Source License

public int match(FieldDeclaration node, MatchingNodeSet nodeSet) {
    int referencesLevel = IMPOSSIBLE_MATCH;
    if (this.pattern.findReferences)
        // must be a write only access with an initializer
        if (this.pattern.writeAccess && !this.pattern.readAccess && node.initialization != null)
            if (matchesName(this.pattern.name, node.name))
                referencesLevel = this.pattern.mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;

    int declarationsLevel = IMPOSSIBLE_MATCH;
    if (this.pattern.findDeclarations) {
        switch (node.getKind()) {
        case AbstractVariableDeclaration.FIELD:
        case AbstractVariableDeclaration.ENUM_CONSTANT:
            if (matchesName(this.pattern.name, node.name))
                if (matchesTypeReference(((FieldPattern) this.pattern).typeSimpleName, node.type))
                    declarationsLevel = this.pattern.mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
            break;
        }/* w ww .  j  a v a 2  s.c om*/
    }
    return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Creates an IField from the given field declaration and type.
 *//*from   w w  w.  j  a va2s.c  o m*/
protected IJavaElement createHandle(FieldDeclaration fieldDeclaration, TypeDeclaration typeDeclaration,
        IJavaElement parent) {
    if (!(parent instanceof IType))
        return parent;
    IType type = (IType) parent;

    switch (fieldDeclaration.getKind()) {
    case AbstractVariableDeclaration.FIELD:
    case AbstractVariableDeclaration.ENUM_CONSTANT:
        return ((IType) parent).getField(new String(fieldDeclaration.name));
    }
    if (type.isBinary()) {
        // do not return initializer for binary types
        // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=98378
        return type;
    }
    // find occurrence count of the given initializer in its type declaration
    int occurrenceCount = 0;
    FieldDeclaration[] fields = typeDeclaration.fields;
    int length = fields == null ? 0 : fields.length;
    for (int i = 0; i < length; i++) {
        if (fields[i].getKind() == AbstractVariableDeclaration.INITIALIZER) {
            occurrenceCount++;
            if (fields[i].equals(fieldDeclaration))
                break;
        }
    }
    return ((IType) parent).getInitializer(occurrenceCount);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.util.HandleFactory.java

License:Open Source License

/**
 * Create handle by adding child to parent obtained by recursing into parent scopes.
 *//*from ww  w  .j av a 2s .  c  o m*/
private 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:
        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;
}

From source file:org.eclipse.ajdt.core.parserbridge.AJSourceElementNotifier.java

License:Open Source License

protected void notifySourceElementRequestor(FieldDeclaration fieldDeclaration, TypeDeclaration declaringType) {

    // range check
    boolean isInRange = initialPosition <= fieldDeclaration.declarationSourceStart
            && eofPosition >= fieldDeclaration.declarationSourceEnd;

    switch (fieldDeclaration.getKind()) {
    case AbstractVariableDeclaration.ENUM_CONSTANT:
        if (this.reportReferenceInfo) {
            // accept constructor reference for enum constant
            if (fieldDeclaration.initialization instanceof AllocationExpression) {
                AllocationExpression alloc = (AllocationExpression) fieldDeclaration.initialization;
                requestor.acceptConstructorReference(declaringType.name,
                        alloc.arguments == null ? 0 : alloc.arguments.length, alloc.sourceStart);
            }/*from  www . j  av a2  s .c o m*/
        }
        // fall through next case
    case AbstractVariableDeclaration.FIELD:
        int fieldEndPosition = this.sourceEnds.get(fieldDeclaration);
        if (fieldEndPosition == -1) {
            // use the declaration source end by default
            fieldEndPosition = fieldDeclaration.declarationSourceEnd;
        }
        if (isInRange) {
            int currentModifiers = fieldDeclaration.modifiers;

            // remember deprecation so as to not lose it below
            boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0
                    || hasDeprecatedAnnotation(fieldDeclaration.annotations);

            char[] typeName = null;
            if (fieldDeclaration.type == null) {
                // enum constant
                typeName = declaringType.name;
                currentModifiers |= ClassFileConstants.AccEnum;
            } else {
                // regular field
                typeName = CharOperation.concatWith(fieldDeclaration.type.getParameterizedTypeName(), '.');
            }
            ISourceElementRequestor.FieldInfo fieldInfo = new ISourceElementRequestor.FieldInfo();
            fieldInfo.declarationStart = fieldDeclaration.declarationSourceStart;
            fieldInfo.name = fieldDeclaration.name;
            fieldInfo.modifiers = deprecated
                    ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated
                    : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
            fieldInfo.type = typeName;
            fieldInfo.nameSourceStart = fieldDeclaration.sourceStart;
            fieldInfo.nameSourceEnd = fieldDeclaration.sourceEnd;
            fieldInfo.categories = (char[][]) this.nodesToCategories.get(fieldDeclaration);
            fieldInfo.annotations = fieldDeclaration.annotations;
            fieldInfo.node = fieldDeclaration;
            requestor.enterField(fieldInfo);
        }
        this.visitIfNeeded(fieldDeclaration, declaringType);
        if (isInRange) {
            requestor.exitField(
                    // filter out initializations that are not a constant (simple check)
                    (fieldDeclaration.initialization == null
                            || fieldDeclaration.initialization instanceof ArrayInitializer
                            || fieldDeclaration.initialization instanceof AllocationExpression
                            || fieldDeclaration.initialization instanceof ArrayAllocationExpression
                            || fieldDeclaration.initialization instanceof Assignment
                            || fieldDeclaration.initialization instanceof ClassLiteralAccess
                            || fieldDeclaration.initialization instanceof MessageSend
                            || fieldDeclaration.initialization instanceof ArrayReference
                            || fieldDeclaration.initialization instanceof ThisReference) ? -1
                                    : fieldDeclaration.initialization.sourceStart,
                    fieldEndPosition, fieldDeclaration.declarationSourceEnd);
        }
        break;
    case AbstractVariableDeclaration.INITIALIZER:
        if (isInRange) {
            requestor.enterInitializer(fieldDeclaration.declarationSourceStart, fieldDeclaration.modifiers);
        }
        this.visitIfNeeded((Initializer) fieldDeclaration);
        if (isInRange) {
            requestor.exitInitializer(fieldDeclaration.declarationSourceEnd);
        }
        break;
    }
}

From source file:org.eclipse.che.jdt.internal.core.util.HandleFactory.java

License:Open Source License

/**
 * Create handle by adding child to parent obtained by recursing into parent scopes.
 *///ww  w. java  2s  . c o  m
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;
}

From source file:org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding.java

License:Open Source License

public FieldBinding resolveTypeFor(FieldBinding field) {
    if ((field.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0)
        return field;

    if (this.scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
        if ((field.getAnnotationTagBits() & TagBits.AnnotationDeprecated) != 0)
            field.modifiers |= ClassFileConstants.AccDeprecated;
    }//from  w  w  w . j a  v a  2 s  .c  om
    if (isViewedAsDeprecated() && !field.isDeprecated())
        field.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly;
    if (hasRestrictedAccess())
        field.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess;
    FieldDeclaration[] fieldDecls = this.scope.referenceContext.fields;
    int length = fieldDecls == null ? 0 : fieldDecls.length;
    for (int f = 0; f < length; f++) {
        if (fieldDecls[f].binding != field)
            continue;

        MethodScope initializationScope = field.isStatic() ? this.scope.referenceContext.staticInitializerScope
                : this.scope.referenceContext.initializerScope;
        FieldBinding previousField = initializationScope.initializedField;
        try {
            initializationScope.initializedField = field;
            FieldDeclaration fieldDecl = fieldDecls[f];
            TypeBinding fieldType = fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT
                    ? initializationScope.environment().convertToRawType(this,
                            false /*do not force conversion of enclosing types*/) // enum constant is implicitly of declaring enum type
                    : fieldDecl.type.resolveType(initializationScope, true /* check bounds*/);
            field.type = fieldType;
            field.modifiers &= ~ExtraCompilerModifiers.AccUnresolved;
            if (fieldType == null) {
                fieldDecl.binding = null;
                return null;
            }
            if (fieldType == TypeBinding.VOID) {
                this.scope.problemReporter().variableTypeCannotBeVoid(fieldDecl);
                fieldDecl.binding = null;
                return null;
            }
            if (fieldType.isArrayType() && ((ArrayBinding) fieldType).leafComponentType == TypeBinding.VOID) {
                this.scope.problemReporter().variableTypeCannotBeVoidArray(fieldDecl);
                fieldDecl.binding = null;
                return null;
            }
            if ((fieldType.tagBits & TagBits.HasMissingType) != 0) {
                field.tagBits |= TagBits.HasMissingType;
            }
            TypeBinding leafType = fieldType.leafComponentType();
            if (leafType instanceof ReferenceBinding && (((ReferenceBinding) leafType).modifiers
                    & ExtraCompilerModifiers.AccGenericSignature) != 0) {
                field.modifiers |= ExtraCompilerModifiers.AccGenericSignature;
            }
        } finally {
            initializationScope.initializedField = previousField;
        }
        return field;
    }
    return null; // should never reach this point
}

From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java

License:Open Source License

public RecoveredElement buildInitialRecoveryState() {

    /* initialize recovery by retrieving available reduced nodes
     * also rebuild bracket balance/*from w ww.j a v a 2s  . c o  m*/
     */
    this.lastCheckPoint = 0;
    this.lastErrorEndPositionBeforeRecovery = this.scanner.currentPosition;

    RecoveredElement element = null;
    if (this.referenceContext instanceof CompilationUnitDeclaration) {
        element = new RecoveredUnit(this.compilationUnit, 0, this);

        /* ignore current stack state, since restarting from the beginnning
           since could not trust simple brace count */
        // restart recovery from scratch
        this.compilationUnit.currentPackage = null;
        this.compilationUnit.imports = null;
        this.compilationUnit.types = null;
        this.currentToken = 0;
        this.listLength = 0;
        this.listTypeParameterLength = 0;
        this.endPosition = 0;
        this.endStatementPosition = 0;
        return element;
    } else {
        if (this.referenceContext instanceof AbstractMethodDeclaration) {
            element = new RecoveredMethod((AbstractMethodDeclaration) this.referenceContext, null, 0, this);
            this.lastCheckPoint = ((AbstractMethodDeclaration) this.referenceContext).bodyStart;
            if (this.statementRecoveryActivated) {
                element = element.add(new Block(0), 0);
            }
        } else {
            /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */
            if (this.referenceContext instanceof TypeDeclaration) {
                TypeDeclaration type = (TypeDeclaration) this.referenceContext;
                FieldDeclaration[] fieldDeclarations = type.fields;
                int length = fieldDeclarations == null ? 0 : fieldDeclarations.length;
                for (int i = 0; i < length; i++) {
                    FieldDeclaration field = fieldDeclarations[i];
                    if (field != null && field.getKind() == AbstractVariableDeclaration.INITIALIZER
                            && ((Initializer) field).block != null
                            && field.declarationSourceStart <= this.scanner.initialPosition
                            && this.scanner.initialPosition <= field.declarationSourceEnd
                            && this.scanner.eofPosition <= field.declarationSourceEnd + 1) {
                        element = new RecoveredInitializer(field, null, 1, this);
                        this.lastCheckPoint = field.declarationSourceStart;
                        break;
                    }
                }
            }
        }
    }

    if (element == null)
        return element;

    for (int i = 0; i <= this.astPtr; i++) {
        ASTNode node = this.astStack[i];
        if (node instanceof AbstractMethodDeclaration) {
            AbstractMethodDeclaration method = (AbstractMethodDeclaration) node;
            if (method.declarationSourceEnd == 0) {
                element = element.add(method, 0);
                this.lastCheckPoint = method.bodyStart;
            } else {
                element = element.add(method, 0);
                this.lastCheckPoint = method.declarationSourceEnd + 1;
            }
            continue;
        }
        if (node instanceof Initializer) {
            Initializer initializer = (Initializer) node;
            // ignore initializer with no block
            if (initializer.block == null)
                continue;
            if (initializer.declarationSourceEnd == 0) {
                element = element.add(initializer, 1);
                this.lastCheckPoint = initializer.sourceStart;
            } else {
                element = element.add(initializer, 0);
                this.lastCheckPoint = initializer.declarationSourceEnd + 1;
            }
            continue;
        }
        if (node instanceof FieldDeclaration) {
            FieldDeclaration field = (FieldDeclaration) node;
            if (field.declarationSourceEnd == 0) {
                element = element.add(field, 0);
                if (field.initialization == null) {
                    this.lastCheckPoint = field.sourceEnd + 1;
                } else {
                    this.lastCheckPoint = field.initialization.sourceEnd + 1;
                }
            } else {
                element = element.add(field, 0);
                this.lastCheckPoint = field.declarationSourceEnd + 1;
            }
            continue;
        }
        if (node instanceof TypeDeclaration) {
            TypeDeclaration type = (TypeDeclaration) node;
            if ((type.modifiers & ClassFileConstants.AccEnum) != 0) {
                // do not allow enums to be build as recovery types
                // https://bugs.eclipse.org/bugs/show_bug.cgi?id=340691
                continue;
            }
            if (type.declarationSourceEnd == 0) {
                element = element.add(type, 0);
                this.lastCheckPoint = type.bodyStart;
            } else {
                element = element.add(type, 0);
                this.lastCheckPoint = type.declarationSourceEnd + 1;
            }
            continue;
        }
        if (node instanceof ImportReference) {
            ImportReference importRef = (ImportReference) node;
            element = element.add(importRef, 0);
            this.lastCheckPoint = importRef.declarationSourceEnd + 1;
        }
        if (this.statementRecoveryActivated) {
            if (node instanceof Block) {
                Block block = (Block) node;
                element = element.add(block, 0);
                this.lastCheckPoint = block.sourceEnd + 1;
            } else if (node instanceof LocalDeclaration) {
                LocalDeclaration statement = (LocalDeclaration) node;
                element = element.add(statement, 0);
                this.lastCheckPoint = statement.sourceEnd + 1;
            } else if (node instanceof Expression) {
                if (node instanceof Assignment || node instanceof PrefixExpression
                        || node instanceof PostfixExpression || node instanceof MessageSend
                        || node instanceof AllocationExpression) {
                    // recover only specific expressions
                    Expression statement = (Expression) node;
                    element = element.add(statement, 0);
                    if (statement.statementEnd != -1) {
                        this.lastCheckPoint = statement.statementEnd + 1;
                    } else {
                        this.lastCheckPoint = statement.sourceEnd + 1;
                    }
                }
            } else if (node instanceof Statement) {
                Statement statement = (Statement) node;
                element = element.add(statement, 0);
                this.lastCheckPoint = statement.sourceEnd + 1;
            }
        }
    }

    if (this.statementRecoveryActivated) {
        if (this.pendingRecoveredType != null
                && this.scanner.startPosition - 1 <= this.pendingRecoveredType.declarationSourceEnd) {
            // Add the pending type to the AST if this type isn't already added in the AST.
            element = element.add(this.pendingRecoveredType, 0);
            this.lastCheckPoint = this.pendingRecoveredType.declarationSourceEnd + 1;
            this.pendingRecoveredType = null;
        }
    }
    return element;
}

From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java

License:Open Source License

public ASTNode[] parseClassBodyDeclarations(char[] source, int offset, int length,
        CompilationUnitDeclaration unit) {
    boolean oldDiet = this.diet;
    /* automaton initialization */
    initialize();/*from w  ww.ja v  a2 s . co  m*/
    goForClassBodyDeclarations();
    /* scanner initialization */
    this.scanner.setSource(source);
    this.scanner.resetTo(offset, offset + length - 1);
    if (this.javadocParser != null && this.javadocParser.checkDocComment) {
        this.javadocParser.scanner.setSource(source);
        this.javadocParser.scanner.resetTo(offset, offset + length - 1);
    }

    /* type declaration should be parsed as member type declaration */
    this.nestedType = 1;

    /* unit creation */
    TypeDeclaration referenceContextTypeDeclaration = new TypeDeclaration(unit.compilationResult);
    referenceContextTypeDeclaration.name = Util.EMPTY_STRING.toCharArray();
    referenceContextTypeDeclaration.fields = new FieldDeclaration[0];
    this.compilationUnit = unit;
    unit.types = new TypeDeclaration[1];
    unit.types[0] = referenceContextTypeDeclaration;
    this.referenceContext = unit;

    /* run automaton */
    try {
        this.diet = true;
        parse();
    } catch (AbortCompilation ex) {
        this.lastAct = ERROR_ACTION;
    } finally {
        this.diet = oldDiet;
    }

    ASTNode[] result = null;
    if (this.lastAct == ERROR_ACTION) {
        if (!this.options.performMethodsFullRecovery && !this.options.performStatementsRecovery) {
            return null;
        }
        // collect all body declaration inside the compilation unit except the default constructor
        final List bodyDeclarations = new ArrayList();
        ASTVisitor visitor = new ASTVisitor() {
            public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
                if (!methodDeclaration.isDefaultConstructor()) {
                    bodyDeclarations.add(methodDeclaration);
                }
                return false;
            }

            public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
                bodyDeclarations.add(fieldDeclaration);
                return false;
            }

            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
                bodyDeclarations.add(memberTypeDeclaration);
                return false;
            }
        };
        unit.ignoreFurtherInvestigation = false;
        unit.traverse(visitor, unit.scope);
        unit.ignoreFurtherInvestigation = true;
        result = (ASTNode[]) bodyDeclarations.toArray(new ASTNode[bodyDeclarations.size()]);
    } else {
        int astLength;
        if (this.astLengthPtr > -1 && (astLength = this.astLengthStack[this.astLengthPtr--]) != 0) {
            result = new ASTNode[astLength];
            this.astPtr -= astLength;
            System.arraycopy(this.astStack, this.astPtr + 1, result, 0, astLength);
        } else {
            // empty class body declaration (like ';' see https://bugs.eclipse.org/bugs/show_bug.cgi?id=280079).
            result = new ASTNode[0];
        }
    }
    boolean containsInitializers = false;
    TypeDeclaration typeDeclaration = null;
    for (int i = 0, max = result.length; i < max; i++) {
        // parse each class body declaration
        ASTNode node = result[i];
        if (node instanceof TypeDeclaration) {
            ((TypeDeclaration) node).parseMethods(this, unit);
        } else if (node instanceof AbstractMethodDeclaration) {
            ((AbstractMethodDeclaration) node).parseStatements(this, unit);
        } else if (node instanceof FieldDeclaration) {
            FieldDeclaration fieldDeclaration = (FieldDeclaration) node;
            switch (fieldDeclaration.getKind()) {
            case AbstractVariableDeclaration.INITIALIZER:
                containsInitializers = true;
                if (typeDeclaration == null) {
                    typeDeclaration = referenceContextTypeDeclaration;
                }
                if (typeDeclaration.fields == null) {
                    typeDeclaration.fields = new FieldDeclaration[1];
                    typeDeclaration.fields[0] = fieldDeclaration;
                } else {
                    int length2 = typeDeclaration.fields.length;
                    FieldDeclaration[] temp = new FieldDeclaration[length2 + 1];
                    System.arraycopy(typeDeclaration.fields, 0, temp, 0, length2);
                    temp[length2] = fieldDeclaration;
                    typeDeclaration.fields = temp;
                }
                break;
            }
        }
        if (((node.bits & ASTNode.HasSyntaxErrors) != 0)
                && (!this.options.performMethodsFullRecovery && !this.options.performStatementsRecovery)) {
            return null;
        }
    }
    if (containsInitializers) {
        FieldDeclaration[] fieldDeclarations = typeDeclaration.fields;
        for (int i = 0, max = fieldDeclarations.length; i < max; i++) {
            Initializer initializer = (Initializer) fieldDeclarations[i];
            initializer.parseStatements(this, typeDeclaration, unit);
            if (((initializer.bits & ASTNode.HasSyntaxErrors) != 0)
                    && (!this.options.performMethodsFullRecovery && !this.options.performStatementsRecovery)) {
                return null;
            }
        }
    }
    return result;
}

From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java

License:Open Source License

protected void recoverStatements() {
    class MethodVisitor extends ASTVisitor {
        public ASTVisitor typeVisitor;

        TypeDeclaration enclosingType; // used only for initializer

        TypeDeclaration[] types = new TypeDeclaration[0];
        int typePtr = -1;

        public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
            endVisitMethod(constructorDeclaration, scope);
        }/*from   w ww.j  a va  2 s .c o  m*/

        public void endVisit(Initializer initializer, MethodScope scope) {
            if (initializer.block == null)
                return;
            TypeDeclaration[] foundTypes = null;
            int length = 0;
            if (this.typePtr > -1) {
                length = this.typePtr + 1;
                foundTypes = new TypeDeclaration[length];
                System.arraycopy(this.types, 0, foundTypes, 0, length);
            }
            ReferenceContext oldContext = Parser.this.referenceContext;
            Parser.this.recoveryScanner.resetTo(initializer.bodyStart, initializer.bodyEnd);
            Scanner oldScanner = Parser.this.scanner;
            Parser.this.scanner = Parser.this.recoveryScanner;
            parseStatements(this.enclosingType, initializer.bodyStart, initializer.bodyEnd, foundTypes,
                    Parser.this.compilationUnit);
            Parser.this.scanner = oldScanner;
            Parser.this.referenceContext = oldContext;

            for (int i = 0; i < length; i++) {
                foundTypes[i].traverse(this.typeVisitor, scope);
            }
        }

        public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
            endVisitMethod(methodDeclaration, scope);
        }

        private void endVisitMethod(AbstractMethodDeclaration methodDeclaration, ClassScope scope) {
            TypeDeclaration[] foundTypes = null;
            int length = 0;
            if (this.typePtr > -1) {
                length = this.typePtr + 1;
                foundTypes = new TypeDeclaration[length];
                System.arraycopy(this.types, 0, foundTypes, 0, length);
            }
            ReferenceContext oldContext = Parser.this.referenceContext;
            Parser.this.recoveryScanner.resetTo(methodDeclaration.bodyStart, methodDeclaration.bodyEnd);
            Scanner oldScanner = Parser.this.scanner;
            Parser.this.scanner = Parser.this.recoveryScanner;
            parseStatements(methodDeclaration, methodDeclaration.bodyStart, methodDeclaration.bodyEnd,
                    foundTypes, Parser.this.compilationUnit);
            Parser.this.scanner = oldScanner;
            Parser.this.referenceContext = oldContext;

            for (int i = 0; i < length; i++) {
                foundTypes[i].traverse(this.typeVisitor, scope);
            }
        }

        public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
            this.typePtr = -1;
            return true;
        }

        public boolean visit(Initializer initializer, MethodScope scope) {
            this.typePtr = -1;
            if (initializer.block == null)
                return false;
            return true;
        }

        public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
            this.typePtr = -1;
            return true;
        }

        private boolean visit(TypeDeclaration typeDeclaration) {
            if (this.types.length <= ++this.typePtr) {
                int length = this.typePtr;
                System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length);
            }
            this.types[this.typePtr] = typeDeclaration;
            return false;
        }

        public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
            return this.visit(typeDeclaration);
        }

        public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) {
            return this.visit(typeDeclaration);
        }
    }
    class TypeVisitor extends ASTVisitor {
        public MethodVisitor methodVisitor;

        TypeDeclaration[] types = new TypeDeclaration[0];
        int typePtr = -1;

        public void endVisit(TypeDeclaration typeDeclaration, BlockScope scope) {
            endVisitType();
        }

        public void endVisit(TypeDeclaration typeDeclaration, ClassScope scope) {
            endVisitType();
        }

        private void endVisitType() {
            this.typePtr--;
        }

        public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
            if (constructorDeclaration.isDefaultConstructor())
                return false;

            constructorDeclaration.traverse(this.methodVisitor, scope);
            return false;
        }

        public boolean visit(Initializer initializer, MethodScope scope) {
            if (initializer.block == null)
                return false;
            this.methodVisitor.enclosingType = this.types[this.typePtr];
            initializer.traverse(this.methodVisitor, scope);
            return false;
        }

        public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
            methodDeclaration.traverse(this.methodVisitor, scope);
            return false;
        }

        private boolean visit(TypeDeclaration typeDeclaration) {
            if (this.types.length <= ++this.typePtr) {
                int length = this.typePtr;
                System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length);
            }
            this.types[this.typePtr] = typeDeclaration;
            return true;
        }

        public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) {
            return this.visit(typeDeclaration);
        }

        public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) {
            return this.visit(typeDeclaration);
        }
    }

    MethodVisitor methodVisitor = new MethodVisitor();
    TypeVisitor typeVisitor = new TypeVisitor();
    methodVisitor.typeVisitor = typeVisitor;
    typeVisitor.methodVisitor = methodVisitor;

    if (this.referenceContext instanceof AbstractMethodDeclaration) {
        ((AbstractMethodDeclaration) this.referenceContext).traverse(methodVisitor, (ClassScope) null);
    } else if (this.referenceContext instanceof TypeDeclaration) {
        TypeDeclaration typeContext = (TypeDeclaration) this.referenceContext;

        int length = typeContext.fields.length;
        for (int i = 0; i < length; i++) {
            final FieldDeclaration fieldDeclaration = typeContext.fields[i];
            switch (fieldDeclaration.getKind()) {
            case AbstractVariableDeclaration.INITIALIZER:
                Initializer initializer = (Initializer) fieldDeclaration;
                if (initializer.block == null)
                    break;
                methodVisitor.enclosingType = typeContext;
                initializer.traverse(methodVisitor, (MethodScope) null);
                break;
            }
        }
    }
}

From source file:org.nabucco.framework.mda.model.java.ast.extension.type.TypeDeclarationExtension.java

License:Open Source License

public StringBuffer printBody(int indent, StringBuffer output) {
    output.append(" {"); //$NON-NLS-1$

    // Inner classes are not supported

    if (this.memberTypes != null) {

        throw new IllegalArgumentException(
                "Inner classes are not supported! Found in '" + new String(this.name) + ".java'.");

        // for (int i = 0; i < this.memberTypes.length; i++) {
        // if (this.memberTypes[i] != null) {
        // output.append('\n');
        // this.memberTypes[i].print(indent + 1, output);
        // } }//from ww  w .  j  av a 2 s  . c o m
    }

    if (this.fields != null) {
        for (int i = 0; i < this.fields.length; i++) {

            FieldDeclaration field = this.fields[i];

            if (field != null) {
                output.append('\n');
                field.print(indent + 1, output);

                if (field.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT) {

                    if (i == this.fields.length - 1) {
                        output.append(SEMICOLON);
                    } else {

                        FieldDeclaration nextField = fields[i + 1];

                        if (nextField == null
                                || nextField.getKind() != AbstractVariableDeclaration.ENUM_CONSTANT) {
                            output.append(SEMICOLON);
                        }
                    }
                }
            }
        }
    }
    if (this.methods != null) {

        Arrays.sort(this.methods, AbstractMethodDeclarationComparator.getInstance());

        for (int i = 0; i < this.methods.length; i++) {
            if (this.methods[i] != null) {
                output.append('\n');
                this.methods[i].print(indent + 1, output);
            }
        }
    }
    output.append('\n');
    return printIndent(indent, output).append('}');
}