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

The following examples show how to use com.intellij.psi.PsiFile#accept() . These examples are extracted from open source projects. 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
@NotNull
@Override
public DataIndexer<String, TemplateAnnotationUsage, FileContent> getIndexer() {
    return inputData -> {
        final Map<String, TemplateAnnotationUsage> map = new HashMap<>();

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

        if (!AnnotationUtil.isValidForIndex(inputData)) {
            return map;
        }

        psiFile.accept(new MyPsiRecursiveElementWalkingVisitor(map));

        return map;
    };
}
 
Example 2
private void collectServices(Project project) {
    FileBasedIndex index = FileBasedIndex.getInstance();
    Collection<VirtualFile> containingFiles = index.getContainingFiles(
            FileTypeIndex.NAME,
            PhpFileType.INSTANCE,
            GlobalSearchScope.allScope(project)
    );
    containingFiles.removeIf(virtualFile -> !(virtualFile.getName().contains("ext_localconf.php")));

    for (VirtualFile projectFile : containingFiles) {
        PsiFile psiFile = PsiManager.getInstance(project).findFile(projectFile);
        if (psiFile != null) {
            CoreServiceDefinitionParserVisitor visitor = new CoreServiceDefinitionParserVisitor(serviceMap);
            psiFile.accept(visitor);

            serviceMap.putAll(visitor.getServiceMap());
        }
    }
}
 
Example 3
@NotNull
@Override
public DataIndexer<String, String, FileContent> getIndexer() {
    return inputData -> {
        final Map<String, String> map = new THashMap<>();

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

        if(!IndexUtil.isValidForIndex(inputData, psiFile)) {
            return map;
        }

        psiFile.accept(new MyPsiRecursiveElementWalkingVisitor(map));

        return map;
    };
}
 
Example 4
Source Project: intellij-swagger   File: SpecIndexer.java    License: MIT License 6 votes vote down vote up
private Set<String> getReferencedFilesJson(final PsiFile file, final VirtualFile specDirectory) {
  final Set<String> result = new HashSet<>();

  file.accept(
      new JsonRecursiveElementVisitor() {
        @Override
        public void visitProperty(@NotNull JsonProperty property) {
          if (ApiConstants.REF_KEY.equals(property.getName()) && property.getValue() != null) {
            final String refValue = StringUtils.removeAllQuotes(property.getValue().getText());

            if (SwaggerFilesUtils.isFileReference(refValue)) {
              getReferencedFileIndexValue(property.getValue(), refValue, specDirectory)
                  .ifPresent(result::add);
            }
          }
          super.visitProperty(property);
        }
      });

  return result;
}
 
Example 5
Source Project: intellij-swagger   File: SpecIndexer.java    License: MIT License 6 votes vote down vote up
private Set<String> getReferencedFilesYaml(final PsiFile file, final VirtualFile specDirectory) {
  final Set<String> result = new HashSet<>();

  file.accept(
      new YamlRecursivePsiElementVisitor() {
        @Override
        public void visitKeyValue(@NotNull YAMLKeyValue yamlKeyValue) {
          if (ApiConstants.REF_KEY.equals(yamlKeyValue.getKeyText())
              && yamlKeyValue.getValue() != null) {
            final String refValue = StringUtils.removeAllQuotes(yamlKeyValue.getValueText());

            if (SwaggerFilesUtils.isFileReference(refValue)) {
              getReferencedFileIndexValue(yamlKeyValue.getValue(), refValue, specDirectory)
                  .ifPresent(result::add);
            }
          }
          super.visitKeyValue(yamlKeyValue);
        }
      });

  return result;
}
 
Example 6
@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 7
@NotNull
@Override
public DataIndexer<String, DispatcherEvent, FileContent> getIndexer() {
    return inputData -> {
        Map<String, DispatcherEvent> map = new HashMap<>();

        PsiFile psiFile = inputData.getPsiFile();
        if(!Symfony2ProjectComponent.isEnabledForIndex(psiFile.getProject())) {
            return map;
        }

        psiFile.accept(new MyPsiRecursiveElementWalkingVisitor(map));

        return map;
    };

}
 
Example 8
@NotNull
@Override
public DataIndexer<String, Set<String>, FileContent> getIndexer() {
    return inputData -> {
        final Map<String, Set<String>> map = new THashMap<>();

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

        if(!AnnotationUtil.isValidForIndex(inputData)) {
            return map;
        }

        psiFile.accept(new PhpDocTagAnnotationRecursiveElementWalkingVisitor(pair -> {
            map.put(pair.getFirst(), new HashSet<>());
            return true;
        }));

        return map;
    };
}
 
Example 9
/**
 * Find all annotation usages for given class name
 *
 * Doctrine\ORM\Mapping\Entity => ORM\Entity(), Entity()
 *
 * @param project current Project
 * @param fqnClassName Foobar\ClassName
 * @return targets
 */
public static Collection<PhpDocTag> getImplementationsForAnnotation(@NotNull Project project, @NotNull String fqnClassName) {
    Collection<PhpDocTag> psiElements = new HashSet<>();

    for (PsiFile psiFile : getFilesImplementingAnnotation(project, fqnClassName)) {
        psiFile.accept(new PhpDocTagAnnotationRecursiveElementWalkingVisitor(pair -> {
            if(StringUtils.stripStart(pair.getFirst(), "\\").equalsIgnoreCase(StringUtils.stripStart(fqnClassName, "\\"))) {
                psiElements.add(pair.getSecond());
            }

            return true;
        }));
    }

    return psiElements;
}
 
Example 10
private void maybeRecomputeEventClasses() {
  List<VirtualFile> myFilesToScan;
  synchronized (filesToScan) {
    if (filesToScan.isEmpty()) return;

    myFilesToScan = new ArrayList<VirtualFile>(filesToScan);
    filesToScan.clear();
  }

  for (VirtualFile virtualFile : myFilesToScan) {
    synchronized (fileToEventClasses) {
      getEventClasses(virtualFile).clear();
    }
    PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile);
    if (psiFile == null) throw new IllegalStateException("huh? " + virtualFile);
    if (psiFile.getFileType() instanceof JavaFileType) {

      final long startTime = System.currentTimeMillis();
      psiFile.accept(new PsiRecursiveElementVisitor() {
        @Override public void visitElement(PsiElement element) {
          if (element instanceof PsiMethod
              && SubscriberMetadata.isAnnotatedWithSubscriber((PsiMethod) element)) {
            maybeAddSubscriberMethod((PsiMethod) element);
          } else {
            super.visitElement(element);
          }
        }
      });
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Searched for @Subscribe in %s in %dms",
            virtualFile, System.currentTimeMillis() - startTime));
      }
    }
  }

  optimizeEventClassIndex();
}
 
Example 11
Source Project: buck   File: DependenciesOptimizer.java    License: Apache License 2.0 5 votes vote down vote up
private void optimizeDeps(@NotNull PsiFile file) {
  final PropertyVisitor visitor = new PropertyVisitor();
  file.accept(
      new BuckVisitor() {
        @Override
        public void visitElement(PsiElement node) {
          node.acceptChildren(this);
          node.accept(visitor);
        }
      });

  // Commit modifications.
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
  manager.doPostponedOperationsAndUnblockDocument(manager.getDocument(file));
}
 
Example 12
@NotNull
@Override
public Collection<FluidNamespace> provideForElement(@NotNull PsiElement element) {
    List<FluidNamespace> namespaces = new ArrayList<>();

    Project project = element.getProject();
    for (PsiFile psiFile : FilenameIndex.getFilesByName(project, "ext_localconf.php", GlobalSearchScope.allScope(project))) {
        GlobalsNamespaceVisitor visitor = new GlobalsNamespaceVisitor();
        psiFile.accept(visitor);

        namespaces.addAll(visitor.namespaces);
    }

    return namespaces;
}
 
Example 13
private Map<String, FluidVariable> collectInlineViewHelperSetVariables(@NotNull PsiElement psiElement) {
    if (!containsLanguage(FluidLanguage.INSTANCE, psiElement)) {
        return new THashMap<>();
    }

    PsiFile psi = extractLanguagePsiForElement(FluidLanguage.INSTANCE, psiElement);
    if (psi == null) {
        return new THashMap<>();
    }

    InlineFVariableVisitor visitor = new InlineFVariableVisitor();
    psi.accept(visitor);

    return visitor.variables;
}
 
Example 14
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 15
public void testOneQueryWithError() {
    parametersService.registerParametersProvider(emptyParametersProvider);
    PsiFile psiFile = myFixture.configureByText("test.cyp", "MATCH () ETURN n;");
    psiFile.accept(statementCollector);

    verify(eventMock, times(0)).handleError(any(), any());

    assertThat(statementCollector.hasErrors())
        .isTrue();
    assertThat(statementCollector.getParameters())
        .isEmpty();
    assertThat(statementCollector.getQueries())
        .isEmpty();
}
 
Example 16
public void testMultipleCorrectQueriesInDifferentLinesWithParameters() {
    parametersService.registerParametersProvider(validParametersProvider);
    PsiFile psiFile = myFixture.configureByText("test.cyp", "CREATE (n {name: $name});\nMATCH (m) RETURN m;");
    psiFile.accept(statementCollector);

    verify(eventMock, times(0)).handleError(any(), any());

    assertThat(statementCollector.hasErrors())
        .isFalse();
    assertThat(statementCollector.getParameters())
        .containsValues("Andrew");
    assertThat(statementCollector.getQueries())
        .containsExactly("CREATE (n {name: $name});", "MATCH (m) RETURN m;");
}
 
Example 17
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
  final boolean isNmml = FileUtilRt.extensionEquals(file.getName(), NMMLFileType.DEFAULT_EXTENSION);
  if (!isNmml || !(file instanceof XmlFile)) {
    return ProblemDescriptor.EMPTY_ARRAY;
  }
  MyVisitor visitor = new MyVisitor();
  file.accept(visitor);

  if (ContainerUtil.exists(visitor.getResult(), new Condition<XmlTag>() {
    @Override
    public boolean value(XmlTag tag) {
      final XmlAttribute ifAttribute = tag.getAttribute("if");
      return "debug".equals(ifAttribute != null ? ifAttribute.getValue() : null);
    }
  })) {
    // all good
    return ProblemDescriptor.EMPTY_ARRAY;
  }

  final XmlTag lastTag = ContainerUtil.iterateAndGetLastItem(visitor.getResult());

  if (lastTag == null) {
    return ProblemDescriptor.EMPTY_ARRAY;
  }

  final ProblemDescriptor descriptor = manager.createProblemDescriptor(
    lastTag,
    HaxeBundle.message("haxe.inspections.nme.build.directory.descriptor"),
    new AddTagFix(),
    ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
    isOnTheFly
  );

  return new ProblemDescriptor[]{descriptor};
}
 
Example 18
public static void optimzeDeps(@NotNull PsiFile file) {
  final PropertyVisitor visitor = new PropertyVisitor();
  file.accept(new BuckVisitor() {
    @Override
    public void visitElement(PsiElement node) {
      node.acceptChildren(this);
      node.accept(visitor);
    }
  });

  // Commit modifications
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
  manager.doPostponedOperationsAndUnblockDocument(manager.getDocument(file));
}
 
Example 19
Source Project: needsmoredojo   File: DefineResolver.java    License: Apache License 2.0 4 votes vote down vote up
public void gatherDefineAndParameters(PsiFile psiFile, final List<PsiElement> defines, final List<PsiElement> parameters)
{
    psiFile.accept(getDefineAndParametersVisitor(defines, parameters));
}
 
Example 20
@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);
}