下面列出了com.intellij.psi.PsiElement#getChildren ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** 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;
}
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;
}
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.");
}
}
}
}
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;
}
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;
}
@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;
}
@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;
}
@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;
}
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);
}
}
}
@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;
}
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);
}
}
}
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;
}
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()]);
}
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;
}
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);
}
}
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);
}
}
/**
* 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;
}
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;
}
}
}
}
}
@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;
}
/**
* 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;
}