Example usage for org.eclipse.jdt.internal.core.search.indexing IIndexConstants INTERFACE_AND_ANNOTATION_SUFFIX

List of usage examples for org.eclipse.jdt.internal.core.search.indexing IIndexConstants INTERFACE_AND_ANNOTATION_SUFFIX

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core.search.indexing IIndexConstants INTERFACE_AND_ANNOTATION_SUFFIX.

Prototype

char INTERFACE_AND_ANNOTATION_SUFFIX

To view the source code for org.eclipse.jdt.internal.core.search.indexing IIndexConstants INTERFACE_AND_ANNOTATION_SUFFIX.

Click Source Link

Usage

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

License:Open Source License

/**
 * Returns a search pattern based on a given string pattern. The string patterns support '*' wild-cards.
 * The remaining parameters are used to narrow down the type of expected results.
 *
 * <br>/* ww  w. ja v a  2s . c o  m*/
 *   Examples:
 *   <ul>
 *       <li>search for case insensitive references to <code>Object</code>:
 *         <code>createSearchPattern("Object", IJavaSearchConstants.TYPE, IJavaSearchConstants.REFERENCES, false);</code></li>
 *     <li>search for case sensitive references to exact <code>Object()</code> constructor:
 *         <code>createSearchPattern("java.lang.Object()", IJavaSearchConstants.CONSTRUCTOR, IJavaSearchConstants.REFERENCES, true);</code></li>
 *     <li>search for implementers of <code>java.lang.Runnable</code>:
 *         <code>createSearchPattern("java.lang.Runnable", IJavaSearchConstants.TYPE, IJavaSearchConstants.IMPLEMENTORS, true);</code></li>
 *  </ul>
 * @param stringPattern the given pattern
 * <ul>
 *    <li>Type patterns have the following syntax:
 *       <p><b><code>[qualification '.']typeName ['&lt;' typeArguments '&gt;']</code></b></p>
 *         <p>Examples:</p>
 *         <ul>
 *          <li><code>java.lang.Object</code></li>
 *            <li><code>Runnable</code></li>
 *            <li><code>List&lt;String&gt;</code></li>
 *         </ul>
 *         <p>
 *         Type arguments can be specified to search for references to parameterized types
 *       using following syntax:</p><p>
 *       <b><code>'&lt;' { [ '?' {'extends'|'super'} ] type ( ',' [ '?' {'extends'|'super'} ] type )* | '?' } '&gt;'</code></b>
 *       </p><div style="font-style:italic;">
 *       Note that:
 *       <ul>
 *          <li>'*' is not valid inside type arguments definition &lt;&gt;</li>
 *          <li>'?' is treated as a wildcard when it is inside &lt;&gt; (i.e. it must be put on first position of the type argument)</li>
 *       </ul>
 *       </div>
 *    </li>
 *    <li>Method patterns have the following syntax:
 *       <p><b><code>[declaringType '.'] ['&lt;' typeArguments '&gt;'] methodName ['(' parameterTypes ')'] [returnType]</code></b></p>
 *         <p>Type arguments have the same syntax as explained in the type patterns section.</p>
 *         <p>Examples:</p>
 *         <ul>
 *            <li><code>java.lang.Runnable.run() void</code></li>
 *            <li><code>main(*)</code></li>
 *            <li><code>&lt;String&gt;toArray(String[])</code></li>
 *         </ul>
 *   </li>
 *    <li>Constructor patterns have the following syntax:
 *         <p><b><code>['&lt;' typeArguments '&gt;'] [declaringQualification '.'] typeName ['(' parameterTypes ')']</code></b></p>
 *         <p>Type arguments have the same syntax as explained in the type patterns section.</p>
 *         <p><i>Note that the constructor name should not be entered as it is always the same as the type name.</i></p>
 *         <p>Examples:</p>
 *         <ul>
 *            <li><code>java.lang.Object()</code></li>
 *            <li><code>Test(*)</code></li>
 *            <li><code>&lt;Exception&gt;Sample(Exception)</code></li>
 *         </ul>
 *       <br>
 *    </li>
 *    <li>Field patterns have the following syntax:
 *         <p><b><code>[declaringType '.'] fieldName [fieldType]</code></b></p>
 *         <p>Examples:</p>
 *         <ul>
 *            <li><code>java.lang.String.serialVersionUID long</code></li>
 *            <li><code>field*</code></li>
 *         </ul>
 *    </li>
 *    <li>Package patterns have the following syntax:
 *         <p><b><code>packageNameSegment {'.' packageNameSegment}</code></b></p>
 *         <p>Examples:</p>
 *         <ul>
 *            <li><code>java.lang</code></li>
 *            <li><code>org.e*.jdt.c*e</code></li>
 *         </ul>
 *    </li>
 * </ul>
 * @param searchFor determines the nature of the searched elements
 *   <ul>
 *    <li>{@link IJavaSearchConstants#CLASS}: only look for classes</li>
 *   <li>{@link IJavaSearchConstants#INTERFACE}: only look for interfaces</li>
 *    <li>{@link IJavaSearchConstants#ENUM}: only look for enumeration</li>
 *   <li>{@link IJavaSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li>
 *    <li>{@link IJavaSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li>
 *   <li>{@link IJavaSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li>
 *    <li>{@link IJavaSearchConstants#TYPE}: look for all types (i.e. classes, interfaces, enum and annotation types)</li>
 *   <li>{@link IJavaSearchConstants#FIELD}: look for fields</li>
 *   <li>{@link IJavaSearchConstants#METHOD}: look for methods</li>
 *   <li>{@link IJavaSearchConstants#CONSTRUCTOR}: look for constructors</li>
 *   <li>{@link IJavaSearchConstants#PACKAGE}: look for packages</li>
 *   </ul>
 * @param limitTo determines the nature of the expected matches
 *   <ul>
 *    <li>{@link IJavaSearchConstants#DECLARATIONS DECLARATIONS}: will search declarations matching
 *          with the corresponding element. In case the element is a method, declarations of matching
 *          methods in sub-types will also be found, allowing to find declarations of abstract methods, etc.<br>
 *          Note that additional flags {@link IJavaSearchConstants#IGNORE_DECLARING_TYPE IGNORE_DECLARING_TYPE} and
 *          {@link IJavaSearchConstants#IGNORE_RETURN_TYPE IGNORE_RETURN_TYPE} are ignored for string patterns.
 *          This is due to the fact that client may omit to define them in string pattern to have same behavior.
 *    </li>
 *       <li>{@link IJavaSearchConstants#REFERENCES REFERENCES}: will search references to the given element.</li>
 *       <li>{@link IJavaSearchConstants#ALL_OCCURRENCES ALL_OCCURRENCES}: will search for either declarations or
 *            references as specified above.
 *      </li>
 *       <li>{@link IJavaSearchConstants#IMPLEMENTORS IMPLEMENTORS}: for types, will find all types
 *            which directly implement/extend a given interface.
 *            Note that types may be only classes or only interfaces if {@link IJavaSearchConstants#CLASS CLASS} or
 *            {@link IJavaSearchConstants#INTERFACE INTERFACE} is respectively used instead of {@link IJavaSearchConstants#TYPE TYPE}.
 *      </li>
 *       <li>All other fine grain constants defined in the <b>limitTo</b> category
 *            of the {@link IJavaSearchConstants} are also accepted nature:
 *          <table border=0>
 *              <tr>
 *               <th align=left>Fine grain constant
 *               <th align=left>Meaning
 *              <tr>
 *               <td>{@link IJavaSearchConstants#FIELD_DECLARATION_TYPE_REFERENCE FIELD_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a field declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a local variable declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#PARAMETER_DECLARATION_TYPE_REFERENCE PARAMETER_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used as the type of a method parameter declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#SUPERTYPE_TYPE_REFERENCE SUPERTYPE_TYPE_REFERENCE}
 *               <td>Return only type references used as a super type or as a super interface.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#THROWS_CLAUSE_TYPE_REFERENCE THROWS_CLAUSE_TYPE_REFERENCE}
 *               <td>Return only type references used in a throws clause.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CAST_TYPE_REFERENCE CAST_TYPE_REFERENCE}
 *               <td>Return only type references used in a cast expression.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CATCH_TYPE_REFERENCE CATCH_TYPE_REFERENCE}
 *               <td>Return only type references used in a catch header.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#CLASS_INSTANCE_CREATION_TYPE_REFERENCE CLASS_INSTANCE_CREATION_TYPE_REFERENCE}
 *               <td>Return only type references used in class instance creation.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#RETURN_TYPE_REFERENCE RETURN_TYPE_REFERENCE}
 *               <td>Return only type references used as a method return type.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#IMPORT_DECLARATION_TYPE_REFERENCE IMPORT_DECLARATION_TYPE_REFERENCE}
 *               <td>Return only type references used in an import declaration.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#ANNOTATION_TYPE_REFERENCE ANNOTATION_TYPE_REFERENCE}
 *               <td>Return only type references used as an annotation.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#TYPE_ARGUMENT_TYPE_REFERENCE TYPE_ARGUMENT_TYPE_REFERENCE}
 *               <td>Return only type references used as a type argument in a parameterized type or a parameterized method.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#TYPE_VARIABLE_BOUND_TYPE_REFERENCE TYPE_VARIABLE_BOUND_TYPE_REFERENCE}
 *               <td>Return only type references used as a type variable bound.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#WILDCARD_BOUND_TYPE_REFERENCE WILDCARD_BOUND_TYPE_REFERENCE}
 *               <td>Return only type references used as a wildcard bound.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#INSTANCEOF_TYPE_REFERENCE INSTANCEOF_TYPE_REFERENCE}
 *               <td>Return only type references used as a type of an <code>instanceof</code> expression.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#SUPER_REFERENCE SUPER_REFERENCE}
 *               <td>Return only super field accesses or super method invocations (e.g. using the <code>super</code> qualifier).
 *              <tr>
 *               <td>{@link IJavaSearchConstants#QUALIFIED_REFERENCE QUALIFIED_REFERENCE}
 *               <td>Return only qualified field accesses or qualified method invocations.
 *              <tr>
 *               <td>{@link IJavaSearchConstants#THIS_REFERENCE THIS_REFERENCE}
 *               <td>Return only primary field accesses or primary method invocations (e.g. using the <code>this</code> qualifier).
 *              <tr>
 *               <td>{@link IJavaSearchConstants#IMPLICIT_THIS_REFERENCE IMPLICIT_THIS_REFERENCE}
 *               <td>Return only field accesses or method invocations without any qualification.
 *          </table>
 *      </li>
 *   </ul>
 * @param matchRule one of the following match rules
 *    <ul>
 *       <li>{@link #R_EXACT_MATCH}</li>
 *       <li>{@link #R_PREFIX_MATCH}</li>
 *       <li>{@link #R_PATTERN_MATCH}</li>
 *       <li>{@link #R_CAMELCASE_MATCH}</li>
 *       <li>{@link #R_CAMELCASE_SAME_PART_COUNT_MATCH}</li>
 *    </ul>
 *    , which may be also combined with one of the following flags:
 *    <ul>
 *       <li>{@link #R_CASE_SENSITIVE}</li>
 *       <li>{@link #R_ERASURE_MATCH}</li>
 *       <li>{@link #R_EQUIVALENT_MATCH}</li>
 *    </ul>
 *      For example,
 *      <ul>
 *         <li>{@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE}: if an exact
 *            and case sensitive match is requested,</li>
 *         <li>{@link #R_PREFIX_MATCH} if a case insensitive prefix match is requested</li>
 *         <li>{@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH}: if a case
 *            insensitive and erasure match is requested.</li>
 *      </ul>
 *    <p>Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} has no effect
 *    on non-generic types/methods search.</p>
 *    <p>
 *    Note also that the default behavior for generic types/methods search is to find exact matches.</p>
 * @return a search pattern on the given string pattern, or <code>null</code> if the string pattern is ill-formed
 */
public static SearchPattern createPattern(String stringPattern, int searchFor, int limitTo, int matchRule) {
    if (stringPattern == null || stringPattern.length() == 0)
        return null;

    if ((matchRule = validateMatchRule(stringPattern, matchRule)) == -1) {
        return null;
    }

    // Ignore additional nature flags
    limitTo &= ~(IJavaSearchConstants.IGNORE_DECLARING_TYPE + IJavaSearchConstants.IGNORE_RETURN_TYPE);

    switch (searchFor) {
    case IJavaSearchConstants.CLASS:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.CLASS_SUFFIX);
    case IJavaSearchConstants.CLASS_AND_INTERFACE:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.CLASS_AND_INTERFACE_SUFFIX);
    case IJavaSearchConstants.CLASS_AND_ENUM:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.CLASS_AND_ENUM_SUFFIX);
    case IJavaSearchConstants.INTERFACE:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.INTERFACE_SUFFIX);
    case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
        return createTypePattern(stringPattern, limitTo, matchRule,
                IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX);
    case IJavaSearchConstants.ENUM:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.ENUM_SUFFIX);
    case IJavaSearchConstants.ANNOTATION_TYPE:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.ANNOTATION_TYPE_SUFFIX);
    case IJavaSearchConstants.TYPE:
        return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.TYPE_SUFFIX);
    case IJavaSearchConstants.METHOD:
        return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, false/*not a constructor*/);
    case IJavaSearchConstants.CONSTRUCTOR:
        return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, true/*constructor*/);
    case IJavaSearchConstants.FIELD:
        return createFieldPattern(stringPattern, limitTo, matchRule);
    case IJavaSearchConstants.PACKAGE:
        return createPackagePattern(stringPattern, limitTo, matchRule);
    }
    return null;
}

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

License:Open Source License

boolean match(char patternTypeSuffix, int modifiers) {
    switch (patternTypeSuffix) {
    case IIndexConstants.CLASS_SUFFIX:
        return (modifiers & (Flags.AccAnnotation | Flags.AccInterface | Flags.AccEnum)) == 0;
    case IIndexConstants.CLASS_AND_INTERFACE_SUFFIX:
        return (modifiers & (Flags.AccAnnotation | Flags.AccEnum)) == 0;
    case IIndexConstants.CLASS_AND_ENUM_SUFFIX:
        return (modifiers & (Flags.AccAnnotation | Flags.AccInterface)) == 0;
    case IIndexConstants.INTERFACE_SUFFIX:
        return (modifiers & Flags.AccInterface) != 0;
    case IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX:
        return (modifiers & (Flags.AccInterface | Flags.AccAnnotation)) != 0;
    case IIndexConstants.ENUM_SUFFIX:
        return (modifiers & Flags.AccEnum) != 0;
    case IIndexConstants.ANNOTATION_TYPE_SUFFIX:
        return (modifiers & Flags.AccAnnotation) != 0;
    }//from  w w  w .  j  a  va 2 s  .  com
    return true;
}

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 ww  w. j  ava2 s . 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)./*  w w  w.  j  a  v a2  s .c  o  m*/
 *
 * @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.BasicSearchEngine.java

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope using  a case sensitive exact match
 * with the given qualified names and type names.
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[][], char[][], org.eclipse.jdt.core.search.IJavaSearchScope,
 * org.eclipse.jdt.core.search.TypeNameRequestor, int, org.eclipse.core.runtime.IProgressMonitor)
 *    for detailed comment/*from  w w w. j  a  va 2s . co m*/
 */
public void searchAllTypeNames(final char[][] qualifications, final char[][] typeNames, final int matchRule,
        int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor,
        int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException {

    // Debug
    if (VERBOSE) {
        Util.verbose(
                "BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
        Util.verbose("   - package name: " + (qualifications == null ? "null"
                : new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type name: "
                + (typeNames == null ? "null" : new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - match rule: " + getMatchRuleString(matchRule)); //$NON-NLS-1$
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }

    // Create pattern
    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 MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames,
            typeSuffix, matchRule);

    // 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
            QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) 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 qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0
                        : record.qualification.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[qualificationLength + nameLength];
                int pos = 0;
                if (qualificationLength > 0) {
                    System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[qualificationLength - 1] = '/';
                    pos += qualificationLength;
                }
                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);
                }
            }
            nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames,
                    documentPath, accessRestriction);
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 100);
        }
        // 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, 100));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0, length = copies.length; i < length; i++) {
                ICompilationUnit workingCopy = copies[i];
                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;
                        char[] qualification = packageDeclaration;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                            qualification = CharOperation.concat(qualification, parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        char suffix = IIndexConstants.TYPE_SUFFIX;
                        if (type.isClass()) {
                            suffix = IIndexConstants.CLASS_SUFFIX;
                        } else if (type.isInterface()) {
                            suffix = IIndexConstants.INTERFACE_SUFFIX;
                        } else if (type.isEnum()) {
                            suffix = IIndexConstants.ENUM_SUFFIX;
                        } else if (type.isAnnotation()) {
                            suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
                        }
                        if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification,
                                simpleName, suffix, matchRule))) {
                            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) {
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        packageDeclaration, typeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                            typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                // compute enclosing type names
                                char[] qualification = packageDeclaration;
                                TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                while (enclosing != null) {
                                    qualification = CharOperation.concat(qualification, enclosing.name, '.');
                                    enclosingTypeNames = CharOperation
                                            .arrayConcat(new char[][] { enclosing.name }, enclosingTypeNames);
                                    if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                        enclosing = enclosing.enclosingType;
                                    } else {
                                        enclosing = null;
                                    }
                                }
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        qualification, memberTypeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                            packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames,
                                            path, null);
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}

From source file:org.eclipse.che.jdt.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 w  ww .j  ava 2  s. 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, 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-2$
        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, 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];
                        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:org.eclipse.che.jdt.internal.core.search.BasicSearchEngine.java

License:Open Source License

/**
 * Searches for all top-level types and member types in the given scope using  a case sensitive exact match
 * with the given qualified names and type names.
 *
 * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[][], char[][], org.eclipse.jdt.core.search.IJavaSearchScope,
 * org.eclipse.jdt.core.search.TypeNameRequestor, int, IProgressMonitor)
 * for detailed comment//w w  w  .j av  a2 s.  c  om
 */
public void searchAllTypeNames(final char[][] qualifications, final char[][] typeNames, final int matchRule,
        int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor,
        int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException {

    // Debug
    if (VERBOSE) {
        Util.verbose("BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, "
                + "IRestrictedAccessTypeRequestor," + " " + "int, IProgressMonitor)"); //$NON-NLS-3$
        Util.verbose("   - package name: " + (qualifications == null ? "null"
                : new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - type name: "
                + (typeNames == null ? "null" : new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
        Util.verbose("   - match rule: " + getMatchRuleString(matchRule)); //$NON-NLS-1$
        Util.verbose("   - search for: " + searchFor); //$NON-NLS-1$
        Util.verbose("   - scope: " + scope); //$NON-NLS-1$
    }

    // Create pattern
    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 MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames,
            typeSuffix, matchRule);

    // 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
            QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) 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 qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0
                        : record.qualification.length + 1;
                int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
                char[] path = new char[qualificationLength + nameLength];
                int pos = 0;
                if (qualificationLength > 0) {
                    System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1);
                    CharOperation.replace(path, '.', '/');
                    path[qualificationLength - 1] = '/';
                    pos += qualificationLength;
                }
                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);
                }
            }
            nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames,
                    documentPath, accessRestriction);
            return true;
        }
    };

    try {
        if (progressMonitor != null) {
            progressMonitor.beginTask(Messages.engine_searching, 100);
        }
        // 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, 100));

        // add type names from working copies
        if (copies != null) {
            for (int i = 0, length = copies.length; i < length; i++) {
                ICompilationUnit workingCopy = copies[i];
                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;
                        char[] qualification = packageDeclaration;
                        if (parent instanceof IType) {
                            char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.')
                                    .toCharArray();
                            enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
                            qualification = CharOperation.concat(qualification, parentQualifiedName);
                        } else {
                            enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                        }
                        char[] simpleName = type.getElementName().toCharArray();
                        char suffix = IIndexConstants.TYPE_SUFFIX;
                        if (type.isClass()) {
                            suffix = IIndexConstants.CLASS_SUFFIX;
                        } else if (type.isInterface()) {
                            suffix = IIndexConstants.INTERFACE_SUFFIX;
                        } else if (type.isEnum()) {
                            suffix = IIndexConstants.ENUM_SUFFIX;
                        } else if (type.isAnnotation()) {
                            suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
                        }
                        if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification,
                                simpleName, suffix, matchRule))) {
                            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) {
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        packageDeclaration, typeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration,
                                            typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
                                }
                                return true;
                            }

                            public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
                                // compute enclosing type names
                                char[] qualification = packageDeclaration;
                                TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
                                char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
                                while (enclosing != null) {
                                    qualification = CharOperation.concat(qualification, enclosing.name, '.');
                                    enclosingTypeNames = CharOperation
                                            .arrayConcat(new char[][] { enclosing.name }, enclosingTypeNames);
                                    if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
                                        enclosing = enclosing.enclosingType;
                                    } else {
                                        enclosing = null;
                                    }
                                }
                                SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(
                                        qualification, memberTypeDeclaration.name,
                                        convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)),
                                        matchRule);
                                if (pattern.matchesDecodedKey(decodedPattern)) {
                                    nameRequestor.acceptType(memberTypeDeclaration.modifiers,
                                            packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames,
                                            path, null);
                                }
                                return true;
                            }
                        }
                        parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
                    }
                }
            }
        }
    } finally {
        if (progressMonitor != null) {
            progressMonitor.done();
        }
    }
}