Example usage for org.eclipse.jdt.internal.compiler.ast TypeDeclaration ANNOTATION_TYPE_DECL

List of usage examples for org.eclipse.jdt.internal.compiler.ast TypeDeclaration ANNOTATION_TYPE_DECL

Introduction

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

Prototype

int ANNOTATION_TYPE_DECL

To view the source code for org.eclipse.jdt.internal.compiler.ast TypeDeclaration ANNOTATION_TYPE_DECL.

Click Source Link

Usage

From source file:ch.uzh.ifi.seal.changedistiller.structuredifferencing.java.JavaStructureTreeBuilder.java

License:Apache License

@Override
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
    int kind = TypeDeclaration.kind(typeDeclaration.modifiers);
    Type type = null;/*from  w  ww.  java2s  .c om*/
    switch (kind) {
    case TypeDeclaration.INTERFACE_DECL:
        type = Type.INTERFACE;
        break;
    case TypeDeclaration.CLASS_DECL:
        type = Type.CLASS;
        break;
    case TypeDeclaration.ANNOTATION_TYPE_DECL:
        type = Type.ANNOTATION;
        break;
    case TypeDeclaration.ENUM_DECL:
        type = Type.ENUM;
        break;
    default:
        assert (false);
    }
    push(type, String.valueOf(typeDeclaration.name), typeDeclaration);
    fQualifiers.push(typeDeclaration.name);
    return true;
}

From source file:com.android.tools.lint.psi.EcjPsiBuilder.java

License:Apache License

@NonNull
private EcjPsiClass toClass(@NonNull EcjPsiSourceElement parent, @NonNull TypeDeclaration declaration) {
    EcjPsiClass cls = new EcjPsiClass(mManager, declaration, new String(declaration.name));
    parent.adoptChild(cls);//w w  w .j  a va 2s. com
    cls.setRange(declaration.declarationSourceStart, declaration.declarationSourceEnd + 1);
    EcjPsiModifierList modifierList = toModifierList(cls, declaration);
    cls.setNameIdentifier(toIdentifier(cls, declaration.name, toRange(declaration)));
    cls.setModifierList(modifierList);

    int kind = TypeDeclaration.kind(declaration.modifiers);
    switch (kind) {
    case TypeDeclaration.CLASS_DECL: {
        // Class: set body, super class, extended interfaces, and type variables
        cls.setSuperClass(declaration.superclass);
        cls.setSuperInterfaces(declaration.superInterfaces);
        cls.setTypeParameterList(toTypeParameterList(cls, declaration.typeParameters));
        cls.setExtendsList(toTypeReferenceList(cls, declaration.superclass, Role.EXTENDS_LIST));
        cls.setImplementsList(toTypeReferenceList(cls, declaration.superInterfaces, Role.IMPLEMENTS_LIST));
        initializeClassBody(cls, declaration);
        break;
    }
    case TypeDeclaration.INTERFACE_DECL: {
        // Interface: set body, super interface, and type variables
        modifierList.setModifiers(modifierList.getModifiers() | Modifier.STATIC | Modifier.ABSTRACT);
        cls.setSuperInterfaces(declaration.superInterfaces);
        cls.setTypeParameterList(toTypeParameterList(cls, declaration.typeParameters));
        cls.setImplementsList(toTypeReferenceList(cls, declaration.superInterfaces, Role.EXTENDS_LIST));
        initializeClassBody(cls, declaration);
        break;
    }
    case TypeDeclaration.ENUM_DECL: {
        // Enum: set enum body, and implemented interfaces
        cls.setSuperInterfaces(declaration.superInterfaces);
        cls.setImplementsList(toTypeReferenceList(cls, declaration.superInterfaces, Role.IMPLEMENTS_LIST));
        modifierList.setModifiers(modifierList.getModifiers() | Modifier.STATIC | Modifier.FINAL);
        initializeClassBody(cls, declaration);
        break;
    }
    case TypeDeclaration.ANNOTATION_TYPE_DECL: {
        // Annotation: set body
        modifierList.setModifiers(modifierList.getModifiers() | Modifier.STATIC | Modifier.ABSTRACT);
        initializeClassBody(cls, declaration);
        break;
    }
    }

    return cls;
}

From source file:com.android.tools.lint.psi.EcjPsiClass.java

License:Apache License

@Override
public boolean isAnnotationType() {
    return TypeDeclaration.kind(mEcjModifiers) == TypeDeclaration.ANNOTATION_TYPE_DECL;
}

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private TypeDeclaration convert(SourceType typeHandle, CompilationResult compilationResult)
        throws JavaModelException {
    SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) typeHandle.getElementInfo();
    if (typeInfo.isAnonymousMember())
        throw new AnonymousMemberFound();
    /* create type declaration - can be member type */
    TypeDeclaration type = new TypeDeclaration(compilationResult);
    if (typeInfo.getEnclosingType() == null) {
        if (typeHandle.isAnonymous()) {
            type.name = CharOperation.NO_CHAR;
            type.bits |= (ASTNode.IsAnonymousType | ASTNode.IsLocalType);
        } else {//w w  w  . ja v a 2 s.  c  o  m
            if (typeHandle.isLocal()) {
                type.bits |= ASTNode.IsLocalType;
            }
        }
    } else {
        type.bits |= ASTNode.IsMemberType;
    }
    if ((type.bits & ASTNode.IsAnonymousType) == 0) {
        type.name = typeInfo.getName();
    }
    type.name = typeInfo.getName();
    int start, end; // only positions available
    type.sourceStart = start = typeInfo.getNameSourceStart();
    type.sourceEnd = end = typeInfo.getNameSourceEnd();
    type.modifiers = typeInfo.getModifiers();
    type.declarationSourceStart = typeInfo.getDeclarationSourceStart();
    type.declarationSourceEnd = typeInfo.getDeclarationSourceEnd();
    type.bodyEnd = type.declarationSourceEnd;

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert annotations */
        type.annotations = convertAnnotations(typeHandle);
    }
    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=324850, even in a 1.4 project, we
       must internalize type variables and observe any parameterization of super class
       and/or super interfaces in order to be able to detect overriding in the presence
       of generics.
     */
    char[][] typeParameterNames = typeInfo.getTypeParameterNames();
    if (typeParameterNames.length > 0) {
        int parameterCount = typeParameterNames.length;
        char[][][] typeParameterBounds = typeInfo.getTypeParameterBounds();
        type.typeParameters = new TypeParameter[parameterCount];
        for (int i = 0; i < parameterCount; i++) {
            type.typeParameters[i] = createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start,
                    end);
        }
    }

    /* set superclass and superinterfaces */
    if (typeInfo.getSuperclassName() != null) {
        type.superclass = createTypeReference(typeInfo.getSuperclassName(), start, end,
                true /* include generics */);
        type.superclass.bits |= ASTNode.IsSuperType;
    }
    char[][] interfaceNames = typeInfo.getInterfaceNames();
    int interfaceCount = interfaceNames == null ? 0 : interfaceNames.length;
    if (interfaceCount > 0) {
        type.superInterfaces = new TypeReference[interfaceCount];
        for (int i = 0; i < interfaceCount; i++) {
            type.superInterfaces[i] = createTypeReference(interfaceNames[i], start, end,
                    true /* include generics */);
            type.superInterfaces[i].bits |= ASTNode.IsSuperType;
        }
    }
    /* convert member types */
    if ((this.flags & MEMBER_TYPE) != 0) {
        SourceType[] sourceMemberTypes = typeInfo.getMemberTypeHandles();
        int sourceMemberTypeCount = sourceMemberTypes.length;
        type.memberTypes = new TypeDeclaration[sourceMemberTypeCount];
        for (int i = 0; i < sourceMemberTypeCount; i++) {
            type.memberTypes[i] = convert(sourceMemberTypes[i], compilationResult);
            type.memberTypes[i].enclosingType = type;
        }
    }

    /* convert intializers and fields*/
    InitializerElementInfo[] initializers = null;
    int initializerCount = 0;
    if ((this.flags & LOCAL_TYPE) != 0) {
        initializers = typeInfo.getInitializers();
        initializerCount = initializers.length;
    }
    SourceField[] sourceFields = null;
    int sourceFieldCount = 0;
    if ((this.flags & FIELD) != 0) {
        sourceFields = typeInfo.getFieldHandles();
        sourceFieldCount = sourceFields.length;
    }
    int length = initializerCount + sourceFieldCount;
    if (length > 0) {
        type.fields = new FieldDeclaration[length];
        for (int i = 0; i < initializerCount; i++) {
            type.fields[i] = convert(initializers[i], compilationResult);
        }
        int index = 0;
        for (int i = initializerCount; i < length; i++) {
            type.fields[i] = convert(sourceFields[index++], type, compilationResult);
        }
    }

    /* convert methods - need to add default constructor if necessary */
    boolean needConstructor = (this.flags & CONSTRUCTOR) != 0;
    boolean needMethod = (this.flags & METHOD) != 0;
    if (needConstructor || needMethod) {

        SourceMethod[] sourceMethods = typeInfo.getMethodHandles();
        int sourceMethodCount = sourceMethods.length;

        /* source type has a constructor ?           */
        /* by default, we assume that one is needed. */
        int extraConstructor = 0;
        int methodCount = 0;
        int kind = TypeDeclaration.kind(type.modifiers);
        boolean isAbstract = kind == TypeDeclaration.INTERFACE_DECL
                || kind == TypeDeclaration.ANNOTATION_TYPE_DECL;
        if (!isAbstract) {
            extraConstructor = needConstructor ? 1 : 0;
            for (int i = 0; i < sourceMethodCount; i++) {
                if (sourceMethods[i].isConstructor()) {
                    if (needConstructor) {
                        extraConstructor = 0; // Does not need the extra constructor since one constructor already exists.
                        methodCount++;
                    }
                } else if (needMethod) {
                    methodCount++;
                }
            }
        } else {
            methodCount = needMethod ? sourceMethodCount : 0;
        }
        type.methods = new AbstractMethodDeclaration[methodCount + extraConstructor];
        if (extraConstructor != 0) { // add default constructor in first position
            type.methods[0] = type.createDefaultConstructor(false, false);
        }
        int index = 0;
        boolean hasAbstractMethods = false;
        for (int i = 0; i < sourceMethodCount; i++) {
            SourceMethod sourceMethod = sourceMethods[i];
            SourceMethodElementInfo methodInfo = (SourceMethodElementInfo) sourceMethod.getElementInfo();
            boolean isConstructor = methodInfo.isConstructor();
            if ((methodInfo.getModifiers() & ClassFileConstants.AccAbstract) != 0) {
                hasAbstractMethods = true;
            }
            if ((isConstructor && needConstructor) || (!isConstructor && needMethod)) {
                AbstractMethodDeclaration method = convert(sourceMethod, methodInfo, compilationResult);
                if (isAbstract || method.isAbstract()) { // fix-up flag
                    method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
                }
                type.methods[extraConstructor + index++] = method;
            }
        }
        if (hasAbstractMethods)
            type.bits |= ASTNode.HasAbstractMethods;
    }

    return type;
}

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

License:Open Source License

public boolean isInterface() throws JavaModelException {
    IBinaryType info = (IBinaryType) getElementInfo();
    switch (TypeDeclaration.kind(info.getModifiers())) {
    case TypeDeclaration.INTERFACE_DECL:
    case TypeDeclaration.ANNOTATION_TYPE_DECL: // annotation is interface too
        return true;
    }//from  www.j av  a  2 s. co m
    return false;
}

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

License:Open Source License

/**
 * @see org.eclipse.jdt.core.IType#isAnnotation()
 * @since 3.0//w w w.  ja v a  2s  .c  o m
 */
public boolean isAnnotation() throws JavaModelException {
    IBinaryType info = (IBinaryType) getElementInfo();
    return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.ANNOTATION_TYPE_DECL;
}

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

License:Open Source License

char convertTypeKind(int typeDeclarationKind) {
    switch (typeDeclarationKind) {
    case TypeDeclaration.CLASS_DECL:
        return IIndexConstants.CLASS_SUFFIX;
    case TypeDeclaration.INTERFACE_DECL:
        return IIndexConstants.INTERFACE_SUFFIX;
    case TypeDeclaration.ENUM_DECL:
        return IIndexConstants.ENUM_SUFFIX;
    case TypeDeclaration.ANNOTATION_TYPE_DECL:
        return IIndexConstants.ANNOTATION_TYPE_SUFFIX;
    default:/*from w  w  w.  j a va 2s  .co m*/
        return IIndexConstants.TYPE_SUFFIX;
    }
}

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

License:Open Source License

boolean match(char patternTypeSuffix, char[] patternPkg, int matchRulePkg, char[] patternTypeName,
        int matchRuleType, int typeKind, char[] pkg, char[] typeName) {
    switch (patternTypeSuffix) {
    case IIndexConstants.CLASS_SUFFIX:
        if (typeKind != TypeDeclaration.CLASS_DECL)
            return false;
        break;//from   w w  w  .  jav a2s. co  m
    case IIndexConstants.CLASS_AND_INTERFACE_SUFFIX:
        if (typeKind != TypeDeclaration.CLASS_DECL && typeKind != TypeDeclaration.INTERFACE_DECL)
            return false;
        break;
    case IIndexConstants.CLASS_AND_ENUM_SUFFIX:
        if (typeKind != TypeDeclaration.CLASS_DECL && typeKind != TypeDeclaration.ENUM_DECL)
            return false;
        break;
    case IIndexConstants.INTERFACE_SUFFIX:
        if (typeKind != TypeDeclaration.INTERFACE_DECL)
            return false;
        break;
    case IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX:
        if (typeKind != TypeDeclaration.INTERFACE_DECL && typeKind != TypeDeclaration.ANNOTATION_TYPE_DECL)
            return false;
        break;
    case IIndexConstants.ENUM_SUFFIX:
        if (typeKind != TypeDeclaration.ENUM_DECL)
            return false;
        break;
    case IIndexConstants.ANNOTATION_TYPE_SUFFIX:
        if (typeKind != TypeDeclaration.ANNOTATION_TYPE_DECL)
            return false;
        break;
    case IIndexConstants.TYPE_SUFFIX: // nothing
    }

    boolean isPkgCaseSensitive = (matchRulePkg & SearchPattern.R_CASE_SENSITIVE) != 0;
    if (patternPkg != null && !CharOperation.equals(patternPkg, pkg, isPkgCaseSensitive))
        return false;

    boolean isCaseSensitive = (matchRuleType & SearchPattern.R_CASE_SENSITIVE) != 0;
    if (patternTypeName != null) {
        boolean isCamelCase = (matchRuleType
                & (SearchPattern.R_CAMELCASE_MATCH | SearchPattern.R_CAMELCASE_SAME_PART_COUNT_MATCH)) != 0;
        int matchMode = matchRuleType & JavaSearchPattern.MATCH_MODE_MASK;
        if (!isCaseSensitive && !isCamelCase) {
            patternTypeName = CharOperation.toLowerCase(patternTypeName);
        }
        boolean matchFirstChar = !isCaseSensitive || patternTypeName[0] == typeName[0];
        switch (matchMode) {
        case SearchPattern.R_EXACT_MATCH:
            return matchFirstChar && CharOperation.equals(patternTypeName, typeName, isCaseSensitive);
        case SearchPattern.R_PREFIX_MATCH:
            return matchFirstChar && CharOperation.prefixEquals(patternTypeName, typeName, isCaseSensitive);
        case SearchPattern.R_PATTERN_MATCH:
            return CharOperation.match(patternTypeName, typeName, isCaseSensitive);
        case SearchPattern.R_REGEXP_MATCH:
            // TODO (frederic) implement regular expression match
            break;
        case SearchPattern.R_CAMELCASE_MATCH:
            if (matchFirstChar && CharOperation.camelCaseMatch(patternTypeName, typeName, false)) {
                return true;
            }
            return !isCaseSensitive && matchFirstChar
                    && CharOperation.prefixEquals(patternTypeName, typeName, false);
        case SearchPattern.R_CAMELCASE_SAME_PART_COUNT_MATCH:
            return matchFirstChar && CharOperation.camelCaseMatch(patternTypeName, typeName, true);
        }
    }
    return true;

}

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

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope.
 * The search can be selecting specific types (given a package or a type name
 * prefix and match modes)./*from  ww w.j  a  v a 2s .  c  om*/
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[], int, char[], int, int,
 * org.eclipse.jdt.core.search.IJavaSearchScope, org.eclipse.jdt.core.search.TypeNameRequestor, int,
 * org.eclipse.core.runtime.IProgressMonitor)
 *    for detailed comment
 */
public void searchAllTypeNames(final char[] packageName, final int packageMatchRule, final char[] typeName,
        final int typeMatchRule, int searchFor, IJavaSearchScope scope,
        final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor)
        throws JavaModelException {

    // Validate match rule first
    final int validatedTypeMatchRule = SearchPattern
            .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule);

    // Debug
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, "
                        + "int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - package match rule: " + getMatchRuleString(packageMatchRule)); //$NON-NLS-1$
        Util.verbose("   - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$
        if (validatedTypeMatchRule != typeMatchRule) {
            Util.verbose("   - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$
        }
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }
    if (validatedTypeMatchRule == -1)
        return; // invalid match rule => return no results

    final char typeSuffix;
    switch (searchFor) {
    case IJavaSearchConstants.CLASS:
        typeSuffix = IIndexConstants.CLASS_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_INTERFACE:
        typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.CLASS_AND_ENUM:
        typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE:
        typeSuffix = IIndexConstants.INTERFACE_SUFFIX;
        break;
    case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
        typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX;
        break;
    case IJavaSearchConstants.ENUM:
        typeSuffix = IIndexConstants.ENUM_SUFFIX;
        break;
    case IJavaSearchConstants.ANNOTATION_TYPE:
        typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
        break;
    default:
        typeSuffix = IIndexConstants.TYPE_SUFFIX;
        break;
    }
    final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH
            ? new TypeDeclarationPattern(packageName, null, typeName, typeSuffix, validatedTypeMatchRule)
            : new QualifiedTypeDeclarationPattern(packageName, packageMatchRule, typeName, typeSuffix,
                    validatedTypeMatchRule);

    // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
    final HashSet workingCopyPaths = new HashSet();
    String workingCopyPath = null;
    ICompilationUnit[] copies = getWorkingCopies();
    final int copiesLength = copies == null ? 0 : copies.length;
    if (copies != null) {
        if (copiesLength == 1) {
            workingCopyPath = copies[0].getPath().toString();
        } else {
            for (int i = 0; i < copiesLength; i++) {
                ICompilationUnit workingCopy = copies[i];
                workingCopyPaths.add(workingCopy.getPath().toString());
            }
        }
    }
    final String singleWkcpPath = workingCopyPath;

    // Index requestor
    IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {
        public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord,
                SearchParticipant participant, AccessRuleSet access) {
            // Filter unexpected types
            TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord;
            if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
                return true; // filter out local and anonymous classes
            }
            switch (copiesLength) {
            case 0:
                break;
            case 1:
                if (singleWkcpPath.equals(documentPath)) {
                    return true; // filter out *the* working copy
                }
                break;
            default:
                if (workingCopyPaths.contains(documentPath)) {
                    return true; // filter out working copies
                }
                break;
            }

            // Accept document path
            AccessRestriction accessRestriction = null;
            if (access != null) {
                // Compute document relative path
                int pkgLength = (record.pkg == null || record.pkg.length == 0) ? 0 : record.pkg.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[pkgLength + nameLength];
                int pos = 0;
                if (pkgLength > 0) {
                    System.arraycopy(record.pkg, 0, path, pos, pkgLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[pkgLength - 1] = '/';
                    pos += pkgLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.simpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            if (match(record.typeSuffix, record.modifiers)) {
                nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName,
                        record.enclosingTypeNames, documentPath, accessRestriction);
            }
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 1000);
        }
        // add type names from indexes
        indexManager.performConcurrentJob(
                new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only
                        scope, searchRequestor, indexManager),
                waitingPolicy,
                progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0; i < copiesLength; i++) {
                final ICompilationUnit workingCopy = copies[i];
                if (scope instanceof HierarchyScope) {
                    if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor))
                        continue;
                } else {
                    if (!scope.encloses(workingCopy))
                        continue;
                }
                final String path = workingCopy.getPath().toString();
                if (workingCopy.isConsistent()) {
                    IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
                    char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR
                            : packageDeclarations[0].getElementName().toCharArray();
                    IType[] allTypes = workingCopy.getAllTypes();
                    for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
                        IType type = allTypes[j];
                        IJavaElement parent = type.getParent();
                        char[][] enclosingTypeNames;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        int kind;
                        if (type.isEnum()) {
                            kind = TypeDeclaration.ENUM_DECL;
                        } else if (type.isAnnotation()) {
                            kind = TypeDeclaration.ANNOTATION_TYPE_DECL;
                        } else if (type.isClass()) {
                            kind = TypeDeclaration.CLASS_DECL;
                        } else /*if (type.isInterface())*/ {
                            kind = TypeDeclaration.INTERFACE_DECL;
                        }
                        if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule,
                                kind, packageDeclaration, simpleName)) {
                            if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                ((TypeNameMatchRequestorWrapper) nameRequestor).requestor.acceptTypeNameMatch(
                                        new JavaSearchTypeNameMatch(type, type.getFlags()));
                            } else {
                                nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName,
                                        enclosingTypeNames, path, null);
                            }
                        }
                    }
                } else {
                    Parser basicParser = getParser();
                    org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
                    CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0,
                            this.compilerOptions.maxProblemsPerUnit);
                    CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
                    if (parsedUnit != null) {
                        final char[] packageDeclaration = parsedUnit.currentPackage == null
                                ? CharOperation.NO_CHAR
                                : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
                        class AllTypeDeclarationsVisitor extends ASTVisitor {
                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false; // no local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration,
                                    CompilationUnitScope compilationUnitScope) {
                                if (match(typeSuffix, packageName, packageMatchRule, typeName,
                                        validatedTypeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers),
                                        packageDeclaration, typeDeclaration.name)) {
                                    if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                        IType type = workingCopy.getType(new String(typeName));
                                        ((TypeNameMatchRequestorWrapper) nameRequestor).requestor
                                                .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type,
                                                        typeDeclaration.modifiers));
                                    } else {
                                        nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                                typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                    }
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                if (match(typeSuffix, packageName, packageMatchRule, typeName,
                                        validatedTypeMatchRule,
                                        TypeDeclaration.kind(memberTypeDeclaration.modifiers),
                                        packageDeclaration, memberTypeDeclaration.name)) {
                                    // compute enclosing type names
                                    TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                    char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                    while (enclosing != null) {
                                        enclosingTypeNames = CharOperation.arrayConcat(
                                                new char[][] { enclosing.name }, enclosingTypeNames);
                                        if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                            enclosing = enclosing.enclosingType;
                                        } else {
                                            enclosing = null;
                                        }
                                    }
                                    // report
                                    if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
                                        IType type = workingCopy.getType(new String(enclosingTypeNames[0]));
                                        for (int j = 1, l = enclosingTypeNames.length; j < l; j++) {
                                            type = type.getType(new String(enclosingTypeNames[j]));
                                        }
                                        ((TypeNameMatchRequestorWrapper) nameRequestor).requestor
                                                .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0));
                                    } else {
                                        nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                                packageDeclaration, memberTypeDeclaration.name,
                                                enclosingTypeNames, path, null);
                                    }
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
                if (progressMonitor != null) {
                    if (progressMonitor.isCanceled())
                        throw new OperationCanceledException();
                    progressMonitor.worked(1);
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.indexing.BinaryIndexer.java

License:Open Source License

public void indexDocument() {
    try {//from  w  w w. ja va 2s  .c  om
        final byte[] contents = this.document.getByteContents();
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=107124
        // contents can potentially be null if a IOException occurs while retrieving the contents
        if (contents == null)
            return;
        final String path = this.document.getPath();
        ClassFileReader reader = new ClassFileReader(contents, path == null ? null : path.toCharArray());

        // first add type references
        char[] className = replace('/', '.', reader.getName()); // looks like java/lang/String
        // need to extract the package name and the simple name
        int packageNameIndex = CharOperation.lastIndexOf('.', className);
        char[] packageName = null;
        char[] name = null;
        if (packageNameIndex >= 0) {
            packageName = CharOperation.subarray(className, 0, packageNameIndex);
            name = CharOperation.subarray(className, packageNameIndex + 1, className.length);
        } else {
            packageName = CharOperation.NO_CHAR;
            name = className;
        }
        char[] enclosingTypeName = null;
        boolean isNestedType = reader.isNestedType();
        if (isNestedType) {
            if (reader.isAnonymous()) {
                name = CharOperation.NO_CHAR;
            } else {
                name = reader.getInnerSourceName();
            }
            if (reader.isLocal() || reader.isAnonymous()) {
                // set specific ['0'] value for local and anonymous to be able to filter them
                enclosingTypeName = ONE_ZERO;
            } else {
                char[] fullEnclosingName = reader.getEnclosingTypeName();
                int nameLength = fullEnclosingName.length - packageNameIndex - 1;
                if (nameLength <= 0) {
                    // See PR 1GIR345: ITPJCORE:ALL - Indexer: NegativeArraySizeException
                    return;
                }
                enclosingTypeName = new char[nameLength];
                System.arraycopy(fullEnclosingName, packageNameIndex + 1, enclosingTypeName, 0, nameLength);
            }
        }
        // type parameters
        char[][] typeParameterSignatures = null;
        char[] genericSignature = reader.getGenericSignature();
        if (genericSignature != null) {
            CharOperation.replace(genericSignature, '/', '.');
            typeParameterSignatures = Signature.getTypeParameters(genericSignature);
        }

        // eliminate invalid innerclasses (1G4KCF7)
        if (name == null)
            return;

        char[][] superinterfaces = replace('/', '.', reader.getInterfaceNames());
        char[][] enclosingTypeNames = enclosingTypeName == null ? null : new char[][] { enclosingTypeName };
        int modifiers = reader.getModifiers();
        switch (TypeDeclaration.kind(modifiers)) {
        case TypeDeclaration.CLASS_DECL:
            char[] superclass = replace('/', '.', reader.getSuperclassName());
            addClassDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces,
                    typeParameterSignatures, false);
            break;
        case TypeDeclaration.INTERFACE_DECL:
            addInterfaceDeclaration(modifiers, packageName, name, enclosingTypeNames, superinterfaces,
                    typeParameterSignatures, false);
            break;
        case TypeDeclaration.ENUM_DECL:
            superclass = replace('/', '.', reader.getSuperclassName());
            addEnumDeclaration(modifiers, packageName, name, enclosingTypeNames, superclass, superinterfaces,
                    false);
            break;
        case TypeDeclaration.ANNOTATION_TYPE_DECL:
            addAnnotationTypeDeclaration(modifiers, packageName, name, enclosingTypeNames, false);
            break;
        }

        // Look for references in class annotations
        IBinaryAnnotation[] annotations = reader.getAnnotations();
        if (annotations != null) {
            for (int a = 0, length = annotations.length; a < length; a++) {
                IBinaryAnnotation annotation = annotations[a];
                addBinaryAnnotation(annotation);
            }
        }
        long tagBits = reader.getTagBits() & TagBits.AllStandardAnnotationsMask;
        if (tagBits != 0) {
            addBinaryStandardAnnotations(tagBits);
        }

        int extraFlags = ExtraFlags.getExtraFlags(reader);

        // first reference all methods declarations and field declarations
        MethodInfo[] methods = (MethodInfo[]) reader.getMethods();
        boolean noConstructor = true;
        if (methods != null) {
            for (int i = 0, max = methods.length; i < max; i++) {
                MethodInfo method = methods[i];
                boolean isConstructor = method.isConstructor();
                char[] descriptor = method.getMethodDescriptor();
                char[][] parameterTypes = decodeParameterTypes(descriptor, isConstructor && isNestedType);
                char[] returnType = decodeReturnType(descriptor);
                char[][] exceptionTypes = replace('/', '.', method.getExceptionTypeNames());
                if (isConstructor) {
                    noConstructor = false;
                    char[] signature = method.getGenericSignature();
                    if (signature == null) {
                        if (reader.isNestedType() && ((modifiers & ClassFileConstants.AccStatic) == 0)) {
                            signature = removeFirstSyntheticParameter(descriptor);
                        } else {
                            signature = descriptor;
                        }
                    }
                    addConstructorDeclaration(name, parameterTypes == null ? 0 : parameterTypes.length,
                            signature, parameterTypes, method.getArgumentNames(), method.getModifiers(),
                            packageName, modifiers, exceptionTypes, extraFlags);
                } else {
                    if (!method.isClinit()) {
                        addMethodDeclaration(method.getSelector(), parameterTypes, returnType, exceptionTypes);
                    }
                }
                // look for references in method annotations
                annotations = method.getAnnotations();
                if (annotations != null) {
                    for (int a = 0, length = annotations.length; a < length; a++) {
                        IBinaryAnnotation annotation = annotations[a];
                        addBinaryAnnotation(annotation);
                    }
                }
                tagBits = method.getTagBits() & TagBits.AllStandardAnnotationsMask;
                if (tagBits != 0) {
                    addBinaryStandardAnnotations(tagBits);
                }
            }
        }
        if (noConstructor) {
            addDefaultConstructorDeclaration(className, packageName, modifiers, extraFlags);
        }
        FieldInfo[] fields = (FieldInfo[]) reader.getFields();
        if (fields != null) {
            for (int i = 0, max = fields.length; i < max; i++) {
                FieldInfo field = fields[i];
                char[] fieldName = field.getName();
                char[] fieldType = decodeFieldType(replace('/', '.', field.getTypeName()));
                addFieldDeclaration(fieldType, fieldName);
                // look for references in field annotations
                annotations = field.getAnnotations();
                if (annotations != null) {
                    for (int a = 0, length = annotations.length; a < length; a++) {
                        IBinaryAnnotation annotation = annotations[a];
                        addBinaryAnnotation(annotation);
                    }
                }
                tagBits = field.getTagBits() & TagBits.AllStandardAnnotationsMask;
                if (tagBits != 0) {
                    addBinaryStandardAnnotations(tagBits);
                }
            }
        }
        // record all references found inside the .class file
        extractReferenceFromConstantPool(contents, reader);
    } catch (ClassFormatException e) {
        // ignore
        this.document.removeAllIndexEntries();
        Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath()
                + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (RuntimeException e) {
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154
        // logging the entry that could not be indexed and continue with the next one
        // we remove all entries relative to the boggus document
        this.document.removeAllIndexEntries();
        Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath()
                + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$
    }
}