@NotNull public static <T extends PsiJavaCodeReferenceElement> JavaResolveResult[] multiResolveImpl( @NotNull T element, boolean incompleteCode, @NotNull ResolveCache.PolyVariantContextResolver<? super T> resolver) { FileASTNode fileElement = SharedImplUtil.findFileElement(element.getNode()); if (fileElement == null) { PsiUtilCore.ensureValid(element); LOG.error("fileElement == null!"); return JavaResolveResult.EMPTY_ARRAY; } PsiFile psiFile = SharedImplUtil.getContainingFile(fileElement); PsiManager manager = psiFile == null ? null : psiFile.getManager(); if (manager == null) { PsiUtilCore.ensureValid(element); LOG.error("getManager() == null!"); return JavaResolveResult.EMPTY_ARRAY; } boolean valid = psiFile.isValid(); if (!valid) { PsiUtilCore.ensureValid(element); LOG.error("psiFile.isValid() == false!"); return JavaResolveResult.EMPTY_ARRAY; } if (element instanceof PsiMethodReferenceExpression) { // method refs: do not cache results during parent conflict resolving, acceptable checks, etc final Map<PsiElement, PsiType> map = LambdaUtil.ourFunctionTypes.get(); if (map != null && map.containsKey(element)) { return (JavaResolveResult[]) resolver.resolve(element, psiFile, incompleteCode); } } return multiResolveImpl(manager.getProject(), psiFile, element, incompleteCode, resolver); }
private static boolean containsError(PsiAnnotation annotation) { final PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement(); if (nameRef == null) { return true; } final PsiClass aClass = (PsiClass) nameRef.resolve(); if (aClass == null || !aClass.isAnnotationType()) { return true; } final Set<String> names = new HashSet<String>(); final PsiAnnotationParameterList annotationParameterList = annotation.getParameterList(); if (PsiUtilCore.hasErrorElementChild(annotationParameterList)) { return true; } final PsiNameValuePair[] attributes = annotationParameterList.getAttributes(); for (PsiNameValuePair attribute : attributes) { final PsiReference reference = attribute.getReference(); if (reference == null) { return true; } final PsiMethod method = (PsiMethod) reference.resolve(); if (method == null) { return true; } final PsiAnnotationMemberValue value = attribute.getValue(); if (value == null || PsiUtilCore.hasErrorElementChild(value)) { return true; } if (value instanceof PsiAnnotation && containsError((PsiAnnotation) value)) { return true; } if (!hasCorrectType(value, method.getReturnType())) { return true; } final String name = attribute.getName(); if (!names.add(name != null ? name : PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)) { return true; } } for (PsiMethod method : aClass.getMethods()) { if (!(method instanceof PsiAnnotationMethod)) { continue; } final PsiAnnotationMethod annotationMethod = (PsiAnnotationMethod) method; if (annotationMethod.getDefaultValue() == null && !names.contains(annotationMethod.getName())) { return true; // missing a required argument } } return false; }
@Nullable public static <E extends PsiElement> E findArgumentList( PsiFile file, int offset, int lbraceOffset) { if (file == null) return null; ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers( file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage()); if (handlers != null) { for (ParameterInfoHandler handler : handlers) { if (handler instanceof ParameterInfoHandlerWithTabActionSupport) { final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport) handler; // please don't remove typecast in the following line; it's required to compile the code // under old JDK 6 versions final E e = (E) ParameterInfoUtils.findArgumentList( file, offset, lbraceOffset, parameterInfoHandler2); if (e != null) return e; } } } return null; }
public static RemoveUnusedVariableUtil.RemoveMode showSideEffectsWarning( List<PsiElement> sideEffects, PsiVariable variable, Editor editor, boolean canCopeWithSideEffects, @NonNls String beforeText, @NonNls String afterText) { if (sideEffects.isEmpty()) return RemoveUnusedVariableUtil.RemoveMode.DELETE_ALL; if (ApplicationManager.getApplication().isUnitTestMode()) { return canCopeWithSideEffects ? RemoveUnusedVariableUtil.RemoveMode.MAKE_STATEMENT : RemoveUnusedVariableUtil.RemoveMode.DELETE_ALL; } Project project = editor.getProject(); HighlightManager highlightManager = HighlightManager.getInstance(project); PsiElement[] elements = PsiUtilCore.toPsiElementArray(sideEffects); EditorColorsManager manager = EditorColorsManager.getInstance(); TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); highlightManager.addOccurrenceHighlights(editor, elements, attributes, true, null); SideEffectWarningDialog dialog = new SideEffectWarningDialog( project, false, variable, beforeText, afterText, canCopeWithSideEffects); dialog.show(); int code = dialog.getExitCode(); return RemoveUnusedVariableUtil.RemoveMode.values()[code]; }
@Override public PsiType visitClassType(PsiClassType classType) { final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics(); final PsiClass aClass = resolveResult.getElement(); if (aClass == null) return classType; PsiUtilCore.ensureValid(aClass); if (aClass instanceof PsiTypeParameter) { final PsiTypeParameter typeParameter = (PsiTypeParameter) aClass; if (containsInMap(typeParameter)) { PsiType result = substituteTypeParameter(typeParameter); if (result != null) { PsiUtil.ensureValidType(result); } return result; } return classType; } final Map<PsiTypeParameter, PsiType> hashMap = new HashMap<PsiTypeParameter, PsiType>(2); if (!processClass(aClass, resolveResult.getSubstitutor(), hashMap)) { return null; } PsiClassType result = JavaPsiFacade.getElementFactory(aClass.getProject()) .createType(aClass, createSubstitutor(hashMap), classType.getLanguageLevel()); PsiUtil.ensureValidType(result); return result; }
private static String getName( final PsiClass psiClass, final LookupItem<?> item, boolean diamond) { if (item instanceof JavaPsiClassReferenceElement) { String forced = ((JavaPsiClassReferenceElement) item).getForcedPresentableName(); if (forced != null) { return forced; } } String name = PsiUtilCore.getName(psiClass); if (item.getAttribute(LookupItem.FORCE_QUALIFY) != null) { if (psiClass.getContainingClass() != null) { name = psiClass.getContainingClass().getName() + "." + name; } } if (diamond) { return name + "<>"; } PsiSubstitutor substitutor = (PsiSubstitutor) item.getAttribute(LookupItem.SUBSTITUTOR); if (substitutor != null) { final PsiTypeParameter[] params = psiClass.getTypeParameters(); if (params.length > 0) { return name + formatTypeParameters(substitutor, params); } } return StringUtil.notNullize(name); }
@Override public PsiType visitClassType(final PsiClassType classType) { PsiClassType alreadyComputed = myResultMap.get(classType); if (alreadyComputed != null) { return alreadyComputed; } final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics(); final PsiClass psiClass = classResolveResult.getElement(); final PsiSubstitutor substitutor = classResolveResult.getSubstitutor(); if (psiClass == null) return classType; PsiUtilCore.ensureValid(psiClass); final PsiClass mappedClass = mapClass(psiClass); if (mappedClass == null) return classType; PsiClassType mappedType = new PsiCorrectedClassType( classType.getLanguageLevel(), classType, new CorrectedResolveResult(psiClass, mappedClass, substitutor, classResolveResult)); myResultMap.put(classType, mappedType); return mappedType; }
public SearchScope union(LocalSearchScope scope2) { if (equals(scope2)) return this; PsiElement[] elements1 = getScope(); PsiElement[] elements2 = scope2.getScope(); boolean[] united = new boolean[elements2.length]; List<PsiElement> result = new ArrayList<PsiElement>(); loop1: for (final PsiElement element1 : elements1) { for (int j = 0; j < elements2.length; j++) { final PsiElement element2 = elements2[j]; final PsiElement unionElement = scopeElementsUnion(element1, element2); if (unionElement != null && unionElement.getContainingFile() != null) { result.add(unionElement); united[j] = true; break loop1; } } result.add(element1); } for (int i = 0; i < united.length; i++) { final boolean b = united[i]; if (!b) { result.add(elements2[i]); } } return new LocalSearchScope(PsiUtilCore.toPsiElementArray(result)); }
public static SafeDeleteProcessor createInstance( Project project, @Nullable Runnable prepareSuccessfulCallBack, PsiElement[] elementsToDelete, boolean isSearchInComments, boolean isSearchNonJava, boolean askForAccessors) { ArrayList<PsiElement> elements = new ArrayList<PsiElement>(Arrays.asList(elementsToDelete)); HashSet<PsiElement> elementsToDeleteSet = new HashSet<PsiElement>(Arrays.asList(elementsToDelete)); for (PsiElement psiElement : elementsToDelete) { for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { if (delegate.handlesElement(psiElement)) { Collection<PsiElement> addedElements = delegate.getAdditionalElementsToDelete( psiElement, elementsToDeleteSet, askForAccessors); if (addedElements != null) { elements.addAll(addedElements); } break; } } } return new SafeDeleteProcessor( project, prepareSuccessfulCallBack, PsiUtilCore.toPsiElementArray(elements), isSearchInComments, isSearchNonJava); }
public void disableTool(@NotNull PsiElement element) { final Project project = element.getProject(); final DependencyValidationManager validationManager = DependencyValidationManager.getInstance(project); if (myTools != null) { for (ScopeToolState state : myTools) { final NamedScope scope = state.getScope(project); if (scope != null) { final PackageSet packageSet = scope.getValue(); if (packageSet != null) { final PsiFile file = element.getContainingFile(); if (file != null) { if (packageSet.contains(file, validationManager)) { state.setEnabled(false); return; } } else { if (packageSet instanceof PackageSetBase && ((PackageSetBase) packageSet) .contains(PsiUtilCore.getVirtualFile(element), project, validationManager)) { state.setEnabled(false); return; } } } } } myDefaultState.setEnabled(false); } else { myDefaultState.setEnabled(false); setEnabled(false); } }
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) { if (ApplicationManager.getApplication().isUnitTestMode()) { return null; } if (!(element instanceof PsiMethod) && !(element instanceof PsiClass)) { return null; } if (!PsiUtil.isPluginProject(element.getProject())) { return null; } final VirtualFile file = PsiUtilCore.getVirtualFile(element); if (file == null || !ProjectFileIndex.SERVICE .getInstance(element.getProject()) .isInTestSourceContent(file)) { return null; } if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod) element; if (isTestMethod(method)) { return new LineMarkerInfo<PsiMethod>( method, method.getModifierList().getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, null, new TestDataNavigationHandler(), GutterIconRenderer.Alignment.LEFT); } } else { final PsiClass psiClass = (PsiClass) element; final String basePath = getTestDataBasePath(psiClass); if (basePath != null) { PsiModifierList modifierList = psiClass.getModifierList(); assert modifierList != null; return new LineMarkerInfo<PsiClass>( psiClass, modifierList.getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, new TooltipProvider(basePath), new GutterIconNavigationHandler<PsiClass>() { @Override public void navigate(MouseEvent e, PsiClass elt) { final VirtualFile baseDir = VfsUtil.findFileByIoFile(new File(basePath), true); if (baseDir != null) { new OpenFileDescriptor(psiClass.getProject(), baseDir).navigate(true); } } }, GutterIconRenderer.Alignment.LEFT); } } return null; }
private PsiElement[] collectNonBinaryElements() { List<PsiElement> result = new ArrayList<PsiElement>(); for (PsiElement element : myElements) { if (!(element instanceof PsiBinaryFile)) { result.add(element); } } return PsiUtilCore.toPsiElementArray(result); }
@Override public void setHighlightingEnabled(@NotNull PsiFile file, boolean value) { VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file); if (value) { myDisabledHighlightingFiles.remove(virtualFile); } else { myDisabledHighlightingFiles.add(virtualFile); } }
@Nullable @Override public Document getDocument(@NotNull PsiFile file) { if (file instanceof PsiBinaryFile) return null; Document document = getCachedDocument(file); if (document != null) { if (!file.getViewProvider().isPhysical() && document.getUserData(HARD_REF_TO_PSI) == null) { PsiUtilCore.ensureValid(file); cachePsi(document, file); } return document; } FileViewProvider viewProvider = file.getViewProvider(); if (!viewProvider.isEventSystemEnabled()) return null; document = FileDocumentManager.getInstance().getDocument(viewProvider.getVirtualFile()); if (document != null) { if (document.getTextLength() != file.getTextLength()) { String message = "Document/PSI mismatch: " + file + " (" + file.getClass() + "); physical=" + viewProvider.isPhysical(); if (document.getTextLength() + file.getTextLength() < 8096) { message += "\n=== document ===\n" + document.getText() + "\n=== PSI ===\n" + file.getText(); } throw new AssertionError(message); } if (!viewProvider.isPhysical()) { PsiUtilCore.ensureValid(file); cachePsi(document, file); file.putUserData(HARD_REF_TO_DOCUMENT, document); } } return document; }
@Override public boolean isInContext(@NotNull PsiFile file, int offset) { if (!PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(ErlangLanguage.INSTANCE)) return false; PsiElement element = file.findElementAt(offset); if (element instanceof PsiWhiteSpace) { return false; } return element != null && isInContext(element); }
private static boolean notJetAnnotationEntry(final PsiElement found) { if (found instanceof JetAnnotationEntry) return false; VirtualFile faultyContainer = PsiUtilCore.getVirtualFile(found); LOG.error("Non annotation in annotations list: " + faultyContainer + "; element:" + found); if (faultyContainer != null && faultyContainer.isValid()) { FileBasedIndex.getInstance().requestReindex(faultyContainer); } return true; }
@Override protected boolean isResolved(@NotNull JSReferenceExpression methodExpression) { if (JstdResolveUtil.isResolvedToFunction(methodExpression)) { return true; } VirtualFile virtualFile = PsiUtilCore.getVirtualFile(methodExpression); if (virtualFile != null) { return JstdLibraryUtil.isFileInJstdLibScope(methodExpression.getProject(), virtualFile); } return true; }
@NotNull public final PsiElement[] getSelectedPSIElements() { List<PsiElement> psiElements = new ArrayList<PsiElement>(); for (Object element : getSelectedElements()) { final PsiElement psiElement = getPSIElement(element); if (psiElement != null) { psiElements.add(psiElement); } } return PsiUtilCore.toPsiElementArray(psiElements); }
public boolean satisfies(@NotNull PsiElement element, @NotNull ResolveState state) { final String name = PsiUtilCore.getName(element); if (StringUtil.isNotEmpty(name) && (myMatcher == null || myMatcher.value(name))) { if (myFilter.isClassAcceptable(element.getClass()) && myFilter.isAcceptable( new CandidateInfo(element, state.get(PsiSubstitutor.KEY)), myElement)) { return true; } } return false; }
public static PsiElement[] move( @NotNull PsiElement container, @NotNull PsiElement[] statements, boolean generateDefaultInitializers) { if (statements.length == 0) { return statements; } Project project = container.getProject(); List<PsiElement> resultStatements = new ArrayList<PsiElement>(); List<KtProperty> propertiesDeclarations = new ArrayList<KtProperty>(); // Dummy element to add new declarations at the beginning KtPsiFactory psiFactory = KtPsiFactoryKt.KtPsiFactory(project); PsiElement dummyFirstStatement = container.addBefore(psiFactory.createExpression("dummyStatement"), statements[0]); try { SearchScope scope = new LocalSearchScope(container); int lastStatementOffset = statements[statements.length - 1].getTextRange().getEndOffset(); for (PsiElement statement : statements) { if (needToDeclareOut(statement, lastStatementOffset, scope)) { if (statement instanceof KtProperty && ((KtProperty) statement).getInitializer() != null) { KtProperty property = (KtProperty) statement; KtProperty declaration = createVariableDeclaration(property, generateDefaultInitializers); declaration = (KtProperty) container.addBefore(declaration, dummyFirstStatement); propertiesDeclarations.add(declaration); container.addAfter(psiFactory.createNewLine(), declaration); KtBinaryExpression assignment = createVariableAssignment(property); resultStatements.add(property.replace(assignment)); } else { PsiElement newStatement = container.addBefore(statement, dummyFirstStatement); container.addAfter(psiFactory.createNewLine(), newStatement); container.deleteChildRange(statement, statement); } } else { resultStatements.add(statement); } } } finally { dummyFirstStatement.delete(); } ShortenReferences.DEFAULT.process(propertiesDeclarations); return PsiUtilCore.toPsiElementArray(resultStatements); }
public static boolean shouldEnableDeleteAction(PsiElement[] elements) { if (elements == null || elements.length == 0) return false; for (PsiElement element : elements) { VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element); if (virtualFile == null) { return false; } if (!WritingAccessProvider.isPotentiallyWritable(virtualFile, element.getProject())) { return false; } } return true; }
@Override public boolean isHighlightingAvailable(@Nullable PsiFile file) { if (file == null || !file.isPhysical()) return false; if (myDisabledHighlightingFiles.contains(PsiUtilCore.getVirtualFile(file))) return false; if (file instanceof PsiCompiledElement) return false; final FileType fileType = file.getFileType(); if (fileType == StdFileTypes.GUI_DESIGNER_FORM) { return true; } // To enable T.O.D.O. highlighting return !fileType.isBinary(); }
private PsiElement[] collectPsiElements() { RefEntity[] refElements = myTree.getSelectedElements(); List<PsiElement> psiElements = new ArrayList<PsiElement>(); for (RefEntity refElement : refElements) { PsiElement psiElement = refElement instanceof RefElement ? ((RefElement) refElement).getElement() : null; if (psiElement != null && psiElement.isValid()) { psiElements.add(psiElement); } } return PsiUtilCore.toPsiElementArray(psiElements); }
@NotNull private static PsiElement[] getPsiElements(@NotNull UsageTarget[] targets) { List<PsiElement> result = new ArrayList<PsiElement>(); for (UsageTarget target : targets) { if (target instanceof PsiElementUsageTarget) { PsiElement element = ((PsiElementUsageTarget) target).getElement(); if (element != null) { result.add(element); } } } return PsiUtilCore.toPsiElementArray(result); }
@Override public boolean isApplicable(PsiFile file, int offset, boolean wrapping) { PostfixTemplatesSettings settings = PostfixTemplatesSettings.getInstance(); if (wrapping || file == null || settings == null || !settings.isPostfixTemplatesEnabled() || PsiUtilCore.getLanguageAtOffset(file, offset) != JavaLanguage.INSTANCE) { return false; } return StringUtil.isNotEmpty( computeTemplateKeyWithoutContextChecking(file.getText(), offset + 1)); }
private static PsiElement[] getElementsIntersectingRange( PsiFile file, final int startOffset, final int endOffset) { final FileViewProvider viewProvider = file.getViewProvider(); final Set<PsiElement> result = new LinkedHashSet<PsiElement>(); for (Language language : viewProvider.getLanguages()) { final PsiFile psiRoot = viewProvider.getPsi(language); if (HighlightingLevelManager.getInstance(file.getProject()).shouldInspect(psiRoot)) { result.addAll( CollectHighlightsUtil.getElementsInRange(psiRoot, startOffset, endOffset, true)); } } return PsiUtilCore.toPsiElementArray(result); }
@Override @NotNull public PsiElement[] getDescriptionElements() { ArrayList<PsiElement> array = new ArrayList<PsiElement>(); for (ASTNode child = getFirstChildNode(); child != null; child = child.getTreeNext()) { IElementType i = child.getElementType(); if (i == DOC_TAG) break; if (i != DOC_COMMENT_START && i != DOC_COMMENT_END && i != DOC_COMMENT_LEADING_ASTERISKS) { array.add(child.getPsi()); } } return PsiUtilCore.toPsiElementArray(array); }
// returns true if processor is run or is going to be run after showing popup public static boolean chooseAmbiguousTarget( @NotNull Editor editor, int offset, @NotNull PsiElementProcessor<PsiElement> processor, @NotNull String titlePattern, @Nullable PsiElement[] elements) { if (TargetElementUtil.inVirtualSpace(editor, offset)) { return false; } final PsiReference reference = TargetElementUtil.findReference(editor, offset); if (elements == null || elements.length == 0) { elements = reference == null ? PsiElement.EMPTY_ARRAY : PsiUtilCore.toPsiElementArray( underModalProgress( reference.getElement().getProject(), "Resolving Reference...", () -> suggestCandidates(reference))); } if (elements.length == 1) { PsiElement element = elements[0]; LOG.assertTrue(element != null); processor.execute(element); return true; } if (elements.length > 1) { String title; if (reference == null) { title = titlePattern; } else { final TextRange range = reference.getRangeInElement(); final String elementText = reference.getElement().getText(); LOG.assertTrue( range.getStartOffset() >= 0 && range.getEndOffset() <= elementText.length(), Arrays.toString(elements) + ";" + reference); final String refText = range.substring(elementText); title = MessageFormat.format(titlePattern, refText); } NavigationUtil.getPsiElementPopup( elements, new DefaultPsiElementCellRenderer(), title, processor) .showInBestPositionFor(editor); return true; } return false; }
private static void collectSourceRoots( PsiElement[] psiElements, ProjectFileIndex fileIndex, Set<VirtualFile> initialRoots) { for (PsiElement element : psiElements) { final VirtualFile file = PsiUtilCore.getVirtualFile(element); if (file != null) { final VirtualFile sourceRootForFile = fileIndex.getSourceRootForFile(file); if (sourceRootForFile != null) { initialRoots.add(sourceRootForFile); } } else if (element instanceof PsiDirectoryContainer) { collectSourceRoots( ((PsiDirectoryContainer) element).getDirectories(), fileIndex, initialRoots); } } }
@Override public void run() { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); myUsageView.close(); ArrayList<PsiElement> elements = new ArrayList<PsiElement>(); for (SmartPsiElementPointer pointer : myPointers) { final PsiElement element = pointer.getElement(); if (element != null) { elements.add(element); } } if (!elements.isEmpty()) { SafeDeleteHandler.invoke(myProject, PsiUtilCore.toPsiElementArray(elements), true); } }