下面列出了com.intellij.psi.PsiStatement#com.intellij.analysis.AnalysisScope 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public AbstractRefactoringPanel(@NotNull AnalysisScope scope,
String detectIndicatorStatusTextKey,
RefactoringType refactoringType,
AbstractTreeTableModel model,
int refactorDepth) {
this.scope = scope;
this.scopeChooserCombo = new ScopeChooserCombo(scope.getProject());
this.detectIndicatorStatusTextKey = detectIndicatorStatusTextKey;
this.refactoringType = refactoringType;
this.model = model;
this.treeTable = new TreeTable(model);
this.refactorDepth = refactorDepth;
refreshLabel.setForeground(JBColor.GRAY);
setLayout(new BorderLayout());
setupGUI();
}
/**
* Opens definition of method and highlights specified element in the method.
*/
public static void highlightStatement(@Nullable PsiMethod sourceMethod,
AnalysisScope scope,
PsiElement statement,
boolean openInEditor) {
new Task.Backgroundable(scope.getProject(), "Search Definition") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
}
@Override
public void onSuccess() {
if (sourceMethod == null || !statement.isValid()) {
return;
}
highlightPsiElement(statement, openInEditor);
}
}.queue();
}
public static void highlightField(@Nullable PsiField sourceField, AnalysisScope scope, boolean openInEditor) {
new Task.Backgroundable(scope.getProject(), "Search Definition") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
}
@Override
public void onSuccess() {
if (sourceField == null || !sourceField.isValid()) {
return;
}
highlightPsiElement(sourceField, openInEditor);
}
}.queue();
}
private static void openDefinition(@Nullable PsiMember unit, AnalysisScope scope) {
new Task.Backgroundable(scope.getProject(), "Search Definition") {
private PsiElement result;
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
result = unit;
}
@Override
public void onSuccess() {
if (result != null) {
EditorHelper.openInEditor(result);
}
}
}.queue();
}
private void performMultipleRefactoringsTest(List<Integer> eliminationGroupSizes) {
initTest();
eliminationGroupSizes = new ArrayList<>(eliminationGroupSizes);
Project project = myFixture.getProject();
while (eliminationGroupSizes.size() != 0) {
Set<TypeCheckEliminationGroup> eliminationGroups =
JDeodorantFacade.getTypeCheckEliminationRefactoringOpportunities(
new ProjectInfo(new AnalysisScope(project), false),
fakeProgressIndicator
);
assertEquals(eliminationGroupSizes.size(), eliminationGroups.size());
TypeCheckEliminationGroup eliminationGroup = eliminationGroups.iterator().next();
assertEquals(eliminationGroupSizes.get(0).intValue(), eliminationGroup.getCandidates().size());
WriteCommandAction.runWriteCommandAction(
project,
() -> createRefactoring(eliminationGroup.getCandidates().get(0), project).apply()
);
if (eliminationGroupSizes.get(0) == 1) {
eliminationGroupSizes.remove(0);
} else {
eliminationGroupSizes.set(0, eliminationGroupSizes.get(0) - 1);
}
}
checkTest();
}
private void testMethod(String methodCode, int fieldNumber) {
String testContent = getPrefix() + methodCode + getSuffix();
myFixture.configureByText("TestFieldAccess.java", testContent);
Project project = myFixture.getProject();
ProjectInfo projectInfo = new ProjectInfo(new AnalysisScope(project), false);
new ASTReader(projectInfo, new ProgressIndicatorBase());
SystemObject systemObject = ASTReader.getSystemObject();
MySystem mySystem = new MySystem(systemObject, true);
MyClass myClass = mySystem.getClassIterator().next();
MyAttribute testField = myClass.getAttributeList().get(fieldNumber);
List<String> entitySet = new ArrayList<>(testField.getFullEntitySet());
String fieldName = "FIELD";
if (fieldNumber == 1) {
fieldName = "extraField";
} else if (fieldNumber == 2) {
fieldName = "SWITCH_CASE_TEST";
}
assertEquals(fieldName + "'s entity set does not contain given method.", 2, entitySet.size());
}
@Nullable
private ExtractClassCandidateGroup getExractClassCandidateGroup(@NotNull String classFileName) {
myFixture.setTestDataPath(PATH_TO_TESTDATA);
myFixture.configureByFile(PATH_TO_TESTS + classFileName);
Project project = myFixture.getProject();
PsiFile psiFile = FilenameIndex.getFilesByName(project, classFileName, GlobalSearchScope.allScope(project))[0];
ProjectInfo projectInfo = new ProjectInfo(new AnalysisScope(project), false);
Set<ExtractClassCandidateGroup> set = getExtractClassRefactoringOpportunities(projectInfo, new ProgressIndicatorBase());
if (set.isEmpty()) {
return null;
}
return set.iterator().next();
}
@Nonnull
public static GlobalInspectionContextImpl createGlobalContextForTool(@Nonnull AnalysisScope scope,
@Nonnull final Project project,
@Nonnull InspectionManagerEx inspectionManager,
@Nonnull final InspectionToolWrapper... toolWrappers) {
final InspectionProfileImpl profile = InspectionProfileImpl.createSimple("test", project, toolWrappers);
GlobalInspectionContextImpl context = new GlobalInspectionContextImpl(project, inspectionManager.getContentManager()) {
@Override
protected List<Tools> getUsedTools() {
try {
InspectionProfileImpl.INIT_INSPECTIONS = true;
for (InspectionToolWrapper tool : toolWrappers) {
profile.enableTool(tool.getShortName(), project);
}
return profile.getAllEnabledInspectionTools(project);
}
finally {
InspectionProfileImpl.INIT_INSPECTIONS = false;
}
}
};
context.setCurrentScope(scope);
return context;
}
protected void launchInspections(@Nonnull final AnalysisScope scope) {
ApplicationManager.getApplication().assertIsDispatchThread();
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
LOG.info("Code inspection started");
ProgressManager.getInstance().run(new Task.Backgroundable(getProject(), InspectionsBundle.message("inspection.progress.title"), true,
createOption()) {
@Override
public void run(@Nonnull ProgressIndicator indicator) {
performInspectionsWithProgress(scope, false, false);
}
@RequiredUIAccess
@Override
public void onSuccess() {
notifyInspectionsFinished();
}
});
}
@Nullable
private AnalysisScope getScope() {
final Set<PsiFile> selectedScope = getSelectedScope(myRightTree);
Set<PsiFile> result = new HashSet<PsiFile>();
((PackageDependenciesNode)myLeftTree.getModel().getRoot()).fillFiles(result, !mySettings.UI_FLATTEN_PACKAGES);
selectedScope.removeAll(result);
if (selectedScope.isEmpty()) return null;
List<VirtualFile> files = new ArrayList<VirtualFile>();
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
for (PsiFile psiFile : selectedScope) {
final VirtualFile file = psiFile.getVirtualFile();
LOG.assertTrue(file != null);
if (fileIndex.isInContent(file)) {
files.add(file);
}
}
if (!files.isEmpty()) {
return new AnalysisScope(myProject, files);
}
return null;
}
public RefManagerImpl(@Nonnull Project project, @Nullable AnalysisScope scope, @Nonnull GlobalInspectionContext context) {
myProject = project;
myScope = scope;
myContext = context;
myPsiManager = PsiManager.getInstance(project);
myRefProject = new RefProjectImpl(this);
for (InspectionExtensionsFactory factory : InspectionExtensionsFactory.EP_NAME.getExtensionList()) {
final RefManagerExtension<?> extension = factory.createRefManagerExtension(this);
if (extension != null) {
myExtensions.put(extension.getID(), extension);
for (Language language : extension.getLanguages()) {
myLanguageExtensions.put(language, extension);
}
}
}
if (scope != null) {
for (Module module : ModuleManager.getInstance(getProject()).getModules()) {
getRefModule(module);
}
}
}
@Override
public void actionPerformed(final AnActionEvent e) {
final AnalysisScope scope = getScope();
LOG.assertTrue(scope != null);
final DependenciesBuilder builder;
if (!myForward) {
builder = new BackwardDependenciesBuilder(myProject, scope, myScopeOfInterest);
} else {
builder = new ForwardDependenciesBuilder(myProject, scope, myTransitiveBorder);
}
ProgressManager.getInstance().runProcessWithProgressAsynchronously(myProject, AnalysisScopeBundle.message("package.dependencies.progress.title"), new Runnable() {
@Override
public void run() {
builder.analyze();
}
}, new Runnable() {
@Override
public void run() {
myBuilders.add(builder);
myDependencies.putAll(builder.getDependencies());
myIllegalDependencies.putAll(builder.getIllegalDependencies());
exclude(myExcluded);
rebuild();
}
}, null, new PerformAnalysisInBackgroundOption(myProject));
}
@Nonnull
public static InspectionResultsView showOfflineView(@Nonnull Project project,
@Nonnull Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap,
@Nonnull InspectionProfile inspectionProfile,
@Nonnull String title) {
final AnalysisScope scope = new AnalysisScope(project);
final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project);
final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
context.setExternalProfile(inspectionProfile);
context.setCurrentScope(scope);
context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>());
final InspectionResultsView view = new InspectionResultsView(project, inspectionProfile, scope, context,
new OfflineInspectionRVContentProvider(resMap, project));
((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted();
view.update();
TreeUtil.selectFirstNode(view.getTree());
context.addView(view, title);
return view;
}
@Override
protected DependenciesBuilder createDependenciesBuilder(AnalysisScope scope) {
return new ForwardDependenciesBuilder(myProject, scope) {
@Override
public void analyze() {
super.analyze();
final Map<PsiFile,Set<PsiFile>> dependencies = getDependencies();
for (PsiFile file : dependencies.keySet()) {
final Set<PsiFile> files = dependencies.get(file);
final Iterator<PsiFile> iterator = files.iterator();
while (iterator.hasNext()) {
PsiFile next = iterator.next();
final VirtualFile virtualFile = next.getVirtualFile();
if (virtualFile == null || !myTargetScope.contains(virtualFile)) {
iterator.remove();
}
}
}
}
};
}
/**
* Opens definition of method and highlights statements, which should be extracted.
*
* @param sourceMethod method from which code is proposed to be extracted into separate method.
* @param scope scope of the current project.
* @param slice computation slice.
*/
private static void openDefinition(@Nullable PsiMethod sourceMethod, AnalysisScope scope, ASTSlice slice) {
new Task.Backgroundable(scope.getProject(), "Search Definition") {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
}
@Override
public void onSuccess() {
if (sourceMethod != null) {
Set<SmartPsiElementPointer<PsiElement>> statements = slice.getSliceStatements();
PsiStatement psiStatement = (PsiStatement) statements.iterator().next().getElement();
if (psiStatement != null && psiStatement.isValid()) {
EditorHelper.openInEditor(psiStatement);
Editor editor = FileEditorManager.getInstance(sourceMethod.getProject()).getSelectedTextEditor();
if (editor != null) {
TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
editor.getMarkupModel().removeAllHighlighters();
statements.stream()
.filter(statement -> statement.getElement() != null)
.forEach(statement ->
editor.getMarkupModel().addRangeHighlighter(statement.getElement().getTextRange().getStartOffset(),
statement.getElement().getTextRange().getEndOffset(), HighlighterLayer.SELECTION,
attributes, HighlighterTargetArea.EXACT_RANGE));
}
}
}
}
}.queue();
}
MoveMethodPanel(@NotNull AnalysisScope scope) {
this.scope = scope;
this.scopeChooserCombo = new ScopeChooserCombo(scope.getProject());
setLayout(new BorderLayout());
model = new MoveMethodTableModel(refactorings);
setupGUI();
}
private void browseCustomScope(Project project) {
EditScopesDialog dialog = EditScopesDialog.showDialog(project, null);
if (dialog.isOK()) {
if (dialog.getSelectedScope() != null) {
customScope = new AnalysisScope(GlobalSearchScopesCore.filterScope(project, dialog.getSelectedScope()), project);
configureComboBox(customScope.getDisplayName());
}
}
}
public AnalysisScope getScope() {
String s = getComboBox().getSelectedItem().toString();
if (IntelliJDeodorantBundle.message("scope.all.files").equals(s)) {
return new AnalysisScope(project);
} else if (IntelliJDeodorantBundle.message("scope.current.file").equals(s)) {
return getCurrentFileScope();
} else if (IntelliJDeodorantBundle.message("scope.opened.files").equals(s)) {
return getOpenedFilesScope();
}
return customScope;
}
private AnalysisScope getCurrentFileScope() {
FileEditor currentEditor = FileEditorManager.getInstance(project).getSelectedEditor();
if (currentEditor != null) {
VirtualFile currentFile = currentEditor.getFile();
PsiFile file = PsiManager.getInstance(project).findFile(currentFile);
if (file instanceof PsiJavaFile)
return new AnalysisScope(project, Collections.singletonList(currentFile));
}
return null;
}
/**
* Adds a panel for each code smell to the main panel.
*
* @param project current project.
*/
private void addRefactoringPanels(Project project) {
JTabbedPane jTabbedPane = new JBTabbedPane();
jTabbedPane.add(IntelliJDeodorantBundle.message("feature.envy.smell.name"), new MoveMethodPanel(new AnalysisScope(project)));
jTabbedPane.add(IntelliJDeodorantBundle.message("long.method.smell.name"), new ExtractMethodPanel(new AnalysisScope(project)));
jTabbedPane.add(IntelliJDeodorantBundle.message("god.class.smell.name"), new GodClassPanel(new AnalysisScope(project)));
jTabbedPane.add(IntelliJDeodorantBundle.message("type.state.checking.smell.name"), new TypeCheckingPanel(new AnalysisScope(project)));
setContent(jTabbedPane);
}
@Override
public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
ContentManager contentManager = toolWindow.getContentManager();
AnalysisScope scope = new AnalysisScope(project);
Content moveMethodPanel = contentManager.getFactory().createContent(new MoveMethodPanel(scope), IntelliJDeodorantBundle.message("feature.envy.smell.name"), false);
Content extractMethodPanel = contentManager.getFactory().createContent(new ExtractMethodPanel(scope), IntelliJDeodorantBundle.message("long.method.smell.name"), false);
Content godClassPanel = contentManager.getFactory().createContent(new GodClassPanel(scope), IntelliJDeodorantBundle.message("god.class.smell.name"), false);
Content typeCheckPanel = contentManager.getFactory().createContent(new TypeCheckingPanel(scope), IntelliJDeodorantBundle.message("type.state.checking.smell.name"), false);
contentManager.addContent(moveMethodPanel);
contentManager.addContent(extractMethodPanel);
contentManager.addContent(godClassPanel);
contentManager.addContent(typeCheckPanel);
}
public GodClassPanel(@NotNull AnalysisScope scope) {
super(scope,
"god.class.identification.indicator",
new ExtractClassRefactoringType(),
new GodClassTreeTableModel(Collections.emptyList(), COLUMN_NAMES),
REFACTOR_DEPTH);
}
TypeCheckingPanel(@NotNull AnalysisScope scope) {
super(scope,
"type.state.checking.identification.indicator",
new TypeCheckRefactoringType(scope.getProject()),
new TypeCheckingTreeTableModel(
Collections.emptyList(),
COLUMN_NAMES,
scope.getProject()
),
REFACTOR_DEPTH
);
}
public ProjectInfo(@NotNull AnalysisScope scope, boolean analyseAllFiles) {
this.project = scope.getProject();
List<PsiJavaFile> psiFiles = analyseAllFiles ? PsiUtils.extractFiles(project) : PsiUtils.extractFiles(project).stream().filter(scope::contains).collect(Collectors.toList());
this.psiClasses = psiFiles.stream()
.flatMap(psiFile -> PsiUtils.extractClasses(psiFile).stream())
.collect(Collectors.toList());
this.psiMethods = psiClasses.stream()
.flatMap(psiClass -> PsiUtils.extractMethods(psiClass).stream())
.collect(Collectors.toList());
}
public void testSubinterface() {
initTest();
Project project = myFixture.getProject();
Set<TypeCheckEliminationGroup> set = JDeodorantFacade.getTypeCheckEliminationRefactoringOpportunities(
new ProjectInfo(new AnalysisScope(project), false), fakeProgressIndicator
);
assertEquals(0, set.size());
checkTest();
}
private List<MoveMethodCandidateRefactoring> getMoveMethodCandidates(String fromClass, String toClass) {
myFixture.addFileToProject("src/resources/A.java", fromClass);
myFixture.addFileToProject("src/resources/B.java", toClass);
myFixture.allowTreeAccessForAllFiles();
Project project = myFixture.getProject();
ProjectInfo projectInfo = new ProjectInfo(new AnalysisScope(project), true);
return JDeodorantFacade.getMoveMethodRefactoringOpportunities(projectInfo, new ProgressIndicatorBase(), new HashSet<>(Arrays.asList("testCases.featureEnvy.A", "testCases.featureEnvy.B")));
}
@Override
public void runInspection(@NotNull AnalysisScope scope, @NotNull InspectionManager manager, @NotNull GlobalInspectionContext globalContext, @NotNull ProblemDescriptionsProcessor processor) {
GaugeErrors.init();
Module[] modules = ModuleManager.getInstance(globalContext.getProject()).getModules();
for (Module module : modules) {
File dir = GaugeUtil.moduleDir(module);
GaugeErrors.add(dir.getAbsolutePath(), GaugeInspectionHelper.getErrors(dir));
}
}
private void processMethodsDuplicates() {
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
if (!myTargetSuperClass.isValid()) return;
final Query<PsiClass> search = ClassInheritorsSearch.search(myTargetSuperClass);
final Set<VirtualFile> hierarchyFiles = new HashSet<VirtualFile>();
for (PsiClass aClass : search) {
final PsiFile containingFile = aClass.getContainingFile();
if (containingFile != null) {
final VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile != null) {
hierarchyFiles.add(virtualFile);
}
}
}
final Set<PsiMember> methodsToSearchDuplicates = new HashSet<PsiMember>();
for (PsiMember psiMember : myMembersAfterMove) {
if (psiMember instanceof PsiMethod && psiMember.isValid() && ((PsiMethod)psiMember).getBody() != null) {
methodsToSearchDuplicates.add(psiMember);
}
}
MethodDuplicatesHandler.invokeOnScope(myProject, methodsToSearchDuplicates, new AnalysisScope(myProject, hierarchyFiles), true);
}
});
}
}, MethodDuplicatesHandler.REFACTORING_NAME, true, myProject);
}
/**
* Runs the global inspection. If building of the reference graph was requested by one of the
* global inspection tools, this method is called after the graph has been built and before the
* external usages are processed. The default implementation of the method passes each node
* of the graph for processing to {@link #checkElement(RefEntity, AnalysisScope, InspectionManager, GlobalInspectionContext)}.
*
* @param scope the scope on which the inspection was run.
* @param manager the inspection manager instance for the project on which the inspection was run.
* @param globalContext the context for the current global inspection run.
* @param problemDescriptionsProcessor the collector for problems reported by the inspection
*/
public void runInspection(@Nonnull final AnalysisScope scope,
@Nonnull final InspectionManager manager,
@Nonnull final GlobalInspectionContext globalContext,
@Nonnull final ProblemDescriptionsProcessor problemDescriptionsProcessor) {
globalContext.getRefManager().iterate(new RefVisitor() {
@Override public void visitElement(@Nonnull RefEntity refEntity) {
if (!globalContext.shouldCheck(refEntity, GlobalInspectionTool.this)) return;
CommonProblemDescriptor[] descriptors = checkElement(refEntity, scope, manager, globalContext, problemDescriptionsProcessor);
if (descriptors != null) {
problemDescriptionsProcessor.addProblemElement(refEntity, descriptors);
}
}
});
}
@Override
public final void runInspection(@Nonnull AnalysisScope scope,
@Nonnull InspectionManager manager,
@Nonnull GlobalInspectionContext globalContext,
@Nonnull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
throw new IncorrectOperationException("You must override checkFile() instead");
}