下面列出了怎么用com.intellij.psi.PsiNamedElement的API类实例代码及写法,或者点击链接到github查看源代码。
@RequiredReadAction
public static void openTargets(@Nonnull Collection<? extends PsiElement> members, @Nonnull MouseEvent mouseEvent, @Nonnull String text, @Nonnull final Function<PsiElement, PsiElement> map)
{
NavigatablePsiElement[] navigatablePsiElements = members.toArray(new NavigatablePsiElement[members.size()]);
ContainerUtil.sort(navigatablePsiElements, (o1, o2) ->
{
PsiElement map1 = map.fun(o1);
PsiElement map2 = map.fun(o2);
if(map1 instanceof PsiNamedElement && map2 instanceof PsiNamedElement)
{
return Comparing.compare(((PsiNamedElement) map1).getName(), ((PsiNamedElement) map2).getName());
}
return 0;
});
PsiElementListNavigator.openTargets(mouseEvent, navigatablePsiElements, text, text, new PsiMappedElementListCellRender(map));
}
protected static <T extends PsiNamedElement> int getChildIndex(T element, PsiElement parent, String name, Class<T> hisClass) {
PsiElement[] children = parent.getChildren();
int index = 0;
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 (namedChild.equals(element)) {
return index;
}
index++;
}
}
}
return index;
}
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;
}
@RequiredReadAction
private static void process(@Nonnull ProblemsHolder holder, @Nullable PsiElement range, @Nonnull PsiElement target)
{
if(range == null)
{
return;
}
// #hasAttribute() is cache result, #findAttribute() not
if(DotNetAttributeUtil.hasAttribute(target, DotNetTypes.System.ObsoleteAttribute))
{
DotNetAttribute attribute = DotNetAttributeUtil.findAttribute(target, DotNetTypes.System.ObsoleteAttribute);
if(attribute == null)
{
return;
}
String message = getMessage(attribute);
if(message == null)
{
message = CSharpInspectionBundle.message("target.is.obsolete", CSharpElementTreeNode.getPresentableText((PsiNamedElement) target));
}
holder.registerProblem(range, message, ProblemHighlightType.LIKE_DEPRECATED);
}
}
/**
* Populates the structure view. Uses HaskellUtil to get backing information.
*/
@NotNull
@Override
public TreeElement[] getChildren() {
if (element instanceof HaskellFile) {
List<PsiNamedElement> elems =
HaskellUtil.findDefinitionNodes((HaskellFile) element.getContainingFile(),
null);
List<TreeElement> treeElems = ContainerUtil.newArrayListWithCapacity(elems.size());
for (PsiNamedElement elem : elems) {
//noinspection ObjectAllocationInLoop
treeElems.add(new HaskellStructureViewElement(elem));
}
return treeElems.toArray(new TreeElement[treeElems.size()]);
}
return EMPTY_ARRAY;
}
public InplaceVariableIntroducer(PsiNamedElement elementToRename,
Editor editor,
Project project,
String title, E[] occurrences,
@Nullable E expr) {
super(editor, elementToRename, project);
myTitle = title;
myOccurrences = occurrences;
if (expr != null) {
final ASTNode node = expr.getNode();
final ASTNode astNode = LanguageTokenSeparatorGenerators.INSTANCE.forLanguage(expr.getLanguage())
.generateWhitespaceBetweenTokens(node.getTreePrev(), node);
if (astNode != null) {
new WriteCommandAction<Object>(project, "Normalize declaration") {
@Override
protected void run(Result<Object> result) throws Throwable {
node.getTreeParent().addChild(astNode, node);
}
}.execute();
}
myExpr = expr;
}
myExprMarker = myExpr != null && myExpr.isPhysical() ? createMarker(myExpr) : null;
initOccurrencesMarkers();
}
/**
* Returns all top-level assignment statements, function definitions and loaded symbols (ignoring
* aliases).
*/
private static ImmutableSet<String> symbolsInScope(BuildFile file) {
Set<String> symbols = new HashSet<>();
Processor<BuildElement> processor =
buildElement -> {
if (buildElement instanceof LoadedSymbol) {
StringLiteral s = ((LoadedSymbol) buildElement).getImport();
if (s != null) {
symbols.add(s.getStringContents());
}
} else if (buildElement instanceof PsiNamedElement) {
String name = buildElement.getName();
if (name != null) {
symbols.add(name);
}
}
return true;
};
file.searchSymbolsInScope(processor, /* stopAtElement= */ null);
return ImmutableSet.copyOf(symbols);
}
@Override
protected void collectNavigationMarkers(@NotNull PsiElement element,
Collection<? super RelatedItemLineMarkerInfo> result) {
if (false && element instanceof PsiNamedElement) {
PsiNamedElement namedElement = (PsiNamedElement) element;
String value = namedElement.getName();
if (value != null) {
Project project = element.getProject();
final List<HaskellUtil.FoundDefinition> found =
HaskellUtil.findDefinitionNode(project, value, namedElement);
final List<PsiNamedElement> namedNodes = ContainerUtil.newArrayList();
for (HaskellUtil.FoundDefinition fd : found) {
namedNodes.add(fd.element);
}
if (namedNodes.size() > 0) {
NavigationGutterIconBuilder<PsiElement> builder =
NavigationGutterIconBuilder.create(HaskellIcons.FILE).
setTargets(namedNodes).
setTooltipText("Navigate to element definition");
result.add(builder.createLineMarkerInfo(element));
}
}
}
}
@Nullable
protected static <T extends PsiNamedElement> T restoreElementInternal(@Nonnull PsiElement parent,
String name,
int index,
@Nonnull 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;
}
/** Return the root of a def subtree chosen from among the
* matches from xpathToIDNodes that matches namedElement's text.
* Assumption: ID nodes are direct children of def subtree roots.
*/
public static PsiElement resolve(ScopeNode scope,
Language language,
PsiNamedElement namedElement,
String xpathToIDNodes)
{
Collection<? extends PsiElement> defIDNodes =
XPath.findAll(language, scope, xpathToIDNodes);
String id = namedElement.getName();
PsiElement idNode = Trees.toMap(defIDNodes).get(id); // Find identifier node of variable definition
if ( idNode!=null ) {
return idNode.getParent(); // return the def subtree root
}
// If not found, ask the enclosing scope/context to resolve.
// That might lead back to this method, but probably with a
// different xpathToIDNodes (which is why I don't call this method
// directly).
ScopeNode context = scope.getContext();
if ( context!=null ) {
return context.resolve(namedElement);
}
// must be top scope; no resolution for element
return null;
}
public String getElementTooltip(T element) {
final Set<? extends T> dependencies = getDependenciesOf(element);
if (dependencies == null || dependencies.size() == 0) return null;
ArrayList<String> strings = new ArrayList<String>();
for (T dep : dependencies) {
if (dep instanceof PsiNamedElement) {
strings.add(dep.getName());
}
}
if (strings.isEmpty()) return null;
return RefactoringBundle.message("uses.0", StringUtil.join(strings, ", "));
}
@NotNull
protected String extractPathName(@NotNull PsiElement element, @NotNull ORTypes types) {
String path = "";
PsiElement prevLeaf = PsiTreeUtil.prevVisibleLeaf(element);
if (prevLeaf != null && prevLeaf.getNode().getElementType() == types.DOT) {
// Extract the qualified name of current element
PsiElement prevSibling = prevLeaf.getPrevSibling();
if (prevSibling instanceof PsiNamedElement) {
String name = ((PsiNamedElement) prevSibling).getName();
path = name == null ? "" : name;
prevSibling = prevSibling.getPrevSibling();
}
while (prevSibling != null && prevSibling.getNode().getElementType() == types.DOT) {
prevSibling = prevSibling.getPrevSibling();
if (prevSibling instanceof PsiNamedElement) {
path = ((PsiNamedElement) prevSibling).getName() + "." + path;
prevSibling = prevSibling.getPrevSibling();
} else {
break;
}
}
}
return path;
}
@NotNull
public static String getQualifiedPath(@NotNull PsiNameIdentifierOwner element) {
String path = "";
PsiElement parent = element.getParent();
while (parent != null) {
if (parent instanceof PsiQualifiedElement) {
if (parent instanceof PsiNameIdentifierOwner && ((PsiNameIdentifierOwner) parent).getNameIdentifier() == element) {
return ((PsiQualifiedElement) parent).getPath();
}
return ((PsiQualifiedElement) parent).getQualifiedName() + (path.isEmpty() ? "" : "." + path);
} else {
if (parent instanceof PsiNameIdentifierOwner) {
String parentName = ((PsiNamedElement) parent).getName();
if (parentName != null && !parentName.isEmpty()) {
path = parentName + (path.isEmpty() ? "" : "." + path);
}
}
parent = parent.getParent();
}
}
try {
PsiFile containingFile = element.getContainingFile(); // Fail in 2019.2... ?
return ((FileBase) containingFile).getModuleName() + (path.isEmpty() ? "" : "." + path);
} catch (PsiInvalidElementAccessException e) {
return path;
}
}
@NotNull
public PsiLetStub createStub(@NotNull PsiLet psi, StubElement parentStub) {
List<String> deconstructedNames = new ArrayList<>();
if (psi.isDeconsruction()) {
List<PsiElement> elements = psi.getDeconstructedElements();
for (PsiElement element : elements) {
if (element instanceof PsiNamedElement) {
deconstructedNames.add(((PsiNamedElement) element).getName());
}
}
}
return new PsiLetStub(parentStub, this, psi.getName(), psi.getQualifiedName(), psi.getAlias(), psi.isFunction(), deconstructedNames);
}
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)) {
String newName;
if (oldClassName.equals(name)) {
newName = newClassName;
} else {
String canonicalName = nameToCanonicalName(name, element);
final String newCanonicalName = suggester.suggestName(canonicalName);
if (newCanonicalName.length() == 0) {
LOG.error("oldClassName = " + oldClassName + ", newClassName = " + newClassName + ", name = " + name + ", canonicalName = " +
canonicalName + ", newCanonicalName = " + newCanonicalName);
}
newName = canonicalNameToName(newCanonicalName, element);
}
if (!newName.equals(name)) {
myRenames.put(element, newName);
}
else {
myRenames.put(element, null);
}
}
if (myRenames.get(element) == null) {
myElements.remove(varIndex);
}
}
}
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement element) {
if (element instanceof PsiNamedElement) {
String name = ((PsiNamedElement) element).getName();
return name == null ? "" : name;
}
return "desc name of element ";
}
@Nullable
@RequiredReadAction
private static String getName(@Nullable PsiElement psiElement)
{
if(psiElement instanceof DotNetVariable || psiElement instanceof CSharpMethodDeclaration)
{
return ((PsiNamedElement) psiElement).getName();
}
return null;
}
@Override
public String getElementText(PsiElement element) {
VirtualFile file = element instanceof PsiFile ? PsiUtilCore.getVirtualFile(element) : element instanceof VirtualFile ? (VirtualFile)element : null;
if (file != null) {
return VfsPresentationUtil.getPresentableNameForUI(element.getProject(), file);
}
String name = element instanceof PsiNamedElement ? ((PsiNamedElement)element).getName() : null;
return StringUtil.notNullize(name, "<unnamed>");
}
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement psiElement) {
if (!(psiElement instanceof PsiNamedElement)) {
return "";
}
return Strings.nullToEmpty(((PsiNamedElement) psiElement).getName());
}
@Nullable
@Override
public PsiElement resolve(PsiNamedElement element) {
// System.out.println(getClass().getSimpleName()+
// ".resolve("+myElement.getName()+
// " at "+Integer.toHexString(myElement.hashCode())+")");
return SymtabUtils.resolve(this, SampleLanguage.INSTANCE,
element, "/script/function/ID");
}
/**
* Finds a name definition inside a Haskell file. All definitions are found when name
* is null.
*/
@NotNull
public static List<PsiNamedElement> findDefinitionNodes(@Nullable HaskellFile haskellFile, @Nullable String name) {
List<PsiNamedElement> ret = ContainerUtil.newArrayList();
findDefinitionNode(haskellFile, name, null, ret);
return ret;
}
@Nullable
public static <T extends PsiNamedElement> T getParentOfTypeWithNameOrNull(@NotNull PsiElement element, @NotNull Class<T> aClass, @NotNull String name) {
PsiElement parent = element.getParent();
if(!aClass.isInstance(parent) || !(parent instanceof PsiNamedElement) || !name.equals(((PsiNamedElement) parent).getName())) {
return null;
}
return (T) parent;
}
public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException {
if (source == null) throw new IncorrectOperationException("Reference is invalid");
if (source instanceof PsiNamedElement) {
return ((PsiNamedElement) source).setName(newElementName);
}
return resolve();
}
@Override
public PsiElement setName(@NonNls @Nonnull String name) throws IncorrectOperationException
{
for(T element : myElements)
{
if(element instanceof PsiNamedElement)
{
((PsiNamedElement) element).setName(name);
}
}
return this;
}
private List<ArrayField> getSecurityDefinitions() {
final PsiFile containingFile = completionHelper.getPsiFile().getContainingFile();
final List<? extends PsiNamedElement> securityDefinitions =
new PathFinder().findNamedChildren("$.securityDefinitions", containingFile);
return securityDefinitions
.stream()
.map(PsiNamedElement::getName)
.map(ArrayField::new)
.collect(Collectors.toList());
}
public static void logPsiParentChain(PsiElement elem) {
while (elem != null) {
if (elem instanceof PsiNamedElement) {
System.out.println(elem.getClass().getName() + " --> Name: " + ((PsiNamedElement)elem).getName());
if (elem instanceof RClass)
System.out.println(" ----- Class qualified name: " + ((RClass)elem).getQualifiedName());
} else
System.out.println(elem.getClass().getName() + " --> No name");
elem = elem.getParent();
}
}
@RequiredReadAction
private static void appendName(PsiNamedElement element, StringBuilder builder, boolean isFullDocumentation)
{
if(isFullDocumentation)
{
builder.append("<b>").append(element.getName()).append("</b>");
}
else
{
builder.append(element.getName());
}
}
private PsiNamedElement getNextNamedParent(final PsiElement psiElement) {
if (psiElement == null) {
return null;
}
if (psiElement instanceof PsiNamedElement) {
final PsiNamedElement namedElement = (PsiNamedElement) psiElement;
if (namedElement.getName() != null && !namedElement.getName().contains(DUMMY_IDENTIFIER)) {
return namedElement;
}
}
return getNextNamedParent(psiElement.getParent());
}
private List<? extends PsiNamedElement> findChildrenByPathFrom(
final PathExpression pathExpression,
final PsiElement psiElement,
Predicate<PsiElement> childFilter) {
if (psiElement == null) {
return new ArrayList<>();
}
if (pathExpression.isEmpty()) {
return getNamedChildren(psiElement, childFilter);
}
final String currentNodeName = pathExpression.getCurrentPath();
final PathExpression remainingPathExpression = pathExpression.afterFirst();
if ("parent".equals(currentNodeName)) {
return findChildrenByPathFrom(
ROOT_PATH_EXPRESSION, getNextObjectParent(psiElement), childFilter);
}
final Optional<? extends PsiElement> childByName =
getChildByName(psiElement, currentNodeName, childFilter);
return childByName
.map(el -> findChildrenByPathFrom(remainingPathExpression, el, childFilter))
.orElseGet(ArrayList::new);
}
private Optional<? extends PsiElement> getChildByName(
final PsiElement psiElement, final String name, Predicate<PsiElement> childFilter) {
if (ROOT_PATH.equals(name)) {
return Optional.of(psiElement);
}
List<PsiNamedElement> children =
Arrays.stream(psiElement.getChildren())
.filter(child -> child instanceof PsiNamedElement)
.map(child -> (PsiNamedElement) child)
.collect(Collectors.toList());
if (children.isEmpty()) {
Optional<PsiElement> navigatablePsiElement =
Arrays.stream(psiElement.getChildren())
.filter(child -> child instanceof NavigatablePsiElement)
.filter(child -> !(child instanceof JsonStringLiteral))
.findFirst();
return navigatablePsiElement.isPresent()
? getChildByName(navigatablePsiElement.get(), name, childFilter)
: Optional.empty();
}
final String unescapedName = unescape(name);
return children.stream().filter(child -> unescapedName.equals(child.getName())).findFirst();
}