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

The following examples show how to use com.intellij.psi.PsiFile#accept() . 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: SpecIndexer.java    From intellij-swagger with 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 2
Source File: AnnotationUtil.java    From idea-php-annotation-plugin with MIT License 6 votes vote down vote up
/**
 * 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 3
Source File: AnnotationUsageIndex.java    From idea-php-annotation-plugin with MIT License 6 votes vote down vote up
@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 4
Source File: EventAnnotationStubIndex.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@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 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: TemplateAnnotationIndex.java    From idea-php-generics-plugin with MIT License 6 votes vote down vote up
@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 7
Source File: SpecIndexer.java    From intellij-swagger with 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 8
Source File: ConfigEntityTypeAnnotationIndex.java    From idea-php-drupal-symfony2-bridge with MIT License 6 votes vote down vote up
@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 9
Source File: CoreServiceParser.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
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 10
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 11
Source File: InTemplateDeclarationVariableProvider.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
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 12
Source File: PhpGlobalsNamespaceProvider.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@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
Source File: StatementCollectorTest.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
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 14
Source File: DependenciesOptimizer.java    From buck with 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 15
Source File: StatementCollectorTest.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
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 16
Source File: NMEBuildDirectoryInspection.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: DependenciesOptimizer.java    From Buck-IntelliJ-Plugin with Apache License 2.0 5 votes vote down vote up
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 18
Source File: OttoProjectHandler.java    From otto-intellij-plugin with Apache License 2.0 5 votes vote down vote up
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 19
Source File: DefineResolver.java    From needsmoredojo with 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
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);
}