private static UsageTarget[] getTargetsForSQLReference( PsiElement psiElement, SQLRefReference sqlRefReferenceForID) { final List<PsiElement> primaryElementList = Lists.newArrayList(); final List<PsiElement> secondaryElementList = Lists.newArrayList(); if (psiElement.getLanguage() instanceof JavaLanguage) { for (final SmartPsiElementPointer<PsiElement> elementPointer : sqlRefReferenceForID.getXmlSmartPointersElements()) { primaryElementList.add(elementPointer.getElement()); } } else if (psiElement.getLanguage() instanceof XMLLanguage) { for (final SmartPsiElementPointer<PsiElement> elementPointer : sqlRefReferenceForID.getClassSmartPointersElements()) { primaryElementList.add(elementPointer.getElement()); } for (final SmartPsiElementPointer<PsiElement> elementPointer : sqlRefReferenceForID.getUtilClassSmartPointersElements().values()) { secondaryElementList.add(elementPointer.getElement()); } } PsiElement[] primeElements = new PsiElement[primaryElementList.size()]; PsiElement[] secondaryElements = new PsiElement[secondaryElementList.size()]; primaryElementList.toArray(primeElements); secondaryElementList.toArray(secondaryElements); // return new UsageTarget[]{new PsiElement2UsageTargetAdapter(primeElements[0])}; // return new UsageTarget[new PsiElement2UsageTargetAdapter(primeElements[0],new // FindUsagesOptions(psiElement.getProject())}; return new UsageTarget[] { new PsiElement2UsageTargetComposite( primeElements, secondaryElements, new FindUsagesOptions(psiElement.getProject())) }; }
@Nullable private String verifyInnerClassDestination() { PsiClass targetClass = findTargetClass(); if (targetClass == null) return null; for (PsiElement element : myElementsToMove) { if (PsiTreeUtil.isAncestor(element, targetClass, false)) { return RefactoringBundle.message("move.class.to.inner.move.to.self.error"); } final Language targetClassLanguage = targetClass.getLanguage(); if (!element.getLanguage().equals(targetClassLanguage)) { return RefactoringBundle.message( "move.to.different.language", UsageViewUtil.getType(element), ((PsiClass) element).getQualifiedName(), targetClass.getQualifiedName()); } if (element.getLanguage().equals(Language.findLanguageByID("Groovy"))) { return RefactoringBundle.message("dont.support.inner.classes", "Groovy"); } } while (targetClass != null) { if (targetClass.getContainingClass() != null && !targetClass.hasModifierProperty(PsiModifier.STATIC)) { return RefactoringBundle.message("move.class.to.inner.nonstatic.error"); } targetClass = targetClass.getContainingClass(); } return null; }
/* Method to start visiting */ private void doInit() { if (myChild1 == null || myChild2 == null) return; PsiElement psi1 = myChild1.getPsi(); PsiElement psi2 = myChild2.getPsi(); if (psi1 == null || psi2 == null) return; if (psi1.getLanguage() != MoonFileType.MOON_LANGUAGE || psi2.getLanguage() != MoonFileType.MOON_LANGUAGE) { return; } if (myChild2 != null && mySettings.KEEP_FIRST_COLUMN_COMMENT && SpacingUtil.COMMENT_BIT_SET.contains(myChild2.getElementType())) { myResult = Spacing.createKeepingFirstColumnSpacing(0, Integer.MAX_VALUE, true, 1); return; } if (myChild1 != null && myChild2 != null && myChild1.getElementType() == NEWLINE) { final ASTNode prev = SpacingUtil.getPrevElementType(myChild1); if (prev != null && prev.getElementType() == SHORTCOMMENT) { myResult = Spacing.createSpacing( 0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE); return; } } if (myParent instanceof MoonPsiElement) { ((MoonPsiElement) myParent).accept(this); } }
public static boolean isValidName( final Project project, final PsiElement psiElement, final String newName) { if (newName == null || newName.length() == 0) { return false; } final Condition<String> inputValidator = RenameInputValidatorRegistry.getInputValidator(psiElement); if (inputValidator != null) { return inputValidator.value(newName); } if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) { return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0; } if (psiElement instanceof PomTargetPsiElement) { return !StringUtil.isEmptyOrSpaces(newName); } final PsiFile file = psiElement.getContainingFile(); final Language elementLanguage = psiElement.getLanguage(); final Language fileLanguage = file == null ? null : file.getLanguage(); Language language = fileLanguage == null ? elementLanguage : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage; return LanguageNamesValidation.INSTANCE .forLanguage(language) .isIdentifier(newName.trim(), project); }
public static boolean validElement(@NotNull PsiElement element) { if (element instanceof PsiFile) return true; if (!element.isPhysical()) return false; final RefactoringSupportProvider provider = LanguageRefactoringSupport.INSTANCE.forLanguage(element.getLanguage()); return provider.isSafeDeleteAvailable(element); }
public static TextWithImports getEditorText(final Editor editor) { if (editor == null) { return null; } final Project project = editor.getProject(); if (project == null) return null; String defaultExpression = editor.getSelectionModel().getSelectedText(); if (defaultExpression == null) { int offset = editor.getCaretModel().getOffset(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { PsiElement elementAtCursor = psiFile.findElementAt(offset); if (elementAtCursor != null) { final EditorTextProvider textProvider = EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage()); if (textProvider != null) { final TextWithImports editorText = textProvider.getEditorText(elementAtCursor); if (editorText != null) return editorText; } } } } else { return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression); } return null; }
public boolean satisfiedBy(PsiElement element) { if (element.getLanguage() != GroovyFileType.GROOVY_LANGUAGE) return false; final PsiReference ref = element.getReference(); GrField field; if (ref != null) { PsiElement resolved = ref.resolve(); if (resolved instanceof GrAccessorMethod) { resolved = ((GrAccessorMethod) resolved).getProperty(); } if (!(resolved instanceof GrField)) return false; field = (GrField) resolved; } else { final PsiElement parent = element.getParent(); if (!(parent instanceof GrField)) return false; field = (GrField) parent; if (field.getNameIdentifierGroovy() != element) return false; } final PsiElement varDeclaration = field.getParent(); if (!(varDeclaration instanceof GrVariableDeclaration)) return false; if (((GrVariableDeclaration) varDeclaration).getVariables().length != 1) return false; final GrExpression expression = field.getInitializerGroovy(); return expression instanceof GrClosableBlock; }
private boolean shouldSkipPackages() { if (PsiImplUtil.getRuntimeQualifier(myRefExpr) != null) { return false; } PsiElement parent = myRefExpr.getParent(); return parent == null || parent.getLanguage().isKindOf(GroovyLanguage.INSTANCE); // don't skip in Play! }
static boolean tryFlip(PsiElement left, PsiElement right) { final Language language = left.getLanguage(); for (Flipper handler : EXTENSION.allForLanguage(language)) { if (handler.flip(left, right)) { return true; } } return false; }
@Override public void invoke( @NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) { PsiDocumentManager.getInstance(project).commitAllDocuments(); DumbService.getInstance(project).setAlternativeResolveEnabled(true); try { int offset = editor.getCaretModel().getOffset(); PsiElement[] elements = underModalProgress( project, "Resolving Reference...", () -> findAllTargetElements(project, editor, offset)); FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration"); if (elements.length != 1) { if (elements.length == 0 && suggestCandidates(TargetElementUtil.findReference(editor, offset)).isEmpty()) { PsiElement element = findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset()); if (startFindUsages(editor, element)) { return; } // disable 'no declaration found' notification for keywords final PsiElement elementAtCaret = file.findElementAt(offset); if (elementAtCaret != null) { final NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(elementAtCaret.getLanguage()); if (namesValidator != null && namesValidator.isKeyword(elementAtCaret.getText(), project)) { return; } } } chooseAmbiguousTarget(editor, offset, elements, file); return; } PsiElement element = elements[0]; if (element == findElementToShowUsagesOf(editor, editor.getCaretModel().getOffset()) && startFindUsages(editor, element)) { return; } PsiElement navElement = element.getNavigationElement(); navElement = TargetElementUtil.getInstance().getGotoDeclarationTarget(element, navElement); if (navElement != null) { gotoTargetElement(navElement, editor, file); } } catch (IndexNotReadyException e) { DumbService.getInstance(project) .showDumbModeNotification("Navigation is not available here during index update"); } finally { DumbService.getInstance(project).setAlternativeResolveEnabled(false); } }
public static String cleanRefIdForPsiElement(PsiElement element) { final Language language = element.getLanguage(); if (language instanceof JavaLanguage) { if (element instanceof PsiModifierList) { PsiAnnotation[] annotations = ((PsiAnnotationOwner) element).getAnnotations(); for (PsiAnnotation annotation : annotations) { if (AnnoRefConfigSettings.getInstance(element.getProject()) .getAnnoRefState() .ANNOREF_ANNOTATION_FQN .equals(annotation.getQualifiedName())) { String refKey = SQLRefNamingUtil.cleanAnnoRefForName(annotation.getContainingFile(), annotation); if (refKey != null) { return refKey; } } } } if (element instanceof PsiAnnotation) { final PsiAnnotation psiAnnotation = (PsiAnnotation) element; if (AnnoRefConfigSettings.getInstance(element.getProject()) .getAnnoRefState() .ANNOREF_ANNOTATION_FQN .equals(psiAnnotation.getQualifiedName())) { String cleanedAnnoRef = SQLRefNamingUtil.cleanAnnoRefForName( psiAnnotation.getContainingFile(), psiAnnotation); if (cleanedAnnoRef != null) { return cleanedAnnoRef; } } if (element instanceof PsiJavaToken && ((PsiJavaToken) element).getTokenType() == JavaTokenType.STRING_LITERAL) { final String refKey = StringUtils.cleanQuote(element.getText()); if (refKey != null) { return refKey; } } } } if (language instanceof XMLLanguage) { if (SQLRefNamingUtil.isPropitiousXmlFile(element.getContainingFile())) { final boolean isXmlTokenValid = new FilterElementProcessor( new XmlTokenTypeFilter(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN)) .execute(element); if (isXmlTokenValid) { final String refKey = getSqlRefKey(element); if (refKey != null) { return refKey; } } } } return null; }
@Override public PsiElement qualifyClassReferences(@NotNull PsiElement element) { final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { final ASTNode reference = adjuster.process(element.getNode(), false, false, true, true); return SourceTreeToPsiMap.treeToPsiNotNull(reference); } return element; }
@Override public void visitElement(PsiElement element) { final RefManagerExtension extension = getExtension(element.getLanguage()); if (extension != null) { extension.visitElement(element); } for (PsiElement aChildren : element.getChildren()) { aChildren.accept(this); } }
@Override protected boolean isAvailable(PsiElement element, Editor editor, PsiFile file) { return editor.getSettings().isVariableInplaceRenameEnabled() && element instanceof PsiNameIdentifierOwner && element.getUseScope() instanceof LocalSearchScope && element.getLanguage() == PerlLanguage.INSTANCE && ((PsiNameIdentifierOwner) element).getNameIdentifier() instanceof PerlString && element.getContainingFile().getViewProvider().getAllFiles().size() < 2; }
@Nullable private static Pair<PsiElement, TextRange> findExpression( PsiElement element, boolean allowMethodCalls) { final EditorTextProvider textProvider = EditorTextProvider.EP.forLanguage(element.getLanguage()); if (textProvider != null) { return textProvider.findExpression(element, allowMethodCalls); } return null; }
@Override public void visitElement(PsiElement element) { if (element.getLanguage() != JavaLanguage.INSTANCE) { return; } if (!PsiUtil.isLanguageLevel5OrHigher(element)) { return; } super.visitElement(element); }
public boolean canInlineElement(PsiElement element) { if (element instanceof PsiParameter) { final PsiElement parent = element.getParent(); if (parent instanceof PsiParameterList && parent.getParent() instanceof PsiMethod && element.getLanguage() == JavaLanguage.INSTANCE) { return true; } } return false; }
private static boolean spacesOnly(@Nullable TreeElement node) { if (node == null) return false; if (isWhitespaceOrEmpty(node)) return true; PsiElement psi = node.getPsi(); if (psi == null) { return false; } Language language = psi.getLanguage(); return WhiteSpaceFormattingStrategyFactory.getStrategy(language).containsWhitespacesOnly(node); }
public static boolean isCommentTextElement(final PsiElement element) { final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(element.getLanguage()); if (commenter instanceof CodeDocumentationAwareCommenterEx) { final CodeDocumentationAwareCommenterEx commenterEx = (CodeDocumentationAwareCommenterEx) commenter; if (commenterEx.isDocumentationCommentText(element)) return true; if (element instanceof PsiComment && commenterEx.isDocumentationComment((PsiComment) element)) return false; } return isComment(element); }
@Override public void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException { CheckUtil.checkWritable(element); if (SourceTreeToPsiMap.hasTreeElement(element)) { final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { adjuster.processRange(element.getNode(), startOffset, endOffset, myProject); } } }
@NotNull protected UsageInfo[] findUsages() { final PsiManager manager = myMethod.getManager(); final GlobalSearchScope searchScope = GlobalSearchScope.allScope(manager.getProject()); final List<UsageInfo> usages = new ArrayList<UsageInfo>(); for (PsiReference ref : ReferencesSearch.search(myMethod, searchScope, false)) { final PsiElement element = ref.getElement(); if (element instanceof PsiReferenceExpression) { boolean isInternal = PsiTreeUtil.isAncestor(myMethod, element, true); usages.add(new MethodCallUsageInfo((PsiReferenceExpression) element, isInternal)); } else if (element instanceof PsiDocTagValue) { usages.add(new JavadocUsageInfo(((PsiDocTagValue) element))); } else { throw new UnknownReferenceTypeException(element.getLanguage()); } } if (myTargetClass.isInterface()) { addInheritorUsages(myTargetClass, searchScope, usages); } final PsiCodeBlock body = myMethod.getBody(); if (body != null) { body.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitNewExpression(PsiNewExpression expression) { if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) { usages.add(new InternalUsageInfo(expression)); } super.visitNewExpression(expression); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) { usages.add(new InternalUsageInfo(expression)); } else if (!expression.isQualified()) { final PsiElement resolved = expression.resolve(); if (myTargetVariable.equals(resolved)) { usages.add(new InternalUsageInfo(expression)); } } super.visitReferenceExpression(expression); } }); } return usages.toArray(new UsageInfo[usages.size()]); }
@Override protected boolean isAvailable(PsiElement element, Editor editor, PsiFile file) { final PsiElement nameSuggestionContext = file.findElementAt(editor.getCaretModel().getOffset()); if (element == null && LookupManager.getActiveLookup(editor) != null) { element = PsiTreeUtil.getParentOfType(nameSuggestionContext, PsiNamedElement.class); } final RefactoringSupportProvider supportProvider = element != null ? LanguageRefactoringSupport.INSTANCE.forLanguage(element.getLanguage()) : null; return editor.getSettings().isVariableInplaceRenameEnabled() && supportProvider != null && supportProvider.isMemberInplaceRenameAvailable(element, nameSuggestionContext); }
@Override public boolean processUsage( ChangeInfo changeInfo, UsageInfo usageInfo, boolean beforeMethodChange, UsageInfo[] usages) { if (!(changeInfo instanceof JavaChangeInfo)) return false; PsiElement element = usageInfo.getElement(); if (element == null) return false; if (!GroovyLanguage.INSTANCE.equals(element.getLanguage())) return false; if (beforeMethodChange) { if (usageInfo instanceof OverriderUsageInfo) { processPrimaryMethodInner( ((JavaChangeInfo) changeInfo), (GrMethod) ((OverriderUsageInfo) usageInfo).getElement(), ((OverriderUsageInfo) usageInfo).getBaseMethod()); } } else { if (usageInfo instanceof GrMethodCallUsageInfo) { processMethodUsage( element, ((JavaChangeInfo) changeInfo), ((GrMethodCallUsageInfo) usageInfo).isToChangeArguments(), ((GrMethodCallUsageInfo) usageInfo).isToCatchExceptions(), ((GrMethodCallUsageInfo) usageInfo).getMapToArguments(), ((GrMethodCallUsageInfo) usageInfo).getSubstitutor()); return true; } else if (usageInfo instanceof DefaultConstructorImplicitUsageInfo) { processConstructor( (GrMethod) ((DefaultConstructorImplicitUsageInfo) usageInfo).getConstructor(), (JavaChangeInfo) changeInfo); return true; } else if (usageInfo instanceof NoConstructorClassUsageInfo) { processClassUsage( (GrTypeDefinition) ((NoConstructorClassUsageInfo) usageInfo).getPsiClass(), ((JavaChangeInfo) changeInfo)); return true; } else if (usageInfo instanceof ChangeSignatureParameterUsageInfo) { String newName = ((ChangeSignatureParameterUsageInfo) usageInfo).newParameterName; ((PsiReference) element).handleElementRename(newName); return true; } else { PsiReference ref = element.getReference(); if (ref != null && changeInfo.getMethod() != null) { ref.bindToElement(changeInfo.getMethod()); return true; } } } return false; }
private static boolean isLiteral(PsiElement element) { if (element == null) return false; final ASTNode astNode = element.getNode(); if (astNode == null) { return false; } final IElementType elementType = astNode.getElementType(); final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(element.getLanguage()); if (parserDefinition != null) { final TokenSet literals = parserDefinition.getStringLiteralElements(); return literals.contains(elementType); } return false; }
private static boolean isBrace(@NotNull PsiElement candidate) { final ASTNode node = candidate.getNode(); if (node != null && node.getFirstChildNode() == null) { final PairedBraceMatcher braceMatcher = LanguageBraceMatching.INSTANCE.forLanguage(candidate.getLanguage()); if (braceMatcher != null) { final IElementType elementType = node.getElementType(); for (BracePair pair : braceMatcher.getPairs()) { if (elementType == pair.getLeftBraceType() || elementType == pair.getRightBraceType()) { return true; } } } } return false; }
@Override public Result preprocessEnter( @NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffsetRef, @NotNull final Ref<Integer> caretAdvance, @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) { int caretOffset = caretOffsetRef.get().intValue(); PsiElement psiAtOffset = file.findElementAt(caretOffset); if (psiAtOffset != null && psiAtOffset.getTextOffset() < caretOffset) { ASTNode token = psiAtOffset.getNode(); Document document = editor.getDocument(); CharSequence text = document.getText(); final Language language = psiAtOffset.getLanguage(); final Commenter languageCommenter = LanguageCommenters.INSTANCE.forLanguage(language); final CodeDocumentationAwareCommenter commenter = languageCommenter instanceof CodeDocumentationAwareCommenter ? (CodeDocumentationAwareCommenter) languageCommenter : null; if (commenter != null && token.getElementType() == commenter.getLineCommentTokenType()) { final int offset = CharArrayUtil.shiftForward(text, caretOffset, " \t"); if (offset < document.getTextLength() && text.charAt(offset) != '\n') { String prefix = commenter.getLineCommentPrefix(); assert prefix != null : "Line Comment type is set but Line Comment Prefix is null!"; if (!StringUtil.startsWith(text, offset, prefix)) { if (text.charAt(caretOffset) != ' ' && !prefix.endsWith(" ")) { prefix += " "; } document.insertString(caretOffset, prefix); return Result.Default; } else { int afterPrefix = offset + prefix.length(); if (afterPrefix < document.getTextLength() && text.charAt(afterPrefix) != ' ') { document.insertString(afterPrefix, " "); // caretAdvance.set(0); } caretOffsetRef.set(offset); } return Result.Default; } } } return Result.Continue; }
@Nullable private static PsiFile getRoot(final PsiFile file, final Editor editor) { if (file == null) return null; int offset = editor.getCaretModel().getOffset(); if (offset == editor.getDocument().getTextLength()) offset--; if (offset < 0) return null; PsiElement leafElement = file.findElementAt(offset); if (leafElement == null) return null; if (leafElement.getLanguage() instanceof DependentLanguage) { leafElement = file.getViewProvider().findElementAt(offset, file.getViewProvider().getBaseLanguage()); if (leafElement == null) return null; } ASTNode node = leafElement.getNode(); if (node == null) return null; return (PsiFile) PsiUtilBase.getRoot(node).getPsi(); }
public static String getNewText(PsiElement elt) { Project project = elt.getProject(); PsiFile psiFile = getContainingFile(elt); final Document doc = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (doc == null) return null; final ImplementationTextSelectioner implementationTextSelectioner = LanguageImplementationTextSelectioner.INSTANCE.forLanguage(elt.getLanguage()); int start = implementationTextSelectioner.getTextStartOffset(elt); final int end = implementationTextSelectioner.getTextEndOffset(elt); final int lineStart = doc.getLineStartOffset(doc.getLineNumber(start)); final int lineEnd = end < doc.getTextLength() ? doc.getLineEndOffset(doc.getLineNumber(end)) : doc.getTextLength(); return doc.getCharsSequence().subSequence(lineStart, lineEnd).toString(); }
@Override public PsiElement shortenClassReferences(@NotNull PsiElement element, int flags) throws IncorrectOperationException { CheckUtil.checkWritable(element); if (!SourceTreeToPsiMap.hasTreeElement(element)) return element; final boolean addImports = (flags & DO_NOT_ADD_IMPORTS) == 0; final boolean incompleteCode = (flags & UNCOMPLETE_CODE) != 0; final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { final ASTNode reference = adjuster.process(element.getNode(), addImports, incompleteCode, myProject); return SourceTreeToPsiMap.treeToPsiNotNull(reference); } else { return element; } }
@Nullable PsiElement findMatchingElement(@Nullable PsiElement element, Editor editor) { while (element != null) { if (!JavaLanguage.INSTANCE.equals(element.getLanguage())) { break; } if (predicate instanceof PsiElementEditorPredicate) { if (((PsiElementEditorPredicate) predicate).satisfiedBy(element, editor)) { return element; } } else if (predicate.satisfiedBy(element)) { return element; } element = element.getParent(); if (element instanceof PsiFile) { break; } } return null; }