Example usage for org.eclipse.jdt.core IType getParent

List of usage examples for org.eclipse.jdt.core IType getParent

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType getParent.

Prototype

IJavaElement getParent();

Source Link

Document

Returns the element directly containing this element, or null if this element has no parent.

Usage

From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java

License:Open Source License

private String getVariableSubstitution(IMember context, String variableName) throws JavaModelException {
    IType type;
    if (context instanceof IMethod) {
        String subst = getMethodSubstitions((IMethod) context).getSubstitution(variableName);
        if (subst != null) {
            return subst;
        }//from  w  w w  .  j  ava2  s  .com
        type = context.getDeclaringType();
    } else {
        type = (IType) context;
    }
    String subst = getTypeSubstitions(type).getSubstitution(variableName);
    if (subst != null) {
        return subst;
    }
    IJavaElement parent = type.getParent();
    if (parent instanceof IMethod) {
        return getVariableSubstitution((IMethod) parent, variableName);
    } else if (type.getDeclaringType() != null) {
        return getVariableSubstitution(type.getDeclaringType(), variableName);
    }
    return variableName; // not a type variable
}

From source file:at.bestsolution.fxide.jdt.corext.util.MethodOverrideTester.java

License:Open Source License

private String getVariableErasure(IMember context, String variableName) throws JavaModelException {
    IType type;
    if (context instanceof IMethod) {
        String subst = getMethodSubstitions((IMethod) context).getErasure(variableName);
        if (subst != null) {
            return subst;
        }/*from   www .  java 2 s  .  co m*/
        type = context.getDeclaringType();
    } else {
        type = (IType) context;
    }
    String subst = getTypeSubstitions(type).getErasure(variableName);
    if (subst != null) {
        return subst;
    }
    IJavaElement parent = type.getParent();
    if (parent instanceof IMethod) {
        return getVariableErasure((IMethod) parent, variableName);
    } else if (type.getDeclaringType() != null) {
        return getVariableErasure(type.getDeclaringType(), variableName);
    }
    return variableName; // not a type variable
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a type. Considers the T_* flags.
 *
 * @param type the element to render/*w ww .  j ava 2s.c  o  m*/
 * @param flags the rendering flags. Flags with names starting with 'T_' are considered.
 */
public void appendTypeLabel(IType type, long flags) {

    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) {
        IPackageFragment pack = type.getPackageFragment();
        if (!pack.isDefaultPackage()) {
            appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
    }
    IJavaElement parent = type.getParent();
    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) {
        IType declaringType = type.getDeclaringType();
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
        int parentType = parent.getElementType();
        if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                || parentType == IJavaElement.INITIALIZER) { // anonymous or local
            appendElementLabel(parent, 0);
            fBuffer.append('.');
        }
    }

    String typeName;
    boolean isAnonymous = false;
    if (type.isLambda()) {
        typeName = "() -> {...}"; //$NON-NLS-1$
        try {
            String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
            if (superInterfaceSignatures.length > 0) {
                typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]);
            }
        } catch (JavaModelException e) {
            //ignore
        }

    } else {
        typeName = getElementName(type);
        try {
            isAnonymous = type.isAnonymous();
        } catch (JavaModelException e1) {
            // should not happen, but let's play safe:
            isAnonymous = typeName.length() == 0;
        }
        if (isAnonymous) {
            try {
                if (parent instanceof IField && type.isEnum()) {
                    typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
                } else {
                    String supertypeName = null;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        String supertypeSignature = type.getSuperclassTypeSignature();
                        if (supertypeSignature != null) {
                            supertypeName = getSimpleTypeName(type, supertypeSignature);
                        }
                    }
                    if (supertypeName == null) {
                        typeName = JavaUIMessages.JavaElementLabels_anonym;
                    } else {
                        typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName);
                    }
                }
            } catch (JavaModelException e) {
                //ignore
                typeName = JavaUIMessages.JavaElementLabels_anonym;
            }
        }
    }
    fBuffer.append(typeName);

    if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) {
        if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) {
            BindingKey key = new BindingKey(type.getKey());
            if (key.isParameterizedType()) {
                String[] typeArguments = key.getTypeArguments();
                appendTypeArgumentSignaturesLabel(type, typeArguments, flags);
            } else {
                String[] typeParameters = Signature.getTypeParameters(key.toSignature());
                appendTypeParameterSignaturesLabel(typeParameters, flags);
            }
        } else if (type.exists()) {
            try {
                appendTypeParametersLabels(type.getTypeParameters(), flags);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    }

    // category
    if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) {
        try {
            appendCategoryLabel(type, flags);
        } catch (JavaModelException e) {
            // ignore
        }
    }

    // post qualification
    if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
        IType declaringType = type.getDeclaringType();
        if (declaringType == null && type.isBinary() && isAnonymous) {
            // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type
            String tqn = type.getTypeQualifiedName();
            int lastDollar = tqn.lastIndexOf('$');
            if (lastDollar != 1) {
                String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$
                declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType();
                try {
                    ISourceRange typeSourceRange = type.getSourceRange();
                    if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) {
                        IJavaElement realParent = declaringType.getTypeRoot()
                                .getElementAt(typeSourceRange.getOffset() - 1);
                        if (realParent != null) {
                            parent = realParent;
                        }
                    }
                } catch (JavaModelException e) {
                    // ignore
                }
            }
        }
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            int parentType = parent.getElementType();
            if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                    || parentType == IJavaElement.INITIALIZER) { // anonymous or local
                fBuffer.append('.');
                appendElementLabel(parent, 0);
            }
        } else {
            appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
        }
        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }
    }
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

public static String getFullyQualifiedName(IType type, boolean includeOccurrenceCount) {
    IType declaring = type;
    String qualifiedName = "";
    try {//  w w  w .j ava  2s.co m
        while (declaring != null) {
            if (declaring.isAnonymous()) {
                qualifiedName = declaring.getOccurrenceCount() + "" + qualifiedName;
            } else {
                qualifiedName = declaring.getElementName() + qualifiedName;
                if (includeOccurrenceCount) {
                    IJavaElement parent = declaring.getParent();
                    if (parent instanceof IMember && !(parent instanceof IType)) {
                        qualifiedName = type.getOccurrenceCount() + qualifiedName;
                    }
                }
            }
            IJavaElement parent = declaring.getParent();
            while (parent != null) {
                if (parent instanceof IType) {
                    declaring = (IType) parent;
                    break;
                }
                parent = parent.getParent();
            }
            if (parent != null) {
                qualifiedName = "$" + qualifiedName;
            } else {
                declaring = null;
            }
        }
    } catch (JavaModelException e) {
        return type.getFullyQualifiedName();
    }
    String pack = type.getPackageFragment().getElementName();
    if (!"".equals(pack))
        pack = pack + ".";
    qualifiedName = pack + qualifiedName;
    return qualifiedName;
}

From source file:ca.uvic.chisel.javasketch.ui.internal.presentation.TraceThreadLabelProvider.java

License:Open Source License

@Override
public String getText(Object element) {
    try {/*from w  w w . j a v  a  2 s  .  c  om*/
        IJavaElement je = null;

        if (element instanceof ICall) {
            IMessage target = ((ICall) element).getTarget();
            if (target != null) {
                je = JavaSearchUtils.findElement(target.getActivation(), new NullProgressMonitor());
            }
        } else if (element instanceof IThrow) {
            return "Exception";
        } else if (element instanceof IReply) {
            String sig = ((IReply) element).getActivation().getMethod().getSignature();
            return Signature.getSimpleName(Signature.toString(Signature.getReturnType(sig)));
        } else if (element instanceof ITraceModel) {
            je = JavaSearchUtils.findElement((ITraceModel) element, new NullProgressMonitor());
        }
        if (je != null) {
            if (je instanceof IType) {
                IType type = (IType) je;
                //qualify with all the parent type names
                String name = type.getElementName();

                if (type.isAnonymous()) {
                    name = type.getTypeQualifiedName();
                } else if (type.getOccurrenceCount() > 1) {
                    name = type.getOccurrenceCount() + name;
                }
                IJavaElement parent = type.getParent();
                while (parent != null) {
                    if (parent instanceof IType) {
                        IType pt = (IType) parent;
                        int occurrence = pt.getOccurrenceCount();
                        if (pt.isAnonymous()) {
                            name = occurrence + "$" + name;
                        } else {
                            name = ((occurrence > 1) ? occurrence : "") + pt.getElementName() + "$" + name;
                        }
                    }
                    parent = parent.getParent();
                }
                return name;
            }
            return workbenchLabelProvider.getText(je);
        } else if (element instanceof ITraceModel) {
            return uresolvedModelElement((ITraceModel) element);
        }
    } catch (InterruptedException e) {
    } catch (CoreException e) {
    } catch (Exception e) {
    }
    return (element != null) ? element.toString() : "";
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceParticipant.java

License:Open Source License

@Override
protected boolean initialize(Object element) {
    if (sIgnore) {
        return false;
    }/* w  w  w . j  av  a2 s. c  o m*/

    if (element instanceof IField) {
        IField field = (IField) element;
        IType declaringType = field.getDeclaringType();
        if (declaringType != null) {
            if (R_CLASS.equals(declaringType.getParent().getElementName())) {
                String typeName = declaringType.getElementName();
                mType = ResourceType.getEnum(typeName);
                if (mType != null) {
                    mUpdateReferences = getArguments().getUpdateReferences();
                    mFolderType = AdtUtils.getFolderTypeFor(mType);
                    IJavaProject javaProject = (IJavaProject) field.getAncestor(IJavaElement.JAVA_PROJECT);
                    mProject = javaProject.getProject();
                    mOldName = field.getElementName();
                    mNewName = getArguments().getNewName();
                    mFieldRefactoring = null;
                    mRenamedFile = null;
                    createXmlSearchPatterns();
                    return true;
                }
            }
        }

        return false;
    } else if (element instanceof IFile) {
        IFile file = (IFile) element;
        mProject = file.getProject();
        if (BaseProjectHelper.isAndroidProject(mProject)) {
            IPath path = file.getFullPath();
            int segments = path.segmentCount();
            if (segments == 4 && path.segment(1).equals(FD_RES)) {
                String parentName = file.getParent().getName();
                mFolderType = ResourceFolderType.getFolderType(parentName);
                if (mFolderType != null && mFolderType != ResourceFolderType.VALUES) {
                    mType = AdtUtils.getResourceTypeFor(mFolderType);
                    if (mType != null) {
                        mUpdateReferences = getArguments().getUpdateReferences();
                        mProject = file.getProject();
                        mOldName = AdtUtils.stripAllExtensions(file.getName());
                        mNewName = AdtUtils.stripAllExtensions(getArguments().getNewName());
                        mRenamedFile = file;
                        createXmlSearchPatterns();

                        mFieldRefactoring = null;
                        IField field = getResourceField(mProject, mType, mOldName);
                        if (field != null) {
                            mFieldRefactoring = createFieldRefactoring(field);
                        } else {
                            // no corresponding field; aapt has not run yet. Perhaps user has
                            // turned off auto build.
                            mFieldRefactoring = null;
                        }

                        return true;
                    }
                }
            }
        }
    } else if (element instanceof String) {
        String uri = (String) element;
        if (uri.startsWith(PREFIX_RESOURCE_REF) && !uri.startsWith(ANDROID_PREFIX)) {
            RenameResourceProcessor processor = (RenameResourceProcessor) getProcessor();
            mProject = processor.getProject();
            mType = processor.getType();
            mFolderType = AdtUtils.getFolderTypeFor(mType);
            mOldName = processor.getCurrentName();
            mNewName = processor.getNewName();
            assert uri.endsWith(mOldName) && uri.contains(mType.getName()) : uri;
            mUpdateReferences = getArguments().getUpdateReferences();
            if (mNewName.isEmpty()) {
                mUpdateReferences = false;
            }
            mRenamedFile = null;
            createXmlSearchPatterns();
            mFieldRefactoring = null;
            if (!mNewName.isEmpty()) {
                IField field = getResourceField(mProject, mType, mOldName);
                if (field != null) {
                    mFieldRefactoring = createFieldRefactoring(field);
                }
            }

            return true;
        }
    }

    return false;
}

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

License:Open Source License

/**
 * Returns the enclosing type names of the given type.
 *///from ww  w  .  j a va 2s  .  c  om
private static char[][] enclosingTypeNames(IType type) {
    IJavaElement parent = type.getParent();
    switch (parent.getElementType()) {
    case IJavaElement.CLASS_FILE:
        // For a binary type, the parent is not the enclosing type, but the declaring type is.
        // (see bug 20532  Declaration of member binary type not found)
        IType declaringType = type.getDeclaringType();
        if (declaringType == null)
            return CharOperation.NO_CHAR_CHAR;
        return CharOperation.arrayConcat(enclosingTypeNames(declaringType),
                declaringType.getElementName().toCharArray());
    case IJavaElement.COMPILATION_UNIT:
        return CharOperation.NO_CHAR_CHAR;
    case IJavaElement.FIELD:
    case IJavaElement.INITIALIZER:
    case IJavaElement.METHOD:
        IType declaringClass = ((IMember) parent).getDeclaringType();
        return CharOperation.arrayConcat(enclosingTypeNames(declaringClass),
                new char[][] { declaringClass.getElementName().toCharArray(), IIndexConstants.ONE_STAR });
    case IJavaElement.TYPE:
        return CharOperation.arrayConcat(enclosingTypeNames((IType) parent),
                parent.getElementName().toCharArray());
    default:
        return null;
    }
}

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

License:Open Source License

private boolean isPrimaryType(String name, IType type, boolean partialMatch) {
    /*/*from   w w  w . jav  a 2  s. com*/
     * Please have a look at: NameLookup#NameLookup
     * The HashTable this.typesInWorkingCopies contains values which are HashTables themselves.
     * The values of these HashTables are either of IType or IType[].
     * These values are types belonging to a compilation unit. Please check:
     * CompilationUnit#getTypes().
     * Therefore the parents of these types would be compilation units.
     */
    ICompilationUnit cu = (ICompilationUnit) type.getParent();
    String cuName = cu.getElementName().substring(0, cu.getElementName().lastIndexOf('.'));
    if (partialMatch) {
        return cuName.regionMatches(0, name, 0, name.length());
    } else {
        return cuName.equals(name);
    }
}

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

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

From source file:com.codenvy.ide.ext.java.server.internal.core.search.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 ww .j av  a  2 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-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();
        }
    }
}