com.intellij.psi.PsiRecursiveElementWalkingVisitor Java Examples

The following examples show how to use com.intellij.psi.PsiRecursiveElementWalkingVisitor. 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: BladePsiElementFactory.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
@Nullable
public static <T extends PsiElement> T createFromText(@NotNull Project p, final Class<T> aClass, String text) {
    final PsiElement[] ret = new PsiElement[]{null};

    createDummyFile(p, text).accept(new PsiRecursiveElementWalkingVisitor() {
        public void visitElement(PsiElement element) {
            if(ret[0] == null && aClass.isInstance(element)) {
                ret[0] = element;
            }

            super.visitElement(element);
        }
    });

    return (T) ret[0];
}
 
Example #2
Source File: BladePsiElementFactory.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
@Nullable
public static <T extends PsiElement> T createFromText(@NotNull Project p, @NotNull final IElementType elementType, @NotNull String text) {
    final PsiElement[] ret = new PsiElement[]{null};

    createDummyFile(p, text).accept(new PsiRecursiveElementWalkingVisitor() {
        public void visitElement(PsiElement element) {
            if(ret[0] == null && element.getNode().getElementType() == elementType) {
                ret[0] = element;
            }

            super.visitElement(element);
        }
    });

    return (T) ret[0];
}
 
Example #3
Source File: SmartyBlockGoToHandler.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
public static List<PsiElement> getBlockPsiElement(PsiFile psiFile, final String blockName) {
    final List<PsiElement> psiElements = new ArrayList<>();

    psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {

            if(SmartyPattern.getBlockPattern().accepts(element)) {
                String text = element.getText();
                if(blockName.equalsIgnoreCase(text)) {
                    psiElements.add(element);
                }

            }

            super.visitElement(element);
        }
    });

    return psiElements;
}
 
Example #4
Source File: SmartyTemplateLineMarkerProvider.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private static List<PsiElement> getIncludePsiElement(PsiFile psiFile, final String templateName) {
    final List<PsiElement> psiElements = new ArrayList<>();

    psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {

            if(SmartyPattern.getFileIncludePattern().accepts(element)) {
                String text = element.getText();
                if(templateName.equalsIgnoreCase(text)) {
                    psiElements.add(element);
                }

            }

            super.visitElement(element);
        }
    });

    return psiElements;
}
 
Example #5
Source File: Unity3dAssetUtil.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredReadAction
public static CSharpTypeDeclaration findPrimaryType(@Nonnull PsiFile file)
{
	Ref<CSharpTypeDeclaration> typeRef = Ref.create();
	file.accept(new PsiRecursiveElementWalkingVisitor()
	{
		@Override
		public void visitElement(PsiElement element)
		{
			if(element instanceof CSharpTypeDeclaration)
			{
				typeRef.set((CSharpTypeDeclaration) element);
				stopWalking();
			}
			super.visitElement(element);
		}
	});
	return typeRef.get();
}
 
Example #6
Source File: ModifierNotAllowedInspection.java    From intellij-latte with MIT License 6 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LatteMacroTag) {
				checkClassicMacro((LatteMacroTag) element, problems, manager, isOnTheFly);

			} else {
				super.visitElement(element);
			}
		}
	});
	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #7
Source File: YamlPsiElementFactory.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
public static <T extends PsiElement> T createFromText(@NotNull Project p, final Class<T> aClass, String text) {
    final PsiElement[] ret = new PsiElement[]{null};

    createDummyFile(p, text).accept(new PsiRecursiveElementWalkingVisitor() {
        public void visitElement(PsiElement element) {
            if(ret[0] == null && aClass.isInstance(element)) {
                ret[0] = element;
            }

            super.visitElement(element);
        }
    });

    return (T) ret[0];
}
 
Example #8
Source File: ModifierDefinitionInspection.java    From intellij-latte with MIT License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LatteMacroModifier) {
				String filterName = ((LatteMacroModifier) element).getModifierName();
				LatteFilterSettings latteFilter = LatteConfiguration.getInstance(element.getProject()).getFilter(filterName);
				if (latteFilter == null) {
					LocalQuickFix addModifierFix = IntentionManager.getInstance().convertToFix(new AddCustomLatteModifier(filterName));
					ProblemHighlightType type = ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
					String description = "Undefined latte filter '" + filterName + "'";
					ProblemDescriptor problem = manager.createProblemDescriptor(element, description, true, type, isOnTheFly, addModifierFix);
					problems.add(problem);
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #9
Source File: ControllerMethodInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void visitXml(final ProblemsHolder holder, PsiFile psiFile) {
    psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {
            if(XmlHelper.getRouteControllerPattern().accepts(element)) {
                String text = PsiElementUtils.trimQuote(element.getText());
                if(StringUtils.isNotBlank(text)) {
                    InspectionUtil.inspectController(element, text, holder, new XmlLazyRouteName(element));
                }
            }

            super.visitElement(element);
        }
    });
}
 
Example #10
Source File: ControllerMethodInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void visitYaml(final ProblemsHolder holder, PsiFile psiFile) {
    psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {
            if(YamlElementPatternHelper.getSingleLineScalarKey("_controller", "controller").accepts(element)) {
                String text = PsiElementUtils.trimQuote(element.getText());
                if(StringUtils.isNotBlank(text)) {
                    InspectionUtil.inspectController(element, text, holder, new YamlLazyRouteName(element));
                }
            }

            super.visitElement(element);
        }
    });
}
 
Example #11
Source File: EventMethodCallInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void visitYamlFile(PsiFile psiFile, final ProblemsHolder holder, @NotNull final ContainerCollectionResolver.LazyServiceCollector lazyServiceCollector) {

        psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                annotateCallMethod(element, holder, lazyServiceCollector);
                super.visitElement(element);
            }
        });

    }
 
Example #12
Source File: EventMethodCallInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void visitXmlFile(@NotNull PsiFile psiFile, @NotNull final ProblemsHolder holder, @NotNull final ContainerCollectionResolver.LazyServiceCollector lazyServiceCollector) {

        psiFile.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
            @Override
            public void visitElement(PsiElement element) {

                if(XmlHelper.getTagAttributePattern("tag", "method").inside(XmlHelper.getInsideTagPattern("services")).inFile(XmlHelper.getXmlFilePattern()).accepts(element) ||
                   XmlHelper.getTagAttributePattern("call", "method").inside(XmlHelper.getInsideTagPattern("services")).inFile(XmlHelper.getXmlFilePattern()).accepts(element)
                  )
                {

                    // attach to text child only
                    PsiElement[] psiElements = element.getChildren();
                    if(psiElements.length < 2) {
                        return;
                    }

                    String serviceClassValue = XmlHelper.getServiceDefinitionClass(element);
                    if(serviceClassValue != null && StringUtils.isNotBlank(serviceClassValue)) {
                        registerMethodProblem(psiElements[1], holder, serviceClassValue, lazyServiceCollector);
                    }

                }

                super.visitElement(element);
            }
        });

    }
 
Example #13
Source File: PhpElementsUtil.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
/**
 * Find a string return value of a method context "function() { return 'foo'}"
 * First match wins
 */
@Nullable
static public String getMethodReturnAsString(@NotNull Method method) {

    final Set<String> values = new HashSet<>();
    method.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {

            if(PhpElementsUtil.getMethodReturnPattern().accepts(element)) {
                String value = PhpElementsUtil.getStringValue(element);
                if(value != null && StringUtils.isNotBlank(value)) {
                    values.add(value);
                }
            }

            super.visitElement(element);
        }
    });

    if(values.size() == 0) {
        return null;
    }

    // we support only first item
    return values.iterator().next();
}
 
Example #14
Source File: ModifierNotAllowedInspection.java    From intellij-latte with MIT License 5 votes vote down vote up
private static void checkClassicMacro(
		LatteMacroTag macroTag,
		@NotNull List<ProblemDescriptor> problems,
		@NotNull final InspectionManager manager,
		final boolean isOnTheFly
) {
	String name = macroTag.getMacroName();
	LatteTagSettings macro = LatteConfiguration.getInstance(macroTag.getProject()).getTag(name);
	if (macro == null || macro.isAllowedModifiers()) {
		return;
	}

	LatteMacroContent content = macroTag.getMacroContent();
	if (content == null) {
		return;
	}

	content.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LatteMacroModifier && !((LatteMacroModifier) element).isVariableModifier()) {
				String description = "Modifiers are not allowed here";
				ProblemDescriptor problem = manager.createProblemDescriptor(element, description, true, ProblemHighlightType.GENERIC_ERROR, isOnTheFly);
				problems.add(problem);

			} else {
				super.visitElement(element);
			}
		}
	});
}
 
Example #15
Source File: DeprecatedTagInspection.java    From intellij-latte with MIT License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}
	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LatteMacroTag) {
				String macroName = ((LatteMacroTag) element).getMacroName();
				LatteTagSettings macro = LatteConfiguration.getInstance(element.getProject()).getTag(macroName);
				if (macro != null && macro.isDeprecated()) {
					String description = macro.getDeprecatedMessage() != null && macro.getDeprecatedMessage().length() > 0
							? macro.getDeprecatedMessage()
							: "Tag {" + macroName + "} is deprecated";
					ProblemDescriptor problem = manager.createProblemDescriptor(element, description, true, ProblemHighlightType.LIKE_DEPRECATED, isOnTheFly);
					problems.add(problem);

				}
			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #16
Source File: PhpElementsUtil.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
/**
 * Find a string return value of a method context "function() { return 'foo'}"
 * First match wins
 */
@Nullable
static public String getMethodReturnAsString(@NotNull Method method) {

    final Set<String> values = new HashSet<>();
    method.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {

            if(PhpElementsUtil.getMethodReturnPattern().accepts(element)) {
                String value = PhpElementsUtil.getStringValue(element);
                if(value != null && StringUtils.isNotBlank(value)) {
                    values.add(value);
                }
            }

            super.visitElement(element);
        }
    });

    if(values.size() == 0) {
        return null;
    }

    // we support only first item
    return values.iterator().next();
}
 
Example #17
Source File: MethodUsagesInspection.java    From intellij-latte with MIT License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LattePhpMethod) {
				if (((LattePhpMethod) element).isFunction()) {
					processFunction((LattePhpMethod) element, problems, manager, isOnTheFly);

				} else {
					processMethod((LattePhpMethod) element, problems, manager, isOnTheFly);
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #18
Source File: PhpElementsUtil.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
/**
 * Find a string return value of a method context "function() { return 'foo'}"
 * First match wins
 */
@Nullable
static public String getMethodReturnAsString(@NotNull PhpClass phpClass, @NotNull String methodName) {

    Method method = phpClass.findMethodByName(methodName);
    if(method == null) {
        return null;
    }

    final Set<String> values = new HashSet<>();
    method.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {

            if(PhpElementsUtil.getMethodReturnPattern().accepts(element)) {
                String value = PhpElementsUtil.getStringValue(element);
                if(value != null && StringUtils.isNotBlank(value)) {
                    values.add(value);
                }
            }

            super.visitElement(element);
        }
    });

    if(values.size() == 0) {
        return null;
    }

    // we support only first item
    return values.iterator().next();
}
 
Example #19
Source File: LatteIterableTypeInspection.java    From intellij-latte with MIT License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof BaseLattePhpElement) {
				if (!LattePhpVariableUtil.isNextDefinitionOperator(element)) {
					for (LattePhpArrayUsage usage : ((BaseLattePhpElement) element).getPhpArrayUsageList()) {
						if (usage.getPhpArrayContent().getFirstChild() == null) {
							addError(manager, problems, usage, "Can not use [] for reading", isOnTheFly);
						}
					}
				}

			} else if (element instanceof LattePhpForeach) {
				LattePhpType type = ((LattePhpForeach) element).getPhpExpression().getPhpType();
				if (!type.isMixed() && !type.isIterable(element.getProject())) {
					addProblem(
							manager,
							problems,
							((LattePhpForeach) element).getPhpExpression(),
							"Invalid argument supplied to 'foreach'. Expected types: 'array' or 'object', '" + type.toString() + "' provided.",
							isOnTheFly
					);
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #20
Source File: ClassUsagesInspection.java    From intellij-latte with MIT License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LattePhpClassReference) {
				String className = ((LattePhpClassReference) element).getClassName();
				Collection<PhpClass> classes = LattePhpUtil.getClassesByFQN(element.getProject(), className);
				if (classes.size() == 0) {
					addError(manager, problems, element, "Undefined class '" + className + "'", isOnTheFly);

				} else {
					for (PhpClass phpClass : classes) {
						if (phpClass.isDeprecated()) {
							addDeprecated(manager, problems, element, "Used class '" + className + "' is marked as deprecated", isOnTheFly);
							break;

						} else if (phpClass.isInternal()) {
							addDeprecated(manager, problems, element, "Used class '" + className + "' is marked as internal", isOnTheFly);
							break;
						}
					}
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #21
Source File: CreateMethodQuickFix.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
private void buildEventVariables(@NotNull final Project project, final StringBuilder stringBuilder, Method classMethod) {
    classMethod.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(PsiElement element) {
            if ((element instanceof StringLiteralExpression) && ((StringLiteralExpression) element).getContents().equals(generatorContainer.getHookName())) {
                PsiElement parent = element.getParent();
                if(parent instanceof ParameterList) {
                    PsiElement[] parameterList = ((ParameterList) parent).getParameters();
                    if(parameterList.length > 1) {
                        if(parameterList[1] instanceof ArrayCreationExpression) {
                            Map<String, PsiElement> eventParameters = PhpElementsUtil.getArrayCreationKeyMap((ArrayCreationExpression) parameterList[1]);
                            for(Map.Entry<String, PsiElement> entrySet : eventParameters.entrySet()) {
                                stringBuilder.append("\n");
                                PhpPsiElement psiElement = PhpElementsUtil.getArrayValue((ArrayCreationExpression) parameterList[1], entrySet.getKey());
                                if(psiElement instanceof PhpTypedElement) {

                                    Set<String> classes = new HashSet<>();

                                    PhpType type = ((PhpTypedElement) psiElement).getType();
                                    for (PhpClass aClass : PhpElementsUtil.getClassFromPhpTypeSet(project, type.getTypes())) {
                                        // force absolute namespace
                                        classes.add("\\" + StringUtils.stripStart(aClass.getPresentableFQN(), "\\"));
                                    }

                                    if(classes.size() > 0) {
                                        stringBuilder.append("/** @var ").append(StringUtils.join(classes, "|")).append("$").append(entrySet.getKey()).append(" */\n");
                                    }
                                }
                                stringBuilder.append("$").append(entrySet.getKey()).append(" = ").append("$args->get('").append(entrySet.getKey()).append("');\n");
                            }
                        }
                    }
                }
            }
            super.visitElement(element);
        }
    });
}
 
Example #22
Source File: ScanSourceCommentsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void scanCommentsInFile(Project project, final VirtualFile vFile) {
  if (!vFile.isDirectory() && vFile.getFileType() instanceof LanguageFileType) {
    PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
    if (psiFile == null) return;

    for (PsiFile root : psiFile.getViewProvider().getAllFiles()) {
      root.accept(new PsiRecursiveElementWalkingVisitor() {
        @Override
        public void visitComment(PsiComment comment) {
          commentFound(vFile, comment.getText());
        }
      });
    }
  }
}
 
Example #23
Source File: SimpleDuplicatesFinder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void deannotatePattern() {
  for (final PsiElement patternComponent : myPattern) {
    patternComponent.accept(new PsiRecursiveElementWalkingVisitor() {
      @Override public void visitElement(PsiElement element) {
        if (element.getUserData(PARAMETER) != null) {
          element.putUserData(PARAMETER, null);
        }
      }
    });
  }
}
 
Example #24
Source File: SimpleDuplicatesFinder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void annotatePattern() {
  for (final PsiElement patternComponent : myPattern) {
    patternComponent.accept(new PsiRecursiveElementWalkingVisitor() {
      @Override
      public void visitElement(PsiElement element) {
        super.visitElement(element);
        if (myParameters.contains(element.getText())) {
          element.putUserData(PARAMETER, element);
        }

      }
    });
  }
}
 
Example #25
Source File: StaticPropertyUsagesInspection.java    From intellij-latte with MIT License 4 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LattePhpStaticVariable) {
				LattePhpType phpType = ((LattePhpStaticVariable) element).getPhpType();

				Collection<PhpClass> phpClasses = phpType.getPhpClasses(element.getProject());
				if (phpClasses == null) {
					return;
				}

				boolean isFound = false;
				String variableName = ((LattePhpStaticVariable) element).getVariableName();
				for (PhpClass phpClass : phpClasses) {
					for (Field field : phpClass.getFields()) {
						if (!field.isConstant() && field.getName().equals(variableName)) {
							PhpModifier modifier = field.getModifier();
							if (modifier.isPrivate()) {
								addProblem(manager, problems, element, "Used private static property '" + variableName + "'", isOnTheFly);
							} else if (modifier.isProtected()) {
								addProblem(manager, problems, element, "Used protected static property '" + variableName + "'", isOnTheFly);
							} else if (field.isDeprecated()) {
								addDeprecated(manager, problems, element, "Used static property '" + variableName + "' is marked as deprecated", isOnTheFly);
							} else if (field.isInternal()) {
								addDeprecated(manager, problems, element, "Used static property '" + variableName + "' is marked as internal", isOnTheFly);
							}

							if (!modifier.isStatic()) {
								String description = "Property '" + variableName + "' is not static but used statically";
								addProblem(manager, problems, element, description, isOnTheFly);

							}
							isFound = true;
						}
					}
				}

				if (!isFound) {
					addProblem(manager, problems, element, "Property '" + variableName + "' not found for type '" + phpType.toString() + "'", isOnTheFly);
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #26
Source File: TwigBlockIndexExtension.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Set<String>, FileContent> getIndexer() {
    return fileContent -> {
        Map<String, Set<String>> blocks = new HashMap<>();

        PsiFile psiFile = fileContent.getPsiFile();
        if(psiFile instanceof TwigFile) {
            for (TwigBlock twigBlock : TwigUtil.getBlocksInFile((TwigFile) psiFile)) {
                // we only index file scope
                // {% embed 'foo.html.twig' %}{% block foo %}{% endembed %}
                PsiElement embedStatement = PsiElementUtils.getParentOfType(twigBlock.getTarget(), TwigElementTypes.EMBED_STATEMENT);
                if(embedStatement == null) {
                    blocks.putIfAbsent("block", new HashSet<>());
                    blocks.get("block").add(twigBlock.getName());
                }
            }

            for(PsiElement psiElement : PsiTreeUtil.getChildrenOfAnyType(psiFile, TwigExtendsTag.class, TwigCompositeElement.class)) {
                if(psiElement instanceof TwigCompositeElement) {
                    // {% use 'foo.html.twig' %}
                    if(psiElement.getNode().getElementType() == TwigElementTypes.TAG) {
                        psiElement.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
                            @Override
                            public void visitElement(PsiElement element) {
                                if(TwigPattern.getTwigTagUseNamePattern().accepts(element) && PsiElementUtils.getParentOfType(element, TwigElementTypes.EMBED_STATEMENT) == null) {
                                    String templateName = TwigUtil.normalizeTemplateName(PsiElementUtils.trimQuote(element.getText()));
                                    if(StringUtils.isNotBlank(templateName)) {
                                        blocks.putIfAbsent("use", new HashSet<>());
                                        blocks.get("use").add(templateName);
                                    }
                                }

                                super.visitElement(element);
                            }
                        });
                    }
                }
            }
        }

        return blocks;
    };
}
 
Example #27
Source File: MsilElementWrapper.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
@RequiredUIAccess
public void navigate(boolean requestFocus)
{
	final Class<? extends PsiElement> navigationElementClass = getNavigationElementClass();

	Consumer<PsiFile> consumer = navigationElementClass == null ? MsilRepresentationNavigateUtil.DEFAULT_NAVIGATOR : new Consumer<PsiFile>()
	{
		@Override
		public void consume(PsiFile file)
		{
			final Ref<Navigatable> navigatableRef = Ref.create();
			file.accept(new PsiRecursiveElementWalkingVisitor()
			{
				@Override
				@RequiredReadAction
				public void visitElement(PsiElement element)
				{
					MsilElementWrapper<T> msilWrapper = MsilElementWrapper.this;
					if(navigationElementClass.isAssignableFrom(element.getClass()) && isEquivalentTo(element, msilWrapper))
					{
						PsiElement elementParent = element.getParent();
						PsiElement wrapperParent = msilWrapper.getParent();
						// check if parent type is equal to self type
						if(elementParent instanceof CSharpTypeDeclaration && wrapperParent instanceof CSharpTypeDeclaration)
						{
							if(!CSharpElementCompareUtil.isEqual(elementParent, wrapperParent, myOriginal))
							{
								return;
							}
						}
						navigatableRef.set((Navigatable) element);
						stopWalking();
						return;
					}
					super.visitElement(element);
				}
			});

			Navigatable navigatable = navigatableRef.get();
			if(navigatable != null)
			{
				navigatable.navigate(true);
			}

			file.navigate(true);
		}
	};

	MsilRepresentationNavigateUtil.navigateToRepresentation(myOriginal, CSharpFileType.INSTANCE, consumer);
}
 
Example #28
Source File: ArrayReturnSourceContributor.java    From idea-php-toolbox with MIT License 4 votes vote down vote up
private void visitReturnElements(@NotNull Project project, @NotNull String className, @NotNull String methodName, @NotNull final ReturnVisitor visitor) {

        for (PhpClass phpClass : PhpIndex.getInstance(project).getAllSubclasses(className)) {

            final Method method = phpClass.findOwnMethodByName(methodName);
            if(method == null) {
                continue;
            }

            method.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
                @Override
                public void visitElement(PsiElement element) {

                    if(!(element instanceof PhpReturn)) {
                        super.visitElement(element);
                        return;
                    }

                    PsiElement firstChild = ((PhpReturn) element).getFirstPsiChild();
                    if(!(firstChild instanceof ArrayCreationExpression)) {
                        return;
                    }

                    for (PsiElement arrayValue : firstChild.getChildren()) {

                        if(arrayValue.getNode().getElementType() != PhpElementTypes.ARRAY_VALUE) {
                            continue;
                        }

                        PsiElement stringLiteral = arrayValue.getFirstChild();
                        if(!(stringLiteral instanceof StringLiteralExpression)) {
                            continue;
                        }

                        String contents = ((StringLiteralExpression) stringLiteral).getContents();
                        if(StringUtils.isNotBlank(contents)) {
                            visitor.visit(method, (StringLiteralExpression) stringLiteral, contents);
                        }

                    }

                    super.visitElement(element);
                }
            });

        }
    }
 
Example #29
Source File: PropertyUsagesInspection.java    From intellij-latte with MIT License 4 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LattePhpProperty) {
				LattePhpType phpType = ((LattePhpProperty) element).getPhpType();

				Collection<PhpClass> phpClasses = phpType.getPhpClasses(element.getProject());
				if (phpClasses == null) {
					return;
				}

				boolean isFound = false;
				String variableName = ((LattePhpProperty) element).getPropertyName();
				for (PhpClass phpClass : phpClasses) {
					for (Field field : phpClass.getFields()) {
						if (!field.isConstant() && field.getName().equals(LattePhpUtil.normalizePhpVariable(variableName))) {
							PhpModifier modifier = field.getModifier();
							if (modifier.isPrivate()) {
								addProblem(manager, problems, element, "Used private property '" + variableName + "'", isOnTheFly);
							} else if (modifier.isProtected()) {
								addProblem(manager, problems, element, "Used protected property '" + variableName + "'", isOnTheFly);
							} else if (field.isDeprecated()) {
								addDeprecated(manager, problems, element, "Used property '" + variableName + "' is marked as deprecated", isOnTheFly);
							} else if (field.isInternal()) {
								addDeprecated(manager, problems, element, "Used property '" + variableName + "' is marked as internal", isOnTheFly);
							}

							if (modifier.isStatic()) {
								String description = "Property '" + variableName + "' is static but used non statically";
								addProblem(manager, problems, element, description, isOnTheFly);

							}
							isFound = true;
						}
					}
				}

				if (!isFound) {
					addProblem(manager, problems, element, "Property '" + variableName + "' not found for type '" + phpType.toString() + "'", isOnTheFly);
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}
 
Example #30
Source File: ConstantUsagesInspection.java    From intellij-latte with MIT License 4 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
	if (!(file instanceof LatteFile)) {
		return null;
	}

	final List<ProblemDescriptor> problems = new ArrayList<>();
	file.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
		@Override
		public void visitElement(PsiElement element) {
			if (element instanceof LattePhpConstant) {
				LattePhpType phpType = ((LattePhpConstant) element).getPhpType();

				Collection<PhpClass> phpClasses = phpType.getPhpClasses(element.getProject());
				if (phpClasses == null) {
					return;
				}

				boolean isFound = false;
				String constantName = ((LattePhpConstant) element).getConstantName();
				for (PhpClass phpClass : phpClasses) {
					for (Field field : phpClass.getFields()) {
						if (field.isConstant() && field.getName().equals(constantName)) {
							PhpModifier modifier = field.getModifier();
							if (modifier.isPrivate()) {
								addProblem(manager, problems, element, "Used private constant '" + constantName + "'", isOnTheFly);
							} else if (modifier.isProtected()) {
								addProblem(manager, problems, element, "Used protected constant '" + constantName + "'", isOnTheFly);
							} else if (field.isDeprecated()) {
								addDeprecated(manager, problems, element, "Used constant '" + constantName + "' is marked as deprecated", isOnTheFly);
							} else if (field.isInternal()) {
								addDeprecated(manager, problems, element, "Used constant '" + constantName + "' is marked as internal", isOnTheFly);
							}
							isFound = true;
						}
					}
				}

				if (!isFound) {
					addProblem(manager, problems, element, "Constant '" + constantName + "' not found for type '" + phpType.toString() + "'", isOnTheFly);
				}

			} else {
				super.visitElement(element);
			}
		}
	});

	return problems.toArray(new ProblemDescriptor[0]);
}