Example usage for org.eclipse.jdt.internal.compiler ExtraFlags getExtraFlags

List of usage examples for org.eclipse.jdt.internal.compiler ExtraFlags getExtraFlags

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler ExtraFlags getExtraFlags.

Prototype

public static int getExtraFlags(TypeDeclaration typeDeclaration) 

Source Link

Usage

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

License:Open Source License

public void searchAllConstructorDeclarations(final char[] packageName, final char[] typeName,
        final int typeMatchRule, IJavaSearchScope scope,
        final IRestrictedAccessConstructorRequestor nameRequestor, int waitingPolicy,
        IProgressMonitor progressMonitor) throws JavaModelException {

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

    final int pkgMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    final char NoSuffix = IIndexConstants.TYPE_SUFFIX; // Used as TYPE_SUFFIX has no effect in method #match(char, char[] , int, char[], int , int, char[], char[])

    // Debug//from w  w  w  . j  a  v a 2 s.c o m
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
        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("   - scope: " + scope); //$NON-NLS-1$
    }
    if (validatedTypeMatchRule == -1)
        return; // invalid match rule => return no results

    // Create pattern
    final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern(packageName, typeName,
            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
            ConstructorDeclarationPattern record = (ConstructorDeclarationPattern) indexRecord;

            if ((record.extraFlags & ExtraFlags.IsMemberType) != 0) {
                return true; // filter out member classes
            }
            if ((record.extraFlags & ExtraFlags.IsLocalType) != 0) {
                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.declaringPackageName == null || record.declaringPackageName.length == 0)
                        ? 0
                        : record.declaringPackageName.length + 1;
                int nameLength = record.declaringSimpleName == null ? 0 : record.declaringSimpleName.length;
                char[] path = new char[pkgLength + nameLength];
                int pos = 0;
                if (pkgLength > 0) {
                    System.arraycopy(record.declaringPackageName, 0, path, pos, pkgLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[pkgLength - 1] = '/';
                    pos += pkgLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            nameRequestor.acceptConstructor(record.modifiers, record.declaringSimpleName, record.parameterCount,
                    record.signature, record.parameterTypes, record.parameterNames,
                    record.declaringTypeModifiers, record.declaringPackageName, record.extraFlags, 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];
                        char[] simpleName = type.getElementName().toCharArray();
                        if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule,
                                0/*no kind*/, packageDeclaration, simpleName) && !type.isMember()) {

                            int extraFlags = ExtraFlags.getExtraFlags(type);

                            boolean hasConstructor = false;

                            IMethod[] methods = type.getMethods();
                            for (int k = 0; k < methods.length; k++) {
                                IMethod method = methods[k];
                                if (method.isConstructor()) {
                                    hasConstructor = true;

                                    String[] stringParameterNames = method.getParameterNames();
                                    String[] stringParameterTypes = method.getParameterTypes();
                                    int length = stringParameterNames.length;
                                    char[][] parameterNames = new char[length][];
                                    char[][] parameterTypes = new char[length][];
                                    for (int l = 0; l < length; l++) {
                                        parameterNames[l] = stringParameterNames[l].toCharArray();
                                        parameterTypes[l] = Signature.toCharArray(Signature
                                                .getTypeErasure(stringParameterTypes[l]).toCharArray());
                                    }

                                    nameRequestor.acceptConstructor(method.getFlags(), simpleName,
                                            parameterNames.length, null, // signature is not used for source type
                                            parameterTypes, parameterNames, type.getFlags(), packageDeclaration,
                                            extraFlags, path, null);
                                }
                            }

                            if (!hasConstructor) {
                                nameRequestor.acceptConstructor(Flags.AccPublic, simpleName, -1, null, // signature is not used for source type
                                        CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, type.getFlags(),
                                        packageDeclaration, extraFlags, 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 AllConstructorDeclarationsVisitor extends ASTVisitor {
                            private TypeDeclaration[] declaringTypes = new TypeDeclaration[0];
                            private int declaringTypesPtr = -1;

                            private void endVisit(TypeDeclaration typeDeclaration) {
                                if (!hasConstructor(typeDeclaration) && typeDeclaration.enclosingType == null) {

                                    if (match(NoSuffix, packageName, pkgMatchRule, typeName,
                                            validatedTypeMatchRule, 0/*no kind*/, packageDeclaration,
                                            typeDeclaration.name)) {
                                        nameRequestor.acceptConstructor(Flags.AccPublic, typeName, -1, null, // signature is not used for source type
                                                CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR,
                                                typeDeclaration.modifiers, packageDeclaration,
                                                ExtraFlags.getExtraFlags(typeDeclaration), path, null);
                                    }
                                }

                                this.declaringTypes[this.declaringTypesPtr] = null;
                                this.declaringTypesPtr--;
                            }

                            public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
                                endVisit(typeDeclaration);
                            }

                            public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
                                endVisit(memberTypeDeclaration);
                            }

                            private boolean hasConstructor(TypeDeclaration typeDeclaration) {
                                AbstractMethodDeclaration[] methods = typeDeclaration.methods;
                                int length = methods == null ? 0 : methods.length;
                                for (int j = 0; j < length; j++) {
                                    if (methods[j].isConstructor()) {
                                        return true;
                                    }
                                }

                                return false;
                            }

                            public boolean visit(ConstructorDeclaration constructorDeclaration,
                                    ClassScope classScope) {
                                TypeDeclaration typeDeclaration = this.declaringTypes[this.declaringTypesPtr];
                                if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule,
                                        0/*no kind*/, packageDeclaration, typeDeclaration.name)) {
                                    Argument[] arguments = constructorDeclaration.arguments;
                                    int length = arguments == null ? 0 : arguments.length;
                                    char[][] parameterNames = new char[length][];
                                    char[][] parameterTypes = new char[length][];
                                    for (int l = 0; l < length; l++) {
                                        Argument argument = arguments[l];
                                        parameterNames[l] = argument.name;
                                        if (argument.type instanceof SingleTypeReference) {
                                            parameterTypes[l] = ((SingleTypeReference) argument.type).token;
                                        } else {
                                            parameterTypes[l] = CharOperation.concatWith(
                                                    ((QualifiedTypeReference) argument.type).tokens, '.');
                                        }
                                    }

                                    TypeDeclaration enclosing = typeDeclaration.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;
                                        }
                                    }

                                    nameRequestor.acceptConstructor(constructorDeclaration.modifiers, typeName,
                                            parameterNames.length, null, // signature is not used for source type
                                            parameterTypes, parameterNames, typeDeclaration.modifiers,
                                            packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path,
                                            null);
                                }
                                return false; // no need to find constructors from local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false;
                            }

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

                            public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
                                return visit(typeDeclaration);
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
                                return visit(memberTypeDeclaration);
                            }
                        }
                        parsedUnit.traverse(new AllConstructorDeclarationsVisitor(), 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 .java  2 s.  c  o m
        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$
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.BasicSearchEngine.java

License:Open Source License

public void searchAllConstructorDeclarations(final char[] packageName, final char[] typeName,
        final int typeMatchRule, IJavaSearchScope scope,
        final IRestrictedAccessConstructorRequestor nameRequestor, int waitingPolicy,
        IProgressMonitor progressMonitor) throws JavaModelException {

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

    final int pkgMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    final char NoSuffix = IIndexConstants.TYPE_SUFFIX; // Used as TYPE_SUFFIX has no effect in method #match(char, char[] , int, char[], int , int, char[], char[])

    // Debug/*from   w w w .j  a v  a2  s . c  om*/
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
        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("   - scope: " + scope); //$NON-NLS-1$
    }
    if (validatedTypeMatchRule == -1)
        return; // invalid match rule => return no results

    // Create pattern
    final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern(packageName, typeName,
            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
            ConstructorDeclarationPattern record = (ConstructorDeclarationPattern) indexRecord;

            if ((record.extraFlags & ExtraFlags.IsMemberType) != 0) {
                return true; // filter out member classes
            }
            if ((record.extraFlags & ExtraFlags.IsLocalType) != 0) {
                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.declaringPackageName == null || record.declaringPackageName.length == 0)
                        ? 0
                        : record.declaringPackageName.length + 1;
                int nameLength = record.declaringSimpleName == null ? 0 : record.declaringSimpleName.length;
                char[] path = new char[pkgLength + nameLength];
                int pos = 0;
                if (pkgLength > 0) {
                    System.arraycopy(record.declaringPackageName, 0, path, pos, pkgLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[pkgLength - 1] = '/';
                    pos += pkgLength;
                }
                if (nameLength > 0) {
                    System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength);
                    pos += nameLength;
                }
                // Update access restriction if path is not empty
                if (pos > 0) {
                    accessRestriction = access.getViolatedRestriction(path);
                }
            }
            nameRequestor.acceptConstructor(record.modifiers, record.declaringSimpleName, record.parameterCount,
                    record.signature, record.parameterTypes, record.parameterNames,
                    record.declaringTypeModifiers, record.declaringPackageName, record.extraFlags, 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, javaProject), // 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];
                        char[] simpleName = type.getElementName().toCharArray();
                        if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule,
                                0/*no kind*/, packageDeclaration, simpleName) && !type.isMember()) {

                            int extraFlags = ExtraFlags.getExtraFlags(type);

                            boolean hasConstructor = false;

                            IMethod[] methods = type.getMethods();
                            for (int k = 0; k < methods.length; k++) {
                                IMethod method = methods[k];
                                if (method.isConstructor()) {
                                    hasConstructor = true;

                                    String[] stringParameterNames = method.getParameterNames();
                                    String[] stringParameterTypes = method.getParameterTypes();
                                    int length = stringParameterNames.length;
                                    char[][] parameterNames = new char[length][];
                                    char[][] parameterTypes = new char[length][];
                                    for (int l = 0; l < length; l++) {
                                        parameterNames[l] = stringParameterNames[l].toCharArray();
                                        parameterTypes[l] = Signature.toCharArray(Signature
                                                .getTypeErasure(stringParameterTypes[l]).toCharArray());
                                    }

                                    nameRequestor.acceptConstructor(method.getFlags(), simpleName,
                                            parameterNames.length, null, // signature is not used for source type
                                            parameterTypes, parameterNames, type.getFlags(), packageDeclaration,
                                            extraFlags, path, null);
                                }
                            }

                            if (!hasConstructor) {
                                nameRequestor.acceptConstructor(Flags.AccPublic, simpleName, -1, null, // signature is not used for source type
                                        CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, type.getFlags(),
                                        packageDeclaration, extraFlags, 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 AllConstructorDeclarationsVisitor extends ASTVisitor {
                            private TypeDeclaration[] declaringTypes = new TypeDeclaration[0];
                            private int declaringTypesPtr = -1;

                            private void endVisit(TypeDeclaration typeDeclaration) {
                                if (!hasConstructor(typeDeclaration) && typeDeclaration.enclosingType == null) {

                                    if (match(NoSuffix, packageName, pkgMatchRule, typeName,
                                            validatedTypeMatchRule, 0/*no kind*/, packageDeclaration,
                                            typeDeclaration.name)) {
                                        nameRequestor.acceptConstructor(Flags.AccPublic, typeName, -1, null, // signature is not used for source type
                                                CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR,
                                                typeDeclaration.modifiers, packageDeclaration,
                                                ExtraFlags.getExtraFlags(typeDeclaration), path, null);
                                    }
                                }

                                this.declaringTypes[this.declaringTypesPtr] = null;
                                this.declaringTypesPtr--;
                            }

                            public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
                                endVisit(typeDeclaration);
                            }

                            public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
                                endVisit(memberTypeDeclaration);
                            }

                            private boolean hasConstructor(TypeDeclaration typeDeclaration) {
                                AbstractMethodDeclaration[] methods = typeDeclaration.methods;
                                int length = methods == null ? 0 : methods.length;
                                for (int j = 0; j < length; j++) {
                                    if (methods[j].isConstructor()) {
                                        return true;
                                    }
                                }

                                return false;
                            }

                            public boolean visit(ConstructorDeclaration constructorDeclaration,
                                    ClassScope classScope) {
                                TypeDeclaration typeDeclaration = this.declaringTypes[this.declaringTypesPtr];
                                if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule,
                                        0/*no kind*/, packageDeclaration, typeDeclaration.name)) {
                                    Argument[] arguments = constructorDeclaration.arguments;
                                    int length = arguments == null ? 0 : arguments.length;
                                    char[][] parameterNames = new char[length][];
                                    char[][] parameterTypes = new char[length][];
                                    for (int l = 0; l < length; l++) {
                                        Argument argument = arguments[l];
                                        parameterNames[l] = argument.name;
                                        if (argument.type instanceof SingleTypeReference) {
                                            parameterTypes[l] = ((SingleTypeReference) argument.type).token;
                                        } else {
                                            parameterTypes[l] = CharOperation.concatWith(
                                                    ((QualifiedTypeReference) argument.type).tokens, '.');
                                        }
                                    }

                                    TypeDeclaration enclosing = typeDeclaration.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;
                                        }
                                    }

                                    nameRequestor.acceptConstructor(constructorDeclaration.modifiers, typeName,
                                            parameterNames.length, null, // signature is not used for source type
                                            parameterTypes, parameterNames, typeDeclaration.modifiers,
                                            packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path,
                                            null);
                                }
                                return false; // no need to find constructors from local/anonymous type
                            }

                            public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
                                return false;
                            }

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

                            public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
                                return visit(typeDeclaration);
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
                                return visit(memberTypeDeclaration);
                            }
                        }
                        parsedUnit.traverse(new AllConstructorDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
                if (progressMonitor != null) {
                    if (progressMonitor.isCanceled())
                        throw new OperationCanceledException();
                    progressMonitor.worked(1);
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.indexing.BinaryIndexer.java

License:Open Source License

public void indexDocument() {
    try {/*from  w  w w .  j  a  v a 2 s .  co m*/
        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 "
                + "again" + "st the .class file vendor"); //$NON-NLS-2$ //$NON-NLS-2$
    }
}