@Override protected Object stubTreeAndIndexDoNotMatch(@NotNull ObjectStubTree stubTree, PsiFileWithStubSupport psiFile) { final VirtualFile virtualFile = psiFile.getVirtualFile(); StubTree stubTreeFromIndex = (StubTree)StubTreeLoader.getInstance().readFromVFile(psiFile.getProject(), virtualFile); String details = "Please report the problem to JetBrains with the file attached"; details += StubTreeLoader.getInstance().getStubAstMismatchDiagnostics(virtualFile, psiFile, stubTree, null); details += "\n" + DebugUtil.currentStackTrace(); String fileText = psiFile instanceof PsiCompiledElement ? "compiled" : psiFile.getText(); return LogMessageEx.createEvent("PSI and index do not match", details, new Attachment(virtualFile.getPath() + "_file.txt", fileText), new Attachment("stubTree.txt", ((PsiFileStubImpl)stubTree.getRoot()).printTree()), new Attachment("stubTreeFromIndex.txt", stubTreeFromIndex == null ? "null" : ((PsiFileStubImpl)stubTreeFromIndex.getRoot()).printTree())); }
@Nullable private static PsiElement getPsiElementAt(Point point, Editor editor) { if (editor.isDisposed()) { return null; } Project project = editor.getProject(); if (project == null || project.isDisposed()) { return null; } PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile == null || psiFile instanceof PsiCompiledElement || !psiFile.isValid()) { return null; } return InjectedLanguageUtil.findElementAtNoCommit(psiFile, editor.logicalPositionToOffset(editor.xyToLogicalPosition(point))); }
public static Object computeConstantExpression(PsiExpression expression, @Nullable Set<PsiVariable> visitedVars, boolean throwExceptionOnOverflow, final PsiConstantEvaluationHelper.AuxEvaluator auxEvaluator) { if (expression == null) return null; JavaConstantExpressionEvaluator evaluator = new JavaConstantExpressionEvaluator(visitedVars, throwExceptionOnOverflow, expression.getProject(), auxEvaluator); if (expression instanceof PsiCompiledElement) { // in case of compiled elements we are not allowed to use PSI walking // but really in Cls there are only so many cases to handle if (expression instanceof PsiPrefixExpression) { PsiElement operand = ((PsiPrefixExpression)expression).getOperand(); if (operand == null) return null; Object value = evaluator.myConstantExpressionVisitor.handle(operand); ConstantExpressionVisitor.store(operand, value); } return evaluator.myConstantExpressionVisitor.handle(expression); } expression.accept(evaluator); Object cached = evaluator.getCached(expression); return cached == NO_VALUE ? null : cached; }
@Nullable public PsiAnnotation findInferredAnnotation(@NotNull PsiModifierListOwner listOwner, @NotNull String annotationFQN) { if(!(listOwner instanceof PsiCompiledElement)) { return null; } if(annotationFQN.equals(AnnotationUtil.NOT_NULL) || annotationFQN.equals(AnnotationUtil.NULLABLE) || annotationFQN.equals(ControlFlowAnalyzer.ORG_JETBRAINS_ANNOTATIONS_CONTRACT)) { PsiAnnotation[] annotations = findInferredAnnotations(listOwner); for(PsiAnnotation annotation : annotations) { if(annotationFQN.equals(annotation.getQualifiedName())) { return annotation; } } return null; } else { return null; } }
@NotNull public PsiAnnotation[] findInferredAnnotations(@NotNull final PsiModifierListOwner listOwner) { if(!(listOwner instanceof PsiCompiledElement)) { return PsiAnnotation.EMPTY_ARRAY; } return CachedValuesManager.getCachedValue(listOwner, new CachedValueProvider<PsiAnnotation[]>() { @Nullable @Override public Result<PsiAnnotation[]> compute() { return CachedValueProvider.Result.create(ProjectBytecodeAnalysis.this.collectInferredAnnotations(listOwner), listOwner); } }); }
@Nullable public static HKey getKey(@NotNull PsiModifierListOwner owner, MessageDigest md) { LOG.assertTrue(owner instanceof PsiCompiledElement, owner); if(owner instanceof PsiMethod) { return BytecodeAnalysisConverter.psiKey((PsiMethod) owner, Out, md); } if(owner instanceof PsiParameter) { PsiElement parent = owner.getParent(); if(parent instanceof PsiParameterList) { PsiElement gParent = parent.getParent(); if(gParent instanceof PsiMethod) { final int index = ((PsiParameterList) parent).getParameterIndex((PsiParameter) owner); return BytecodeAnalysisConverter.psiKey((PsiMethod) gParent, new In(index, In.NOT_NULL_MASK), md); } } } return null; }
public static boolean isAcceptableInContext(@NotNull final PsiElement context, @NotNull final PsiClass psiClass, final boolean filterByScope, final boolean pkgContext) { ProgressManager.checkCanceled(); if(JavaCompletionUtil.isInExcludedPackage(psiClass, false)) { return false; } final String qualifiedName = psiClass.getQualifiedName(); if(qualifiedName == null) { return false; } if(!filterByScope && !(psiClass instanceof PsiCompiledElement)) { return true; } return JavaCompletionUtil.isSourceLevelAccessible(context, psiClass, pkgContext); }
@Override protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if(!(file instanceof PsiJavaFile)) { return false; } if(file instanceof PsiCompiledElement) { return false; } PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiClass targetClass = getTargetClass(editor, file); return targetClass != null && isValidForClass(targetClass); }
private static void createModuleFixes(PsiJavaModuleReference reference, Module currentModule, VirtualFile refVFile, List<LocalQuickFix> result) { ProjectFileIndex index = ProjectRootManager.getInstance(currentModule.getProject()).getFileIndex(); List<PsiElement> targets = Stream.of(reference.multiResolve(true)).map(ResolveResult::getElement).filter(Objects::nonNull).collect(Collectors.toList()); Set<Module> modules = targets.stream().map(e -> !(e instanceof PsiCompiledElement) ? e.getContainingFile() : null).map(f -> f != null ? f.getVirtualFile() : null).filter(vf -> vf != null && index.isInSource(vf)).map(vf -> index.getModuleForFile(vf)).filter(m -> m != null && m != currentModule).collect(Collectors.toSet()); if(!modules.isEmpty()) { result.add(0, new AddModuleDependencyFix(currentModule, refVFile, modules, reference)); } targets.stream().map(e -> e instanceof PsiCompiledElement ? e.getContainingFile() : null).map(f -> f != null ? f.getVirtualFile() : null).flatMap(vf -> vf != null ? index .getOrderEntriesForFile(vf).stream() : Stream.empty()).map(e -> e instanceof LibraryOrderEntry ? ((LibraryOrderEntry) e).getLibrary() : null).filter(Objects::nonNull).distinct() .forEach(l -> result.add(new AddLibraryToDependenciesFix(currentModule, l, reference, null))); }
private void invoke(final Project project, PsiMethod method, Editor editor) { if(method.isConstructor()){ CommonRefactoringUtil.showErrorHint(project, editor, RefactorJBundle.message("cannot.perform.the.refactoring") + RefactorJBundle.message("constructor.returns.can.not.be.wrapped"), null, this.getHelpID()); return; } final PsiType returnType = method.getReturnType(); if(PsiType.VOID.equals(returnType)){ CommonRefactoringUtil.showErrorHint(project, editor, RefactorJBundle.message("cannot.perform.the.refactoring") + RefactorJBundle.message("method.selected.returns.void"), null, this.getHelpID()); return; } method = SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor")); if (method == null) return; if(method instanceof PsiCompiledElement){ CommonRefactoringUtil.showErrorHint(project, editor, RefactorJBundle.message("cannot.perform.the.refactoring") + RefactorJBundle.message( "the.selected.method.cannot.be.wrapped.because.it.is.defined.in.a.non.project.class"), null, this.getHelpID()); return; } new WrapReturnValueDialog(method).show(); }
private static void findAvailableSuperClasses(PsiMethod method, List<PsiClass> sourceClasses){ final PsiMethod[] superMethods = method.findSuperMethods(true); for(PsiMethod superMethod : superMethods){ final PsiClass containingClass = superMethod.getContainingClass(); if(!(containingClass instanceof PsiCompiledElement)){ sourceClasses.add(containingClass); findAvailableSuperClasses(superMethod, sourceClasses); } } }
public static PsiClass[] findAvailableSubClassesForMethod(PsiMethod method){ final Iterable<PsiMethod> query = SearchUtils.findOverridingMethods(method); final List<PsiClass> sourceClasses = new ArrayList<PsiClass>(); for(PsiMethod superMethod : query){ final PsiClass containingClass = superMethod.getContainingClass(); if(!(containingClass instanceof PsiCompiledElement)){ sourceClasses.add(containingClass); } } return sourceClasses.toArray(new PsiClass[sourceClasses.size()]); }
private static void findNonLibrarySupers(PsiClass sourceClass, List<PsiClass> out){ final PsiClass[] supers = sourceClass.getSupers(); for(PsiClass psiClass : supers){ if(!(psiClass instanceof PsiCompiledElement) && !out.contains(psiClass)) { out.add(psiClass); findNonLibrarySupers(psiClass, out); } } }
public static PsiClass[] getNonLibrarySubClasses(PsiClass sourceClass){ final List<PsiClass> out = new ArrayList<PsiClass>(); final Iterable<PsiClass> query = SearchUtils.findClassInheritors(sourceClass, true); for(PsiClass psiClass : query){ if(!(psiClass instanceof PsiCompiledElement)) { out.add(psiClass); } } return out.toArray(new PsiClass[out.size()]); }
protected static boolean processUsagesInText(@NotNull final PsiElement element, @NotNull Collection<String> stringToSearch, @NotNull GlobalSearchScope searchScope, @NotNull Processor<UsageInfo> processor) { final TextRange elementTextRange = ApplicationManager.getApplication().runReadAction(new NullableComputable<TextRange>() { @Override public TextRange compute() { if (!element.isValid() || element instanceof PsiCompiledElement) return null; return element.getTextRange(); } }); UsageInfoFactory factory = new UsageInfoFactory() { @Override public UsageInfo createUsageInfo(@NotNull PsiElement usage, int startOffset, int endOffset) { if (elementTextRange != null && usage.getContainingFile() == element.getContainingFile() && elementTextRange.contains(startOffset) && elementTextRange.contains(endOffset)) { return null; } PsiReference someReference = usage.findReferenceAt(startOffset); if (someReference != null) { PsiElement refElement = someReference.getElement(); for (PsiReference ref : PsiReferenceService.getService().getReferences(refElement, new PsiReferenceService.Hints(element, null))) { if (element.getManager().areElementsEquivalent(ref.resolve(), element)) { TextRange range = ref.getRangeInElement().shiftRight(refElement.getTextRange().getStartOffset() - usage.getTextRange().getStartOffset()); return new UsageInfo(usage, range.getStartOffset(), range.getEndOffset(), true); } } } return new UsageInfo(usage, startOffset, endOffset, true); } }; for (String s : stringToSearch) { if (!PsiSearchHelperImpl.processTextOccurrences(element, s, searchScope, processor, factory)) return false; } return true; }
public static void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file, Surrounder surrounder) { if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return; if (file instanceof PsiCompiledElement) { HintManager.getInstance().showErrorHint(editor, "Can't modify decompiled code"); return; } List<AnAction> applicable = buildSurroundActions(project, editor, file, surrounder); if (applicable != null) { showPopup(editor, applicable); } else if (!ApplicationManager.getApplication().isUnitTestMode()) { HintManager.getInstance().showErrorHint(editor, "Couldn't find Surround With variants applicable to the current context"); } }
private void registerListeners(final Editor editor) { if (editor.isOneLineMode()) { return; } Project project = editor.getProject(); if (project == null || project.isDisposed()) { return; } PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile == null || psiFile instanceof PsiCompiledElement || !isSupportedFile(psiFile)) { return; } editor.addEditorMouseMotionListener(this); KeyListener keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT && !editor.isOneLineMode()) { PointerInfo pointerInfo = MouseInfo.getPointerInfo(); if (pointerInfo != null) { Point location = pointerInfo.getLocation(); SwingUtilities.convertPointFromScreen(location, editor.getContentComponent()); alarm.cancelAllRequests(); alarm.addRequest(new PreviewRequest(location, editor, true), 100); } } } }; editor.getContentComponent().addKeyListener(keyListener); EDITOR_LISTENER_ADDED.set(editor, keyListener); }
@NotNull private static Collection<PsiElement> getPsiElementsAt(Point point, Editor editor) { if (editor.isDisposed()) { return Collections.emptySet(); } Project project = editor.getProject(); if (project == null || project.isDisposed()) { return Collections.emptySet(); } final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = editor.getDocument(); PsiFile psiFile = documentManager.getPsiFile(document); if (psiFile == null || psiFile instanceof PsiCompiledElement || !psiFile.isValid()) { return Collections.emptySet(); } final Set<PsiElement> elements = Collections.newSetFromMap(new WeakHashMap<PsiElement, Boolean>()); final int offset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(point)); if (documentManager.isCommitted(document)) { ContainerUtil.addIfNotNull(elements, InjectedLanguageUtil.findElementAtNoCommit(psiFile, offset)); } for (PsiFile file : psiFile.getViewProvider().getAllFiles()) { ContainerUtil.addIfNotNull(elements, file.findElementAt(offset)); } return elements; }
@Override public int compare(ElementNode n1, ElementNode n2) { if (n1.getDelegate() instanceof ClassMemberWithElement && n2.getDelegate() instanceof ClassMemberWithElement) { PsiElement element1 = ((ClassMemberWithElement)n1.getDelegate()).getElement(); PsiElement element2 = ((ClassMemberWithElement)n2.getDelegate()).getElement(); if (!(element1 instanceof PsiCompiledElement) && !(element2 instanceof PsiCompiledElement)) { return element1.getTextOffset() - element2.getTextOffset(); } } return n1.getOrder() - n2.getOrder(); }
public static <T> void replaceInjectionsWithUndo(final Project project, final T add, final T remove, final List<? extends PsiElement> psiElementsToRemove, final PairProcessor<T, T> actualProcessor) { final UndoableAction action = new GlobalUndoableAction() { @Override public void undo() { actualProcessor.process(remove, add); } @Override public void redo() { actualProcessor.process(add, remove); } }; final List<PsiFile> psiFiles = ContainerUtil.mapNotNull(psiElementsToRemove, new NullableFunction<PsiElement, PsiFile>() { @Override public PsiFile fun(final PsiElement psiAnnotation) { return psiAnnotation instanceof PsiCompiledElement ? null : psiAnnotation.getContainingFile(); } }); new WriteCommandAction.Simple(project, "Language Injection Configuration Update", PsiUtilCore.toPsiFileArray(psiFiles)) { @Override public void run() { for (PsiElement annotation : psiElementsToRemove) { annotation.delete(); } actualProcessor.process(add, remove); UndoManager.getInstance(project).undoableActionPerformed(action); } @Override protected UndoConfirmationPolicy getUndoConfirmationPolicy() { return UndoConfirmationPolicy.REQUEST_CONFIRMATION; } }.execute(); }
@Nullable public static String getParameterName(@NotNull PsiParameter param) { if (param instanceof PsiCompiledElement) { // don't try to find out a compiled parameter name return null; } else { return param.getName(); } }
@Override protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (file instanceof PsiCompiledElement) return false; if (!GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) return false; PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiClass targetClass = getTargetClass(editor, file); if (targetClass == null) return false; if (targetClass.isInterface()) 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(); // To enable T.O.D.O. highlighting return !fileType.isBinary(); }
private void registerListeners(final Editor editor) { if (editor.isOneLineMode()) { return; } Project project = editor.getProject(); if (project == null || project.isDisposed()) { return; } PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile == null || psiFile instanceof PsiCompiledElement || !isSupportedFile(psiFile)) { return; } editor.addEditorMouseMotionListener(this); KeyListener keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SHIFT && !editor.isOneLineMode()) { PointerInfo pointerInfo = MouseInfo.getPointerInfo(); if (pointerInfo != null) { Point location = pointerInfo.getLocation(); SwingUtilities.convertPointFromScreen(location, editor.getContentComponent()); alarm.cancelAllRequests(); alarm.addRequest(new PreviewRequest(location, editor, true), 100); } } } }; editor.getContentComponent().addKeyListener(keyListener); editor.putUserData(EDITOR_LISTENER_ADDED, keyListener); }
public static <T> void replaceInjectionsWithUndo(final Project project, final T add, final T remove, final List<? extends PsiElement> psiElementsToRemove, final PairProcessor<T, T> actualProcessor) { final UndoableAction action = new GlobalUndoableAction() { public void undo() { actualProcessor.process(remove, add); } public void redo() { actualProcessor.process(add, remove); } }; final List<PsiFile> psiFiles = ContainerUtil.mapNotNull(psiElementsToRemove, new NullableFunction<PsiElement, PsiFile>() { public PsiFile fun(final PsiElement psiAnnotation) { return psiAnnotation instanceof PsiCompiledElement ? null : psiAnnotation.getContainingFile(); } }); new WriteCommandAction.Simple(project, "Language Injection Configuration Update", PsiUtilCore.toPsiFileArray(psiFiles)) { public void run() { for (PsiElement annotation : psiElementsToRemove) { annotation.delete(); } actualProcessor.process(add, remove); UndoManager.getInstance(project).undoableActionPerformed(action); } @Override protected UndoConfirmationPolicy getUndoConfirmationPolicy() { return UndoConfirmationPolicy.REQUEST_CONFIRMATION; } }.execute(); }
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (file instanceof PsiCompiledElement) return false; if (!GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) return false; PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiClass targetClass = getTargetClass(editor, file); if (targetClass == null) return false; if (targetClass.isInterface()) return false; //? return true; }
public static boolean processUsagesInText(@Nonnull final PsiElement element, @Nonnull Collection<String> stringToSearch, @Nonnull GlobalSearchScope searchScope, @Nonnull Processor<UsageInfo> processor) { final TextRange elementTextRange = ApplicationManager.getApplication().runReadAction(new NullableComputable<TextRange>() { @Override public TextRange compute() { if (!element.isValid() || element instanceof PsiCompiledElement) return null; return element.getTextRange(); } }); UsageInfoFactory factory = new UsageInfoFactory() { @Override public UsageInfo createUsageInfo(@Nonnull PsiElement usage, int startOffset, int endOffset) { if (elementTextRange != null && usage.getContainingFile() == element.getContainingFile() && elementTextRange.contains(startOffset) && elementTextRange.contains(endOffset)) { return null; } PsiReference someReference = usage.findReferenceAt(startOffset); if (someReference != null) { PsiElement refElement = someReference.getElement(); for (PsiReference ref : PsiReferenceService.getService().getReferences(refElement, new PsiReferenceService.Hints(element, null))) { if (element.getManager().areElementsEquivalent(ref.resolve(), element)) { TextRange range = ref.getRangeInElement().shiftRight(refElement.getTextRange().getStartOffset() - usage.getTextRange().getStartOffset()); return new UsageInfo(usage, range.getStartOffset(), range.getEndOffset(), true); } } } return new UsageInfo(usage, startOffset, endOffset, true); } }; for (String s : stringToSearch) { if (!PsiSearchHelperImpl.processTextOccurrences(element, s, searchScope, processor, factory)) return false; } return true; }
public static void invoke(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file, Surrounder surrounder) { if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return; if (file instanceof PsiCompiledElement) { HintManager.getInstance().showErrorHint(editor, "Can't modify decompiled code"); return; } List<AnAction> applicable = buildSurroundActions(project, editor, file, surrounder); if (applicable != null) { showPopup(editor, applicable); } else if (!ApplicationManager.getApplication().isUnitTestMode()) { HintManager.getInstance().showErrorHint(editor, "Couldn't find Surround With variants applicable to the current context"); } }
@Nonnull private static Collection<PsiElement> getPsiElementsAt(Point point, Editor editor) { if (editor.isDisposed()) { return Collections.emptySet(); } Project project = editor.getProject(); if (project == null || project.isDisposed()) { return Collections.emptySet(); } final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = editor.getDocument(); PsiFile psiFile = documentManager.getPsiFile(document); if (psiFile == null || psiFile instanceof PsiCompiledElement || !psiFile.isValid()) { return Collections.emptySet(); } final Set<PsiElement> elements = Collections.newSetFromMap(new WeakHashMap<PsiElement, Boolean>()); final int offset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(point)); if (documentManager.isCommitted(document)) { ContainerUtil.addIfNotNull(elements, InjectedLanguageUtil.findElementAtNoCommit(psiFile, offset)); } for (PsiFile file : psiFile.getViewProvider().getAllFiles()) { ContainerUtil.addIfNotNull(elements, file.findElementAt(offset)); } return elements; }
@Nullable private static PsiElement getOriginalElement(@Nullable PsiElement e) { if (e == null || !e.isValid()) return null; PsiFile containingFile = e.getContainingFile(); if (containingFile != null && containingFile.getVirtualFile() == null) return null; PsiElement orig = e.getOriginalElement(); return !(e instanceof PsiCompiledElement) && orig instanceof PsiCompiledElement ? e : orig; }
@Override public PsiElement handleElementRename(@NotNull String newName) throws IncorrectOperationException { PsiJavaModuleReferenceElement element = getElement(); if(element instanceof PsiCompiledElement) { throw new IncorrectOperationException(JavaCoreBundle.message("psi.error.attempt.to.edit.class.file", element.getContainingFile())); } PsiElementFactory factory = PsiElementFactory.SERVICE.getInstance(element.getProject()); PsiJavaModuleReferenceElement newElement = factory.createModuleFromText("module " + newName + " {}").getNameIdentifier(); return element.replace(newElement); }
private static boolean isLibraryCode(@NotNull PsiMethod method) { if(method instanceof PsiCompiledElement) { return true; } VirtualFile virtualFile = PsiUtilCore.getVirtualFile(method); return virtualFile != null && FileIndexFacade.getInstance(method.getProject()).isInLibrarySource(virtualFile); }
private static boolean isWritable(PsiModifierListOwner owner) { if(owner instanceof PsiCompiledElement) { return false; } VirtualFile vFile = PsiUtilCore.getVirtualFile(owner); return vFile != null && vFile.isInLocalFileSystem(); }