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

The following examples show how to use com.intellij.psi.PsiElement#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: 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 2
Source File: Trees.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Find smallest subtree of t enclosing range startCharIndex..stopCharIndex
 *  inclusively using postorder traversal.  Recursive depth-first-search.
 */
public static PsiElement getRootOfSubtreeEnclosingRegion(PsiElement t,
                                                         int startCharIndex, // inclusive
                                                         int stopCharIndex)  // inclusive
{
	for (PsiElement c : t.getChildren()) {
		PsiElement sub = getRootOfSubtreeEnclosingRegion(c, startCharIndex, stopCharIndex);
		if ( sub!=null ) return sub;
	}
	IElementType elementType = t.getNode().getElementType();
	if ( elementType instanceof RuleIElementType ) {
		TextRange r = t.getNode().getTextRange();
		// is range fully contained in t?  Note: jetbrains uses exclusive right end (use < not <=)
		if ( startCharIndex>=r.getStartOffset() && stopCharIndex<r.getEndOffset() ) {
			return t;
		}
	}
	return null;
}
 
Example 3
Source File: CSharpClassesMoveProcessor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
private static void processDirectoryFiles(List<PsiFile> movedFiles, Map<PsiElement, PsiElement> oldToNewMap, PsiElement psiElement)
{
	if(psiElement instanceof PsiFile)
	{
		final PsiFile movedFile = (PsiFile) psiElement;
		MoveFileHandler.forElement(movedFile).prepareMovedFile(movedFile, movedFile.getParent(), oldToNewMap);
		movedFiles.add(movedFile);
	}
	else if(psiElement instanceof PsiDirectory)
	{
		for(PsiElement element : psiElement.getChildren())
		{
			processDirectoryFiles(movedFiles, oldToNewMap, element);
		}
	}
}
 
Example 4
Source File: XPathTokenElement.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Collection<PsiElement> evaluate(PsiElement t) {
	// return all children of t that match nodeName
	List<PsiElement> nodes = new ArrayList<>();
	for (PsiElement c : t.getChildren()) {
		IElementType elementType = c.getNode().getElementType();
		if ( elementType instanceof TokenIElementType) {
			TokenIElementType tokEl = (TokenIElementType) elementType;
			if ( (tokEl.getANTLRTokenType()==tokenType && !invert) ||
				 (tokEl.getANTLRTokenType()!=tokenType && invert) )
			{
				nodes.add(c);
			}
		}
	}
	return nodes;
}
 
Example 5
Source File: XPathRuleElement.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Collection<PsiElement> evaluate(PsiElement t) {
	// return all children of t that match ANTLR rule index
	List<PsiElement> nodes = new ArrayList<>();
	for (PsiElement c : t.getChildren()) {
		IElementType elementType = c.getNode().getElementType();
		if ( elementType instanceof RuleIElementType) {
			RuleIElementType ruleEl = (RuleIElementType)elementType;
			if ( (ruleEl.getRuleIndex() == ruleIndex && !invert) ||
				 (ruleEl.getRuleIndex() != ruleIndex && invert) )
			{
				nodes.add(c);
			}
		}
	}
	return nodes;
}
 
Example 6
Source File: WeexAnnotator.java    From weex-language-support with MIT License 6 votes vote down vote up
private void checkStructure(PsiElement document, @NotNull AnnotationHolder annotationHolder) {
    PsiElement[] children = document.getChildren();
    List<String> acceptedTag = Arrays.asList("template","element","script", "style");
    for (PsiElement element : children) {
        if (element instanceof HtmlTag) {
            if (!acceptedTag.contains(((HtmlTag) element).getName().toLowerCase())) {
                annotationHolder.createErrorAnnotation(element, "Invalid tag '"
                        + ((HtmlTag) element).getName() + "', only the [template, element, script, style] tags are allowed here.");
            }
            checkAttributes((XmlTag) element, annotationHolder);
        } else {
            if (!(element instanceof PsiWhiteSpace)
                    && !(element instanceof XmlProlog)
                    && !(element instanceof XmlText)
                    && !(element instanceof XmlComment)) {
                String s = element.getText();
                if (s.length() > 20) {
                    s = s.substring(0, 20);
                }
                annotationHolder.createErrorAnnotation(element, "Invalid content '" + s +
                        "', only the [template, script, style] tags are allowed here.");
            }
        }
    }
}
 
Example 7
Source File: EelHelperUtil.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
public static HashMap<String, String> getHelpersInFile(@NotNull PsiFile psiFile) {
    YAMLKeyValue defaultContext = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, "Neos", "Fusion", "defaultContext");

    if (defaultContext == null) {
        defaultContext = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, "TYPO3", "TypoScript", "defaultContext");
    }

    HashMap<String, String> result = new HashMap<>();
    if (defaultContext != null) {
        PsiElement mapping = defaultContext.getLastChild();
        if (mapping instanceof YAMLMapping) {
            for (PsiElement mappingElement : mapping.getChildren()) {
                if (mappingElement instanceof YAMLKeyValue) {
                    YAMLKeyValue keyValue = (YAMLKeyValue) mappingElement;
                    result.put(keyValue.getKeyText(), keyValue.getValueText());
                    NeosProjectService.getLogger().debug(keyValue.getKeyText() + ": " + keyValue.getValueText());
                }
            }
        }
    }

    return result;
}
 
Example 8
Source File: PsiPhpHelper.java    From yiistorm with MIT License 6 votes vote down vote up
public static String getExtendsClassName(PsiElement child) {
    PsiElement psiClass = getClassElement(child);
    if (psiClass != null) {
        PsiElement[] children = psiClass.getChildren();
        for (PsiElement psiClassChild : children) {
            if (isElementType(psiClassChild, EXTENDS_LIST)) {
                PsiElement[] extendsElements = psiClassChild.getChildren();
                for (PsiElement extendsElement : extendsElements) {
                    if (isElementType(extendsElement, CLASS_REFERENCE)) {
                        return extendsElement.getText();

                    }
                }
                break;
            }
        }
    }
    return null;
}
 
Example 9
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 10
Source File: BuckPsiUtils.java    From Buck-IntelliJ-Plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Find the first child with a specific type
 */
public static PsiElement findChildWithType(@NotNull PsiElement element, IElementType type) {
  PsiElement[] children = element.getChildren();
  for (PsiElement child : children) {
    if (child.getNode().getElementType() == type) {
      return child;
    }
  }
  return null;
}
 
Example 11
Source File: XPathWildcardElement.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Collection<PsiElement> evaluate(final PsiElement t) {
	if ( invert ) return new ArrayList<>(); // !* is weird but valid (empty)
	List<PsiElement> kids = new ArrayList<PsiElement>();
	for (PsiElement c : t.getChildren()) {
		kids.add(c);
	}
	return kids;
}
 
Example 12
Source File: NewArrayValueLookupElement.java    From yiistorm with MIT License 5 votes vote down vote up
public void insertIntoArrayConfig(String string, String openFilePath) {

        String relpath = openFilePath.replace(project.getBasePath(), "").substring(1).replace("\\", "/");
        VirtualFile vf = project.getBaseDir().findFileByRelativePath(relpath);

        if (vf == null) {
            return;
        }
        PsiFile pf = PsiManager.getInstance(project).findFile(vf);

        String lineSeparator = " " + ProjectCodeStyleSettingsManager.getSettings(project).getLineSeparator();
        if (vf != null) {

            PsiElement groupStatement = pf.getFirstChild();
            if (groupStatement != null) {
                PsiDocumentManager.getInstance(project).commitDocument(pf.getViewProvider().getDocument());

                pf.getManager().reloadFromDisk(pf);
                for (PsiElement pl : groupStatement.getChildren()) {
                    if (pl.toString().equals("Return")) {
                        PsiElement[] pl2 = pl.getChildren();
                        if (pl2.length > 0 && pl2[0].toString().equals("Array creation expression")) {
                            ArrayCreationExpressionImpl ar = (ArrayCreationExpressionImpl) pl2[0];

                            ArrayHashElement p = (ArrayHashElement) PhpPsiElementFactory.createFromText(project,
                                    PhpElementTypes.HASH_ARRAY_ELEMENT,
                                    "array('" + string + "'=>'')");
                            PsiElement closingBrace = ar.getLastChild();
                            String preLast = closingBrace.getPrevSibling().toString();
                            if (!preLast.equals("Comma")) {
                                pf.getViewProvider().getDocument().insertString(
                                        closingBrace.getTextOffset(), "," + lineSeparator + p.getText());
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
 
Example 13
Source File: PsiUtil.java    From arma-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * Get children of the given PsiElement that extend/are type of the given class
 *
 * @param element  element to get children of
 * @param psiClass class
 * @return list of all children
 */
@NotNull
public static <T extends PsiElement> List<T> findChildrenOfType(@NotNull PsiElement element, @NotNull Class<T> psiClass) {
	List<T> list = new ArrayList<T>();
	PsiElement[] children = element.getChildren();
	for (PsiElement child : children) {
		if (psiClass.isInstance(child)) {
			list.add((T) child);
		}
	}
	return list;
}
 
Example 14
Source File: SimpleDuplicatesFinder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void findPatternOccurrences(@Nonnull final List<SimpleMatch> array, @Nonnull final PsiElement scope,
                                    @Nonnull final PsiElement generatedMethod) {
  if (scope == generatedMethod) return;
  final PsiElement[] children = scope.getChildren();
  for (PsiElement child : children) {
    final SimpleMatch match = isDuplicateFragment(child);
    if (match != null) {
      array.add(match);
      continue;
    }
    findPatternOccurrences(array, child, generatedMethod);
  }
}
 
Example 15
Source File: ThinrDetector.java    From thinr with Apache License 2.0 5 votes vote down vote up
private void markLeakSuspects(PsiElement element, PsiElement lambdaBody, @NonNull final JavaContext context) {
    if (element instanceof PsiReferenceExpression) {
        PsiReferenceExpression ref = (PsiReferenceExpression) element;

        if (ref.getQualifierExpression() == null) {

            PsiElement res = ref.resolve();
            if (!(res instanceof PsiParameter)) {
                if (!(res instanceof PsiClass)) {

                    boolean error = false;
                    if (res instanceof PsiLocalVariable) {
                        PsiLocalVariable lVar = (PsiLocalVariable) res;
                        if (!isParent(lambdaBody, lVar.getParent())) {
                            error = true;
                        }
                    }

                    if (res instanceof PsiField) {
                        PsiField field = (PsiField) res;
                        final PsiModifierList modifierList = field.getModifierList();
                        if (modifierList == null) {
                            error = true;
                        } else if (!modifierList.hasExplicitModifier(PsiModifier.STATIC)) {
                            error = true;
                        }
                    }

                    if (error) {
                        context.report(ISSUE, element, context.getNameLocation(element), "Possible leak");
                    }
                }
            }
        }
    }

    for (PsiElement psiElement : element.getChildren()) {
        markLeakSuspects(psiElement, lambdaBody, context);
    }
}
 
Example 16
Source File: WeexAnnotator.java    From weex-language-support with MIT License 5 votes vote down vote up
private
@NotNull
LintResult verifyFunction(String s) {

    s = CodeUtil.getFunctionNameFromMustache(s);

    LintResult result = new LintResult();

    if (moduleExports == null) {
        result.setCode(LintResultType.UNRESOLVED_VAR);
        result.setDesc("Unresolved function '" + s + "'");
        return result;
    }
    JSProperty data = moduleExports.findProperty("methods");

    if (data == null || data.getValue() == null) {
        result.setCode(LintResultType.UNRESOLVED_VAR);
        result.setDesc("Unresolved function '" + s + "'");
        return result;
    }

    for (PsiElement e : data.getValue().getChildren()) {
        if (e instanceof JSProperty) {
            for (PsiElement e1 : e.getChildren()) {
                if (e1 instanceof JSFunctionExpression) {
                    if (s.equals(((JSFunctionExpression) e1).getName())) {
                        result.setCode(LintResultType.PASSED);
                        result.setDesc("Lint passed");
                        return result;
                    }
                }
            }
        }
    }

    result.setCode(LintResultType.UNRESOLVED_VAR);
    result.setDesc("Unresolved function '" + s + "'");
    return result;
}
 
Example 17
Source File: MyPsiUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static PsiElement[] collectChildrenWithText(PsiElement root, final String text) {
	List<PsiElement> elems = new ArrayList<PsiElement>();
	for (PsiElement child : root.getChildren()) {
		if ( child.getText().equals(text) ) {
			elems.add(child);
		}
	}
	return elems.toArray(new PsiElement[elems.size()]);
}
 
Example 18
Source File: MyPsiUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static PsiElement findChildOfType(PsiElement root, final IElementType tokenType) {
	List<PsiElement> elems = new ArrayList<PsiElement>();
	for (PsiElement child : root.getChildren()) {
		if ( child.getNode().getElementType() == tokenType ) {
			return child;
		}
	}
	return null;
}
 
Example 19
Source File: MoveFilesOrDirectoriesProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void encodeDirectoryFiles(PsiElement psiElement) {
  if (psiElement instanceof PsiFile) {
    FileReferenceContextUtil.encodeFileReferences(psiElement);
  }
  else if (psiElement instanceof PsiDirectory) {
    for (PsiElement element : psiElement.getChildren()) {
      encodeDirectoryFiles(element);
    }
  }
}
 
Example 20
Source File: PsiPhpHelper.java    From yiistorm with MIT License 5 votes vote down vote up
@NotNull
public static List<PsiNamedElement> getAllMethodsFromClass(@NotNull PsiElement psiClass, boolean includeInherited) {
    List<PsiNamedElement> methods = new ArrayList<PsiNamedElement>();
    PsiElement[] children = psiClass.getChildren();   // getFullListOfChildren

    PsiElement extendsList = null;

    for (PsiElement child : children) {
        if (isClassMethod(child)) {
            methods.add((PsiNamedElement) child);
        } else if (includeInherited && isElementType(child, EXTENDS_LIST)) {
            extendsList = child;
        }
    }

    // postponed read of inherited methods so the original methos are first on the list
    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) {
                    methods.addAll(getAllMethodsFromClass(parentClass, true));
                }
                break;
            }
        }
    }

    return methods;
}