@Override public void tokenize(@NotNull PsiNameIdentifierOwner element, TokenConsumer consumer) { PsiElement identifier = element.getNameIdentifier(); if (identifier == null) { return; } PsiElement parent = element; final TextRange range = identifier.getTextRange(); if (range.isEmpty()) return; int offset = range.getStartOffset() - parent.getTextRange().getStartOffset(); if(offset < 0 ) { parent = PsiTreeUtil.findCommonParent(identifier, element); offset = range.getStartOffset() - parent.getTextRange().getStartOffset(); } String text = identifier.getText(); consumer.consumeToken(parent, text, true, offset, TextRange.allOf(text), IdentifierSplitter.getInstance()); }
@Nullable public static PsiElement getNameIdentifier(@NotNull PsiElement element) { if (element instanceof PsiNameIdentifierOwner) { return ((PsiNameIdentifierOwner)element).getNameIdentifier(); } if (element.isPhysical() && element instanceof PsiNamedElement && element.getContainingFile() != null && element.getTextRange() != null) { // Quite hacky way to get name identifier. Depends on getTextOffset overriden properly. final PsiElement potentialIdentifier = element.findElementAt(element.getTextOffset() - element.getTextRange().getStartOffset()); if (potentialIdentifier != null && Comparing.equal(potentialIdentifier.getText(), ((PsiNamedElement)element).getName(), false)) { return potentialIdentifier; } } return null; }
@NotNull @Override public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) { final PsiElement position = parameters.getPosition(); final PsiElement parent = position.getParent(); if (parent instanceof PsiNameIdentifierOwner) { final PsiElement nameIdentifier = ((PsiNameIdentifierOwner)parent).getNameIdentifier(); if (nameIdentifier == position) { return ThreeState.NO; } if (nameIdentifier != null && position.getTextRange().equals(nameIdentifier.getTextRange())) { //sometimes name identifiers are non-physical (e.g. Groovy) return ThreeState.NO; } } return ThreeState.UNSURE; }
@Nullable private static PsiElement findNameIdentifier(Editor editor, PsiFile file, TextRange toDuplicate) { int nonWs = CharArrayUtil.shiftForward(editor.getDocument().getCharsSequence(), toDuplicate.getStartOffset(), "\n\t "); PsiElement psi = file.findElementAt(nonWs); PsiElement named = null; while (psi != null) { TextRange range = psi.getTextRange(); if (range == null || psi instanceof PsiFile || !toDuplicate.contains(psi.getTextRange())) { break; } if (psi instanceof PsiNameIdentifierOwner) { named = ((PsiNameIdentifierOwner)psi).getNameIdentifier(); } psi = psi.getParent(); } return named; }
@Nullable private static PsiElement findTargetMember(@Nullable PsiElement element) { if (element == null) return null; final ChangeSignatureHandler fileHandler = getChangeSignatureHandler(element.getLanguage()); if (fileHandler != null) { final PsiElement targetMember = fileHandler.findTargetMember(element); if (targetMember != null) return targetMember; } PsiReference reference = element.getReference(); if (reference == null && element instanceof PsiNameIdentifierOwner) { return element; } if (reference != null) { return reference.resolve(); } return null; }
private void processElement(@NotNull PsiNameIdentifierOwner element) { final ScopeOwner owner = ScopeUtil.getScopeOwner(element); if (owner instanceof PyClass) { return; } final String name = element.getName(); if (name != null && !myIgnoredNames.contains(name)) { final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(element); final PsiElement builtin = builtinCache.getByName(name); if (builtin != null && !PyUtil.inSameFile(builtin, element)) { final PsiElement identifier = element.getNameIdentifier(); final PsiElement problemElement = identifier != null ? identifier : element; registerProblem(problemElement, String.format("Shadows built-in name '%s'", name), ProblemHighlightType.WEAK_WARNING, null, new PyRenameElementQuickFix(), new PyIgnoreBuiltinQuickFix(name)); } } }
@Override protected void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiNameIdentifierOwner owner = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiVariable.class, PsiMethod.class); if (owner == null) { return; } final RefactoringActionHandler handler = JavaRefactoringActionHandlerFactory.getInstance().createInvertBooleanHandler(); final Runnable runnable = new Runnable() { @Override public void run() { handler.invoke(project, new PsiElement[]{owner}, null); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { ApplicationManager.getApplication().invokeLater(runnable, project.getDisposed()); } }
@Nullable @Override public String getElementDescription(PsiElement element, ElementDescriptionLocation location) { if (!(element instanceof BuildElement)) { return null; } if (location instanceof UsageViewLongNameLocation) { return ((BuildElement) element).getPresentableText(); } if (location instanceof UsageViewShortNameLocation) { if (element instanceof PsiNameIdentifierOwner) { // this is used by rename operations, so needs to be accurate return ((PsiNameIdentifierOwner) element).getName(); } if (element instanceof PsiFile) { return ((PsiFile) element).getName(); } return ((BuildElement) element).getPresentableText(); } return null; }
@NotNull @Override public Tokenizer getTokenizer(PsiElement element) { if (element instanceof PsiWhiteSpace) { return EMPTY_TOKENIZER; } if (element instanceof PsiNameIdentifierOwner) { return new PsiIdentifierOwnerTokenizer(); } if (element.getParent() instanceof PsiNameIdentifierOwner) { return EMPTY_TOKENIZER; } if (element.getNode().getElementType() == JSGraphQLEndpointTokenTypes.IDENTIFIER) { return IDENTIFIER_TOKENIZER; } if (element instanceof PsiComment) { if (SuppressionUtil.isSuppressionComment(element)) { return EMPTY_TOKENIZER; } return myCommentTokenizer; } return EMPTY_TOKENIZER; }
@Nullable @Override public String getPresentableText() { if(element instanceof JSGraphQLEndpointImportDeclaration) { return element.getText(); } final PsiNameIdentifierOwner identifier = PsiTreeUtil.getChildOfType(element, PsiNameIdentifierOwner.class); if (identifier != null) { return identifier.getText(); } final ASTNode astIdentifier = element.getNode().getFirstChildNode(); if (astIdentifier != null && astIdentifier.getElementType() == JSGraphQLEndpointTokenTypes.IDENTIFIER) { return astIdentifier.getText(); } if (element instanceof PsiFile) { return null; } return element.getText(); }
@Nullable @RequiredReadAction public static String getNameWithAt(@NotNull PsiNameIdentifierOwner element) { PsiElement nameIdentifier = element.getNameIdentifier(); if(nameIdentifier == null) { return null; } if(!(nameIdentifier instanceof CSharpIdentifier)) { LOGGER.error("NameIdentifier is not 'CSharpIdentifier' element. Owner: " + element.getClass().getName()); return nameIdentifier.getText(); } String value = ((CSharpIdentifier) nameIdentifier).getValue(); if(value == null) { return null; } return value; }
@Nullable @Override @RequiredReadAction public PsiElement getAnchor(@NotNull PsiElement element) { if(element instanceof MsilElementWrapper || !element.isPhysical()) { return null; } if(element instanceof CSharpTypeDeclaration || element instanceof CSharpFieldDeclaration || element instanceof CSharpMethodDeclaration || element instanceof CSharpConstructorDeclaration || element instanceof CSharpIndexMethodDeclaration || //element instanceof CSharpConversionMethodDeclaration || element instanceof CSharpPropertyDeclaration || element instanceof CSharpEventDeclaration) { return ((PsiNameIdentifierOwner) element).getNameIdentifier(); } return null; }
@RequiredReadAction @Nullable @Override public CompilerCheckBuilder checkImpl(@NotNull CSharpLanguageVersion languageVersion, @NotNull CSharpHighlightContext highlightContext, @NotNull DotNetVirtualImplementOwner element) { PsiElement nameIdentifier = ((PsiNameIdentifierOwner) element).getNameIdentifier(); if(nameIdentifier == null) { return null; } final Pair<CSharpLikeMethodDeclarationImplUtil.ResolveVirtualImplementResult, PsiElement> resultPair = CSharpLikeMethodDeclarationImplUtil.resolveVirtualImplementation(element, element); switch(resultPair.getFirst()) { case CANT_HAVE: case FOUND: default: return null; case NOT_FOUND: return newBuilder(nameIdentifier, formatElement(element)); } }
@RequiredReadAction @Nullable @Override public HighlightInfoFactory checkImpl(@NotNull CSharpLanguageVersion languageVersion, @NotNull CSharpHighlightContext highlightContext, @NotNull DotNetQualifiedElement element) { PsiElement parent = element.getParent(); if(!(parent instanceof CSharpTypeDeclaration) | !(element instanceof PsiNameIdentifierOwner) || element instanceof CSharpConstructorDeclaration || element instanceof CSharpConversionMethodDeclaration || element instanceof CSharpEnumConstantDeclaration) { return null; } if(Comparing.equal(element.getName(), ((CSharpTypeDeclaration) parent).getName())) { PsiElement nameIdentifier = ((PsiNameIdentifierOwner) element).getNameIdentifier(); if(nameIdentifier == null) { return null; } return newBuilder(nameIdentifier, element.getName()); } return null; }
@RequiredReadAction @Nullable @Override public HighlightInfoFactory checkImpl(@NotNull CSharpLanguageVersion languageVersion, @NotNull CSharpHighlightContext highlightContext, @NotNull DotNetModifierListOwner element) { PsiElement parent = element.getParent(); if(parent instanceof DotNetTypeDeclaration && ((DotNetTypeDeclaration) parent).hasModifier(DotNetModifier.STATIC)) { if(CSharpPsiUtilImpl.isTypeLikeElement(element)) { return null; } if(!element.hasModifier(DotNetModifier.STATIC)) { PsiElement nameIdentifier = ((PsiNameIdentifierOwner) element).getNameIdentifier(); return newBuilder(ObjectUtil.notNull(nameIdentifier, element), formatElement(element)).addQuickFix(new AddModifierFix (DotNetModifier.STATIC, element)); } } return null; }
@NotNull @Override @RequiredDispatchThread public String getText() { String text; if(myExecutableChild instanceof PsiNameIdentifierOwner) { TextRange textRange = new TextRange(myExecutableChild.getTextOffset(), myExecutableChild.getTextRange().getEndOffset()); text = textRange.substring(myExecutableChild.getContainingFile().getText()); } else { text = myExecutableChild.getText(); } return StringUtil.shortenTextWithEllipsis(text, 100, 0); }
@Nullable @RequiredReadAction public static PsiElement getNameIdentifier(@Nonnull PsiElement element) { if (element instanceof PsiNameIdentifierOwner) { return ((PsiNameIdentifierOwner)element).getNameIdentifier(); } if (element.isPhysical() && element instanceof PsiNamedElement && element.getContainingFile() != null && element.getTextRange() != null) { // Quite hacky way to get name identifier. Depends on getTextOffset overriden properly. final PsiElement potentialIdentifier = element.findElementAt(element.getTextOffset() - element.getTextRange().getStartOffset()); if (potentialIdentifier != null && Comparing.equal(potentialIdentifier.getText(), ((PsiNamedElement)element).getName(), false)) { return potentialIdentifier; } } return null; }
@Nullable static PsiModifierListOwner getAnnotationOwner(@Nullable PsiElement element) { if(element == null) { return null; } PsiElement owner = element.getParent(); if(!(owner instanceof PsiModifierListOwner) || !(owner instanceof PsiNameIdentifierOwner)) { return null; } if(owner instanceof PsiParameter || owner instanceof PsiLocalVariable) { return null; } // support non-Java languages where getNameIdentifier may return non-physical psi with the same range PsiElement nameIdentifier = ((PsiNameIdentifierOwner) owner).getNameIdentifier(); if(nameIdentifier == null || !nameIdentifier.getTextRange().equals(element.getTextRange())) { return null; } return (PsiModifierListOwner) owner; }
/** returns name identifier, which is valid for reporting */ @Nullable static public PsiElement getNameIdentifier(@Nullable PsiNameIdentifierOwner element) { if (null != element) { PsiElement id = element.getNameIdentifier(); boolean isIdReportable = null != id && id.getTextLength() > 0; return isIdReportable ? id : null; } return null; }
static void reportAccessorOrMutator( @NotNull final ProblemsHolder problemsHolder, @NotNull final PsiNameIdentifierOwner method, @NotNull final PhpClass methodClass, @NotNull final String methodName ) { if (methodName.endsWith("Attribute")) { final boolean isAccessor = methodName.startsWith("get"); final boolean isMutator = !isAccessor && methodName.startsWith("set"); if (isAccessor || isMutator) { final PsiElement methodIdentifier = method.getNameIdentifier(); assert methodIdentifier != null; Function methodReference = (Function) method; if (isMutator) { final Method methodAccessor = PhpClassUtil.findMethodDeclaration(methodClass, "get" + methodName.substring(3)); if (methodAccessor != null) { methodReference = methodAccessor; } } String methodReturnType = "mixed"; if (isAccessor || !Objects.equals(methodReference, method)) { methodReturnType = PhpFunctionUtil.getReturnType(methodReference).toString(); } final String methodPropertyPart = methodName.substring(3, methodName.length() - 9); validatePropertyAnnotation(problemsHolder, methodClass, methodIdentifier, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, methodPropertyPart), methodReturnType); } } }
@Nullable private static PsiElement getReportableElement( @NotNull final PsiNameIdentifierOwner phpClass, @NotNull final PhpClassMember fieldPrimaryKey ) { if (Objects.equals(fieldPrimaryKey.getContainingClass(), phpClass)) { return fieldPrimaryKey.getNameIdentifier(); } return phpClass.getNameIdentifier(); }
public static void moveCaretAfterNameIdentifier(PsiNameIdentifierOwner createdElement) { final Project project = createdElement.getProject(); final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { final VirtualFile virtualFile = createdElement.getContainingFile().getVirtualFile(); if (virtualFile != null) { if (FileDocumentManager.getInstance().getDocument(virtualFile) == editor.getDocument()) { final PsiElement nameIdentifier = createdElement.getNameIdentifier(); if (nameIdentifier != null) { editor.getCaretModel().moveToOffset(nameIdentifier.getTextRange().getEndOffset()); } } } } }
/** * Set name for a given element if it implements {@link PsiNameIdentifierOwner} and * {@link PsiNameIdentifierOwner#getNameIdentifier()} resolves to an instance of * {@link GenericNameNode}. */ public static PsiElement setName(PsiNameIdentifierOwner element, String name) { PsiElement nameIdentifier = element.getNameIdentifier(); if (nameIdentifier instanceof GenericNameNode) { GenericNameNode nameNode = (GenericNameNode) nameIdentifier; return nameNode.setName(name); } throw new IncorrectOperationException(OPERATION_NOT_SUPPORTED); }
public void collectNavigationMarkers(List<PsiElement> elements, Collection<? super RelatedItemLineMarkerInfo> result, boolean forNavigation) { //noinspection ForLoopReplaceableByForEach for (int i = 0, size = elements.size(); i < size; i++) { PsiElement element = elements.get(i); collectNavigationMarkers(element, result); if (forNavigation && element instanceof PsiNameIdentifierOwner) { PsiElement nameIdentifier = ((PsiNameIdentifierOwner)element).getNameIdentifier(); if (nameIdentifier != null && !elements.contains(nameIdentifier)) { collectNavigationMarkers(nameIdentifier, result); } } } }
@Override public InplaceRefactoring doRename(@NotNull final PsiElement elementToRename, final Editor editor, final DataContext dataContext) { if (elementToRename instanceof PsiNameIdentifierOwner) { final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(elementToRename); if (processor.isInplaceRenameSupported()) { final StartMarkAction startMarkAction = StartMarkAction.canStart(elementToRename.getProject()); if (startMarkAction == null || processor.substituteElementToRename(elementToRename, editor) == elementToRename) { processor.substituteElementToRename(elementToRename, editor, new Pass<PsiElement>() { @Override public void pass(PsiElement element) { final MemberInplaceRenamer renamer = createMemberRenamer(element, (PsiNameIdentifierOwner)elementToRename, editor); boolean startedRename = renamer.performInplaceRename(); if (!startedRename) { performDialogRename(elementToRename, editor, dataContext, renamer.myInitialName); } } }); return null; } else { final InplaceRefactoring inplaceRefactoring = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER); if (inplaceRefactoring != null && inplaceRefactoring.getClass() == MemberInplaceRenamer.class) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(editor)); if (templateState != null) { templateState.gotoEnd(true); } } } } } performDialogRename(elementToRename, editor, dataContext, null); return null; }
protected static int initOccurrencesNumber(PsiNameIdentifierOwner nameIdentifierOwner) { final ProgressManager progressManager = ProgressManager.getInstance(); final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(nameIdentifierOwner.getProject()); final GlobalSearchScope scope = GlobalSearchScope.projectScope(nameIdentifierOwner.getProject()); final String name = nameIdentifierOwner.getName(); final boolean isCheapToSearch = name != null && searchHelper.isCheapEnoughToSearch(name, scope, null, progressManager.getProgressIndicator()) != PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES; return isCheapToSearch ? ReferencesSearch.search(nameIdentifierOwner).findAll().size() : - 1; }
private void processElement(@NotNull PsiNameIdentifierOwner element) { final ScopeOwner owner = ScopeUtil.getScopeOwner(element); if (owner instanceof PyClass) { return; } final String name = element.getName(); if (name != null) { final PsiElement identifier = element.getNameIdentifier(); final PsiElement problemElement = identifier != null ? identifier : element; if ("_".equals(name)) { return; } if (owner != null) { final ScopeOwner nextOwner = ScopeUtil.getScopeOwner(owner); if (nextOwner != null) { final ResolveProcessor processor = new ResolveProcessor(name); PyResolveUtil.scopeCrawlUp(processor, nextOwner, null, name, null, null); final PsiElement resolved = processor.getResult(); if (resolved != null) { final PyComprehensionElement comprehension = PsiTreeUtil.getParentOfType(resolved, PyComprehensionElement.class); if (comprehension != null && PyUtil.isOwnScopeComprehension(comprehension)) { return; } final Scope scope = ControlFlowCache.getScope(owner); if (scope.isGlobal(name) || scope.isNonlocal(name)) { return; } registerProblem(problemElement, String.format("Shadows name '%s' from outer scope", name), ProblemHighlightType.WEAK_WARNING, null, new PyRenameElementQuickFix()); } } } } }
private static boolean suggestRename(@NotNull PsiNameIdentifierOwner element, @NotNull PsiElement originalElement) { // Target expressions in the same scope are treated as the same variable if ((element instanceof PyTargetExpression) && originalElement instanceof PyTargetExpression) { return false; } // Renaming an __init__ method results in renaming its class else if (element instanceof PyFunction && PyNames.INIT.equals(element.getName()) && ((PyFunction)element).getContainingClass() != null) { return false; } return true; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element instanceof PyReferenceExpression) { final PsiReference reference = element.getReference(); if (reference == null) return; element = reference.resolve(); } final PsiNameIdentifierOwner nameOwner = element instanceof PsiNameIdentifierOwner ? (PsiNameIdentifierOwner)element : PsiTreeUtil.getParentOfType(element, PsiNameIdentifierOwner.class, true); if (nameOwner != null) { final VirtualFile virtualFile = nameOwner.getContainingFile().getVirtualFile(); if (virtualFile != null) { final Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile), true); if (ApplicationManager.getApplication().isUnitTestMode()) { renameInUnitTestMode(project, nameOwner, editor); } else { if (checkLocalScope(element) != null && (nameOwner instanceof PyNamedParameter || nameOwner instanceof PyTargetExpression)) { new VariableInplaceRenamer(nameOwner, editor).performInplaceRename(); } else { PsiElementRenameHandler.invoke(nameOwner, project, ScopeUtil.getScopeOwner(nameOwner), editor); } } } } }
private static void renameInUnitTestMode(@NotNull Project project, @NotNull PsiNameIdentifierOwner nameOwner, @Nullable Editor editor) { final PsiElement substitution = RenamePsiElementProcessor.forElement(nameOwner).substituteElementToRename(nameOwner, editor); if (substitution != null) { new RenameProcessor(project, substitution, "a", false, false).run(); } }
public static void showRenameTemplate(PsiElement context, PsiNameIdentifierOwner element, PsiReference... references) { context = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement( context); final Project project = context.getProject(); final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); final Editor editor = fileEditorManager.getSelectedTextEditor(); if (editor == null) { return; } final TemplateBuilderImpl builder = new TemplateBuilderImpl(context); final Expression macroCallNode = new MacroCallNode( new SuggestVariableNameMacro()); final PsiElement identifier = element.getNameIdentifier(); builder.replaceElement(identifier, "PATTERN", macroCallNode, true); for (PsiReference reference : references) { builder.replaceElement(reference, "PATTERN", "PATTERN", false); } final Template template = builder.buildInlineTemplate(); final TextRange textRange = context.getTextRange(); final int startOffset = textRange.getStartOffset(); editor.getCaretModel().moveToOffset(startOffset); final TemplateManager templateManager = TemplateManager.getInstance(project); templateManager.startTemplate(editor, template); }
public static void showRenameTemplate(PsiElement context, PsiNameIdentifierOwner element) { context = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(context); final Query<PsiReference> query = ReferencesSearch.search(element, element.getUseScope()); final Collection<PsiReference> references = query.findAll(); final Project project = context.getProject(); final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); final Editor editor = fileEditorManager.getSelectedTextEditor(); if (editor == null) { return; } final TemplateBuilderImpl builder = new TemplateBuilderImpl(context); final Expression macroCallNode = new MacroCallNode( new SuggestVariableNameMacro()); final PsiElement identifier = element.getNameIdentifier(); builder.replaceElement(identifier, "PATTERN", macroCallNode, true); for (PsiReference reference : references) { builder.replaceElement(reference, "PATTERN", "PATTERN", false); } final Template template = builder.buildInlineTemplate(); final TextRange textRange = context.getTextRange(); final int startOffset = textRange.getStartOffset(); editor.getCaretModel().moveToOffset(startOffset); final TemplateManager templateManager = TemplateManager.getInstance(project); templateManager.startTemplate(editor, template); }
private static boolean suggestRename(@NotNull PsiNameIdentifierOwner element, @NotNull PsiElement originalElement) { // Target expressions in the same scope are treated as the same variable if (element instanceof PyTargetExpression && originalElement instanceof PyTargetExpression) { return false; } // Renaming an __init__ method results in renaming its class else if (element instanceof PyFunction && PyNames.INIT.equals(element.getName()) && ((PyFunction) element).getContainingClass() != null) { return false; } return true; }