private static PsiReferenceProcessor createReferenceProcessor(@NotNull final List<UsagesProcessor> processors, final GlobalInspectionContext context) { return new PsiReferenceProcessor() { @Override public boolean execute(PsiReference reference) { AnalysisScope scope = context.getRefManager().getScope(); if (scope != null && scope.contains(reference.getElement()) && reference.getElement().getLanguage() == StdLanguages.JAVA || PsiTreeUtil.getParentOfType(reference.getElement(), PsiDocComment.class) != null) { return true; } synchronized (processors) { UsagesProcessor[] processorsArrayed = processors.toArray(new UsagesProcessor[processors.size()]); for (UsagesProcessor processor : processorsArrayed) { if (!processor.process(reference)) { processors.remove(processor); } } } return !processors.isEmpty(); } }; }
@Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { final PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class); if (parameter != null) { if (!parameter.getLanguage().isKindOf(StdLanguages.JAVA)) return false; final PsiElement declarationScope = parameter.getDeclarationScope(); if (declarationScope instanceof PsiMethod) { final PsiMethod method = (PsiMethod)declarationScope; final PsiClass containingClass = method.getContainingClass(); if (containingClass != null && (!containingClass.isInterface() || PsiUtil.isLanguageLevel8OrHigher(method))) { if (containingClass.findMethodBySignature(generateMethodPrototype(method, parameter), false) != null) { return false; } setText("Generate overloaded " + (method.isConstructor() ? "constructor" : "method") + " with default parameter value"); return true; } } } return false; }
private static Icon replaceIcon(VirtualFile file, @Iconable.IconFlags int flags, Project project, Icon baseIcon) { FileType fileType = file.getFileType(); if (fileType == StdFileTypes.JAVA && !FileIndexUtil.isJavaSourceFile(project, file)) { return PlatformIcons.JAVA_OUTSIDE_SOURCE_ICON; } PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (psiFile instanceof PsiClassOwner && psiFile.getViewProvider().getBaseLanguage() == StdLanguages.JAVA) { PsiClass[] classes = ((PsiClassOwner)psiFile).getClasses(); if (classes.length > 0) { // prefer icon of the class named after file final String fileName = file.getNameWithoutExtension(); for (PsiClass aClass : classes) { if (aClass instanceof SyntheticElement) { return baseIcon; } if (Comparing.strEqual(aClass.getName(), fileName)) { return aClass.getIcon(flags); } } return classes[classes.length - 1].getIcon(flags); } } return baseIcon; }
@Override public ChangeInfo createInitialChangeInfo(final @NotNull PsiElement element) { final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false); if (method != null && isInsideMethodSignature(element, method)) { //do not initialize change signature on return type change if (element.getTextRange().getEndOffset() <= method.getTextOffset()) return null; return DetectedJavaChangeInfo.createFromMethod(method); } else { final PsiVariable variable = PsiTreeUtil.getParentOfType(element, PsiVariable.class); if (variable != null) { return new RenameChangeInfo(variable, null) { @Override public Language getLanguage() { return StdLanguages.JAVA; } }; } } return null; }
@Override public void checkApplicability(final PsiFile psiFile, final Editor editor) throws IncorrectOperationException { final JspFile jspFile = (JspFile)psiFile; final TextRange selectedRange = JavaI18nUtil.getSelectedRange(editor, jspFile); // must contain no or balanced tags only // must not contain scriptlets or custom tags PsiFile root = jspFile.getBaseLanguageRoot(); root.accept(new PsiRecursiveElementVisitor(){ @Override public void visitElement(PsiElement element) { TextRange elementRange = element.getTextRange(); if (elementRange.intersectsStrict(selectedRange)) { // in JSPX base language root is a Jspx file itself if (jspFile.getLanguage() != StdLanguages.JSPX && element instanceof OuterLanguageElement || element instanceof XmlTag && !selectedRange.contains(elementRange) && (!elementRange.contains(selectedRange) || !((XmlTag)element).getValue().getTextRange().contains(selectedRange))) { throw new IncorrectOperationException(CodeInsightBundle.message("i18nize.jsp.error")); } } super.visitElement(element); } }); }
private static PsiReferenceProcessor createReferenceProcessor(@NotNull final List<UsagesProcessor> processors, final GlobalInspectionContext context) { return new PsiReferenceProcessor() { @Override public boolean execute(PsiReference reference) { AnalysisScope scope = context.getRefManager().getScope(); if (scope.contains(reference.getElement()) && reference.getElement().getLanguage() == StdLanguages.JAVA || PsiTreeUtil.getParentOfType(reference.getElement(), PsiDocComment.class) != null) { return true; } synchronized (processors) { UsagesProcessor[] processorsArrayed = processors.toArray(new UsagesProcessor[processors.size()]); for (UsagesProcessor processor : processorsArrayed) { if (!processor.process(reference)) { processors.remove(processor); } } } return !processors.isEmpty(); } }; }
@Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { final PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class); if (parameter != null) { if (!parameter.getLanguage().isKindOf(StdLanguages.JAVA)) return false; final PsiElement declarationScope = parameter.getDeclarationScope(); if (declarationScope instanceof PsiMethod) { final PsiMethod method = (PsiMethod)declarationScope; final PsiClass containingClass = method.getContainingClass(); if (containingClass != null && !containingClass.isInterface()) { return containingClass.findMethodBySignature(generateMethodPrototype(method, parameter), false) == null; } } } return false; }
@Nullable private static PsiJavaFile createJavaFileFromClipboardContent(final Project project) { PsiJavaFile file = null; Transferable content = CopyPasteManager.getInstance().getContents(); if (content != null) { String text = null; try { text = (String)content.getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { // ignore; } if (text != null) { file = (PsiJavaFile) PsiFileFactory.getInstance(project).createFileFromText("A.java", StdLanguages.JAVA, text); } } return file; }
@Nullable public PsiElement adjustElement(final PsiElement psiElement) { final ProjectFileIndex index = ProjectRootManager.getInstance(psiElement.getProject()).getFileIndex(); final PsiFile containingFile = psiElement.getContainingFile(); if (containingFile != null) { final VirtualFile file = containingFile.getVirtualFile(); if (file != null && (index.isInSourceContent(file) || index.isInLibraryClasses(file) || index.isInLibrarySource(file))) { if (psiElement instanceof PsiJavaFile) { final PsiJavaFile psiJavaFile = (PsiJavaFile)psiElement; if (psiJavaFile.getViewProvider().getBaseLanguage() == StdLanguages.JAVA) { final PsiClass[] psiClasses = psiJavaFile.getClasses(); if (psiClasses.length == 1) { return psiClasses[0]; } } } if (psiElement instanceof PsiClass) return psiElement; } return containingFile; } return psiElement.isPhysical() ? psiElement : null; }
@Nullable private static PsiClass getOwnerClass(PsiElement element) { while (!(element instanceof PsiFile)) { if (element instanceof PsiClass && element.getParent() instanceof PsiJavaFile) { // top-level class final PsiClass psiClass = (PsiClass)element; if (JspPsiUtil.isInJspFile(psiClass)) { return null; } final PsiFile containingFile = psiClass.getContainingFile(); if (containingFile == null) { return null; } return StdLanguages.JAVA.equals(containingFile.getLanguage())? psiClass : null; } element = element.getParent(); } return null; }
@Override protected void setUp() throws Exception { super.setUp(); final LocalInspectionTool[] tools = configureLocalInspectionTools(); CodeInsightTestFixtureImpl.configureInspections(tools, getProject(), Collections.<String>emptyList(), getTestRootDisposable()); DaemonCodeAnalyzerImpl daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(getProject()); daemonCodeAnalyzer.prepareForTest(); final StartupManagerImpl startupManager = (StartupManagerImpl)StartupManagerEx.getInstanceEx(getProject()); startupManager.runStartupActivities(); startupManager.startCacheUpdate(); startupManager.runPostStartupActivities(); DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(false); if (isPerformanceTest()) { IntentionManager.getInstance().getAvailableIntentionActions(); // hack to avoid slowdowns in PyExtensionFactory PathManagerEx.getTestDataPath(); // to cache stuff ReferenceProvidersRegistry.getInstance(); // pre-load tons of classes InjectedLanguageManager.getInstance(getProject()); // zillion of Dom Sem classes LanguageAnnotators.INSTANCE.allForLanguage(JavaLanguage.INSTANCE); // pile of annotator classes loads LanguageAnnotators.INSTANCE.allForLanguage(StdLanguages.XML); ProblemHighlightFilter.EP_NAME.getExtensions(); Extensions.getExtensions(ImplicitUsageProvider.EP_NAME); Extensions.getExtensions(XmlSchemaProvider.EP_NAME); Extensions.getExtensions(XmlFileNSInfoProvider.EP_NAME); Extensions.getExtensions(ExternalAnnotatorsFilter.EXTENSION_POINT_NAME); Extensions.getExtensions(IndexPatternBuilder.EP_NAME); } }
@Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull final CompletionResultSet result) { PsiElement position = parameters.getPosition(); PsiFile file = position.getContainingFile(); if (parameters.getCompletionType() != CompletionType.BASIC || !JavaCompletionContributor.mayStartClassName(result) || !file.getLanguage().isKindOf(StdLanguages.XML)) { return; } final boolean empty = result.runRemainingContributors(parameters, true).isEmpty(); if (!empty && parameters.getInvocationCount() == 0) { result.restartCompletionWhenNothingMatches(); } if (empty && JavaClassReferenceCompletionContributor.findJavaClassReference(file, parameters.getOffset()) != null || parameters.isExtendedCompletion()) { CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, new Consumer<CompletionResult>() { @Override public void consume(final CompletionResult completionResult) { LookupElement lookupElement = completionResult.getLookupElement(); JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); if (classElement != null) { classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); } lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction result.passResult(completionResult); } }); } }
private static Language getLanguage(PsiElement element) { Language lang = element.getLanguage(); if (lang == StdLanguages.XML) { PsiElement parent = element.getParent(); lang = parent.getLanguage(); } return lang; }
@Override @NotNull public Collection<EncapsulatableClassMember> fun(PsiClass s) { if (s.getLanguage() != StdLanguages.JAVA) return Collections.emptyList(); final List<EncapsulatableClassMember> result = new ArrayList<EncapsulatableClassMember>(); for (PsiField field : s.getFields()) { if (!(field instanceof PsiEnumConstant)) { result.add(new PsiFieldMember(field)); } } return result; }
@Override public boolean canSelect(PsiElement e) { Language l = e.getLanguage(); if (!(l.equals(JavaLanguage.INSTANCE) || l.equals(StdLanguages.XML) || l.equals(StdLanguages.ANT))) { return false; } return PsiTreeUtil.getParentOfType(e, PsiComment.class) == null; }
@Override public boolean isInContext(@NotNull final PsiFile file, final int offset) { if (PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(StdLanguages.JAVA)) { PsiElement element = file.findElementAt(offset); if (element instanceof PsiWhiteSpace && offset > 0) { element = file.findElementAt(offset-1); } return PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null; } return false; }
@Override public boolean isInContext(@NotNull final PsiFile file, final int offset) { if (PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(StdLanguages.JAVA)) { return isStringLiteral(file.findElementAt(offset)); } return false; }
@Nullable public static PsiExpression findExpressionInRange(PsiFile file, int startOffset, int endOffset) { if (!file.getViewProvider().getLanguages().contains(StdLanguages.JAVA)) return null; PsiExpression expression = findElementInRange(file, startOffset, endOffset, PsiExpression.class); if (expression == null && findStatementsInRange(file, startOffset, endOffset).length == 0) { PsiElement element2 = file.getViewProvider().findElementAt(endOffset - 1, StdLanguages.JAVA); if (element2 instanceof PsiJavaToken) { final PsiJavaToken token = (PsiJavaToken)element2; final IElementType tokenType = token.getTokenType(); if (tokenType.equals(JavaTokenType.SEMICOLON)) { expression = findElementInRange(file, startOffset, element2.getTextRange().getStartOffset(), PsiExpression.class); } } } if (expression == null && findStatementsInRange(file, startOffset, endOffset).length == 0) { PsiElement element = PsiTreeUtil.skipSiblingsBackward(file.findElementAt(endOffset), PsiWhiteSpace.class); if (element != null) { element = PsiTreeUtil.skipSiblingsBackward(element.getLastChild(), PsiWhiteSpace.class, PsiComment.class); if (element != null) { final int newEndOffset = element.getTextRange().getEndOffset(); if (newEndOffset < endOffset) { expression = findExpressionInRange(file, startOffset, newEndOffset); } } } } if (expression instanceof PsiReferenceExpression && expression.getParent() instanceof PsiMethodCallExpression) return null; return expression; }
private static boolean conversionMayApply(ASTNode element) { PsiElement psi = element.getPsi(); if (psi == null || !psi.isValid()) return false; final PsiFile file = psi.getContainingFile(); final Language baseLanguage = file.getViewProvider().getBaseLanguage(); return baseLanguage == StdLanguages.JSPX && file.getLanguage() != baseLanguage; }
@Override public boolean canInlineElement(final PsiElement element) { if (element.getLanguage() != StdLanguages.JAVA) return false; if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; if (method.isConstructor() && !InlineMethodHandler.isChainingConstructor(method)) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) return false; return findClassInheritors(containingClass); } } if (!(element instanceof PsiClass)) return false; if (element instanceof PsiAnonymousClass) return false; return findClassInheritors((PsiClass)element); }
@Override public boolean processPrimaryMethod(ChangeInfo changeInfo) { if (!StdLanguages.JAVA.equals(changeInfo.getLanguage()) || !(changeInfo instanceof JavaChangeInfo)) return false; final PsiElement element = changeInfo.getMethod(); LOG.assertTrue(element instanceof PsiMethod); if (changeInfo.isGenerateDelegate()) { generateDelegate((JavaChangeInfo)changeInfo); } processPrimaryMethod((JavaChangeInfo)changeInfo, (PsiMethod)element, null, true); return true; }
private void addMethodConflicts(MultiMap<PsiElement, String> conflicts) { String newMethodName = myChangeInfo.getNewName(); try { PsiMethod prototype; final PsiMethod method = myChangeInfo.getMethod(); if (!StdLanguages.JAVA.equals(method.getLanguage())) return; PsiManager manager = method.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final CanonicalTypes.Type returnType = myChangeInfo.getNewReturnType(); if (returnType != null) { prototype = factory.createMethod(newMethodName, returnType.getType(method, manager)); } else { prototype = factory.createConstructor(); prototype.setName(newMethodName); } JavaParameterInfo[] parameters = myChangeInfo.getNewParameters(); for (JavaParameterInfo info : parameters) { PsiType parameterType = info.createType(method, manager); if (parameterType == null) { parameterType = JavaPsiFacade.getElementFactory(method.getProject()).createTypeFromText(CommonClassNames.JAVA_LANG_OBJECT, method); } PsiParameter param = factory.createParameter(info.getName(), parameterType); prototype.getParameterList().add(param); } ConflictsUtil.checkMethodConflicts(method.getContainingClass(), method, prototype, conflicts); } catch (IncorrectOperationException e) { LOG.error(e); } }
private Map<ProblemDescriptor, HighlightDisplayLevel> runXmlFileSchemaValidation(@NotNull XmlFile xmlFile) { final AnnotationHolderImpl holder = new AnnotationHolderImpl(new AnnotationSession(xmlFile)); final List<ExternalAnnotator> annotators = ExternalLanguageAnnotators.allForFile(StdLanguages.XML, xmlFile); for (ExternalAnnotator<?, ?> annotator : annotators) { processAnnotator(xmlFile, holder, annotator); } if (!holder.hasAnnotations()) return Collections.emptyMap(); Map<ProblemDescriptor, HighlightDisplayLevel> problemsMap = new LinkedHashMap<ProblemDescriptor, HighlightDisplayLevel>(); for (final Annotation annotation : holder) { final HighlightInfo info = HighlightInfo.fromAnnotation(annotation); if (info.getSeverity() == HighlightSeverity.INFORMATION) continue; final PsiElement startElement = xmlFile.findElementAt(info.startOffset); final PsiElement endElement = info.startOffset == info.endOffset ? startElement : xmlFile.findElementAt(info.endOffset - 1); if (startElement == null || endElement == null) continue; final ProblemDescriptor descriptor = myInspectionManager.createProblemDescriptor(startElement, endElement, info.getDescription(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false); final HighlightDisplayLevel level = info.getSeverity() == HighlightSeverity.ERROR? HighlightDisplayLevel.ERROR: HighlightDisplayLevel.WARNING; problemsMap.put(descriptor, level); } return problemsMap; }
@NotNull @Override public FileType detectFileType(@NotNull PsiElement context) { PsiFile file = context instanceof PsiFile ? (PsiFile)context : context.getContainingFile(); Language contextLanguage = context instanceof PsiFile ? null : context.getLanguage(); if (file.getLanguage() == StdLanguages.HTML || (file.getFileType() == StdFileTypes.JSP && contextLanguage == StdLanguages.HTML)) { return StdFileTypes.HTML; } return StdFileTypes.XML; }
@Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getProject(); if (project == null) return; PsiFile file = e.getData(CommonDataKeys.PSI_FILE); Editor editor = e.getData(CommonDataKeys.EDITOR); String text = StringUtil.notNullize(getSelectionText(editor)); Language language = text.isEmpty() ? null : getLanguageFromCaret(project, editor, file); doCreateNewScratch(project, true, ObjectUtils.notNull(language, StdLanguages.TEXT), text); }
@Nullable private String parseAttributeName() { String name = ""; ZenCodingToken token = getToken(); while (token != null) { if ((token instanceof IdentifierToken)) { name += ((IdentifierToken)token).getText(); } else if (token instanceof OperationToken && (((OperationToken)token).getSign() == '+' || ((OperationToken)token).getSign() == '-')) { name += ((OperationToken)token).getSign(); } else { break; } advance(); token = getToken(); } if (name.isEmpty()) { return null; } final XmlTag tag = XmlElementFactory.getInstance(myCallback.getProject()).createTagFromText("<tag " + name + "=''/>", StdLanguages.HTML); XmlAttribute[] attributes = tag.getAttributes(); if (attributes.length == 1) { return attributes[0].getName(); } else { return null; } }
@Override @Nullable public ProblemDescriptor[] checkFile(@NotNull final PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) { if (file == null) return null; if (file.getViewProvider().getPsi(StdLanguages.JAVA) == null) return null; final DependencyValidationManager validationManager = DependencyValidationManager.getInstance(file.getProject()); if (!validationManager.hasRules()) return null; if (validationManager.getApplicableRules(file).length == 0) return null; final ArrayList<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>(); ForwardDependenciesBuilder builder = new ForwardDependenciesBuilder(file.getProject(), new AnalysisScope(file)); DependenciesBuilder.analyzeFileDependencies(file, new DependenciesBuilder.DependencyProcessor() { @Override public void process(PsiElement place, PsiElement dependency) { PsiFile dependencyFile = dependency.getContainingFile(); if (dependencyFile != null && dependencyFile.isPhysical() && dependencyFile.getVirtualFile() != null) { final DependencyRule[] rule = validationManager.getViolatorDependencyRules(file, dependencyFile); for (DependencyRule dependencyRule : rule) { StringBuffer message = new StringBuffer(); message .append(InspectionsBundle.message("inspection.dependency.violator.problem.descriptor", dependencyRule.getDisplayText())); problems.add(manager.createProblemDescriptor(place, message.toString(), isOnTheFly, new LocalQuickFix[]{new EditDependencyRulesAction(dependencyRule)}, ProblemHighlightType.GENERIC_ERROR_OR_WARNING)); } } } }); return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); }
@Override public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet result) { PsiElement position = parameters.getPosition(); PsiFile file = position.getContainingFile(); if (parameters.getCompletionType() != CompletionType.BASIC || !JavaCompletionContributor.mayStartClassName(result) || !file.getLanguage().isKindOf(StdLanguages.XML)) { return; } final boolean empty = result.runRemainingContributors(parameters, true).isEmpty(); if (!empty && parameters.getInvocationCount() == 0) { result.restartCompletionWhenNothingMatches(); } if (empty && JavaClassReferenceCompletionContributor.findJavaClassReference(file, parameters.getOffset()) != null || parameters.isExtendedCompletion()) { CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, new Consumer<CompletionResult>() { @Override public void consume(final CompletionResult completionResult) { LookupElement lookupElement = completionResult.getLookupElement(); JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY); if (classElement != null) { classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE); } lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction result.passResult(completionResult); } }); } }
@Override public boolean canSelect(PsiElement e) { Language l = e.getLanguage(); if (!(l.equals(StdLanguages.JAVA) || l.equals(StdLanguages.XML) || l.equals(StdLanguages.ANT))) { return false; } return PsiTreeUtil.getParentOfType(e, PsiComment.class) == null; }
@Override public boolean isInContext(@NotNull final PsiFile file, final int offset) { if (PsiUtilBase.getLanguageAtOffset(file, offset).isKindOf(StdLanguages.JAVA)) { PsiElement element = file.findElementAt(offset); if (element instanceof PsiWhiteSpace && offset > 0) { element = file.findElementAt(offset-1); } return PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null; } return false; }
@Override public boolean isInContext(@NotNull final PsiFile file, final int offset) { if (PsiUtilBase.getLanguageAtOffset(file, offset).isKindOf(StdLanguages.JAVA)) { return isStringLiteral(file.findElementAt(offset)); } return false; }
public boolean canInlineElement(final PsiElement element) { if (element.getLanguage() != StdLanguages.JAVA) return false; if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; if (method.isConstructor() && !InlineMethodHandler.isChainingConstructor(method)) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) return false; return findClassInheritors(containingClass); } } if (!(element instanceof PsiClass)) return false; if (element instanceof PsiAnonymousClass) return false; return findClassInheritors((PsiClass)element); }