public static void findUsages( @NotNull FindModel findModel, @NotNull final Project project, @NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) { findUsages(findModel, project, consumer, processPresentation, Collections.emptySet()); }
@NotNull private static Set<PsiClassType> filterInProjectExceptions( @Nullable PsiMethod targetMethod, @NotNull List<PsiClassType> unhandledExceptions) { if (targetMethod == null) return Collections.emptySet(); Set<PsiClassType> result = new HashSet<PsiClassType>(); if (targetMethod.getManager().isInProject(targetMethod)) { PsiMethod[] superMethods = targetMethod.findSuperMethods(); for (PsiMethod superMethod : superMethods) { Set<PsiClassType> classTypes = filterInProjectExceptions(superMethod, unhandledExceptions); result.addAll(classTypes); } if (superMethods.length == 0) { result.addAll(unhandledExceptions); } } else { PsiClassType[] referencedTypes = targetMethod.getThrowsList().getReferencedTypes(); for (PsiClassType referencedType : referencedTypes) { PsiClass psiClass = referencedType.resolve(); if (psiClass == null) continue; for (PsiClassType exception : unhandledExceptions) { if (referencedType.isAssignableFrom(exception)) result.add(exception); } } } return result; }
public String[] knownNamespaces() { final PsiElement parentElement = getParent(); BidirectionalMap<String, String> map = initNamespaceMaps(parentElement); Set<String> known = Collections.emptySet(); if (map != null) { known = new HashSet<String>(map.values()); } if (parentElement instanceof XmlTag) { if (known.isEmpty()) return ((XmlTag) parentElement).knownNamespaces(); ContainerUtil.addAll(known, ((XmlTag) parentElement).knownNamespaces()); } else { XmlExtension xmlExtension = XmlExtension.getExtensionByElement(this); if (xmlExtension != null) { final XmlFile xmlFile = xmlExtension.getContainingFile(this); if (xmlFile != null) { final XmlTag rootTag = xmlFile.getRootTag(); if (rootTag != null && rootTag != this) { if (known.isEmpty()) return rootTag.knownNamespaces(); ContainerUtil.addAll(known, rootTag.knownNamespaces()); } } } } return ArrayUtil.toStringArray(known); }
@NotNull private static Set<PsiClass> findRelatedActivitiesForMenu( @NotNull XmlFile file, @NotNull AndroidFacet facet) { final String resType = ResourceType.MENU.getName(); final String resourceName = AndroidCommonUtils.getResourceName(resType, file.getName()); final PsiField[] fields = AndroidResourceUtil.findResourceFields(facet, resType, resourceName, true); if (fields.length == 0) { return Collections.emptySet(); } final Module module = facet.getModule(); final GlobalSearchScope scope = module.getModuleScope(false); final PsiClass activityClass = findActivityClass(module); if (activityClass == null) { return Collections.emptySet(); } final Set<PsiClass> result = new HashSet<PsiClass>(); ReferencesSearch.search(fields[0], scope) .forEach( new Processor<PsiReference>() { @Override public boolean process(PsiReference reference) { final PsiElement element = reference.getElement(); if (element == null) { return true; } final PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (aClass != null && !result.contains(aClass) && aClass.isInheritor(activityClass, true)) { result.add(aClass); } return true; } }); return result; }
@NotNull private Set<String> addAllRestrictedProperties() { if (myRefExpr.getQualifier() != null) { return Collections.emptySet(); } Set<String> propertyNames = new HashSet<String>(); for (GrTypeDefinition containingClass = PsiTreeUtil.getParentOfType(myRefExpr, GrTypeDefinition.class); containingClass != null; containingClass = PsiTreeUtil.getParentOfType(containingClass, GrTypeDefinition.class)) { for (PsiField field : containingClass.getFields()) { propertyNames.add(field.getName()); } } return propertyNames; }
@Override public Collection<? extends PsiFile> getStepDefinitionContainers( @NotNull GherkinFile featureFile) { final Module module = ModuleUtilCore.findModuleForPsiElement(featureFile); if (module == null) { return Collections.emptySet(); } List<AbstractStepDefinition> stepDefs = loadStepsFor(featureFile, module); Set<PsiFile> result = new HashSet<PsiFile>(); for (AbstractStepDefinition stepDef : stepDefs) { PsiElement stepDefElement = stepDef.getElement(); if (stepDefElement != null) { final PsiFile psiFile = stepDefElement.getContainingFile(); if (isWritableStepLikeFile(psiFile, psiFile.getParent())) { result.add(psiFile); } } } return result; }
@NotNull private Set<PsiFile> getFilesForFastWordSearch() { String stringToFind = myFindModel.getStringToFind(); if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) { return Collections.emptySet(); } SearchScope customScope = myFindModel.getCustomScope(); GlobalSearchScope scope = myPsiDirectory != null ? GlobalSearchScopesCore.directoryScope(myPsiDirectory, true) : myModule != null ? myModule.getModuleContentScope() : customScope instanceof GlobalSearchScope ? (GlobalSearchScope) customScope : toGlobal(customScope); if (scope == null) { scope = ProjectScope.getContentScope(myProject); } final Set<PsiFile> resultFiles = new LinkedHashSet<PsiFile>(); if (TrigramIndex.ENABLED) { final Set<Integer> keys = ContainerUtil.newTroveSet(); TrigramBuilder.processTrigrams( stringToFind, new TrigramBuilder.TrigramProcessor() { @Override public boolean execute(int value) { keys.add(value); return true; } }); if (!keys.isEmpty()) { final List<VirtualFile> hits = new ArrayList<VirtualFile>(); final GlobalSearchScope finalScope = scope; ApplicationManager.getApplication() .runReadAction( new Runnable() { @Override public void run() { FileBasedIndex.getInstance() .getFilesWithKey( TrigramIndex.INDEX_ID, keys, new CommonProcessors.CollectProcessor<VirtualFile>(hits), finalScope); } }); for (VirtualFile hit : hits) { if (myFileMask.value(hit)) { PsiFile file = findFile(hit); if (file != null) { resultFiles.add(file); } } } return resultFiles; } } PsiSearchHelperImpl helper = (PsiSearchHelperImpl) PsiSearchHelper.SERVICE.getInstance(myProject); helper.processFilesWithText( scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, new Processor<VirtualFile>() { @Override public boolean process(VirtualFile file) { if (myFileMask.value(file)) { ContainerUtil.addIfNotNull(resultFiles, findFile(file)); } return true; } }); // in case our word splitting is incorrect CacheManager cacheManager = CacheManager.SERVICE.getInstance(myProject); PsiFile[] filesWithWord = cacheManager.getFilesWithWord( stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive()); for (PsiFile file : filesWithWord) { if (myFileMask.value(file.getVirtualFile())) { resultFiles.add(file); } } return resultFiles; }
public static Set<PsiField> getNonInitializedFields(PsiElement element) { final PsiStatement statement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, true, PsiClass.class); if (statement == null || method == null || !method.isConstructor()) { return Collections.emptySet(); } PsiElement parent = element.getParent(); while (parent != statement) { PsiElement next = parent.getParent(); if (next instanceof PsiAssignmentExpression && parent == ((PsiAssignmentExpression) next).getLExpression()) { return Collections.emptySet(); } if (parent instanceof PsiReferenceExpression && next instanceof PsiExpressionStatement) { return Collections.emptySet(); } parent = next; } final Set<PsiField> fields = new HashSet<PsiField>(); final PsiClass containingClass = method.getContainingClass(); assert containingClass != null; for (PsiField field : containingClass.getFields()) { if (!field.hasModifierProperty(PsiModifier.STATIC) && field.getInitializer() == null && !isInitializedImplicitly(field)) { fields.add(field); } } method.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitAssignmentExpression(PsiAssignmentExpression expression) { if (expression.getTextRange().getStartOffset() < statement.getTextRange().getStartOffset()) { final PsiExpression lExpression = expression.getLExpression(); if (lExpression instanceof PsiReferenceExpression) { //noinspection SuspiciousMethodCalls fields.remove(((PsiReferenceExpression) lExpression).resolve()); } } super.visitAssignmentExpression(expression); } @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { if (expression.getTextRange().getStartOffset() < statement.getTextRange().getStartOffset()) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); if (methodExpression.textMatches("this")) { fields.clear(); } } super.visitMethodCallExpression(expression); } }); return fields; }
@NotNull public Class classToClass(@NotNull PsiClass psiClass) { Set<String> modifiers = modifiersListToModifiersSet(psiClass.getModifierList()); List<Field> fields = fieldsToFieldList(psiClass.getFields(), psiClass); List<Element> typeParameters = elementsToElementList(psiClass.getTypeParameters()); List<Type> implementsTypes = typesToNotNullableTypeList(psiClass.getImplementsListTypes()); List<Type> extendsTypes = typesToNotNullableTypeList(psiClass.getExtendsListTypes()); IdentifierImpl name = new IdentifierImpl(psiClass.getName()); List<Expression> baseClassParams = new LinkedList<Expression>(); List<Member> members = getMembers(psiClass); // we try to find super() call and generate class declaration like that: class A(name: String, i // : Int) : Base(name) SuperVisitor visitor = new SuperVisitor(); psiClass.accept(visitor); Collection<PsiExpressionList> resolvedSuperCallParameters = visitor.getResolvedSuperCallParameters(); if (resolvedSuperCallParameters.size() == 1) { baseClassParams.addAll( expressionsToExpressionList( resolvedSuperCallParameters.toArray(new PsiExpressionList[1])[0].getExpressions())); } // we create primary constructor from all non final fields and fields without initializers if (!psiClass.isEnum() && !psiClass.isInterface() && psiClass.getConstructors().length > 1 && getPrimaryConstructorForThisCase(psiClass) == null) { List<Field> finalOrWithEmptyInitializer = getFinalOrWithEmptyInitializer(fields); Map<String, String> initializers = new HashMap<String, String>(); for (Member m : members) { // and modify secondaries if (m.getKind() == INode.Kind.CONSTRUCTOR) { Function f = (Function) m; if (!((Constructor) f).isPrimary()) { for (Field fo : finalOrWithEmptyInitializer) { String init = getDefaultInitializer(fo); initializers.put(fo.getIdentifier().toKotlin(), init); } List<Statement> newStatements = new LinkedList<Statement>(); for (Statement s : f.getBlock().getStatements()) { boolean isRemoved = false; if (s.getKind() == INode.Kind.ASSIGNMENT_EXPRESSION) { AssignmentExpression assignmentExpression = (AssignmentExpression) s; if (assignmentExpression.getLeft().getKind() == INode.Kind.CALL_CHAIN) { for (Field fo : finalOrWithEmptyInitializer) { String id = fo.getIdentifier().toKotlin(); if (((CallChainExpression) assignmentExpression.getLeft()) .getIdentifier() .toKotlin() .endsWith("." + id)) { initializers.put(id, assignmentExpression.getRight().toKotlin()); isRemoved = true; } } } } if (!isRemoved) { newStatements.add(s); } } newStatements.add( 0, new DummyStringExpression( "val __ = " + createPrimaryConstructorInvocation( name.toKotlin(), finalOrWithEmptyInitializer, initializers))); f.setBlock(new Block(newStatements)); } } } members.add( new Constructor( Identifier.EMPTY_IDENTIFIER, Collections.<String>emptySet(), new ClassType(name), Collections.<Element>emptyList(), new ParameterList(createParametersFromFields(finalOrWithEmptyInitializer)), new Block(createInitStatementsFromFields(finalOrWithEmptyInitializer)), true)); } if (psiClass.isInterface()) { return new Trait( this, name, modifiers, typeParameters, extendsTypes, Collections.<Expression>emptyList(), implementsTypes, members); } if (psiClass.isEnum()) { return new Enum( this, name, modifiers, typeParameters, Collections.<Type>emptyList(), Collections.<Expression>emptyList(), implementsTypes, members); } return new Class( this, name, modifiers, typeParameters, extendsTypes, baseClassParams, implementsTypes, members); }
private static Pair<Set<String>, Set<TextWithImports>> findReferencedVars( Set<String> visibleVars, SourcePosition position) { final int line = position.getLine(); if (line < 0) { return Pair.create(Collections.<String>emptySet(), Collections.<TextWithImports>emptySet()); } final PsiFile positionFile = position.getFile(); if (!positionFile.getLanguage().isKindOf(JavaLanguage.INSTANCE)) { return Pair.create(visibleVars, Collections.<TextWithImports>emptySet()); } final VirtualFile vFile = positionFile.getVirtualFile(); final Document doc = vFile != null ? FileDocumentManager.getInstance().getDocument(vFile) : null; if (doc == null || doc.getLineCount() == 0 || line > (doc.getLineCount() - 1)) { return Pair.create(Collections.<String>emptySet(), Collections.<TextWithImports>emptySet()); } final TextRange limit = calculateLimitRange(positionFile, doc, line); int startLine = Math.max(limit.getStartOffset(), line - 1); startLine = Math.min(startLine, limit.getEndOffset()); while (startLine > limit.getStartOffset() && shouldSkipLine(positionFile, doc, startLine)) { startLine--; } final int startOffset = doc.getLineStartOffset(startLine); int endLine = Math.min(line + 2, limit.getEndOffset()); while (endLine < limit.getEndOffset() && shouldSkipLine(positionFile, doc, endLine)) { endLine++; } final int endOffset = doc.getLineEndOffset(endLine); final TextRange lineRange = new TextRange(startOffset, endOffset); if (!lineRange.isEmpty()) { final int offset = CharArrayUtil.shiftForward(doc.getCharsSequence(), doc.getLineStartOffset(line), " \t"); PsiElement element = positionFile.findElementAt(offset); if (element != null) { PsiMethod method = PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class); if (method != null) { element = method; } else { PsiField field = PsiTreeUtil.getNonStrictParentOfType(element, PsiField.class); if (field != null) { element = field; } else { final PsiClassInitializer initializer = PsiTreeUtil.getNonStrictParentOfType(element, PsiClassInitializer.class); if (initializer != null) { element = initializer; } } } //noinspection unchecked if (element instanceof PsiCompiledElement) { return Pair.create(visibleVars, Collections.<TextWithImports>emptySet()); } else { VariablesCollector collector = new VariablesCollector(visibleVars, adjustRange(element, lineRange)); element.accept(collector); return Pair.create(collector.getVars(), collector.getExpressions()); } } } return Pair.create(Collections.<String>emptySet(), Collections.<TextWithImports>emptySet()); }