org.eclipse.jdt.core.search.SearchPattern Java Examples

The following examples show how to use org.eclipse.jdt.core.search.SearchPattern. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static List<TypeNameMatch> findTypeInfos(String typeName, IType contextType, IProgressMonitor pm) throws JavaModelException {
	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[]{contextType.getJavaProject()}, true);
	IPackageFragment currPackage= contextType.getPackageFragment();
	ArrayList<TypeNameMatch> collectedInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(collectedInfos);
	int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
	new SearchEngine().searchAllTypeNames(null, matchMode, typeName.toCharArray(), matchMode, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, pm);

	List<TypeNameMatch> result= new ArrayList<TypeNameMatch>();
	for (Iterator<TypeNameMatch> iter= collectedInfos.iterator(); iter.hasNext();) {
		TypeNameMatch curr= iter.next();
		IType type= curr.getType();
		if (type != null) {
			boolean visible=true;
			try {
				visible= JavaModelUtil.isVisible(type, currPackage);
			} catch (JavaModelException e) {
				//Assume visibile if not available
			}
			if (visible) {
				result.add(curr);
			}
		}
	}
	return result;
}
 
Example #2
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Map<ICompilationUnit, SearchMatch[]> createTypeReferencesMapping(IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(fType, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
	engine.setFiltering(true, true);
	engine.setScope(RefactoringScopeFactory.create(fType));
	engine.setStatus(status);
	engine.searchPattern(new SubProgressMonitor(pm, 1));
	final SearchResultGroup[] groups= (SearchResultGroup[]) engine.getResults();
	Map<ICompilationUnit, SearchMatch[]> result= new HashMap<ICompilationUnit, SearchMatch[]>();
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		result.put(cu, group.getSearchResults());
	}
	return result;
}
 
Example #3
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IJavaElement[] getReferencingElementsFromSameClass(IMember member, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	Assert.isNotNull(member);
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
	engine.setFiltering(true, true);
	engine.setScope(SearchEngine.createJavaSearchScope(new IJavaElement[] { member.getDeclaringType() }));
	engine.setStatus(status);
	engine.searchPattern(new SubProgressMonitor(pm, 1));
	SearchResultGroup[] groups= (SearchResultGroup[]) engine.getResults();
	Set<IJavaElement> result= new HashSet<IJavaElement>(3);
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		SearchMatch[] results= group.getSearchResults();
		for (int j= 0; j < results.length; j++) {
			SearchMatch searchResult= results[j];
			result.add(SearchUtils.getEnclosingJavaElement(searchResult));
		}
	}
	return result.toArray(new IJavaElement[result.size()]);
}
 
Example #4
Source File: InteractiveUnresolvedTypeResolver.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void findCandidateTypes(final JvmDeclaredType contextType, final String typeSimpleName,
		IJavaSearchScope searchScope, final IAcceptor<JvmDeclaredType> acceptor) throws JavaModelException {
	BasicSearchEngine searchEngine = new BasicSearchEngine();
	final IVisibilityHelper contextualVisibilityHelper = new ContextualVisibilityHelper(visibilityHelper, contextType);
	searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, typeSimpleName.toCharArray(),
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.TYPE, searchScope,
			new IRestrictedAccessTypeRequestor() {
				@Override
				public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
						char[][] enclosingTypeNames, String path, AccessRestriction access) {
					final String qualifiedTypeName = getQualifiedTypeName(packageName, enclosingTypeNames,
							simpleTypeName);
					if ((access == null
							|| (access.getProblemId() != IProblem.ForbiddenReference && !access.ignoreIfBetter()))
						&& !TypeFilter.isFiltered(packageName, simpleTypeName)) {
						JvmType importType = typeRefs.findDeclaredType(qualifiedTypeName, contextType.eResource());
						if (importType instanceof JvmDeclaredType
								&& contextualVisibilityHelper.isVisible((JvmDeclaredType) importType)) {
							acceptor.accept((JvmDeclaredType) importType);
						}
					}
				}
			}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
}
 
Example #5
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes the compilation units referencing the subtype to replace.
 *
 * @param type
 *            the subtype
 * @param monitor
 *            the progress monitor to use
 * @param status
 *            the refactoring status
 * @return the referenced compilation units (element type:
 *         <code>&lt;IJavaProject, Collection&lt;SearchResultGroup&gt;&gt;</code>)
 * @throws JavaModelException
 *             if an error occurs
 */
protected final Map<IJavaProject, Set<SearchResultGroup>> getReferencingCompilationUnits(final IType type, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	try {
		monitor.beginTask("", 100); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
		final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2();
		engine.setOwner(fOwner);
		engine.setFiltering(true, true);
		engine.setStatus(status);
		engine.setScope(RefactoringScopeFactory.create(type));
		engine.setPattern(SearchPattern.createPattern(type, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
		engine.searchPattern(new SubProgressMonitor(monitor, 100));
		@SuppressWarnings("unchecked")
		Map<IJavaProject, Set<SearchResultGroup>> result= (Map<IJavaProject, Set<SearchResultGroup>>) engine.getAffectedProjects();
		return result;
	} finally {
		monitor.done();
	}
}
 
Example #6
Source File: AddImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor) throws JavaModelException {
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject());

	int typeKinds= SimilarElementsRequestor.ALL_TYPES;
	if (nameNode != null) {
		typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
	}

	ArrayList<TypeNameMatch> typeInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
	int matchMode= SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
	new SearchEngine().searchAllTypeNames(null, matchMode, simpleTypeName.toCharArray(), matchMode, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);

	ArrayList<TypeNameMatch> typeRefsFound= new ArrayList<TypeNameMatch>(typeInfos.size());
	for (int i= 0, len= typeInfos.size(); i < len; i++) {
		TypeNameMatch curr= typeInfos.get(i);
		if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
			if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr)) {
				typeRefsFound.add(curr);
			}
		}
	}
	return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
 
Example #7
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param scope search scope
 * @param pm mrogress monitor
 * @return all package fragments in <code>scope</code> with same name as <code>fPackage</code>, excluding fPackage
 * @throws CoreException if search failed
 */
private IPackageFragment[] getNamesakePackages(IJavaSearchScope scope, IProgressMonitor pm) throws CoreException {
	SearchPattern pattern= SearchPattern.createPattern(fPackage.getElementName(), IJavaSearchConstants.PACKAGE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

	final HashSet<IPackageFragment> packageFragments= new HashSet<>();
	SearchRequestor requestor= new SearchRequestor() {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(match);
			if (enclosingElement instanceof IPackageFragment) {
				IPackageFragment pack= (IPackageFragment) enclosingElement;
				if (! fPackage.equals(pack)) {
					packageFragments.add(pack);
				}
			}
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);

	return packageFragments.toArray(new IPackageFragment[packageFragments.size()]);
}
 
Example #8
Source File: OriginalEditorSelector.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private SearchResult findTypesBySimpleName(String simpleTypeName, final boolean searchForSources) {
	final SearchResult result = new SearchResult();
	try {
		new SearchEngine().searchAllTypeNames(null, 0, // match all package names
				simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
					IJavaSearchConstants.TYPE,
					SearchEngine.createWorkspaceScope(),
					new TypeNameMatchRequestor() {
						@Override
						public void acceptTypeNameMatch(TypeNameMatch match) {
							IPackageFragmentRoot fragmentRoot = match.getPackageFragmentRoot();
							boolean externalLib = fragmentRoot.isArchive() || fragmentRoot.isExternal();
							if (externalLib ^ searchForSources) {
								result.foundTypes.add(match.getType());
							}
						}
					}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, // wait for the jdt index to be ready
					new NullProgressMonitor());
	} catch (JavaModelException e) {
		logger.error(e.getMessage(), e);
	}
	return result;
}
 
Example #9
Source File: WebXmlValidator.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Searches for a class that matches a pattern.
 */
@VisibleForTesting
static boolean performSearch(SearchPattern pattern, IJavaSearchScope scope,
    IProgressMonitor monitor) {
  try {
    SearchEngine searchEngine = new SearchEngine();
    TypeSearchRequestor requestor = new TypeSearchRequestor();
    searchEngine.search(pattern,
        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
        scope, requestor, monitor);
    return requestor.foundMatch();
  } catch (CoreException ex) {
    logger.log(Level.SEVERE, ex.getMessage());
    return false;
  }
}
 
Example #10
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void addAccessorOccurrences(IProgressMonitor pm, IMethod accessor, String editName, String newAccessorName, RefactoringStatus status) throws CoreException {
	Assert.isTrue(accessor.exists());

	IJavaSearchScope scope= RefactoringScopeFactory.create(accessor);
	SearchPattern pattern= SearchPattern.createPattern(accessor, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	SearchResultGroup[] groupedResults= RefactoringSearchEngine.search(
		pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status);

	for (int i= 0; i < groupedResults.length; i++) {
		ICompilationUnit cu= groupedResults[i].getCompilationUnit();
		if (cu == null) {
			continue;
		}
		SearchMatch[] results= groupedResults[i].getSearchResults();
		for (int j= 0; j < results.length; j++){
			SearchMatch searchResult= results[j];
			TextEdit edit= new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName);
			addTextEdit(fChangeManager.get(cu), editName, edit);
		}
	}
}
 
Example #11
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private IMethod[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm) throws CoreException {
	final List<IMethod> results= new ArrayList<>();
	SearchPattern pattern= createNewMethodPattern();
	IJavaSearchScope scope= RefactoringScopeFactory.create(getMethod().getJavaProject());
	SearchRequestor requestor= new SearchRequestor() {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			Object method= match.getElement();
			if (method instanceof IMethod) {
				results.add((IMethod) method);
			}
			else {
				JavaLanguageServerPlugin.logError("Unexpected element in search match: " + match.toString()); //$NON-NLS-1$
			}
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
	return results.toArray(new IMethod[results.size()]);
}
 
Example #12
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IMethod[] searchForDeclarationsOfClashingMethods(IProgressMonitor pm) throws CoreException {
	final List<IMethod> results= new ArrayList<IMethod>();
	SearchPattern pattern= createNewMethodPattern();
	IJavaSearchScope scope= RefactoringScopeFactory.create(getMethod().getJavaProject());
	SearchRequestor requestor= new SearchRequestor() {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			Object method= match.getElement();
			if (method instanceof IMethod) // check for bug 90138: [refactoring] [rename] Renaming method throws internal exception
				results.add((IMethod) method);
			else
				JavaPlugin.logErrorMessage("Unexpected element in search match: " + match.toString()); //$NON-NLS-1$
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
	return results.toArray(new IMethod[results.size()]);
}
 
Example #13
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<SearchResultGroup> getReferencesToTypesInPackage(IProgressMonitor pm, ReferencesInBinaryContext binaryRefs, RefactoringStatus status) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$
	IJavaSearchScope referencedFromNamesakesScope= RefactoringScopeFactory.create(fPackage, true, false);
	IPackageFragment[] namesakePackages= getNamesakePackages(referencedFromNamesakesScope, new SubProgressMonitor(pm, 1));
	if (namesakePackages.length == 0) {
		pm.done();
		return new ArrayList<SearchResultGroup>(0);
	}

	IJavaSearchScope scope= SearchEngine.createJavaSearchScope(namesakePackages);
	IType[] typesToSearch= getTypesInPackage(fPackage);
	if (typesToSearch.length == 0) {
		pm.done();
		return new ArrayList<SearchResultGroup>(0);
	}
	SearchPattern pattern= RefactoringSearchEngine.createOrPattern(typesToSearch, IJavaSearchConstants.REFERENCES);
	CollectingSearchRequestor requestor= new CuCollectingSearchRequestor(binaryRefs);
	SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
	pm.done();
	return new ArrayList<SearchResultGroup>(Arrays.asList(results));
}
 
Example #14
Source File: JavaSearchQuery.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getMatchMode(String pattern) {
	if (pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1) {
		return SearchPattern.R_PATTERN_MATCH;
	} else if (SearchUtils.isCamelCasePattern(pattern)) {
		return SearchPattern.R_CAMELCASE_MATCH;
	}
	return SearchPattern.R_EXACT_MATCH;
}
 
Example #15
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchResultGroup[] getReferences(IMember member, IProgressMonitor monitor, RefactoringStatus status) throws JavaModelException {
	final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(SearchPattern.createPattern(member, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
	engine.setFiltering(true, true);
	engine.setScope(RefactoringScopeFactory.create(member));
	engine.setStatus(status);
	engine.searchPattern(new SubProgressMonitor(monitor, 1));
	return (SearchResultGroup[]) engine.getResults();
}
 
Example #16
Source File: TargetProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ICompilationUnit[] getAffectedCompilationUnits(final RefactoringStatus status, ReferencesInBinaryContext binaryRefs, IProgressMonitor pm) throws CoreException {
	IMethod method= (IMethod)fMethodBinding.getJavaElement();
	Assert.isTrue(method != null);

	SearchPattern pattern= SearchPattern.createPattern(method, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	IJavaSearchScope scope= RefactoringScopeFactory.create(method, true, false);
	final HashSet<ICompilationUnit> affectedCompilationUnits= new HashSet<ICompilationUnit>();
	CollectingSearchRequestor requestor= new CollectingSearchRequestor(binaryRefs) {
		private ICompilationUnit fLastCU;
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			if (filterMatch(match))
				return;
			if (match.isInsideDocComment())
				return; // TODO: should warn user (with something like a ReferencesInBinaryContext)

			ICompilationUnit unit= SearchUtils.getCompilationUnit(match);
			if (match.getAccuracy() == SearchMatch.A_INACCURATE) {
				if (unit != null) {
					status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match,
						JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength())));
				} else {
					status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match);
				}
			} else if (unit != null) {
				if (! unit.equals(fLastCU)) {
					fLastCU= unit;
					affectedCompilationUnits.add(unit);
				}
			}
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, new SubProgressMonitor(pm, 1));
	return affectedCompilationUnits.toArray(new ICompilationUnit[affectedCompilationUnits.size()]);
}
 
Example #17
Source File: WebXmlValidator.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static boolean classExists(IJavaProject project, String typeName) {
  if (Strings.isNullOrEmpty(typeName)) {
    return false;
  }
  SearchPattern pattern = SearchPattern.createPattern(typeName,
      IJavaSearchConstants.CLASS,
      IJavaSearchConstants.DECLARATIONS,
      SearchPattern.R_EXACT_MATCH | SearchPattern.R_ERASURE_MATCH);
  IJavaSearchScope scope = project == null ? SearchEngine.createWorkspaceScope()
      : SearchEngine.createJavaSearchScope(new IJavaElement[] {project});
  return performSearch(pattern, scope, null);
}
 
Example #18
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
public static Collection/*<MethodDeclarationUnitPair>*/ 
		findCallees(IProgressMonitor progressMonitor, String methodName, IJavaProject project, boolean isConstructor) 
{
	try {
           MethodSearchRequestor.MethodDeclarationsSearchRequestor searchRequestor = 
           	new MethodSearchRequestor.MethodDeclarationsSearchRequestor();
           SearchEngine searchEngine = new SearchEngine();

           IProgressMonitor monitor = new SubProgressMonitor(
           		progressMonitor, 5, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
           monitor.beginTask("Searching for declaration of " + methodName +
           		(project != null ? " in " + project.getProject().getName() : ""), 100);
           IJavaSearchScope searchScope = getSearchScope(project);
           int matchType = !isConstructor ? IJavaSearchConstants.METHOD : IJavaSearchConstants.CONSTRUCTOR;
           SearchPattern pattern = SearchPattern.createPattern(
           		methodName, 
				matchType,
				IJavaSearchConstants.DECLARATIONS, 
				SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE );
           
           searchEngine.search(
           		pattern, 
				new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                   searchScope, 
				searchRequestor, 
				monitor
				);
           monitor.done();

           return searchRequestor.getMethodUnitPairs();
       } catch (CoreException e) {
           JavaPlugin.log(e);

           return new LinkedList();
       }
}
 
Example #19
Source File: SourceRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private boolean isSourceType(final String qualifiedClassname, final IJavaProject javaProject)
        throws JavaModelException {
    final SearchEngine sEngine = new SearchEngine();
    final IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject },
            IJavaSearchScope.SOURCES);
    final TypeNameFoundRequestor nameRequestor = new TypeNameFoundRequestor();
    sEngine.searchAllTypeNames(NamingUtils.getPackageName(qualifiedClassname).toCharArray(),
            SearchPattern.R_EXACT_MATCH,
            NamingUtils.getSimpleName(qualifiedClassname)
                    .toCharArray(),
            SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.CLASS_AND_INTERFACE, searchScope, nameRequestor,
            IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
            Repository.NULL_PROGRESS_MONITOR);
    return nameRequestor.isFound();
}
 
Example #20
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private IType[] searchForOuterTypesOfReferences(IMethod[] newNameMethods, IProgressMonitor pm) throws CoreException {
	final Set<IType> outerTypesOfReferences= new HashSet<>();
	SearchPattern pattern= RefactoringSearchEngine.createOrPattern(newNameMethods, IJavaSearchConstants.REFERENCES);
	IJavaSearchScope scope= createRefactoringScope(getMethod());
	SearchRequestor requestor= new SearchRequestor() {
		@Override
		public void acceptSearchMatch(SearchMatch match) throws CoreException {
			Object element= match.getElement();
			if (!(element instanceof IMember))
			 {
				return; // e.g. an IImportDeclaration for a static method import
			}
			IMember member= (IMember) element;
			IType declaring= member.getDeclaringType();
			if (declaring == null) {
				return;
			}
			IType outer= declaring.getDeclaringType();
			if (outer != null) {
				outerTypesOfReferences.add(declaring);
			}
		}
	};
	new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(),
			scope, requestor, pm);
	return outerTypesOfReferences.toArray(new IType[outerTypesOfReferences.size()]);
}
 
Example #21
Source File: AndLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public AndLocator(AndPattern pattern) {
	super(pattern);

	SearchPattern[] patterns = pattern.patterns;
	PatternLocator[] locators = new PatternLocator[patterns.length];
	this.levels = new int[patterns.length];
	for (int i=0, l=patterns.length; i<l; i++) {
		locators[i] = PatternLocator.patternLocator(patterns[i]);
		this.levels[i] = IMPOSSIBLE_MATCH;
	}
	this.patternLocators = locators;
}
 
Example #22
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private List<SearchResultGroup> getReferencesToTypesInNamesakes(IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	pm.beginTask("", 2); //$NON-NLS-1$
	// e.g. renaming B-p.p; project C requires B, X and has ref to B-p.p and X-p.p;
	// goal: find refs to X-p.p in CUs from fOccurrences

	// (1) find namesake packages (scope: all packages referenced by CUs in fOccurrences and fPackage)
	IJavaElement[] elements= new IJavaElement[fOccurrences.length + 1];
	for (int i= 0; i < fOccurrences.length; i++) {
		elements[i]= fOccurrences[i].getCompilationUnit();
	}
	elements[fOccurrences.length]= fPackage;
	IJavaSearchScope namesakePackagesScope= RefactoringScopeFactory.createReferencedScope(elements);
	IPackageFragment[] namesakePackages= getNamesakePackages(namesakePackagesScope, new SubProgressMonitor(pm, 1));
	if (namesakePackages.length == 0) {
		pm.done();
		return new ArrayList<>(0);
	}

	// (2) find refs in fOccurrences and fPackage to namesake packages
	// (from fOccurrences (without namesakes): may have shared star import)
	// (from fPackage: may have unimported references to types of namesake packages)
	IType[] typesToSearch= getTypesInPackages(namesakePackages);
	if (typesToSearch.length == 0) {
		pm.done();
		return new ArrayList<>(0);
	}
	SearchPattern pattern= RefactoringSearchEngine.createOrPattern(typesToSearch, IJavaSearchConstants.REFERENCES);
	IJavaSearchScope scope= getPackageAndOccurrencesWithoutNamesakesScope();
	SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, scope, new SubProgressMonitor(pm, 1), status);
	pm.done();
	return new ArrayList<>(Arrays.asList(results));
}
 
Example #23
Source File: IndexSelector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IJavaElement[] getFocusedElementsAndTypes(SearchPattern pattern, IJavaElement focusElement, ObjectVector superTypes) throws JavaModelException {
	if (pattern instanceof MethodPattern) {
		// For method pattern, it needs to walk along the focus type super hierarchy
		// and add jars/projects of all the encountered types.
		IType type = (IType) pattern.focus.getAncestor(IJavaElement.TYPE);
		MethodPattern methodPattern = (MethodPattern) pattern;
		String selector = new String(methodPattern.selector);
		int parameterCount = methodPattern.parameterCount;
		ITypeHierarchy superHierarchy = type.newSupertypeHierarchy(null);
		IType[] allTypes = superHierarchy.getAllSupertypes(type);
		int length = allTypes.length;
		SimpleSet focusSet = new SimpleSet(length+1);
		if (focusElement != null) focusSet.add(focusElement);
		for (int i=0; i<length; i++) {
			IMethod[] methods = allTypes[i].getMethods();
			int mLength = methods.length;
			for (int m=0; m<mLength; m++) {
				if (parameterCount == methods[m].getNumberOfParameters() && methods[m].getElementName().equals(selector)) {
					IPackageFragmentRoot root = (IPackageFragmentRoot) allTypes[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
					IJavaElement element = root.isArchive() ? root : root.getParent();
					focusSet.add(element);
					if (superTypes != null) superTypes.add(allTypes[i]);
					break;
				}
			}
		}
		// Rebuilt a contiguous array
		IJavaElement[] focuses = new IJavaElement[focusSet.elementSize];
		Object[] values = focusSet.values;
		int count = 0;
		for (int i = values.length; --i >= 0;) {
			if (values[i] != null) {
				focuses[count++] = (IJavaElement) values[i];
			}
		}
		return focuses;
	}
	if (focusElement == null) return new IJavaElement[0];
	return new IJavaElement[] { focusElement };
}
 
Example #24
Source File: CreateCopyOfCompilationUnitChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchPattern createSearchPattern(IType type) throws JavaModelException {
	SearchPattern pattern= SearchPattern.createPattern(type, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	IMethod[] constructors= JavaElementUtil.getAllConstructors(type);
	if (constructors.length == 0)
		return pattern;
	SearchPattern constructorDeclarationPattern= RefactoringSearchEngine.createOrPattern(constructors, IJavaSearchConstants.DECLARATIONS);
	return SearchPattern.createOrPattern(pattern, constructorDeclarationPattern);
}
 
Example #25
Source File: RefactoringSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SearchResultGroup[] internalSearch(SearchEngine searchEngine, SearchPattern pattern, IJavaSearchScope scope,
		CollectingSearchRequestor requestor, IProgressMonitor monitor, RefactoringStatus status) throws JavaModelException {
	try {
		searchEngine.search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, monitor);
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}
	return groupByCu(requestor.getResults(), status);
}
 
Example #26
Source File: ConstructorPattern.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean matchesDecodedKey(SearchPattern decodedPattern) {
	ConstructorPattern pattern = (ConstructorPattern) decodedPattern;

	return pattern.parameterCount != -1
		&& (this.parameterCount == pattern.parameterCount || this.parameterCount == -1 || this.varargs)
		&& matchesName(this.declaringSimpleName, pattern.declaringSimpleName);
}
 
Example #27
Source File: RefactoringSearchEngine2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the search pattern to be used during search.
 * <p>
 * This method must be called before {@link RefactoringSearchEngine2#searchPattern(IProgressMonitor)}
 *
 * @param elements the set of elements
 * @param limitTo determines the nature of the expected matches. This is a combination of {@link org.eclipse.jdt.core.search.IJavaSearchConstants}.
 */
public final void setPattern(final IJavaElement[] elements, final int limitTo) {
	Assert.isNotNull(elements);
	Assert.isTrue(elements.length > 0);
	SearchPattern pattern= SearchPattern.createPattern(elements[0], limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	IJavaElement element= null;
	for (int index= 1; index < elements.length; index++) {
		element= elements[index];
		pattern= SearchPattern.createOrPattern(pattern, SearchPattern.createPattern(element, limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
	}
	setPattern(pattern);
}
 
Example #28
Source File: MoveCuUpdateCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static SearchResultGroup[] getReferences(ICompilationUnit unit, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
	final SearchPattern pattern = RefactoringSearchEngine.createOrPattern(unit.getTypes(), IJavaSearchConstants.REFERENCES);
	if (pattern != null) {
		String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getFileName(unit));
		ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
		Collector requestor = new Collector(((IPackageFragment) unit.getParent()), binaryRefs);
		IJavaSearchScope scope = RefactoringScopeFactory.create(unit, true, false);

		SearchResultGroup[] result = RefactoringSearchEngine.search(pattern, scope, requestor, new SubProgressMonitor(pm, 1), status);
		binaryRefs.addErrorIfNecessary(status);
		return result;
	}
	return new SearchResultGroup[] {};
}
 
Example #29
Source File: RefactoringSearchEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static ICompilationUnit[] findAffectedCompilationUnits(SearchPattern pattern, IJavaSearchScope scope, final IProgressMonitor pm, RefactoringStatus status, final boolean tolerateInAccurateMatches) throws JavaModelException {

		boolean hasNonCuMatches = false;

		class ResourceSearchRequestor extends SearchRequestor {
			boolean hasPotentialMatches = false;
			Set<IResource> resources = new HashSet<>(5);
			private IResource fLastResource;

			@Override
			public void acceptSearchMatch(SearchMatch match) {
				if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) {
					hasPotentialMatches = true;
				}
				if (fLastResource != match.getResource()) {
					fLastResource = match.getResource();
					resources.add(fLastResource);
				}
			}
		}
		ResourceSearchRequestor requestor = new ResourceSearchRequestor();
		try {
			new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
		} catch (CoreException e) {
			throw new JavaModelException(e);
		}

		List<IJavaElement> result = new ArrayList<>(requestor.resources.size());
		for (Iterator<IResource> iter = requestor.resources.iterator(); iter.hasNext();) {
			IResource resource = iter.next();
			IJavaElement element = JavaCore.create(resource);
			if (element instanceof ICompilationUnit) {
				result.add(element);
			} else {
				hasNonCuMatches = true;
			}
		}
		addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches);
		return result.toArray(new ICompilationUnit[result.size()]);
	}
 
Example #30
Source File: MatchingNodeSet.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int addMatch(ASTNode node, int matchLevel) {
	int maskedLevel = matchLevel & PatternLocator.MATCH_LEVEL_MASK;
	switch (maskedLevel) {
		case PatternLocator.INACCURATE_MATCH:
			if (matchLevel != maskedLevel) {
				addTrustedMatch(node, new Integer(SearchMatch.A_INACCURATE+(matchLevel & PatternLocator.FLAVORS_MASK)));
			} else {
				addTrustedMatch(node, POTENTIAL_MATCH);
			}
			break;
		case PatternLocator.POSSIBLE_MATCH:
			addPossibleMatch(node);
			break;
		case PatternLocator.ERASURE_MATCH:
			if (matchLevel != maskedLevel) {
				addTrustedMatch(node, new Integer(SearchPattern.R_ERASURE_MATCH+(matchLevel & PatternLocator.FLAVORS_MASK)));
			} else {
				addTrustedMatch(node, ERASURE_MATCH);
			}
			break;
		case PatternLocator.ACCURATE_MATCH:
			if (matchLevel != maskedLevel) {
				addTrustedMatch(node, new Integer(SearchMatch.A_ACCURATE+(matchLevel & PatternLocator.FLAVORS_MASK)));
			} else {
				addTrustedMatch(node, EXACT_MATCH);
			}
			break;
	}
	return matchLevel;
}