Java Code Examples for com.intellij.psi.util.PsiTreeUtil#findChildrenOfType()

The following examples show how to use com.intellij.psi.util.PsiTreeUtil#findChildrenOfType() . 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: HaskellUtil.java    From intellij-haskforce with Apache License 2.0 6 votes vote down vote up
/**
 * Find definitions that have been re-exported.
 *
 * <code>
 *   module Foo (module Bar, foo) where
 *   import Bar
 *   import Baz (foo)
 * </code>
 */
private static void findDefinitionNodeInExport(@NotNull Project project, HaskellFile f, @Nullable String name,
                                               @Nullable PsiNamedElement e, List<PsiNamedElement> result) {
    List<HaskellPsiUtil.Import> imports = HaskellPsiUtil.parseImports(f);
    for (HaskellExport export : PsiTreeUtil.findChildrenOfType(f, HaskellExport.class)) {
        boolean exportFn = export.getQvar() != null && export.getQvar().getQvarid() != null
                && export.getQvar().getQvarid().getVarid().getName().equals(name);
        String moduleName = exportFn
                ? getModule(export.getQvar().getQvarid().getConidList())
                : export.getModuletoken() != null && export.getQconid() != null ? export.getQconid().getText() : null;
        if (!exportFn && moduleName == null) continue;
        for (HaskellPsiUtil.Import imprt : imports) {
            if (moduleName != null && !moduleName.equals(imprt.module) && !moduleName.equals(imprt.alias)) continue;
            boolean hidden = imprt.getHidingNames() != null && ArrayUtil.contains(name, imprt.getHidingNames());
            boolean notImported = imprt.getImportedNames() != null && !ArrayUtil.contains(name, imprt.getImportedNames());
            if (hidden || notImported) continue;
            for (HaskellFile f2 : HaskellModuleIndex.getFilesByModuleName(project, imprt.module, GlobalSearchScope.allScope(project))) {
                findDefinitionNode(f2, name, e, result);
                findDefinitionNodeInExport(project, f2, name, e, result);
            }
        }
    }
}
 
Example 2
Source File: HaxelibClasspathUtils.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 * Turn some text into a file, parse it using the .hxml parser, and
 * return any HXML classpaths.
 *
 * @param project to include created files in.
 * @param text to parse.
 * @return A (possibly empty) list containing all of the classpaths found in the text.
 */
@NotNull
public static List<String> getHXMLFileClasspaths(@NotNull Project project, @NotNull String text) {
  if (text.isEmpty()) {
    return Collections.EMPTY_LIST;
  }

  List<String> strings1;
  strings1 = new ArrayList<String>();
  PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(HXMLFileType.INSTANCE, "data.hxml", text, 0, text.length() - 1);

  Collection<HXMLClasspath> hxmlClasspaths = PsiTreeUtil.findChildrenOfType(psiFile, HXMLClasspath.class);
  for (HXMLClasspath hxmlClasspath : hxmlClasspaths) {
    strings1.add(HXMLPsiImplUtil.getValue(hxmlClasspath));
  }
  return strings1;
}
 
Example 3
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private void completionOfOperationKeywordsInSchemaDefinition() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
            final PsiElement completionElement = parameters.getPosition();
            final GraphQLOperationTypeDefinition operationTypeDefinition = PsiTreeUtil.getParentOfType(completionElement, GraphQLOperationTypeDefinition.class);
            if (operationTypeDefinition != null && operationTypeDefinition.getOperationType() == null) {
                final Set<String> keywords = Sets.newLinkedHashSet(Lists.newArrayList("query", "mutation", "subscription"));
                for (GraphQLOperationTypeDefinition existingDefinition : PsiTreeUtil.findChildrenOfType(operationTypeDefinition.getParent(), GraphQLOperationTypeDefinition.class)) {
                    if (existingDefinition.getOperationType() != null) {
                        keywords.remove(existingDefinition.getOperationType().getText());
                    }
                }
                keywords.forEach(keyword -> result.addElement(LookupElementBuilder.create(keyword).bold().withInsertHandler(AddColonSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP)));
            }
        }
    };
    extend(CompletionType.BASIC, psiElement(GraphQLElementTypes.NAME).inside(GraphQLOperationTypeDefinition.class), provider);
}
 
Example 4
Source File: BashFunctionDefImpl.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public Set<String> findLocalScopeVariables() {
    if (localScopeVariables == null) {
        synchronized (stateLock) {
            if (localScopeVariables == null) {
                localScopeVariables = Sets.newLinkedHashSetWithExpectedSize(10);

                Collection<BashVarDef> varDefs = PsiTreeUtil.findChildrenOfType(this, BashVarDef.class);
                for (BashVarDef varDef : varDefs) {
                    if (varDef.isLocalVarDef() && this.isEquivalentTo(BashPsiUtils.findNextVarDefFunctionDefScope(varDef))) {
                        localScopeVariables.add(varDef.getReferenceName());
                    }
                }
            }
        }
    }

    return localScopeVariables;
}
 
Example 5
Source File: UnescapingPsiBuilderTest.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic() throws Exception {
    BashProjectSettings.storedSettings(getProject()).setEvalEscapesEnabled(true);

    //this feature needs the experimental settings
    try {
        PsiFile file = myFixture.configureByFile("basic/basic.bash");
        Assert.assertNotNull(file);

        Collection<BashEvalBlock> evalBlocks = PsiTreeUtil.findChildrenOfType(file, BashEvalBlock.class);
        Assert.assertNotNull(evalBlocks);
        Assert.assertEquals(2, evalBlocks.size());

        Iterator<BashEvalBlock> iterator = evalBlocks.iterator();

        BashEvalBlock first = iterator.next();
        Assert.assertEquals(1, first.getChildren().length);

        BashEvalBlock second = iterator.next();
        Assert.assertEquals(2, second.getChildren().length);
    } finally {
        BashProjectSettings.storedSettings(getProject()).setEvalEscapesEnabled(false);
    }
}
 
Example 6
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private void completeOperationTypeNamesInSchemaDefinition() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
            final PsiElement completionElement = parameters.getPosition();
            final TypeDefinitionRegistry registry = GraphQLTypeDefinitionRegistryServiceImpl.getService(completionElement.getProject()).getRegistry(parameters.getOriginalFile());
            if (registry != null) {
                final Collection<GraphQLTypeName> currentTypes = PsiTreeUtil.findChildrenOfType(PsiTreeUtil.getTopmostParentOfType(completionElement, GraphQLElement.class), GraphQLTypeName.class);
                final Set<String> currentTypeNames = currentTypes.stream().map(PsiNamedElement::getName).collect(Collectors.toSet());
                registry.types().values().forEach(type -> {
                    if (type instanceof ObjectTypeDefinition && !currentTypeNames.contains(type.getName())) {
                        result.addElement(LookupElementBuilder.create(type.getName()));
                    }
                });
            }
        }
    };
    extend(CompletionType.BASIC, psiElement(GraphQLElementTypes.NAME).afterLeaf(":").inside(GraphQLOperationTypeDefinition.class), provider);
}
 
Example 7
Source File: SoyReferenceTest.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
public void testVariableReferencesInElement() {
  myFixture.configureByFiles("CompletionSourceElement.soy");
  PsiElement container = PsiTreeUtil.findChildOfType(myFixture.getFile(), SoyMsgStatement.class);
  Collection<SoyVariableReferenceIdentifier> vars =
      PsiTreeUtil.findChildrenOfType(container, SoyVariableReferenceIdentifier.class);
  assertSize(4, vars);
  for (SoyVariableReferenceIdentifier var : vars) {
    switch (var.getText()) {
      case "$planet": // @param
        assertInstanceOf(var.getReference().resolve(), SoyParamDefinitionIdentifier.class);
        break;
      case "$probe": // @inject
        assertInstanceOf(var.getReference().resolve(), SoyParamDefinitionIdentifier.class);
        break;
      case "$isLoaded": // @state
        assertInstanceOf(var.getReference().resolve(), SoyParamDefinitionIdentifier.class);
        break;
      case "$shape": // {let}
        assertInstanceOf(var.getReference().resolve(), SoyVariableDefinitionIdentifier.class);
        break;
    }
  }
}
 
Example 8
Source File: JsonnetFoldingBuilder.java    From intellij-jsonnet with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
    List<FoldingDescriptor> descriptors = new ArrayList<>();
    Collection<PsiElement> literalExpressions = PsiTreeUtil.findChildrenOfType(root, JsonnetObj.class);
    literalExpressions.addAll(PsiTreeUtil.findChildrenOfType(root, JsonnetArr.class));
    literalExpressions.addAll(PsiTreeUtil.findChildrenOfType(root, JsonnetArrcomp.class));
    for (final PsiElement literalExpression : literalExpressions) {
        FoldingGroup group = FoldingGroup.newGroup(
                "jsonnet-" + literalExpression.getTextRange().getStartOffset() +
                        "-" + literalExpression.getTextRange().getEndOffset()
        );
        int start = literalExpression.getTextRange().getStartOffset() + 1;
        int end = literalExpression.getTextRange().getEndOffset() - 1;
        if (end > start)
            descriptors.add(
                    new FoldingDescriptor(
                            literalExpression.getNode(),
                            new TextRange(start, end),
                            group
                    ) {
                        @Override
                        public String getPlaceholderText() {
                            return "...";
                        }
                    }
            );
    }
    return descriptors.toArray(new FoldingDescriptor[0]);
}
 
Example 9
Source File: JsxParsingTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testTagPropWithParen() {
    PsiTag tag = (PsiTag) firstElement(parseCode("<div style=(x) onFocus=a11y.onFocus/>"));

    Collection<PsiTagProperty> properties = PsiTreeUtil.findChildrenOfType(tag, PsiTagProperty.class);
    assertEquals(2, properties.size());
    Iterator<PsiTagProperty> itProperties = properties.iterator();
    assertEquals("style=(x)", itProperties.next().getText());
    assertEquals("onFocus=a11y.onFocus", itProperties.next().getText());
}
 
Example 10
Source File: SignatureParsingTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testJsObject() {
    PsiLet e = first(letExpressions(parseCode("let x: < a: string; b: 'a > Js.t -> string")));
    ORSignature signature = e.getORSignature();

    assertEquals(2, signature.getTypes().length);
    PsiSignatureItem jsObj = signature.getItems()[0];
    List<PsiObjectField> fields = new ArrayList<>(PsiTreeUtil.findChildrenOfType(jsObj, PsiObjectField.class));
    assertSize(2, fields);
    assertEquals(fields.get(0).getName(), "a");
    assertEquals(fields.get(1).getName(), "b");
}
 
Example 11
Source File: VariantCallParsingTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testPatternMatch() {
    PsiSwitch e = firstOfType(
            parseCode("match action with | UpdateDescription(desc) -> let open ReasonReact.SideEffects in (fun _self -> onDescriptionChange desc)"),
            PsiSwitch.class);
    PsiPatternMatchBody body = PsiTreeUtil.findChildOfType(e, PsiPatternMatchBody.class);
    assertEquals("let open ReasonReact.SideEffects in (fun _self -> onDescriptionChange desc)", body.getText());
    Collection<PsiUpperSymbol> uppers = PsiTreeUtil.findChildrenOfType(body, PsiUpperSymbol.class);
    assertEquals("ReasonReact, SideEffects", Joiner.join(", ", uppers.stream().map(PsiElement::getText).collect(Collectors.toList())));
}
 
Example 12
Source File: NutzInjectConfFoldingBuilder.java    From NutzCodeInsight with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean b) {
    Project project = root.getProject();
    List<FoldingDescriptor> descriptors = new ArrayList<>();
    Collection<VirtualFile> propertiesFiles = FilenameIndex.getAllFilesByExt(project, "properties", GlobalSearchScope.projectScope(project));
    Collection<PsiLiteralExpression> literalExpressions = PsiTreeUtil.findChildrenOfType(root, PsiLiteralExpression.class);
    for (final PsiLiteralExpression literalExpression : literalExpressions) {
        if (!NutzInjectConfUtil.isInjectConf(literalExpression)) {
            continue;
        }
        String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
        String key = NutzInjectConfUtil.getKey(value);
        if (key != null) {
            final List<String> properties = NutzInjectConfUtil.findProperties(project, propertiesFiles, key);
            final TextRange textRange = new TextRange(literalExpression.getTextRange().getStartOffset() + 1, literalExpression.getTextRange().getEndOffset() - 1);
            String data;
            if (properties.size() == 1) {
                data = properties.get(0);
            } else if (properties.size() > 1) {
                data = properties.get(0) + "[该键值存在多个配置文件中!]";
            } else {
                data = "[" + key + "]不存在,使用时可能产生异常,请检查!";
            }
            descriptors.add(new NutzLocalizationFoldingDescriptor(literalExpression.getNode(), textRange, data));
        }
    }
    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 13
Source File: RTRepeatExpression.java    From react-templates-plugin with MIT License 5 votes vote down vote up
public Collection<JSDefinitionExpression> getDefinitions() {
    final PsiElement firstChild = getFirstChild();
    if (firstChild instanceof JSDefinitionExpression) {
        return Collections.singletonList((JSDefinitionExpression) firstChild);
    }
    if (firstChild instanceof JSParenthesizedExpression) {
        final PsiElement commaExpression = PsiTreeUtil.findChildOfType(firstChild, JSCommaExpression.class);
        if (commaExpression != null) {
            return PsiTreeUtil.findChildrenOfType(commaExpression, JSDefinitionExpression.class);
        }
    }
    return Collections.emptyList();
}
 
Example 14
Source File: ANTLRv4FoldingBuilder.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void addActionFoldingDescriptors(List<FoldingDescriptor> descriptors, PsiElement root) {
    for (AtAction atAction : PsiTreeUtil.findChildrenOfType(root, AtAction.class)) {
        PsiElement action = atAction.getLastChild();
        String actionText = action.getText();
        if ( actionText != null && actionText.contains("\n")) {
            descriptors.add(new FoldingDescriptor(atAction, action.getTextRange()));
        }
    }
}
 
Example 15
Source File: PhpFoldingBuilder.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement psiElement, @NotNull Document document, boolean b) {

    if (!Symfony2ProjectComponent.isEnabled(psiElement) || !(psiElement instanceof PhpFile)) {
        return new FoldingDescriptor[0];
    }

    boolean codeFoldingPhpRoute = Settings.getInstance(psiElement.getProject()).codeFoldingPhpRoute;
    boolean codeFoldingPhpModel = Settings.getInstance(psiElement.getProject()).codeFoldingPhpModel;
    boolean codeFoldingPhpTemplate = Settings.getInstance(psiElement.getProject()).codeFoldingPhpTemplate;

    // we dont need to do anything
    if(!codeFoldingPhpRoute && !codeFoldingPhpModel && !codeFoldingPhpTemplate) {
        return new FoldingDescriptor[0];
    }

    List<FoldingDescriptor> descriptors = new ArrayList<>();

    Collection<StringLiteralExpression> stringLiteralExpressiones = PsiTreeUtil.findChildrenOfType(psiElement, StringLiteralExpression.class);
    for(StringLiteralExpression stringLiteralExpression: stringLiteralExpressiones) {

        if(codeFoldingPhpModel) {
            attachModelShortcuts(descriptors, stringLiteralExpression);
        }

        if(codeFoldingPhpTemplate) {
            attachTemplateShortcuts(descriptors, stringLiteralExpression);
        }

    }

    // strip ".[php|html].twig"
    if(codeFoldingPhpRoute) {
        attachRouteShortcuts(descriptors, stringLiteralExpressiones);
    }

    return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
 
Example 16
Source File: RTRepeatExpression.java    From react-templates-plugin with MIT License 5 votes vote down vote up
public Collection<JSDefinitionExpression> getDefinitions() {
    final PsiElement firstChild = getFirstChild();
    if (firstChild instanceof JSDefinitionExpression) {
        return Collections.singletonList((JSDefinitionExpression) firstChild);
    }
    if (firstChild instanceof JSParenthesizedExpression) {
        final PsiElement commaExpression = PsiTreeUtil.findChildOfType(firstChild, JSCommaExpression.class);
        if (commaExpression != null) {
            return PsiTreeUtil.findChildrenOfType(commaExpression, JSDefinitionExpression.class);
        }
    }
    return Collections.emptyList();
}
 
Example 17
Source File: WeavePsiUtils.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
public static List<WeaveNamedElement> findFunctions(@NotNull PsiElement element) {
    final List<WeaveNamedElement> result = new ArrayList<>();
    PsiElement parent = element.getParent();
    while (isNotWeaveFile(parent)) {
        if (parent instanceof WeaveDocument) {
            final Collection<WeaveVariableDefinition> vars = PsiTreeUtil.findChildrenOfType(((WeaveDocument) parent).getHeader(), WeaveVariableDefinition.class);
            final Collection<WeaveFunctionDefinition> functionDirectives = PsiTreeUtil.findChildrenOfType(((WeaveDocument) parent).getHeader(), WeaveFunctionDefinition.class);
            result.addAll(functionDirectives);
            result.addAll(vars.stream().filter(var -> var.getExpression() instanceof WeaveLambdaLiteral).collect(Collectors.toList()));
            break;
        }
        parent = parent.getParent();
    }
    return result;
}
 
Example 18
Source File: ComponentsMethodDeclarationHandlerTest.java    From litho with Apache License 2.0 5 votes vote down vote up
private static PsiIdentifier findIdentifier(PsiElement cls, String name) {
  final Collection<PsiIdentifier> identifiers =
      PsiTreeUtil.findChildrenOfType(cls, PsiIdentifier.class);
  for (PsiIdentifier identifier : identifiers) {
    if (identifier.textMatches(name)) return identifier;
  }
  return null;
}
 
Example 19
Source File: ORSignatureTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings({"SameParameterValue", "ConstantConditions"})
@NotNull
private ORSignature makeSignature(@NotNull Language lang, String sig, boolean debug) {
    PsiFileFactory instance = PsiFileFactory.getInstance(getProject());
    PsiFile psiFile = instance.createFileFromText("Dummy." + lang.getAssociatedFileType().getDefaultExtension(), lang, "let x:" + sig);
    if (debug) {
        System.out.println(DebugUtil.psiToString(psiFile, true, true));
    }
    Collection<PsiSignatureItem> items = PsiTreeUtil.findChildrenOfType(psiFile, PsiSignatureItem.class);
    return new ORSignature(RmlLanguage.INSTANCE, items);
}
 
Example 20
Source File: JsxParsingTest.java    From reasonml-idea-plugin with MIT License 4 votes vote down vote up
public void testIncorrectProp() {
    PsiTag e = (PsiTag) firstElement(parseCode("<MyComp prunningProp prop=1/>"));

    Collection<PsiTagProperty> properties = PsiTreeUtil.findChildrenOfType(e, PsiTagProperty.class);
    assertEquals(2, properties.size());
}