com.intellij.psi.PsiNamedElement Java Examples

The following examples show how to use com.intellij.psi.PsiNamedElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CSharpLineMarkerUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #2
Source File: HaskellStructureViewElement.java    From intellij-haskforce with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: GotoTargetHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: SymtabUtils.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** 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;
}
 
Example #5
Source File: AbstractElementSignatureProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: ObsoleteInspection.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #7
Source File: AbstractElementSignatureProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: HaskellLineMarkerProvider.java    From intellij-haskforce with Apache License 2.0 6 votes vote down vote up
@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));
            }
        }
    }
}
 
Example #9
Source File: InplaceVariableIntroducer.java    From consulo with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #10
Source File: CommonMacroCompletionContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: HaskellReferenceContributor.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
@Override
public void registerReferenceProviders(PsiReferenceRegistrar registrar) {
    PsiElementPattern.Capture<PsiNamedElement> variableCapture =
            PlatformPatterns.psiElement(PsiNamedElement.class).withParent(HaskellVars.class).withParent(HaskellGendecl.class).withLanguage(HaskellLanguage.INSTANCE);
    registrar.registerReferenceProvider(variableCapture,
            new HaskellReferenceProvider());
}
 
Example #12
Source File: FileReferenceCompletionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final PsiElement o1, final PsiElement o2) {
  if (o1 instanceof PsiNamedElement && o2 instanceof PsiNamedElement) {
    return Comparing.equal(((PsiNamedElement)o1).getName(), ((PsiNamedElement)o2).getName());
  }
  return o1.equals(o2);
}
 
Example #13
Source File: HaskellStructureViewElement.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public String getAlphaSortKey() {
    if (element instanceof PsiNamedElement) {
        String name = ((PsiNamedElement) element).getName();
        return name == null ? "" : name;
    }
    return "";
}
 
Example #14
Source File: JSGraphQLEndpointFindUsagesProvider.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement element) {
    if (element.getParent() instanceof PsiNamedElement) {
        return StringUtil.notNullize(((PsiNamedElement)element.getParent()).getName());
    }
    return "";
}
 
Example #15
Source File: JSGraphQLEndpointFindUsagesProvider.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public boolean canFindUsagesFor(@NotNull PsiElement psiElement) {
    if(!psiElement.isValid()) {
        return false;
    }
    return psiElement instanceof PsiNamedElement;
}
 
Example #16
Source File: CSharpNamedTreeElement.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
@RequiredUIAccess
public String getPresentableText()
{
	PsiNamedElement value = getValue();
	if(value instanceof DotNetLikeMethodDeclaration)
	{
		return CSharpElementPresentationUtil.formatMethod((DotNetLikeMethodDeclaration) value, CSharpElementPresentationUtil.METHOD_SCALA_LIKE_FULL);
	}
	else if(value instanceof DotNetTypeDeclaration)
	{
		return DotNetElementPresentationUtil.formatTypeWithGenericParameters((DotNetTypeDeclaration)value);
	}
	else if(value instanceof DotNetFieldDeclaration)
	{
		return CSharpElementPresentationUtil.formatField((DotNetFieldDeclaration) value);
	}
	else if(value instanceof DotNetPropertyDeclaration)
	{
		return CSharpElementPresentationUtil.formatProperty((DotNetPropertyDeclaration) value, CSharpElementPresentationUtil.PROPERTY_SCALA_LIKE_FULL);
	}
	else if(value instanceof DotNetNamespaceDeclaration)
	{
		return ((DotNetNamespaceDeclaration) value).getPresentableQName();
	}
	else
	{
		return value.getName();
	}
}
 
Example #17
Source File: AutomaticRenamingDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void updateRenamer() {
  for (int i = 0; i < myRenames.length; i++) {
    PsiNamedElement element = myRenames[i];
    if (myShouldRename[i]) {
      myRenamer.setRename(element, myNewNames[i]);
    }
    else {
      myRenamer.doNotRename(element);
    }
  }
}
 
Example #18
Source File: PresentationUtil.java    From protobuf-jetbrains-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns presentation name for given element.
 */
@Nullable
public static String getNameForElement(PsiElement element) {
    if (element instanceof DataType) {
        DataType type = (DataType) element;
        return type.getFullName();
    }
    if (element instanceof ProtoRootNode) {
        ProtoRootNode rootNode = (ProtoRootNode) element;
        String packageName = rootNode.getPackageName();
        if (packageName.isEmpty()) {
            return null;
        }
        return packageName;
    }
    if (element instanceof MessageField) {
        MessageField field = (MessageField) element;
        String fieldName = field.getFieldName();
        DataTypeContainer container = PsiTreeUtil.getParentOfType(element, DataTypeContainer.class);
        String conteinerName = getNameForElement(container);
        if (conteinerName != null) {
            return ProtostuffBundle.message("element.context.display", fieldName, conteinerName);
        } else {
            return fieldName;
        }
    }
    if (element instanceof PsiNamedElement) {
        PsiNamedElement namedElement = (PsiNamedElement) element;
        return namedElement.getName();
    }
    return null;
}
 
Example #19
Source File: PlainTextFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected String getTextByElement(Object element) {
  String elementValue = null;
  if (element instanceof PsiNamedElement) {
    elementValue = ((PsiNamedElement)element).getName();
  }
  else if (element instanceof PsiElement) {
    elementValue = ((PsiElement)element).getText();
  }
  return elementValue;
}
 
Example #20
Source File: RootSecurityCompletion.java    From intellij-swagger with MIT License 5 votes vote down vote up
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());
}
 
Example #21
Source File: CompletionProviderUtils.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
static Collection<LookupElement> createFromPsiItems(Collection<? extends PsiNamedElement> elements, @Nullable Icon icon, @Nullable Integer groupId) {
    return elements.stream().map(psi -> {
        LookupElementBuilder element = LookupElementBuilder.create(psi).withCaseSensitivity(true);
        if (icon != null) {
            element = element.withIcon(icon);
        }
        if (groupId != null) {
            return PrioritizedLookupElement.withGrouping(element, groupId);
        }
        return element;
    }).collect(Collectors.toList());
}
 
Example #22
Source File: CSharpInheritedMembersNodeProvider.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredReadAction
public Collection<CSharpNamedTreeElement> provideNodes(TreeElement treeElement)
{
	if(!(treeElement instanceof CSharpNamedTreeElement))
	{
		return Collections.emptyList();
	}

	PsiNamedElement value = ((CSharpNamedTreeElement) treeElement).getValue();

	if(!(value instanceof CSharpTypeDeclaration))
	{
		return Collections.emptyList();
	}

	CSharpResolveContext context = CSharpResolveContextUtil.createContext(DotNetGenericExtractor.EMPTY, value.getResolveScope(), value);

	List<PsiElement> elements = new ArrayList<>();
	context.processElements(element -> {
		elements.add(element);
		return true;
	}, true);

	// remove self elements
	context.processElements(element -> {
		elements.remove(element);
		return true;
	}, false);

	return elements.stream().map(element -> new CSharpNamedTreeElement((PsiNamedElement) element)).collect(Collectors.toList());
}
 
Example #23
Source File: DeleteNameDescriptionLocation.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String getElementDescription(@Nonnull final PsiElement element, @Nonnull final ElementDescriptionLocation location) {
  if (location instanceof DeleteNameDescriptionLocation) {
    if (element instanceof PsiNamedElement) {
      return ((PsiNamedElement)element).getName();
    }
  }
  return null;
}
 
Example #24
Source File: PsiPhpHelper.java    From yiistorm with MIT License 5 votes vote down vote up
public static PsiElement findMethodInClass(String methodName, PsiElement psiClass, boolean inherited) {
    if (methodName != null && !methodName.isEmpty() && psiClass != null) {
        PsiElement[] children = psiClass.getChildren();
        PsiElement extendsList = null;
        for (PsiElement child : children) {
            if (isClassMethod(child)) {
                if (methodName.equals(((PsiNamedElement) child).getName())) {
                    return child;
                }
            } else if (inherited && isElementType(child, EXTENDS_LIST)) {
                extendsList = child;
            }
        }

        // postponed read of inherited methods so original methods have higher priority
        if (extendsList != null) {
            PsiElement[] extendsElements = extendsList.getChildren();
            for (PsiElement extendsElement : extendsElements) {
                if (isElementType(extendsElement, CLASS_REFERENCE)) {
                    List<PsiElement> classes = getPsiElementsFromClassName(extendsElement.getText(), extendsElement.getProject());
                    for (PsiElement parentClass : classes) {
                        PsiElement method = findMethodInClass(methodName, parentClass, true);
                        if (method != null) {
                            return method;
                        }
                    }
                    break;
                }
            }
        }

    }
    return null;
}
 
Example #25
Source File: CppFindUsagesProvider.java    From CppTools with Apache License 2.0 5 votes vote down vote up
@NotNull
public String getDescriptiveName(PsiElement psiElement) {
  if (psiElement instanceof PsiNamedElement) {
    final String name = ((PsiNamedElement) psiElement).getName();

    return name != null ? name:"";
  }
  
  return psiElement.getText();
}
 
Example #26
Source File: PathFinder.java    From intellij-swagger with MIT License 5 votes vote down vote up
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();
}
 
Example #27
Source File: PathFinder.java    From intellij-swagger with MIT License 5 votes vote down vote up
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);
}
 
Example #28
Source File: CSharpDocumentationProvider.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@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());
	}
}
 
Example #29
Source File: RailwaysPsiUtils.java    From railways with MIT License 5 votes vote down vote up
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();
    }
}
 
Example #30
Source File: PathFinder.java    From intellij-swagger with MIT License 5 votes vote down vote up
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());
}