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

The following examples show how to use com.intellij.psi.PsiFile#acceptChildren() . 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: IgnoreRelativeEntryInspection.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * Checks if entries are relative.
 *
 * @param file       current working file yo check
 * @param manager    {@link InspectionManager} to ask for {@link ProblemDescriptor}'s from
 * @param isOnTheFly true if called during on the fly editor highlighting. Called from Inspect Code action
 *                   otherwise
 * @return <code>null</code> if no problems found or not applicable at file level
 */
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file,
                                     @NotNull InspectionManager manager, boolean isOnTheFly) {
    if (!(file instanceof IgnoreFile)) {
        return null;
    }

    final ProblemsHolder problemsHolder = new ProblemsHolder(manager, file, isOnTheFly);

    file.acceptChildren(new IgnoreVisitor() {
        @Override
        public void visitEntry(@NotNull IgnoreEntry entry) {
            String path = entry.getText().replaceAll("\\\\(.)", "$1");
            if (path.contains("./")) {
                problemsHolder.registerProblem(entry, IgnoreBundle.message("codeInspection.relativeEntry.message"),
                        new IgnoreRelativeEntryFix(entry));
            }
            super.visitEntry(entry);
        }
    });

    return problemsHolder.getResultsArray();
}
 
Example 2
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 3
Source File: BladeExtendsStubIndex.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {
    return fileContent -> {
        Map<String, Void> map = new THashMap<>();
        PsiFile psiFile = fileContent.getPsiFile();

        if(!(psiFile instanceof BladeFileImpl)) {
            return map;
        }

        psiFile.acceptChildren(new BladeDirectivePsiElementWalkingVisitor(BladeTokenTypes.EXTENDS_DIRECTIVE, map));

        return map;
    };
}
 
Example 4
Source File: CodeGenerationUtils.java    From JHelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void removeUnusedCode(PsiFile file) {
	while (true) {
		Collection<PsiElement> toDelete = new ArrayList<>();
		Project project = file.getProject();
		SearchScope scope = GlobalSearchScope.fileScope(project, file.getVirtualFile());
		file.acceptChildren(new DeletionMarkingVisitor(toDelete, scope));
		if (toDelete.isEmpty()) {
			break;
		}
		WriteCommandAction.writeCommandAction(project).run(
				() -> {
					for (PsiElement element : toDelete) {
						element.delete();
					}
				}
		);

	}
}
 
Example 5
Source File: ConfigKeyStubIndex.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {
    return fileContent -> {
        final Map<String, Void> map = new THashMap<>();

        PsiFile psiFile = fileContent.getPsiFile();
        if(!(psiFile instanceof PhpFile)) {
            return map;
        }

        ConfigFileUtil.ConfigFileMatchResult result = ConfigFileUtil.matchConfigFile(fileContent.getProject(), fileContent.getFile());

        // config/app.php
        // config/testing/app.php
        if(result.matches()) {
            psiFile.acceptChildren(new ArrayReturnPsiRecursiveVisitor(result.getKeyPrefix(), (key, psiKey, isRootElement) -> {
                if (!isRootElement) {
                    map.put(key, null);
                }
            }));
        }

        return map;
    };
}
 
Example 6
Source File: ShopwareSubscriperMethodInspection.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
    PsiFile psiFile = holder.getFile();

    if(!ShopwareProjectComponent.isValidForProject(psiFile)) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    String name = psiFile.getName();

    if(name.contains("Bootstrap")) {
        psiFile.acceptChildren(new MyBootstrapRecursiveElementWalkingVisitor(holder));
        return super.buildVisitor(holder, isOnTheFly);
    }

    return new MySubscriberRecursiveElementWalkingVisitor(holder);
}
 
Example 7
Source File: TaggedExtendsInterfaceClassInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
    if(!Symfony2ProjectComponent.isEnabled(holder.getProject())) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    return new PsiElementVisitor() {
        @Override
        public void visitFile(PsiFile psiFile) {
            if(psiFile instanceof YAMLFile) {
                psiFile.acceptChildren(new YmlClassElementWalkingVisitor(holder, new ContainerCollectionResolver.LazyServiceCollector(holder.getProject())));
            } else if(psiFile instanceof XmlFile) {
                psiFile.acceptChildren(new XmlClassElementWalkingVisitor(holder, new ContainerCollectionResolver.LazyServiceCollector(holder.getProject())));
            }
        }
    };
}
 
Example 8
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 9
Source File: DockerComposeYamlVariablesProvider.java    From idea-php-dotenv-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<KeyValuePsiElement> getElements(PsiFile psiFile) {

    if(psiFile instanceof YAMLFile) {
        DockerComposeYamlPsiElementsVisitor visitor = new DockerComposeYamlPsiElementsVisitor();
        psiFile.acceptChildren(visitor);

        return visitor.getCollectedItems();
    }

    return Collections.emptyList();
}
 
Example 10
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 11
Source File: ClassToUtilConverter.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
public void convertToUtilPattern(PsiFile file)
{
    // steps:
    // get the return declare statement
    // get all of the literal expressions

    file.acceptChildren(getVisitorToConvertToUtilPattern());
}
 
Example 12
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 13
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 14
Source File: DuplicateKeyInspection.java    From idea-php-dotenv-plugin with MIT License 5 votes vote down vote up
@NotNull
private ProblemsHolder analyzeFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    DotEnvPsiElementsVisitor visitor = new DotEnvPsiElementsVisitor();
    file.acceptChildren(visitor);

    ProblemsHolder problemsHolder = new ProblemsHolder(manager, file, isOnTheFly);

    Map<String, PsiElement> existingKeys = new HashMap<>();
    Set<PsiElement> markedElements = new HashSet<>();
    for(KeyValuePsiElement keyValue : visitor.getCollectedItems()) {
        final String key = keyValue.getKey();

        if(existingKeys.containsKey(key)) {
            problemsHolder.registerProblem(keyValue.getElement(), "Duplicate key");

            PsiElement markedElement = existingKeys.get(key);
            if(!markedElements.contains(markedElement)) {
                problemsHolder.registerProblem(markedElement, "Duplicate key");
                markedElements.add(markedElement);
            }
        } else {
            existingKeys.put(key, keyValue.getElement());
        }
    }

    return problemsHolder;
}
 
Example 15
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 16
Source File: GoEnvironmentVariablesUsagesProvider.java    From idea-php-dotenv-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<KeyUsagePsiElement> getUsages(PsiFile psiFile) {
    if(psiFile instanceof GoFile) {
        GoEnvironmentCallsVisitor visitor = new GoEnvironmentCallsVisitor();
        psiFile.acceptChildren(visitor);

        return visitor.getCollectedItems();
    }

    return Collections.emptyList();
}
 
Example 17
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]);
}
 
Example 18
Source File: RoutingUtil.java    From idea-php-laravel-plugin with MIT License 4 votes vote down vote up
public static void visitRoutesForAs(@NotNull PsiFile psiFile, @NotNull RouteAsNameVisitor visitor) {
    psiFile.acceptChildren(new RouteNamePsiRecursiveElementVisitor(visitor));
}
 
Example 19
Source File: BladeTemplateUtil.java    From idea-php-laravel-plugin with MIT License 4 votes vote down vote up
public static void visitYield(@NotNull PsiFile psiFile, DirectiveParameterVisitor visitor) {
    psiFile.acceptChildren(new DirectivePsiRecursiveElementWalkingVisitor(visitor, BladeTokenTypes.YIELD_DIRECTIVE));
}
 
Example 20
Source File: BladeTemplateUtil.java    From idea-php-laravel-plugin with MIT License 4 votes vote down vote up
private static void visitSectionOrYield(@NotNull final PsiFile psiFile, final DirectiveParameterVisitor visitor, @NotNull BladeDirectiveElementType... elementTypes) {
    psiFile.acceptChildren(new DirectivePsiRecursiveElementWalkingVisitor(visitor, elementTypes));
}