下面列出了怎么用com.intellij.psi.search.SearchScope的API类实例代码及写法,或者点击链接到github查看源代码。
@NotNull
@SuppressWarnings("unused")
public Collection<PsiReference> findReferences(@NotNull PsiElement element, @NotNull SearchScope searchScope,
boolean searchInCommentsAndStrings) {
if (element instanceof LSPPsiElement) {
if (elements.contains(element)) {
return elements.stream().map(PsiElement::getReference).filter(Objects::nonNull).collect(Collectors.toList());
}
EditorEventManager manager = EditorEventManagerBase.forEditor(FileUtils.editorFromPsiFile(element.getContainingFile()));
if (manager != null) {
Pair<List<PsiElement>, List<VirtualFile>> refs = manager.references(element.getTextOffset(), true, false);
if (refs.getFirst() != null && refs.getSecond() != null) {
addEditors(refs.getSecond());
return refs.getFirst().stream().map(PsiElement::getReference).filter(Objects::nonNull).collect(Collectors.toList());
}
}
}
return new ArrayList<>();
}
public MicroProfileProjectInfo getMicroProfileProjectInfo(Module module,
List<MicroProfilePropertiesScope> scopes, ClasspathKind classpathKind, IPsiUtils utils,
DocumentFormat documentFormat) {
MicroProfileProjectInfo info = createInfo(module, classpathKind);
long startTime = System.currentTimeMillis();
boolean excludeTestCode = classpathKind == ClasspathKind.SRC;
PropertiesCollector collector = new PropertiesCollector(info, scopes);
SearchScope scope = createSearchScope(module, scopes, classpathKind == ClasspathKind.TEST);
SearchContext context = new SearchContext(module, scope, collector, utils, documentFormat);
DumbService.getInstance(module.getProject()).runReadActionInSmartMode(() -> {
Query<PsiModifierListOwner> query = createSearchQuery(context);
beginSearch(context);
query.forEach((Consumer<? super PsiModifierListOwner>) psiMember -> collectProperties(psiMember, context));
endSearch(context);
});
LOGGER.info("End computing MicroProfile properties for '" + info.getProjectURI() + "' in "
+ (System.currentTimeMillis() - startTime) + "ms.");
return info;
}
@Override
public void highlightUsages(@Nonnull PsiFile file, @Nonnull Editor editor, boolean clearHighlights) {
PsiElement target = getElement();
if (file instanceof PsiCompiledFile) file = ((PsiCompiledFile)file).getDecompiledPsiFile();
Project project = target.getProject();
final FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager();
final FindUsagesHandler handler = findUsagesManager.getFindUsagesHandler(target, true);
// in case of injected file, use host file to highlight all occurrences of the target in each injected file
PsiFile context = InjectedLanguageManager.getInstance(project).getTopLevelFile(file);
SearchScope searchScope = new LocalSearchScope(context);
Collection<PsiReference> refs = handler == null ? ReferencesSearch.search(target, searchScope, false).findAll() : handler.findReferencesToHighlight(target, searchScope);
new HighlightUsagesHandler.DoHighlightRunnable(new ArrayList<>(refs), project, target, editor, context, clearHighlights).run();
}
@Test
public void testUseScope() throws Exception {
PsiReference variableReference = configure();
PsiFile included = addFile("included.bash");
PsiFile notIncluded = addFile("notIncluded.bash");
PsiElement varDef = variableReference.resolve();
Assert.assertNotNull("Var must resolve", varDef);
Assert.assertTrue("var def must resolve to the definition in included.bash", included.equals(varDef.getContainingFile()));
SearchScope varDefUseScope = varDef.getUseScope();
Assert.assertTrue("Invalid type of scope: " + varDefUseScope, varDefUseScope instanceof GlobalSearchScope);
GlobalSearchScope useScope = (GlobalSearchScope) varDefUseScope;
Assert.assertTrue("The use scope must contain the original file itself.", useScope.contains(included.getVirtualFile()));
//must contain the file which contains the include statement
Assert.assertTrue("The use scope must contain the files which include the source file.", useScope.contains(myFile.getVirtualFile()));
//must not contain the file which does not include the inspected file
Assert.assertFalse("The use scope must not contain any other file.", useScope.contains(notIncluded.getVirtualFile()));
}
private static void removeUnusedCode(PsiFile file) {
while (true) {
Collection<PsiElement> toDelete = new ArrayList<>();
Project project = file.getProject();
SearchScope scope = GlobalSearchScope.fileScope(project, file.getVirtualFile());
file.acceptChildren(new DeletionMarkingVisitor(toDelete, scope));
if (toDelete.isEmpty()) {
break;
}
WriteCommandAction.writeCommandAction(project).run(
() -> {
for (PsiElement element : toDelete) {
element.delete();
}
}
);
}
}
@Nonnull
private static MyModel setTableModel(@Nonnull JTable table,
@Nonnull UsageViewImpl usageView,
@Nonnull final List<UsageNode> data,
@Nonnull AtomicInteger outOfScopeUsages,
@Nonnull SearchScope searchScope) {
ApplicationManager.getApplication().assertIsDispatchThread();
final int columnCount = calcColumnCount(data);
MyModel model = table.getModel() instanceof MyModel ? (MyModel)table.getModel() : null;
if (model == null || model.getColumnCount() != columnCount) {
model = new MyModel(data, columnCount);
table.setModel(model);
ShowUsagesTableCellRenderer renderer = new ShowUsagesTableCellRenderer(usageView, outOfScopeUsages, searchScope);
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
TableColumn column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(0);
column.setCellRenderer(renderer);
}
}
return model;
}
@Override
public boolean execute(@Nonnull final AllTypesSearch.SearchParameters queryParameters, @Nonnull final Processor<? super DotNetTypeDeclaration> consumer)
{
SearchScope scope = queryParameters.getScope();
if(scope instanceof GlobalSearchScope)
{
return processAllClassesInGlobalScope((GlobalSearchScope) scope, consumer, queryParameters);
}
PsiElement[] scopeRoots = ((LocalSearchScope) scope).getScope();
for(final PsiElement scopeRoot : scopeRoots)
{
if(!processScopeRootForAllClasses(scopeRoot, consumer))
{
return false;
}
}
return true;
}
@Override
public void applyTo(@Nonnull FindModel findModel, @Nonnull FindPopupScopeUI.ScopeType selectedScope) {
if (selectedScope == PROJECT) {
findModel.setProjectScope(true);
}
else if (selectedScope == DIRECTORY) {
String directory = myDirectoryChooser.getDirectory();
findModel.setDirectoryName(directory);
}
else if (selectedScope == MODULE) {
findModel.setModuleName((String)myModuleComboBox.getSelectedItem());
}
else if (selectedScope == SCOPE) {
SearchScope selectedCustomScope = myScopeCombo.getSelectedScope();
String customScopeName = selectedCustomScope == null ? null : selectedCustomScope.getDisplayName();
findModel.setCustomScopeName(customScopeName);
findModel.setCustomScope(selectedCustomScope);
findModel.setCustomScope(true);
}
}
@Nonnull
private static SearchScope calcScope(@Nonnull Project project, @Nullable DataContext dataContext) {
String defaultScopeName = FindSettings.getInstance().getDefaultScopeName();
List<SearchScope> predefined = PredefinedSearchScopeProvider.getInstance().getPredefinedScopes(project, dataContext, true, false, false,
false);
SearchScope resultScope = null;
for (SearchScope scope : predefined) {
if (scope.getDisplayName().equals(defaultScopeName)) {
resultScope = scope;
break;
}
}
if (resultScope == null) {
resultScope = ProjectScope.getProjectScope(project);
}
return resultScope;
}
SearchForUsagesRunnable(@Nonnull UsageViewManagerImpl usageViewManager,
@Nonnull Project project,
@Nonnull AtomicReference<UsageViewImpl> usageViewRef,
@Nonnull UsageViewPresentation presentation,
@Nonnull UsageTarget[] searchFor,
@Nonnull Factory<UsageSearcher> searcherFactory,
@Nonnull FindUsagesProcessPresentation processPresentation,
@Nonnull SearchScope searchScopeToWarnOfFallingOutOf,
@javax.annotation.Nullable UsageViewManager.UsageViewStateListener listener) {
myProject = project;
myUsageViewRef = usageViewRef;
myPresentation = presentation;
mySearchFor = searchFor;
mySearcherFactory = searcherFactory;
myProcessPresentation = processPresentation;
mySearchScopeToWarnOfFallingOutOf = searchScopeToWarnOfFallingOutOf;
myListener = listener;
myUsageViewManager = usageViewManager;
}
@Nullable
@Override
public SearchScope getAdditionalResolveScope(VirtualFile file, Project project) {
if (ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) {
return ComponentScope.getInstance();
}
return null;
}
@Test
public void getFindUsagesOptions() {
testHelper.getPsiClass(
psiClasses -> {
PsiClass layoutSpec = psiClasses.get(0);
// Associate generatedComponentVirtualFile with mockedGeneratedComponentCls
PsiClass mockedGeneratedComponentCls = mock(PsiClass.class);
PsiFile mockedGeneratedComponentFile = mock(PsiFile.class);
when(mockedGeneratedComponentCls.getContainingFile())
.thenReturn(mockedGeneratedComponentFile);
VirtualFile generatedComponentVirtualFile = createPresentInScopeVirtualFile();
when(mockedGeneratedComponentFile.getVirtualFile())
.thenReturn(generatedComponentVirtualFile);
VirtualFile presentInScopeVirtualFile = createPresentInScopeVirtualFile();
// We mock this function because project search is not working in test environment
Function<PsiClass, PsiClass> findGeneratedComponent =
psiClass -> mockedGeneratedComponentCls;
GeneratedClassFindUsagesHandler handler =
new GeneratedClassFindUsagesHandler(layoutSpec, findGeneratedComponent);
// Search scope should not contain generated component
SearchScope searchScope = handler.getFindUsagesOptions(null).searchScope;
assertThat(searchScope.contains(presentInScopeVirtualFile)).isTrue();
assertThat(searchScope.contains(generatedComponentVirtualFile)).isFalse();
return true;
},
"LayoutSpec.java");
}
private static void addPropertyUsages(@NotNull DotEnvProperty property, @NotNull SearchScope scope, @NotNull SearchRequestCollector collector) {
final String propertyName = property.getName();
if (StringUtil.isNotEmpty(propertyName)) {
/*SearchScope additional = GlobalSearchScope.EMPTY_SCOPE;
for (CustomPropertyScopeProvider provider : CustomPropertyScopeProvider.EP_NAME.getExtensionList()) {
additional = additional.union(provider.getScope(property.getProject()));
}
SearchScope propScope = scope.intersectWith(property.getUseScope()).intersectWith(additional);*/
collector.searchWord(propertyName, scope, UsageSearchContext.ANY, true, property);
collector.searchWord("process.env." + propertyName, scope, UsageSearchContext.ANY, true, property);
}
}
public void selectItem(@Nullable Object selection) {
if (selection == null) return;
JComboBox combo = getComboBox();
DefaultComboBoxModel model = (DefaultComboBoxModel)combo.getModel();
for (int i = 0; i < model.getSize(); i++) {
ScopeDescriptor descriptor = (ScopeDescriptor)model.getElementAt(i);
if (selection instanceof String && selection.equals(descriptor.getDisplayName()) || selection instanceof SearchScope && descriptor.scopeEquals((SearchScope)selection)) {
combo.setSelectedIndex(i);
break;
}
}
}
/**
* Search for package-local references.<br>
* Returns null if the resulting scope is empty
*/
@Nullable
private static SearchScope limitScopeToFile(SearchScope scope, PsiFile file) {
if (scope instanceof LocalSearchScope) {
return ((LocalSearchScope) scope).isInScope(file.getVirtualFile())
? new LocalSearchScope(file)
: null;
}
return scope.intersectWith(new LocalSearchScope(file));
}
private static void searchForString(
SearchParameters params, SearchScope scope, PsiElement element, String string) {
if (scope instanceof GlobalSearchScope) {
scope =
GlobalSearchScope.getScopeRestrictedByFileTypes(
(GlobalSearchScope) scope, BuildFileType.INSTANCE);
}
params.getOptimizer().searchWord(string, scope, UsageSearchContext.IN_STRINGS, true, element);
}
private static boolean inScope(SearchParameters queryParameters, BuildFile buildFile) {
SearchScope scope = queryParameters.getScopeDeterminedByUser();
if (scope instanceof GlobalSearchScope) {
return ((GlobalSearchScope) scope).contains(buildFile.getVirtualFile());
}
return ((LocalSearchScope) scope).isInScope(buildFile.getVirtualFile());
}
@Nullable
@Override
public SearchScope getAdditionalUseScope(PsiElement element) {
if (isImplicitUsageMethod(element)) {
return GlobalSearchScope.allScope(element.getProject());
}
return null;
}
@Nullable
@Override
public SearchScope getAdditionalUseScope(PsiElement element) {
if (isAutoFactoryClass(element)) {
return GlobalSearchScope.allScope(element.getProject());
}
return null;
}
@Nullable
@Override
public SearchScope getAdditionalUseScope(PsiElement element) {
if (!Blaze.isBlazeProject(element.getProject())) {
return null;
}
if (isPyPackageOutsideProject(element) || isPyFileOutsideProject(element)) {
return GlobalSearchScope.projectScope(element.getProject());
}
return null;
}
public static void registerScopeFilter(@Nonnull AbstractLayoutCodeProcessor processor, @Nullable final SearchScope scope) {
if (scope == null) {
return;
}
processor.addFileFilter(scope::contains);
}
/**
* Returns references to the given element. If it is a BashPsiElement a special search scope is used to locate the elements referencing the file.
*
* @param element References to the given element
* @return
*/
@NotNull
@Override
public Collection<PsiReference> findReferences(PsiElement element) {
//fixme fix the custom scope
SearchScope scope = (element instanceof BashPsiElement)
? BashElementSharedImpl.getElementUseScope((BashPsiElement) element, element.getProject())
: GlobalSearchScope.projectScope(element.getProject());
Query<PsiReference> search = ReferencesSearch.search(element, scope);
return search.findAll();
}
@Nullable
SearchScope getSearchScope() {
if (!myUseFileMask.isSelected()) return null;
String text = (String)myFileMask.getSelectedItem();
if (text == null) return null;
final Condition<CharSequence> patternCondition = FindInProjectUtil.createFileMaskCondition(text);
return new GlobalSearchScope() {
@Override
public boolean contains(@Nonnull VirtualFile file) {
return patternCondition.value(file.getNameSequence());
}
@Override
public int compare(@Nonnull VirtualFile file1, @Nonnull VirtualFile file2) {
return 0;
}
@Override
public boolean isSearchInModuleContent(@Nonnull Module aModule) {
return true;
}
@Override
public boolean isSearchInLibraries() {
return true;
}
};
}
@Override
public void setUp() throws Exception {
super.setUp();
project = myFixture.getProject();
moduleHelper = mock(ModuleHelper.class);
scope = mock(SearchScope.class);
collector = mock(StepCollector.class);
}
@Nonnull
@Override
public SearchScope getUseScope()
{
PsiElement parent = getParent();
if(parent instanceof DotNetParameterList)
{
return new LocalSearchScope(parent.getParent());
}
return super.getUseScope();
}
@NotNull
@Override
public SearchScope getUseScope() {
final PsiElement localVar = UsefulPsiTreeUtil.getParentOfType(this, HaxeLocalVarDeclaration.class);
if (localVar != null) {
final PsiElement outerBlock = UsefulPsiTreeUtil.getParentOfType(localVar, HaxeBlockStatement.class);
if (outerBlock != null) {
return new LocalSearchScope(outerBlock);
}
}
return super.getUseScope();
}
@NotNull
@Override
public SearchScope getUseScope() {
if(this instanceof HaxeLocalFunctionDeclaration) {
final PsiElement outerBlock = UsefulPsiTreeUtil.getParentOfType(this, HaxeBlockStatement.class);
if(outerBlock != null) {
return new LocalSearchScope(outerBlock);
}
}
return super.getUseScope();
}
@NotNull
@Override
public SearchScope getUseScope() {
final HaxeComponentType type = HaxeComponentType.typeOf(getParent());
final HaxeComponent component = PsiTreeUtil.getParentOfType(getParent(), HaxeComponent.class, true);
if (type == null || component == null) {
return super.getUseScope();
}
if (type == HaxeComponentType.FUNCTION || type == HaxeComponentType.PARAMETER || type == HaxeComponentType.VARIABLE) {
return new LocalSearchScope(component.getParent());
}
return super.getUseScope();
}
@Nonnull
public SearchScope getScope() {
return ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
@Override
public SearchScope compute() {
return myScope.intersectWith(PsiSearchHelper.SERVICE.getInstance(myElement.getProject()).getUseScope(myElement));
}
});
}
public static Query<PsiMethod> search(final PsiMethod method, SearchScope scope, final boolean checkDeep, HaxeHierarchyTimeoutHandler timeoutHandler) {
if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return cannotBeOverriden(method);
}
})) return EmptyQuery.getEmptyQuery(); // Optimization
return INSTANCE.createUniqueResultsQuery(new SearchParameters(method, scope, checkDeep));
}