Java Code Examples for com.intellij.psi.PsiFile#getChildren()

The following examples show how to use com.intellij.psi.PsiFile#getChildren() . 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: MuleElementDefinitionService.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
public boolean isMuleSchema(PsiFile file) {
    if (!file.getName().endsWith(".xsd")) {
        return false;
    }
    final PsiElement[] children = file.getChildren();
    if (children.length > 0 && children[0] instanceof XmlDocument) {
        final XmlTag rootTag = ((XmlDocument) children[0]).getRootTag();
        if (rootTag != null) {
            final String xmlns = getNamespace(rootTag);
            if (xmlns != null && xmlns.startsWith("http://www.mulesoft.org/schema/mule/")) {
                return true;
            }
        }
    }

    return false;

}
 
Example 2
Source File: ExtJsUtil.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
/**
 * {namespace name=swag-last-registrations/date}
 */
@Nullable
public static String getSnippetNamespaceFromFile(@NotNull PsiFile psiFile) {
    Pattern pattern = Pattern.compile("\\{namespace[^}]*name\\s*=\\s*['|\"]*([^'\\s\"}]*)['|\"]*\\s*");

    for (PsiElement psiElement : psiFile.getChildren()) {
        if(!(psiElement instanceof PsiComment)) {
            continue;
        }

        String text = psiElement.getText();

        // name="foo", name='foo', name=foo
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            String group = matcher.group(1);
            if(StringUtils.isBlank(group)) {
                return null;
            }

            return group;
        }
    }

    return null;
}
 
Example 3
Source File: IncludesProcessor.java    From JHelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void processFile(PsiFile file) {
	if (processedFiles.contains(file)) {
		return;
	}
	processedFiles.add(file);
	for (PsiElement element : file.getChildren()) {
		if (element instanceof OCIncludeDirective) {
			OCIncludeDirective include = (OCIncludeDirective) element;
			if (isInternalInclude(include)) {
				processFile(include.getIncludedFile());
			}
			else {
				processAngleBracketsInclude(include);
			}
			continue;
		}
		if (element instanceof OCPragma) {
			OCPragma pragma = (OCPragma) element;
			if (pragma.getContent(true).first.equals("once")) {
				continue;
			}
		}
		result.append(element.getText());
	}
}
 
Example 4
Source File: ScenarioExecutionProducer.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
private int getScenarioIdentifier(ConfigurationContext context, PsiFile file) {
    int count = NO_SCENARIOS;
    PsiElement selectedElement = context.getPsiLocation();
    if (selectedElement == null) return NON_SCENARIO_CONTEXT;
    String scenarioHeading = (!selectedElement.getClass().equals(SpecScenarioImpl.class)) ? getScenarioHeading(selectedElement) : selectedElement.getText();
    if (scenarioHeading.equals(""))
        return getNumberOfScenarios(file) == 0 ? NO_SCENARIOS : NON_SCENARIO_CONTEXT;
    for (PsiElement psiElement : file.getChildren()) {
        if (psiElement.getClass().equals(SpecScenarioImpl.class)) {
            count++;
            if (psiElement.getNode().getFirstChildNode().getText().equals(scenarioHeading)) {
                return StringUtil.offsetToLineNumber(psiElement.getContainingFile().getText(), psiElement.getTextOffset()) + 1;
            }
        }
    }
    return count == NO_SCENARIOS ? NO_SCENARIOS : NON_SCENARIO_CONTEXT;
}
 
Example 5
Source File: GLSLFileTreeElement.java    From glsl4idea with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void createChildren(@NotNull PsiFile file) {
    PsiElement[] baseNodes = file.getChildren();
    for (PsiElement baseNode : baseNodes) {
        if (baseNode instanceof GLSLVariableDeclaration) {
            final GLSLVariableDeclaration declaration = (GLSLVariableDeclaration) baseNode;
            final GLSLTypeSpecifier typeSpecifier = declaration.getTypeSpecifierNode();

            if (typeSpecifier != null) {
                final GLSLStructDefinition typedef = typeSpecifier.getEmbeddedStructDefinition();
                if (typedef != null) {
                    addChild(new GLSLStructTreeElement(typedef));
                }
            }

            for (GLSLDeclarator declarator : declaration.getDeclarators()) {
                addChild(new GLSLDeclaratorTreeElement(declarator));
            }
        } else if (baseNode instanceof GLSLFunctionDeclaration) {
            addChild(new GLSLFunctionTreeElement((GLSLFunctionDeclaration) baseNode));
        }
    }
}
 
Example 6
Source File: MicroProfileHealthDiagnosticsParticipant.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<Diagnostic> collectDiagnostics(JavaDiagnosticsContext context) {
	PsiFile typeRoot = context.getTypeRoot();
	PsiElement[] elements = typeRoot.getChildren();
	List<Diagnostic> diagnostics = new ArrayList<>();
	collectDiagnostics(elements, diagnostics, context);
	return diagnostics;
}
 
Example 7
Source File: MicroProfileRestClientDiagnosticsParticipant.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<Diagnostic> collectDiagnostics(JavaDiagnosticsContext context) {
	PsiFile typeRoot = context.getTypeRoot();
	PsiElement[] elements = typeRoot.getChildren();
	List<Diagnostic> diagnostics = new ArrayList<>();
	collectDiagnostics(elements, diagnostics, context);
	return diagnostics;
}
 
Example 8
Source File: ComponentsMethodDeclarationHandlerTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Nullable
private PsiClass findClass(String name, PsiFile file) {
  for (PsiElement element : file.getChildren()) {
    if (element instanceof PsiClass && name.equals(((PsiClass) element).getName())) {
      return (PsiClass) element;
    }
  }
  return null;
}
 
Example 9
Source File: LetParsingTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testLetBindingWithJsx() {
    PsiFile file = parseCode("let make = p => { render: x => { <div/>; } }");
    PsiElement[] children = file.getChildren();
    PsiElement element = PsiTreeUtil.nextLeaf(children[1]);

    assertNull(element);
    assertSize(1, expressions(file));
}
 
Example 10
Source File: ExtraModulesUtil.java    From weex-language-support with MIT License 5 votes vote down vote up
private static List<PsiFile> getComponents(PsiDirectory root, PsiFile file) {
    List<PsiFile> results = new ArrayList<PsiFile>();
    if (file != null && file instanceof JSFile) {
        for (PsiElement element : file.getChildren()) {
            if (element instanceof JSExpressionStatement) {
                JSExpression expression = ((JSExpressionStatement) element).getExpression();
                if (expression instanceof JSCallExpression
                        && ((JSCallExpression) expression).getArguments().length == 1
                        && ((JSCallExpression) expression).getArguments()[0] instanceof JSLiteralExpression) {
                    JSLiteralExpression expression1 = (JSLiteralExpression) ((JSCallExpression) expression).getArguments()[0];
                    Object val = expression1.getValue();
                    if (val != null) {
                        String[] temp = val.toString().replace("./", "").split("/");
                        if (temp != null && temp.length > 0) {
                            String fileName = temp[temp.length - 1];
                            if (fileName.toLowerCase().endsWith(".we")) {
                                PsiDirectory start = root;
                                for (int i = 0; i < temp.length - 1; i++) {
                                    PsiDirectory dir = start.findSubdirectory(temp[i]);
                                    if (dir != null) {
                                        start = dir;
                                    }
                                }
                                PsiFile weexScript = start.findFile(temp[temp.length - 1]);
                                if (weexScript != null) {
                                    results.add(weexScript);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return results;
}
 
Example 11
Source File: ScenarioExecutionProducer.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
private int getNumberOfScenarios(PsiFile file) {
    int count = 0;
    for (PsiElement psiElement : file.getChildren())
        if (psiElement.getClass().equals(SpecScenarioImpl.class))
            count++;
    return count;
}
 
Example 12
Source File: MethodObjectTest.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
private void runCheckOnFunFunctionContainsEnclosingClassAccess(@NotNull String classFileName) {
    myFixture.setTestDataPath("./src/test/resources/testdata/");
    myFixture.configureByFile(PATH_TO_TEST_DATA + classFileName);

    class Visitor extends PsiRecursiveElementVisitor {
        private List<PsiMethod> psiMethods = new ArrayList<>();

        @Override
        public void visitElement(PsiElement element) {

            if (element instanceof PsiMethod) {
                psiMethods.add((PsiMethod) element);
            }

            super.visitElement(element);
        }

        private List<PsiMethod> getPsiMethods() {
            return psiMethods;
        }
    }

    Visitor visitor = new Visitor();

    Project project = myFixture.getProject();

    PsiFile psiFile = FilenameIndex.getFilesByName(project, classFileName, GlobalSearchScope.allScope(project))[0];

    for (int i = 0; i < psiFile.getChildren().length; i++) {
        PsiElement psiElement = psiFile.getChildren()[i];
        visitor.visitElement(psiElement);
    }

    PsiMethod psiMethod = null;

    for (int i = 0; i < visitor.getPsiMethods().size(); i++) {
        PsiMethod psiMethod1 = visitor.getPsiMethods().get(i);
        if (psiMethod1.getName().equals("fun")) {
            psiMethod = psiMethod1;
        }
    }

    final ConstructorObject constructorObject = new ConstructorObject();
    constructorObject.setMethodDeclaration(psiMethod);
    constructorObject.setName(psiMethod.getName());
    constructorObject.setClassName(psiMethod.getContainingClass().getName());
    int methodDeclarationStartPosition = psiMethod.getStartOffsetInParent();
    int methodDeclarationEndPosition = methodDeclarationStartPosition + psiMethod.getTextLength();
    constructorObject.setAccess(Access.PUBLIC);

    constructorObject.setMethodBody(new MethodBodyObject(psiMethod.getBody()));

    MethodObject methodObject = new MethodObject(psiMethod, constructorObject);

    if (methodObject.containsFieldAccessOfEnclosingClass()) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}
 
Example 13
Source File: JsonnetCompletionContributor.java    From intellij-jsonnet with Apache License 2.0 4 votes vote down vote up
private static JsonnetObjinside[] resolveExpr0ToObj(JsonnetExpr0 expr0, List<JsonnetExpr> visited) {
    if (expr0.getIfelse() != null) {
        JsonnetIfelse ifelse = expr0.getIfelse();

        ArrayList<JsonnetObjinside> output = new ArrayList<>();
        JsonnetObjinside[] lhsRes = resolveExprToObj(ifelse.getExprList().get(1), visited);
        if (lhsRes != null) {
            output.addAll(Arrays.asList(lhsRes));
        }
        if (ifelse.getExprList().size() == 3) {
            JsonnetObjinside[] rhsRes = resolveExprToObj(ifelse.getExprList().get(2), visited);
            if (rhsRes != null) {
                output.addAll(Arrays.asList(rhsRes));
            }

        }

        return output.toArray(new JsonnetObjinside[0]);
    }
    if (expr0.getExpr() != null) {
        return resolveExprToObj(expr0.getExpr(), visited);
    }
    if (expr0.getOuterlocal() != null) {
        return resolveExprToObj(expr0.getOuterlocal().getExpr(), visited);
    }
    if (expr0.getObj() != null && expr0.getObj().getObjinside() != null) {
        return new JsonnetObjinside[]{expr0.getObj().getObjinside()};
    }
    if (expr0.getText().equals("self")) {
        return new JsonnetObjinside[]{findSelfObject(expr0)};
    }
    if (expr0.getText().equals("$")) {
        return new JsonnetObjinside[]{findOuterObject(expr0)};
    }
    if (expr0.getImportop() != null) {
        JsonnetImportop importop = expr0.getImportop();
        if (importop.getReference() == null) {
            return null;
        }
        PsiFile file = (PsiFile) importop.getReference().resolve();
        if (file == null) { // The imported file does not exist
            return null;
        }

        for (PsiElement c : file.getChildren()) {
            // Apparently children can be line comments and other unwanted rubbish
            if (c instanceof JsonnetExpr) {
                JsonnetObjinside[] res = resolveExprToObj((JsonnetExpr) c, visited);
                if (res != null) return res;
            }
        }
    }
    if (expr0.getIdentifier0() != null) {
        return resolveIdentifierToObj(expr0.getIdentifier0(), visited);
    }

    return null;
}
 
Example 14
Source File: MuleElementDefinitionService.java    From mule-intellij-plugins with Apache License 2.0 4 votes vote down vote up
@NotNull
    private List<MuleModuleDefinition> getModuleDefinitions(Project project, GlobalSearchScope searchScope) {
        final List<MuleModuleDefinition> result = new ArrayList<>();
        final Collection<VirtualFile> files = FileTypeIndex.getFiles(XmlFileType.INSTANCE, searchScope);
        for (VirtualFile file : files) {
            final PsiFile xmlFile = PsiManager.getInstance(project).findFile(file);
            if (xmlFile != null && isMuleSchema(xmlFile)) {
//                System.out.println("xmlFile = " + xmlFile.getName());
                final PsiElement[] children = xmlFile.getChildren();
                final XmlTag rootTag = ((XmlDocument) children[0]).getRootTag();
                if (rootTag != null) {
                    final String namespace = getNamespace(rootTag);
                    final String name = ArrayUtil.getLastElement(namespace.split("/"));
//                    System.out.println("namespace = " + namespace);
//                    System.out.println("name = " + name);
                    final XmlTag[] elements = rootTag.findSubTags("element", MuleSchemaUtils.HTTP_WWW_W3_ORG_2001_XMLSCHEMA);
                    final List<MuleElementDefinition> definitions = new ArrayList<>();
                    for (XmlTag element : elements) {
                        final String elementName = element.getAttributeValue("name");
//                        System.out.println("name = " + elementName);
                        final MuleElementType muleElementType = MuleSchemaUtils.getMuleElementTypeFromElement(element);
                        if (muleElementType != null) {
                            String description = "";
                            final XmlTag annotation = ArrayUtil.getFirstElement(element.findSubTags("annotation", MuleSchemaUtils.HTTP_WWW_W3_ORG_2001_XMLSCHEMA));
                            if (annotation != null) {
                                final XmlTag documentation = ArrayUtil.getFirstElement(annotation.findSubTags("documentation", MuleSchemaUtils.HTTP_WWW_W3_ORG_2001_XMLSCHEMA));
                                if (documentation != null) {
                                    description = documentation.getValue().getText();
                                }
                            }
                            definitions.add(new MuleElementDefinition(element, elementName, description, muleElementType));
//                            System.out.println("muleElementType = " + muleElementType);
//                            System.out.println("description = " + description);
                        }
                    }
                    result.add(new MuleModuleDefinition(name, StringUtil.capitalize(name), namespace, xmlFile, definitions));
                }
            }
        }
        return result;
    }
 
Example 15
Source File: HaxeImportOptimizer.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
private static void reorderImports(final PsiFile file) {
  HaxeFileModel fileModel = HaxeFileModel.fromElement(file);
  List<HaxeImportStatement> allImports = fileModel.getImportStatements();

  if (allImports.size() < 2) {
    return;
  }

  final HaxeImportStatement firstImport = allImports.get(0);
  int startOffset = firstImport.getStartOffsetInParent();
  final HaxeImportStatement lastImport = allImports.get(allImports.size() - 1);
  int endOffset = lastImport.getStartOffsetInParent() + lastImport.getText().length();

  // We assume the common practice of placing all imports in a single "block" at the top of a file. If there is something else (comments,
  // code, etc) there we just stop reordering to prevent data loss.
  for (PsiElement child : file.getChildren()) {
    int childOffset = child.getStartOffsetInParent();
    if (childOffset >= startOffset && childOffset <= endOffset
        && !(child instanceof HaxeImportStatement)
        && !(child instanceof PsiWhiteSpace)) {
      return;
    }
  }

  List<String> sortedImports = new ArrayList<>();

  for (HaxeImportStatement currentImport : allImports) {
    sortedImports.add(currentImport.getText());
  }

  sortedImports.sort(String::compareToIgnoreCase);

  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(file.getProject());
  final Document document = psiDocumentManager.getDocument(file);
  if (document != null) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());

    /* This operation trims the document if necessary (e.g. it happens with "\n" at the very beginning).
       Need to reevaluate offsets here.
     */
    documentManager.doPostponedOperationsAndUnblockDocument(document);

    // Reevaluating offset values according to the previous comment.
    startOffset = firstImport.getStartOffsetInParent();
    endOffset = lastImport.getStartOffsetInParent() + lastImport.getText().length();

    document.deleteString(startOffset, endOffset);

    StringBuilder sortedImportsText = new StringBuilder();
    for (String sortedImport : sortedImports) {
      sortedImportsText.append(sortedImport);
      sortedImportsText.append("\n");
    }
    // Removes last "\n".
    CharSequence sortedImportsTextTrimmed = sortedImportsText.subSequence(0, sortedImportsText.length() - 1);

    documentManager.doPostponedOperationsAndUnblockDocument(document);
    document.insertString(startOffset, sortedImportsTextTrimmed);
  }

  // TODO Reorder usings.
}
 
Example 16
Source File: MakefileLanguage.java    From CppTools with Apache License 2.0 4 votes vote down vote up
@Nullable
public StructureViewBuilder getStructureViewBuilder(final PsiFile psiFile) {
  return new TreeBasedStructureViewBuilder() {
    @NotNull
    @Override
    public StructureViewModel createStructureViewModel(@Nullable Editor editor) {
      return createStructureViewModel(); // todo, new api Idea 14.1
    }

    @NotNull
    public StructureViewModel createStructureViewModel() {
      return new TextEditorBasedStructureViewModel(psiFile) {
        protected PsiFile getPsiFile()   // TODO: change abstract method to constructor parameter?
        {
          return psiFile;
        }

        @NotNull
        public StructureViewTreeElement getRoot() {
          return new PsiTreeElementBase<PsiElement>(psiFile) {
            @NotNull
            public Collection<StructureViewTreeElement> getChildrenBase() {
              final List<StructureViewTreeElement> children = new ArrayList<StructureViewTreeElement>();
              for(PsiElement el:psiFile.getChildren()) {
                final ASTNode node = el.getNode();

                if(node.getElementType() == MakefileTokenTypes.STATEMENT) {
                  for(final ASTNode el2:node.getChildren(null)) {
                    if (el2.getElementType() == MakefileTokenTypes.TARGET_IDENTIFIER) {
                      children.add(new PsiTreeElementBase(el2.getPsi()) {
                        public void navigate(boolean b) {
                          final Navigatable descriptor = EditSourceUtil.getDescriptor(el2.getPsi());
                          if (descriptor != null) descriptor.navigate(b);
                        }

                        public boolean canNavigate() {
                          return true;
                        }

                        public boolean canNavigateToSource() {
                          return canNavigate();
                        }

                        public Collection getChildrenBase() {
                          return Collections.emptyList();
                        }

                        public String getPresentableText() {
                          return el2.getText();
                        }
                      });
                    }
                  }
                }
              }
              return children;
            }

            public String getPresentableText() {
              return "root";
            }
          };
        }

        @NotNull
        public Grouper[] getGroupers() {
          return new Grouper[0];
        }

        @NotNull
        public Sorter[] getSorters() {
          return new Sorter[] {Sorter.ALPHA_SORTER};
        }

        @NotNull
        public Filter[] getFilters() {
          return new Filter[0];
        }

        @NotNull
        protected Class[] getSuitableClasses()
        {
          return new Class[0];
        }
      };
    }
  };
}