static Map<Pair<FeaturePath, PsiElement>, List<UsageInfo>> findJavaUsages( PsiElement element, List<PsiElement> javaElems ) { if( !(element instanceof PsiNamedElement) || javaElems.isEmpty() ) { return Collections.emptyMap(); } Map<Pair<FeaturePath, PsiElement>, List<UsageInfo>> allUsages = new HashMap<>(); for( PsiElement javaElem : javaElems ) { if( javaElem == null ) { continue; } List<UsageInfo> usages = findUsages( javaElem, element ); if( !usages.isEmpty() ) { FeaturePath path = javaElem.getUserData( KEY_FEATURE_PATH ); allUsages.put( new Pair<>( path, javaElem ), usages ); } } return allUsages; }
@Nullable @Override public DiagramRelationshipInfo getDependencyInfo(PsiNamedElement e1, PsiNamedElement e2, DiagramCategory diagramCategory) { if (e1 instanceof SchemaTypeDef && e2 instanceof SchemaTypeDef) { SchemaTypeDef td1 = (SchemaTypeDef) e1; SchemaTypeDef td2 = (SchemaTypeDef) e2; if (td2.extendsParents().contains(e1)) return EXTENDS; SchemaMetaDecl metaDecl = td1.getMetaDecl(); if (metaDecl != null) { SchemaQnTypeRef typeRef = metaDecl.getQnTypeRef(); if (typeRef != null) { SchemaTypeDef typeDef = typeRef.resolve(); if (e2.equals(typeDef)) return META; } } } return null; }
private void doTest() throws Exception { final String filename = getTestName(true) + ".xml"; VirtualFile vfile = VirtualFileManager.getInstance().findFileByUrl("file://" + getTestDataPath() + filename); String text = FileDocumentManager.getInstance().getDocument(vfile).getText(); final int off = text.indexOf("<ren>"); text = text.replace("<ren>", ""); configureFromFileText(filename, text); assertNotNull(myFile); PsiElement element = TargetElementUtil.getInstance().findTargetElement( getEditor(), TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.ELEMENT_NAME_ACCEPTED, off); assertNotNull(element); assertTrue(element instanceof PsiNamedElement); final RenameRefactoring rename = RefactoringFactory.getInstance(getProject()).createRename(element, ((PsiNamedElement)element).getName() + "-after"); rename.setSearchInComments(false); rename.setSearchInNonJavaFiles(false); rename.run(); checkResultByFile(filename + "-after"); }
@NotNull public String getDescriptiveName(@NotNull PsiElement element) { String literalString = tryFindMagicLiteralString(element, true); if (literalString != null) { return literalString; } if (element instanceof PsiNamedElement) { final String name = ((PsiNamedElement)element).getName(); return name == null ? "<unnamed>" : name; } if (element instanceof PyReferenceExpression) { String referencedName = ((PyReferenceExpression)element).getReferencedName(); if (referencedName == null) { return "<unnamed>"; } return referencedName; } return ""; }
@Nullable public static String getName(@NotNull PsiNamedElement element, boolean qualified) { if (element instanceof SchemaQnSegment) { SchemaQnSegment qnSegment = (SchemaQnSegment) element; return qnSegment.getQn().toString(); } String shortName = element.getName(); if (shortName == null) return null; if (qualified) { Qn namespace; if (element instanceof SchemaTypeDef) { SchemaTypeDef typeDef = (SchemaTypeDef) element; namespace = typeDef.getNamespace(); } else namespace = NamespaceManager.getNamespace(element); return namespace == null ? shortName : namespace.append(shortName).toString(); } else return shortName; }
private void addMeta(SchemaTypeDef typeDef, final DiagramNode<PsiNamedElement> node, Collection<PsiNamedElement> allElements) { SchemaMetaDecl metaDecl = typeDef.getMetaDecl(); if (metaDecl != null) { SchemaQnTypeRef typeRef = metaDecl.getQnTypeRef(); if (typeRef != null) { SchemaTypeDef metaType = typeRef.resolve(); if (metaType != null) { DiagramNode<PsiNamedElement> node2 = getOrAddNode(metaType, allElements); if (node2 != null) { edges.add( new DiagramEdgeBase<PsiNamedElement>( node, node2, SchemaDiagramRelationshipManager.META ) {} ); } } } } }
@Override public void collect(final PsiNamedElement member) { if (member.getContainingFile() == myModule) { final PyResolveContext resolveContext = PyResolveContext.defaultContext(); final PsiElement memberBody = PyMoveModuleMembersHelper.expandNamedElementBody(member); assert memberBody != null; memberBody.accept(new PyRecursiveElementVisitor() { @Override public void visitElement(PsiElement element) { for (PsiElement result : PyUtil.multiResolveTopPriority(element, resolveContext)) { if (result != null && isValidSameModuleDependency(result) && result != member) { myCollection.add((PsiNamedElement)result); } } super.visitElement(element); } }); } }
@NotNull @Override public Tokenizer getTokenizer(PsiElement element) { if (element instanceof PsiMethod) { return myMethodNameTokenizer; } if (element instanceof PsiDocComment) { return myDocCommentTokenizer; } if (element instanceof PsiLiteralExpression) { if (SuppressManager.isSuppressedInspectionName((PsiLiteralExpression)element)) { return EMPTY_TOKENIZER; } return myLiteralExpressionTokenizer; } if (element instanceof PsiNamedElement) { return myNamedElementTokenizer; } return super.getTokenizer(element); }
private void doTest(final String... candidatesNames) { myFixture.configureByFile(getTestName(false) + ".java"); final AddMethodQualifierFix addMethodQualifierFix = getQuickFix(); if (candidatesNames.length == 0) { assertNull(addMethodQualifierFix); return; } assertNotNull(addMethodQualifierFix); final Set<String> actualCandidatesNames = new TreeSet<String>(ContainerUtil.map(addMethodQualifierFix.getCandidates(), new Function<PsiNamedElement, String>() { @Override public String fun(final PsiNamedElement psiNamedElement) { final String name = psiNamedElement.getName(); assertNotNull(name); return name; } })); final Set<String> expectedCandidatesNames = new TreeSet<String>(ContainerUtil.list(candidatesNames)); assertEquals(expectedCandidatesNames, actualCandidatesNames); }
@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; }
@Nullable @Override public <T extends PsiNamedElement> T resolveTopLevelMember(@NotNull final Class<T> aClass) { Preconditions.checkState(getModule() != null, "Module is not set"); final String memberName = myQualifiedName.getLastComponent(); if (memberName == null) { return null; } final PyFile file = new QualifiedNameResolverImpl(myQualifiedName.removeLastComponent()).fromModule(getModule()).firstResultOfType(PyFile.class); if (file == null) { return null; } for (final T element : PsiTreeUtil.getChildrenOfTypeAsList(file, aClass)) { if (memberName.equals(element.getName())) { return element; } } return null; }
public Map<String, String> getNewName2PatternNameMap() { Map<String, String> newNameToSearchPatternNameMap = new HashMap<String, String>(1); final Map<String, MatchResult> variableMap = replacementInfo.getVariableMap(); if (variableMap != null) { for (String s : variableMap.keySet()) { final MatchResult matchResult = replacementInfo.getVariableMap().get(s); PsiElement match = matchResult.getMatchRef() != null ? matchResult.getMatch() : null; if (StructuralSearchUtil.isIdentifier(match)) match = match.getParent(); if (match instanceof PsiNamedElement) { final String name = ((PsiNamedElement)match).getName(); newNameToSearchPatternNameMap.put(name, s); } } } return newNameToSearchPatternNameMap; }
@Override @NotNull public String getDescriptiveName(@NotNull PsiElement element) { if (element instanceof XmlTag) { return ((XmlTag)element).getName(); } if (element instanceof XmlAttributeValue) { return ((XmlAttributeValue)element).getValue(); } if (element instanceof PsiNamedElement) { return ((PsiNamedElement)element).getName(); } return element.getText(); }
public boolean addTarget(final PsiElement element) { if (ArrayUtil.find(targets, element) > -1) return false; targets = ArrayUtil.append(targets, element); renderers.put(element, createRenderer(this, element)); if (!hasDifferentNames && element instanceof PsiNamedElement) { final String name = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Override public String compute() { return ((PsiNamedElement)element).getName(); } }); myNames.add(name); hasDifferentNames = myNames.size() > 1; } return true; }
@Nullable protected static <T extends PsiNamedElement> T restoreElementInternal(@NotNull PsiElement parent, String name, int index, @NotNull Class<T> hisClass) { PsiElement[] children = parent.getChildren(); for (PsiElement child : children) { if (ReflectionUtil.isAssignable(hisClass, child.getClass())) { T namedChild = hisClass.cast(child); final String childName = namedChild.getName(); if (Comparing.equal(name, childName)) { if (index == 0) { return namedChild; } index--; } } } return null; }
private void addParents(SchemaTypeDef typeDef, final DiagramNode<PsiNamedElement> node, Collection<PsiNamedElement> allElements) { List<SchemaTypeDef> parents = typeDef.extendsParents(); for (SchemaTypeDef parent : parents) { DiagramNode<PsiNamedElement> node2 = getOrAddNode(parent, allElements); if (node2 != null) { edges.add( new DiagramEdgeBase<PsiNamedElement>( node, node2, SchemaDiagramRelationshipManager.EXTENDS ) {} ); } } }
protected void suggestAllNames(final String oldClassName, String newClassName) { final NameSuggester suggester = new NameSuggester(oldClassName, newClassName); for (int varIndex = myElements.size() - 1; varIndex >= 0; varIndex--) { final PsiNamedElement element = myElements.get(varIndex); final String name = element.getName(); if (!myRenames.containsKey(element) && name != null) { String newName = suggestNameForElement(element, suggester, newClassName, oldClassName); if (!newName.equals(name)) { myRenames.put(element, newName); } else { myRenames.put(element, null); } } if (myRenames.get(element) == null) { myElements.remove(varIndex); } } }
@Override public void navigate(final boolean requestFocus) { if (isPhysical()) { super.navigate(requestFocus); return; } final PsiNamedElement psiNamedElement = XmlUtil.findRealNamedElement(this); Navigatable navigatable = PsiNavigationSupport.getInstance().getDescriptor(psiNamedElement); if (psiNamedElement instanceof XmlEntityDecl) { navigatable = PsiNavigationSupport.getInstance().createNavigatable( psiNamedElement.getProject(), psiNamedElement.getContainingFile().getVirtualFile(), psiNamedElement.getTextRange().getStartOffset() + psiNamedElement.getText().indexOf(getName()) ); } if (navigatable != null) { navigatable.navigate(requestFocus); } }
@Override @NotNull public String getNodeText(@NotNull PsiElement element, boolean useFullName) { if (element instanceof XmlTag) { final XmlTag xmlTag = (XmlTag)element; final PsiMetaData metaData = xmlTag.getMetaData(); final String name = metaData != null ? DescriptiveNameUtil.getMetaDataName(metaData) : xmlTag.getName(); String presentableName = metaData == null ? "<" + name + ">" : name; return presentableName+" of file "+xmlTag.getContainingFile().getName(); } if (element instanceof XmlAttributeValue) { return ((XmlAttributeValue)element).getValue(); } if (element instanceof PsiNamedElement) { return ((PsiNamedElement)element).getName(); } return element.getText(); }
@Override public boolean canFindUsagesFor(@NotNull PsiElement psiElement) { if (psiElement instanceof PsiNamedElement) { return true; } return false; }
@NotNull @Override public String getDescriptiveName(@NotNull PsiElement element) { if (element instanceof PsiNamedElement) { return StringUtil.notNullize(((PsiNamedElement) element).getName()); } return ""; }
@Nullable @Override public String getElementDescription(@NotNull PsiElement element, @NotNull ElementDescriptionLocation location) { if (location instanceof UsageViewLongNameLocation) { if (element instanceof PsiNamedElement && element instanceof AppleScriptPsiElement) { return ((PsiNamedElement) element).getName(); } } return null; }
public ModulePath(List<PsiElement> elements) { m_names = new String[elements.size()]; for (int i = 0; i < elements.size(); i++) { PsiElement element = elements.get(i); m_names[i] = element instanceof FileBase ? ((FileBase) element).asModuleName() : ((PsiNamedElement) element).getName(); } }
@NotNull @Override public String getAlphaSortKey() { if (m_element instanceof PsiNamedElement) { String name = ((PsiNamedElement) m_element).getName(); return name == null ? "" : name; } return ""; }
public static List<String> getWritableVariableNames(SwiftClassDeclaration classDeclaration) { return classDeclaration.getStatementList().stream() .filter(s -> s instanceof SwiftVariableDeclaration) .map(s -> (SwiftVariableDeclaration) s) .filter(v -> !v.isConstant()) .flatMap(v -> v.getPatternInitializerList().stream()) .filter(TearDownUtil::isNilable) .filter(TearDownUtil::isWritable) .map(p -> PsiTreeUtil.findChildOfType(p, SwiftIdentifierPattern.class)) .filter(Objects::nonNull) .map(PsiNamedElement::getName) .collect(Collectors.toList()); }
@NotNull private static String getTestNodeName(EduPluginConfigurator configurator, PsiElement psiElement) { String defaultTestName = configurator.getTestFileName(); if (psiElement instanceof PsiFile) { return defaultTestName; } if (psiElement instanceof PsiNamedElement) { String name = ((PsiNamedElement)psiElement).getName(); return name != null ? name : defaultTestName; } return defaultTestName; }
private void storeTypeManifoldReferences( @NotNull PsiElement element ) { Module mod = ModuleUtilCore.findModuleForPsiElement( element ); if( mod == null ) { return; } ManModule module = ManProject.getModule( mod ); PsiClass psiClass = findPsiClass( (PsiFileSystemItem)element, module ); if( psiClass == null ) { return; } Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.projectScope( mod.getProject() ) ); List<UsageInfo> usages = new ArrayList<>(); for( PsiReference ref: search.findAll() ) { usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(), ref.getRangeInElement().getEndOffset(), element, ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) ); } _usages = usages; if( psiClass instanceof ManifoldPsiClass ) { PsiElement fakeElement = ManGotoDeclarationHandler.find( psiClass, (ManifoldPsiClass)psiClass ); if( fakeElement instanceof PsiNamedElement && isTopLevelClassDeclaration( fakeElement ) ) { _classDeclElement = (PsiNamedElement)fakeElement; } } }
private void handleManifoldRename( PsiElement element, RefactoringElementListener elementListener ) { if( !(element instanceof PsiNamedElement) || _javaUsages.isEmpty() ) { return; } String name = ((PsiNamedElement)element).getName(); String newBaseName = JsonUtil.makeIdentifier( name ); //## find a way to add this as part of the overall rename Undo? ApplicationManager.getApplication().saveAll(); ApplicationManager.getApplication().invokeLater( () -> WriteCommandAction.runWriteCommandAction( element.getProject(), () -> { for( Map.Entry<Pair<FeaturePath, PsiElement>, List<UsageInfo>> entry : _javaUsages.entrySet() ) { Pair<FeaturePath, PsiElement> key = entry.getKey(); List<UsageInfo> value = entry.getValue(); String newFeatureName = newBaseName; FeaturePath path = key.getFirst(); if( path != null ) { newFeatureName = findFeatureName( path ); if( newFeatureName == null ) { newFeatureName = newBaseName; } } if( newFeatureName != null ) { RenameUtil.doRename( key.getSecond(), newFeatureName, value.toArray( new UsageInfo[value.size()] ), element.getProject(), elementListener ); } } } ) ); }
private String findFeatureName( FeaturePath path ) { PsiClass root = path.getRoot(); String fqn = root.getQualifiedName(); PsiClass psiClass = JavaPsiFacade.getInstance( root.getProject() ).findClass( fqn, GlobalSearchScope.moduleScope( ModuleUtilCore.findModuleForPsiElement( root ) ) ); if( psiClass == null ) { return null; } PsiNamedElement renamedFeature = findFeatureElement( psiClass, path.getChild() ); return renamedFeature == null ? null : renamedFeature.getName(); }
private static boolean isJavaElementFor( PsiModifierListOwner modifierListOwner, PsiElement element ) { PsiAnnotation annotation = modifierListOwner.getModifierList().findAnnotation( SourcePosition.class.getName() ); if( annotation != null ) { int textOffset = element.getTextOffset(); int textLength = element instanceof PsiNamedElement ? ((PsiNamedElement)element).getName().length() : element.getTextLength(); PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes(); int offset = -1; for( PsiNameValuePair pair : attributes ) { if( pair.getNameIdentifier().getText().equals( SourcePosition.OFFSET ) ) { String literalValue = pair.getLiteralValue(); if( literalValue == null ) { return false; } offset = Integer.parseInt( literalValue ); break; } } if( offset >= textOffset && offset <= textOffset + textLength ) { return true; } } return false; }
public static String getQualifiedFullName(SmcAction action) { PsiNamedElement transition = PsiTreeUtil.getParentOfType(action, SmcTransition.class); String actionParentName; if (transition != null) { actionParentName = transition.getName(); } else { SmcOnStateNestedElement onState = PsiTreeUtil.getParentOfType(action, SmcOnStateNestedElement.class); actionParentName = onState != null ? onState.getType() : ""; } SmcState state = PsiTreeUtil.getParentOfType(action, SmcState.class); return (state != null ? state.getName() + STRING_DOT : "") + actionParentName + STRING_DOT + action.getFullName(); }
@Override public DiagramDataModel<PsiNamedElement> createDataModel(@NotNull Project project, @Nullable PsiNamedElement psiNamedElement, @Nullable VirtualFile virtualFile, DiagramPresentationModel diagramPresentationModel) { return new SchemaDiagramDataModel(project, (SchemaFile) psiNamedElement, this); }
@Override public void visitPyElement(PyElement node) { if (node instanceof PsiNamedElement && !(node instanceof PyKeywordArgument)) { myBuilder.startNode(node); myBuilder.addNode(ReadWriteInstruction.newInstruction(myBuilder, node, node.getName(), ReadWriteInstruction.ACCESS.WRITE)); } super.visitPyElement(node); }
@Override public void fill() { getSecurityDefinitions().forEach(field -> { final PsiFile containingFile = completionHelper.getPsiFile().getContainingFile(); final List<? extends PsiNamedElement> security = new PathFinder().findChildrenByPathFrom("$.security", containingFile); final List<String> existingNames = extractNames(security); if (!existingNames.contains(field.getName())) { addUnique(field); } }); }
private List<ArrayField> getSecurityDefinitions() { final PsiFile containingFile = completionHelper.getPsiFile().getContainingFile(); final List<? extends PsiNamedElement> securityDefinitions = new PathFinder().findChildrenByPathFrom("$.securityDefinitions", containingFile); return securityDefinitions.stream() .map(PsiNamedElement::getName) .map(ArrayField::new) .collect(Collectors.toList()); }
@Nullable @Override public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) { final List<LookupElement> results = new ArrayList<LookupElement>(); final PsiElement element = context.getPsiElementAtStartOffset(); if (element != null) { for (PsiNamedElement iterableElement : getIterableElements(element)) { results.add(LookupElementBuilder.create(iterableElement)); } } return results.toArray(new LookupElement[results.size()]); }
@NotNull private DiagramNode<PsiNamedElement> addNode(final PsiNamedElement element) { DiagramNode<PsiNamedElement> node = new PsiDiagramNode<PsiNamedElement>(element, getProvider()) { @Nullable @Override public String getTooltip() { return SchemaPresentationUtil.getName(element, true); } }; nodes.put(element, node); return node; }
@Nullable private DiagramNode<PsiNamedElement> getOrAddNode(SchemaTypeDef typeDef, Collection<PsiNamedElement> allElements) { DiagramNode<PsiNamedElement> node = nodes.get(typeDef); if (node == null && allElements.contains(typeDef)) node = addNode(typeDef); return node; }
@Nullable @Override public PsiNamedElement resolve() { String functionName = myElement.getFunctionName(); // first search in local scope (e.g. function passed in as an arg). PsiNamedElement element = ResolveUtil.findInScope(myElement, functionName); if (element != null) { return element; } BuildFile file = myElement.getContainingFile(); if (functionName == null || file == null) { return null; } return file.findFunctionInScope(functionName); }