public void add(NullAnalysisResult duplicate) { for (int i = 0; i < groupedByValue.length; i++) { Collection<PsiElement> elements = groupedByValue[i]; Collection<PsiElement> other = duplicate.groupedByValue[i]; elements.addAll(other); } }
@Nullable private Collection<DfaMemoryState> createInitialStates( @NotNull PsiElement psiBlock, @NotNull InstructionVisitor visitor) { PsiElement container = PsiTreeUtil.getParentOfType(psiBlock, PsiClass.class, PsiLambdaExpression.class); if (container != null && (!(container instanceof PsiClass) || PsiUtil.isLocalOrAnonymousClass((PsiClass) container))) { final PsiElement parent = container.getParent(); final PsiCodeBlock block = DfaPsiUtil.getTopmostBlockInSameClass(parent); if (block != null) { final RunnerResult result = analyzeMethod(block, visitor); if (result == RunnerResult.OK) { final Collection<DfaMemoryState> closureStates = myNestedClosures.get(DfaPsiUtil.getTopmostBlockInSameClass(psiBlock)); if (!closureStates.isEmpty()) { return closureStates; } } return null; } } return Collections.singletonList(createMemoryState()); }
@NotNull private static PsiSubstitutor replaceVariables(Collection<InferenceVariable> inferenceVariables) { final List<InferenceVariable> targetVars = new ArrayList<InferenceVariable>(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; final InferenceVariable[] oldVars = inferenceVariables.toArray(new InferenceVariable[inferenceVariables.size()]); for (InferenceVariable variable : oldVars) { final InferenceVariable newVariable = new InferenceVariable( variable.getCallContext(), variable.getParameter(), variable.getName()); substitutor = substitutor.put( variable, JavaPsiFacade.getElementFactory(variable.getProject()).createType(newVariable)); targetVars.add(newVariable); if (variable.isThrownBound()) { newVariable.setThrownBound(); } } for (int i = 0; i < targetVars.size(); i++) { InferenceVariable var = targetVars.get(i); for (InferenceBound boundType : InferenceBound.values()) { for (PsiType bound : oldVars[i].getBounds(boundType)) { var.addBound(substitutor.substitute(bound), boundType, null); } } } return substitutor; }
public synchronized boolean addRoots( @NotNull String name, Module moduleContext, @NotNull Object elements) { Collection<AbstractTreeNode> nodes = AddToFavoritesAction.createNodes( myProject, moduleContext, elements, true, getViewSettings()); return !nodes.isEmpty() && addRoots(name, nodes); }
private List<HighlightInfo> getHighlights() { if (myReadAccessRanges.isEmpty() && myWriteAccessRanges.isEmpty()) { return Collections.emptyList(); } Set<Pair<Object, TextRange>> existingMarkupTooltips = new HashSet<Pair<Object, TextRange>>(); for (RangeHighlighter highlighter : myEditor.getMarkupModel().getAllHighlighters()) { existingMarkupTooltips.add( Pair.create( highlighter.getErrorStripeTooltip(), new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset()))); } List<HighlightInfo> result = new ArrayList<HighlightInfo>(myReadAccessRanges.size() + myWriteAccessRanges.size()); for (TextRange range : myReadAccessRanges) { ContainerUtil.addIfNotNull( createHighlightInfo( range, HighlightInfoType.ELEMENT_UNDER_CARET_READ, existingMarkupTooltips), result); } for (TextRange range : myWriteAccessRanges) { ContainerUtil.addIfNotNull( createHighlightInfo( range, HighlightInfoType.ELEMENT_UNDER_CARET_WRITE, existingMarkupTooltips), result); } return result; }
@Override @Nullable public Collection<PsiImportStatementBase> findRedundantImports(final PsiJavaFile file) { final PsiImportList importList = file.getImportList(); if (importList == null) return null; final PsiImportStatementBase[] imports = importList.getAllImportStatements(); if (imports.length == 0) return null; Set<PsiImportStatementBase> allImports = new THashSet<PsiImportStatementBase>(Arrays.asList(imports)); final Collection<PsiImportStatementBase> redundant; if (FileTypeUtils.isInServerPageFile(file)) { // remove only duplicate imports redundant = ContainerUtil.newIdentityTroveSet(); ContainerUtil.addAll(redundant, imports); redundant.removeAll(allImports); for (PsiImportStatementBase importStatement : imports) { if (importStatement instanceof JspxImportStatement && importStatement.isForeignFileImport()) { redundant.remove(importStatement); } } } else { redundant = allImports; final List<PsiFile> roots = file.getViewProvider().getAllFiles(); for (PsiElement root : roots) { root.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { if (!reference.isQualified()) { final JavaResolveResult resolveResult = reference.advancedResolve(false); if (!inTheSamePackage(file, resolveResult.getElement())) { final PsiElement resolveScope = resolveResult.getCurrentFileResolveScope(); if (resolveScope instanceof PsiImportStatementBase) { final PsiImportStatementBase importStatementBase = (PsiImportStatementBase) resolveScope; redundant.remove(importStatementBase); } } } super.visitReferenceElement(reference); } private boolean inTheSamePackage(PsiJavaFile file, PsiElement element) { if (element instanceof PsiClass && ((PsiClass) element).getContainingClass() == null) { final PsiFile containingFile = element.getContainingFile(); if (containingFile instanceof PsiJavaFile) { return Comparing.strEqual( file.getPackageName(), ((PsiJavaFile) containingFile).getPackageName()); } } return false; } }); } } return redundant; }
private static void highlightTodos( @NotNull PsiFile file, @NotNull CharSequence text, int startOffset, int endOffset, @NotNull ProgressIndicator progress, @NotNull ProperTextRange priorityRange, @NotNull Collection<HighlightInfo> result, @NotNull Collection<HighlightInfo> outsideResult) { PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(file.getProject()); TodoItem[] todoItems = helper.findTodoItems(file, startOffset, endOffset); if (todoItems.length == 0) return; for (TodoItem todoItem : todoItems) { progress.checkCanceled(); TextRange range = todoItem.getTextRange(); String description = text.subSequence(range.getStartOffset(), range.getEndOffset()).toString(); TextAttributes attributes = todoItem.getPattern().getAttributes().getTextAttributes(); HighlightInfo info = HighlightInfo.createHighlightInfo( HighlightInfoType.TODO, range, description, description, attributes); assert info != null; if (priorityRange.containsRange(info.getStartOffset(), info.getEndOffset())) { result.add(info); } else { outsideResult.add(info); } } }
@Override public Collection<String> findConflicts( PsiElement element, PsiElement[] elements, UsageInfo[] usages) { String methodRefFound = null; if (!ApplicationManager.getApplication().isUnitTestMode() && (element instanceof PsiMethod || element instanceof PsiParameter)) { for (UsageInfo usage : usages) { final PsiElement refElement = usage.getElement(); if (refElement instanceof PsiMethodReferenceExpression) { methodRefFound = RefactoringBundle.message("expand.method.reference.warning"); break; } } } if (methodRefFound != null) { Collection<String> result = new ArrayList<>(); result.add(methodRefFound); final Collection<String> conflicts = super.findConflicts(element, elements, usages); if (conflicts != null) { result.addAll(conflicts); } return result; } return super.findConflicts(element, elements, usages); }
@Nullable public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) { final PsiClass[][] holder = new PsiClass[1][]; final Runnable process = () -> { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final Collection<PsiClass> set = new LinkedHashSet<>(); final PsiManager manager = PsiManager.getInstance(filter.getProject()); final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope()); for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) { if (filter.isAccepted(psiClass)) { if (indicator != null) { indicator.setText2( "Found test class " + ReadAction.compute(psiClass::getQualifiedName)); } set.add(psiClass); } } holder[0] = set.toArray(new PsiClass[set.size()]); }; if (sync) { ProgressManager.getInstance() .runProcessWithProgressSynchronously( process, "Searching For Tests...", true, filter.getProject()); } else { process.run(); } return holder[0]; }
public static MultiMap<PsiElement, UsageInfo> classifyUsages( Collection<? extends PsiElement> elements, UsageInfo[] usages) { final MultiMap<PsiElement, UsageInfo> result = new MultiMap<PsiElement, UsageInfo>(); for (UsageInfo usage : usages) { LOG.assertTrue(usage instanceof MoveRenameUsageInfo); if (usage.getReference() instanceof LightElement) { continue; // filter out implicit references (e.g. from derived class to super class' default // constructor) } MoveRenameUsageInfo usageInfo = (MoveRenameUsageInfo) usage; if (usage instanceof RelatedUsageInfo) { final PsiElement relatedElement = ((RelatedUsageInfo) usage).getRelatedElement(); if (elements.contains(relatedElement)) { result.putValue(relatedElement, usage); } } else { PsiElement referenced = usageInfo.getReferencedElement(); if (elements.contains(referenced)) { result.putValue(referenced, usage); } else if (referenced != null) { PsiElement indirect = referenced.getNavigationElement(); if (elements.contains(indirect)) { result.putValue(indirect, usage); } } } } return result; }
// TODO: Make it work for properties public Collection<DeclarationDescriptor> getJetCallableExtensions( @NotNull Condition<String> acceptedNameCondition, @NotNull JetSimpleNameExpression expression, @NotNull ResolveSession resolveSession, @NotNull GlobalSearchScope searchScope) { Collection<DeclarationDescriptor> resultDescriptors = new ArrayList<DeclarationDescriptor>(); BindingContext context = ResolveSessionUtils.resolveToExpression(resolveSession, expression); JetExpression receiverExpression = expression.getReceiverExpression(); if (receiverExpression != null) { JetType expressionType = context.get(BindingContext.EXPRESSION_TYPE, receiverExpression); JetScope scope = context.get(BindingContext.RESOLUTION_SCOPE, receiverExpression); if (expressionType != null && scope != null) { Collection<String> extensionFunctionsNames = getAllJetExtensionFunctionsNames(searchScope); Set<FqName> functionFQNs = new java.util.HashSet<FqName>(); // Collect all possible extension function qualified names for (String name : extensionFunctionsNames) { if (acceptedNameCondition.value(name)) { Collection<PsiElement> extensionFunctions = getJetExtensionFunctionsByName(name, searchScope); for (PsiElement extensionFunction : extensionFunctions) { if (extensionFunction instanceof JetNamedFunction) { functionFQNs.add(JetPsiUtil.getFQName((JetNamedFunction) extensionFunction)); } else if (extensionFunction instanceof PsiMethod) { FqName functionFQN = JetFromJavaDescriptorHelper.getJetTopLevelDeclarationFQN( (PsiMethod) extensionFunction); if (functionFQN != null) { functionFQNs.add(functionFQN); } } } } } // Iterate through the function with attempt to resolve found functions for (FqName functionFQN : functionFQNs) { for (CallableDescriptor functionDescriptor : ExpressionTypingUtils.canFindSuitableCall( functionFQN, project, receiverExpression, expressionType, scope, resolveSession.getModuleConfiguration())) { resultDescriptors.add(functionDescriptor); } } } } return resultDescriptors; }
@NotNull private static String toVfString(@NotNull Collection<VirtualFile> list) { List<VirtualFile> sub = new ArrayList<VirtualFile>(list).subList(0, Math.min(list.size(), 100)); return list.size() + " files: " + StringUtil.join(sub, file -> file.getName(), ", ") + (list.size() == sub.size() ? "" : "..."); }
private static void addAllIfNotPresent(Collection<String> collection, String... annotations) { for (String annotation : annotations) { LOG.assertTrue(annotation != null); if (!collection.contains(annotation)) { collection.add(annotation); } } }
@NotNull protected ResolveResult[] doMultiResolve() { final Collection<PsiPackage> packages = new HashSet<>(); for (PsiPackage parentPackage : getContext()) { packages.addAll(myReferenceSet.resolvePackageName(parentPackage, getValue())); } return PsiElementResolveResult.createResults(packages); }
private static void copyClassesImpl( final String copyClassName, final Project project, final Map<PsiFile, PsiClass[]> classes, final HashMap<PsiFile, String> map, final Object targetDirectory, final PsiDirectory defaultTargetDirectory, final String commandName, final boolean selectInActivePanel, final boolean openInEditor) { final boolean[] result = new boolean[] {false}; Runnable command = () -> { final Runnable action = () -> { try { PsiDirectory target; if (targetDirectory instanceof PsiDirectory) { target = (PsiDirectory) targetDirectory; } else { target = ((MoveDestination) targetDirectory) .getTargetDirectory(defaultTargetDirectory); } Collection<PsiFile> files = doCopyClasses(classes, map, copyClassName, target, project); if (files != null) { if (openInEditor) { for (PsiFile file : files) { CopyHandler.updateSelectionInActiveProjectView( file, project, selectInActivePanel); } EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()])); } result[0] = true; } } catch (final IncorrectOperationException ex) { ApplicationManager.getApplication() .invokeLater( () -> Messages.showMessageDialog( project, ex.getMessage(), RefactoringBundle.message("error.title"), Messages.getErrorIcon())); } }; ApplicationManager.getApplication().runWriteAction(action); }; CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand(project, command, commandName, null); if (result[0]) { ToolWindowManager.getInstance(project) .invokeLater(() -> ToolWindowManager.getInstance(project).activateEditorComponent()); } }
public Collection<PsiElement> getAdditionalElementsToDelete( @NotNull final PsiElement element, @NotNull final Collection<PsiElement> allElementsToDelete, final boolean askUser) { if (element instanceof PsiField) { PsiField field = (PsiField) element; final Project project = element.getProject(); String propertyName = JavaCodeStyleManager.getInstance(project) .variableNameToPropertyName(field.getName(), VariableKind.FIELD); PsiClass aClass = field.getContainingClass(); if (aClass != null) { boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic); if (getters != null) { final List<PsiMethod> validGetters = new ArrayList<>(1); for (PsiMethod getter : getters) { if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) { validGetters.add(getter); } } getters = validGetters.isEmpty() ? null : validGetters.toArray(new PsiMethod[validGetters.size()]); } PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false); if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical()) setter = null; if (askUser && (getters != null || setter != null)) { final String message = RefactoringMessageUtil.getGetterSetterMessage( field.getName(), RefactoringBundle.message("delete.title"), getters != null ? getters[0] : null, setter); if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog( project, message, RefactoringBundle.message("safe.delete.title"), Messages.getQuestionIcon()) != Messages.YES) { getters = null; setter = null; } } List<PsiElement> elements = new ArrayList<>(); if (setter != null) elements.add(setter); if (getters != null) Collections.addAll(elements, getters); return elements; } } return null; }
private void doPostponedFormattingInner(final FileViewProvider key) { final List<ASTNode> astNodes = myReformatElements.remove(key); final Document document = key.getDocument(); // Sort ranges by end offsets so that we won't need any offset adjustment after reformat or // reindent if (document == null) return; final VirtualFile virtualFile = key.getVirtualFile(); if (!virtualFile.isValid()) return; final TreeSet<PostprocessFormattingTask> postProcessTasks = new TreeSet<PostprocessFormattingTask>(); Collection<Disposable> toDispose = ContainerUtilRt.newArrayList(); try { // process all roots in viewProvider to find marked for reformat before elements and create // appropriate range markers handleReformatMarkers(key, postProcessTasks); toDispose.addAll(postProcessTasks); // then we create ranges by changed nodes. One per node. There ranges can intersect. Ranges // are sorted by end offset. if (astNodes != null) createActionsMap(astNodes, key, postProcessTasks); if ("true".equals(System.getProperty("check.psi.is.valid")) && ApplicationManager.getApplication().isUnitTestMode()) { checkPsiIsCorrect(key); } while (!postProcessTasks.isEmpty()) { // now we have to normalize actions so that they not intersect and ordered in most // appropriate way // (free reformatting -> reindent -> formatting under reindent) final List<PostponedAction> normalizedActions = normalizeAndReorderPostponedActions(postProcessTasks, document); toDispose.addAll(normalizedActions); // only in following loop real changes in document are made for (final PostponedAction normalizedAction : normalizedActions) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(myPsiManager.getProject()); boolean old = settings.ENABLE_JAVADOC_FORMATTING; settings.ENABLE_JAVADOC_FORMATTING = false; try { normalizedAction.execute(key); } finally { settings.ENABLE_JAVADOC_FORMATTING = old; } } } } finally { for (Disposable disposable : toDispose) { //noinspection SSBasedInspection disposable.dispose(); } } }
private static void createValueRootNode( NullAnalysisResult result, SliceRootNode oldRoot, final Map<SliceNode, NullAnalysisResult> map, SliceRootNode root, SliceNode oldRootStart, String nodeName, final int group) { Collection<PsiElement> groupedByValue = result.groupedByValue[group]; if (groupedByValue.isEmpty()) { return; } SliceLeafValueClassNode valueRoot = new SliceLeafValueClassNode(root.getProject(), root, nodeName); root.myCachedChildren.add(valueRoot); Set<PsiElement> uniqueValues = new THashSet<PsiElement>(groupedByValue, SliceLeafAnalyzer.LEAF_ELEMENT_EQUALITY); for (final PsiElement expression : uniqueValues) { SliceNode newRoot = SliceLeafAnalyzer.filterTree( oldRootStart, new NullableFunction<SliceNode, SliceNode>() { @Override public SliceNode fun(SliceNode oldNode) { if (oldNode.getDuplicate() != null) { return null; } for (PsiElement nullSuspect : group(oldNode, map, group)) { if (PsiEquivalenceUtil.areElementsEquivalent(nullSuspect, expression)) { return oldNode.copy(); } } return null; } }, new PairProcessor<SliceNode, List<SliceNode>>() { @Override public boolean process(SliceNode node, List<SliceNode> children) { if (!children.isEmpty()) return true; PsiElement element = node.getValue().getElement(); if (element == null) return false; return PsiEquivalenceUtil.areElementsEquivalent( element, expression); // leaf can be there only if it's filtering expression } }); valueRoot.myCachedChildren.add( new SliceLeafValueRootNode( root.getProject(), expression, valueRoot, Collections.singletonList(newRoot), oldRoot.getValue().params)); } }
private void getInjectedPsiFiles( @NotNull final List<PsiElement> elements1, @NotNull final List<PsiElement> elements2, @NotNull final ProgressIndicator progress, @NotNull final Set<PsiFile> outInjected) { List<DocumentWindow> injected = InjectedLanguageUtil.getCachedInjectedDocuments(myFile); Collection<PsiElement> hosts = new THashSet<PsiElement>(elements1.size() + elements2.size() + injected.size()); // rehighlight all injected PSI regardless the range, // since change in one place can lead to invalidation of injected PSI in (completely) other // place. for (DocumentWindow documentRange : injected) { progress.checkCanceled(); if (!documentRange.isValid()) continue; PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(documentRange); if (file == null) continue; PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file); if (context != null && context.isValid() && !file.getProject().isDisposed() && (myUpdateAll || new ProperTextRange(myStartOffset, myEndOffset) .intersects(context.getTextRange()))) { hosts.add(context); } } hosts.addAll(elements1); hosts.addAll(elements2); final PsiLanguageInjectionHost.InjectedPsiVisitor visitor = new PsiLanguageInjectionHost.InjectedPsiVisitor() { @Override public void visit( @NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) { synchronized (outInjected) { outInjected.add(injectedPsi); } } }; if (!JobUtil.invokeConcurrentlyUnderProgress( new ArrayList<PsiElement>(hosts), progress, false, new Processor<PsiElement>() { @Override public boolean process(PsiElement element) { progress.checkCanceled(); InjectedLanguageUtil.enumerate(element, myFile, false, visitor); return true; } })) throw new ProcessCanceledException(); }
@Override protected void addReferenceAtCaret(Collection<PsiReference> refs) { final V variable = getLocalVariable(); if (variable != null) { for (PsiReference reference : ReferencesSearch.search(variable)) { refs.add(reference); } } else { refs.clear(); } }
public static PsiElement[] getPsiElementsBySignature( Project project, @Nullable String signature) { if (signature == null) { return new PsiElement[0]; } Collection<? extends PhpNamedElement> phpNamedElementCollections = PhpIndex.getInstance(project).getBySignature(signature, null, 0); return phpNamedElementCollections.toArray(new PsiElement[phpNamedElementCollections.size()]); }
@Nullable public static PhpClass getInterface(PhpIndex phpIndex, String className) { // api workaround if (!className.startsWith("\\")) { className = "\\" + className; } Collection<PhpClass> classes = phpIndex.getInterfacesByFQN(className); return classes.isEmpty() ? null : classes.iterator().next(); }
@Nullable public static PhpClass getClassInterface(Project project, @NotNull String className) { // api workaround for at least interfaces if (!className.startsWith("\\")) { className = "\\" + className; } Collection<PhpClass> phpClasses = PhpIndex.getInstance(project).getAnyByFQN(className); return phpClasses.size() == 0 ? null : phpClasses.iterator().next(); }
@Nullable private IProperty getSelectedProperty() { final Collection<DefaultMutableTreeNode> selectedNode = getSelectedNodes(); if (selectedNode.isEmpty()) { return null; } final ResourceBundleEditorViewElement element = getSelectedElement(ContainerUtil.getFirstItem(selectedNode)); return element instanceof ResourceBundlePropertyStructureViewElement ? ((ResourceBundlePropertyStructureViewElement) element).getProperty() : null; }
@NotNull public ResolveResult[] multiResolve(boolean incompleteCode) { Collection<PsiMethod> resMethods = StripesReferenceUtil.getResolutionMethodsAsList(actionBeanClass); ResolveResult[] retval = new ResolveResult[resMethods.size()]; int i = 0; for (PsiMethod method : resMethods) { retval[i++] = new PsiElementResolveResult(method); } return retval; }
/** Return class names form jet sources in given scope which should be visible as Java classes. */ @NotNull @Override public PsiClass[] getClassesByName( @NotNull @NonNls String name, @NotNull GlobalSearchScope scope) { List<PsiClass> result = new ArrayList<PsiClass>(); IDELightClassGenerationSupport lightClassGenerationSupport = IDELightClassGenerationSupport.getInstanceForIDE(project); MultiMap<String, FqName> packageClasses = lightClassGenerationSupport.getAllPackageClasses(scope); // .namespace classes can not be indexed, since they have no explicit declarations Collection<FqName> fqNames = packageClasses.get(name); if (!fqNames.isEmpty()) { for (FqName fqName : fqNames) { PsiClass psiClass = JavaElementFinder.getInstance(project).findClass(fqName.getFqName(), scope); if (psiClass != null) { result.add(psiClass); } } } // Quick check for classes from getAllClassNames() Collection<JetClassOrObject> classOrObjects = JetShortClassNameIndex.getInstance().get(name, project, scope); if (classOrObjects.isEmpty()) { return result.toArray(new PsiClass[result.size()]); } for (JetClassOrObject classOrObject : classOrObjects) { FqName fqName = JetPsiUtil.getFQName(classOrObject); if (fqName != null) { assert fqName.shortName().getName().equals(name) : "A declaration obtained from index has non-matching name:\n" + "in index: " + name + "\n" + "declared: " + fqName.shortName() + "(" + fqName + ")"; PsiClass psiClass = JavaElementFinder.getInstance(project).findClass(fqName.getFqName(), scope); if (psiClass != null) { result.add(psiClass); } } } return result.toArray(new PsiClass[result.size()]); }
public Collection<ClassDescriptor> getJetClassesDescriptors( @NotNull Condition<String> acceptedShortNameCondition, @NotNull KotlinCodeAnalyzer analyzer) { Collection<ClassDescriptor> classDescriptors = new ArrayList<ClassDescriptor>(); for (String fqName : JetFullClassNameIndex.getInstance().getAllKeys(project)) { FqName classFQName = new FqName(fqName); if (acceptedShortNameCondition.value(classFQName.shortName().getName())) { classDescriptors.addAll( ResolveSessionUtils.getClassDescriptorsByFqName(analyzer, classFQName)); } } return classDescriptors; }
private static Collection<String> extractValuesFromParameter(PsiAnnotationMemberValue value) { Collection<String> results = new ArrayList<>(); if (value instanceof PsiArrayInitializerMemberValue) { for (PsiElement child : value.getChildren()) { if (child instanceof PsiLiteralExpression) { results.add((String) ((PsiLiteralExpression) child).getValue()); } } } else { if (value instanceof PsiLiteralExpression) { results.add((String) ((PsiLiteralExpression) value).getValue()); } } return results; }
private static void logStats(Collection<PsiFile> otherFiles, long start) { long time = System.currentTimeMillis() - start; final Multiset<String> stats = HashMultiset.create(); for (PsiFile file : otherFiles) { stats.add( StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()) .toLowerCase()); } List<String> extensions = ContainerUtil.newArrayList(stats.elementSet()); Collections.sort( extensions, new Comparator<String>() { @Override public int compare(String o1, String o2) { return stats.count(o2) - stats.count(o1); } }); String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" + "Most frequent non-indexed file extensions: "; for (int i = 0; i < Math.min(10, extensions.size()); i++) { String extension = extensions.get(i); message += extension + "(" + stats.count(extension) + ") "; } LOG.info(message); }
@Override public Collection<PsiReference> findReferencesToHighlight( final PsiElement target, final SearchScope searchScope) { if (target instanceof PsiMethod) { final PsiMethod[] superMethods = ((PsiMethod) target).findDeepestSuperMethods(); if (superMethods.length == 0) { return MethodReferencesSearch.search((PsiMethod) target, searchScope, true).findAll(); } final Collection<PsiReference> result = new ArrayList<PsiReference>(); for (PsiMethod superMethod : superMethods) { result.addAll(MethodReferencesSearch.search(superMethod, searchScope, true).findAll()); } return result; } return super.findReferencesToHighlight(target, searchScope); }