Java Code Examples for com.intellij.psi.search.GlobalSearchScope

The following are top voted examples for showing how to use com.intellij.psi.search.GlobalSearchScope. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: TS-IJ   File: TSGlobalCachedListGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public Set<TSVarExpr> generate(Project project) {
    Set<TSVarExpr> items = new HashSet<>();
    //Search every file in the project
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (tsFile != null) {
            Collection<TSAssignExpr> assignments = PsiTreeUtil.findChildrenOfType(tsFile, TSAssignExpr.class);
            for (TSAssignExpr assignment : assignments) {
                PsiElement first = assignment.getFirstChild();
                if (!(first instanceof TSVarExpr))
                    continue;

                if (((TSVarExpr)first).isLocal())
                    continue;

                items.add((TSVarExpr) first);

            }
        }
        ProgressManager.progress("Loading Symbols");
    }
    return items;
}
 
Example 2
Project: jgiven-intellij-plugin   File: ReferenceProviderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_process_reference() throws Exception {
    // given
    PsiReference reference1 = mock(PsiReference.class);
    PsiReference reference2 = mock(PsiReference.class);

    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class));
    when(scenarioStateReferenceProvider.findReferences(field)).thenReturn(Arrays.asList(reference1, reference2));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(true);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verify(processor).process(reference1);
    verify(processor).process(reference2);
}
 
Example 3
Project: reasonml-idea-plugin   File: PsiVarNameReference.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public PsiElement resolve() {
    PsiElement parent = PsiTreeUtil.getParentOfType(myElement, PsiLet.class);

    // If name is used in a let definition, it's already the reference
    if (parent instanceof PsiLet && ((PsiLet) parent).getNameIdentifier() == myElement) {
        return myElement;
    }

    // Find the name in the index
    Collection<PsiLet> elements = StubIndex.getElements(IndexKeys.LETS, m_referenceName, myElement.getProject(), GlobalSearchScope.allScope(myElement.getProject()), PsiLet.class);
    if (!elements.isEmpty()) {
        // TODO: only let with correct QN
        PsiLet let = elements.iterator().next();
        return let.getNameIdentifier();
    }

    return null;
}
 
Example 4
Project: manifold-ij   File: MoveTypeManifoldFileProcessor.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public List<UsageInfo> findUsages( PsiFile psiFile, PsiDirectory newParent, boolean searchInComments, boolean searchInNonJavaFiles )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( psiFile );
  ManModule module = ManProject.getModule( mod );
  PsiClass psiClass = findPsiClass( psiFile );
  if( psiClass == null )
  {
    return Collections.emptyList();
  }

  Query<PsiReference> search = ReferencesSearch.search( psiClass, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ) );
  List<UsageInfo> usages = new ArrayList<>();
  for( PsiReference ref: search.findAll() )
  {
    usages.add( new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
      ref.getRangeInElement().getEndOffset(), psiClass,
      ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) ) );
  }
  return usages;
}
 
Example 5
Project: manifold-ij   File: ManShortNamesCache.java   Source Code and License 6 votes vote down vote up
private void findPsiClasses( @NotNull @NonNls String name, @NotNull GlobalSearchScope scope, Set<PsiClass> psiClasses, ManModule start, ManModule module )
{
  for( ITypeManifold tm: module.getTypeManifolds() )
  {
    for( String fqn: tm.getAllTypeNames() )
    {
      String simpleName = ClassUtil.extractClassName( fqn );
      if( simpleName.equals( name ) )
      {
        PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( scope, module, fqn );
        if( psiClass == null )
        {
          return;
        }
        psiClasses.add( psiClass );
      }
    }
  }
  for( Dependency d : module.getDependencies() )
  {
    if( module == start || d.isExported() )
    {
      findPsiClasses( name, scope, psiClasses, start, (ManModule)d.getModule() );
    }
  }
}
 
Example 6
Project: idea-php-typo3-plugin   File: RouteHelper.java   Source Code and License 6 votes vote down vote up
@NotNull
private static PsiElement[] getTargetMethods(@NotNull Project project, @NotNull String routeName) {
    List<PsiElement> result = new ArrayList<>();
    List<RouteStub> values = FileBasedIndex.getInstance().getValues(RouteIndex.KEY, routeName, GlobalSearchScope.allScope(project));
    PhpIndex phpIndex = PhpIndex.getInstance(project);

    for (RouteStub routeStub : values) {
        String fqn = routeStub.getController();

        Collection<PhpClass> classesByFQN = phpIndex.getClassesByFQN(fqn);
        classesByFQN.forEach(c -> {
            if (c.findMethodByName(routeStub.getMethod()) != null) {
                result.add(c.findMethodByName(routeStub.getMethod()));
            }
        });
    }

    return result.toArray(new PsiElement[result.size()]);
}
 
Example 7
Project: manifold-ij   File: VarHandler.java   Source Code and License 6 votes vote down vote up
@Nullable
public PsiType inferType( PsiTypeElement typeElement )
{
  PsiType psiType = null;

  final PsiElement parent = typeElement.getParent();
  if( (parent instanceof PsiLocalVariable && isVar( (PsiLocalVariable)parent )) ||
      (parent instanceof PsiParameter && isVarForEach( (PsiParameter)parent )) )
  {

    if( parent instanceof PsiLocalVariable )
    {
      psiType = processLocalVariableInitializer( ((PsiLocalVariable)parent).getInitializer() );
    }
    else
    {
      psiType = processForeach( ((PsiParameter)parent).getDeclarationScope() );
    }

    if( null == psiType )
    {
      psiType = PsiType.getJavaLangObject( typeElement.getManager(), GlobalSearchScope.allScope( typeElement.getProject() ) );
    }
  }
  return psiType;
}
 
Example 8
Project: idea-php-typo3-plugin   File: IconIndex.java   Source Code and License 6 votes vote down vote up
public static Map<VirtualFile, IconStub> getIconDefinitionByIdentifier(@NotNull Project project, String iconIdentifier) {
    Set<String> identifiers = new HashSet<>();
    identifiers.add(iconIdentifier);

    Map<VirtualFile, IconStub> icons = new THashMap<>();

    FileBasedIndex.getInstance().getFilesWithKey(KEY, identifiers, virtualFile -> {
        FileBasedIndex.getInstance().processValues(KEY, iconIdentifier, virtualFile, (file, value) -> {
            icons.put(file, value);

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return icons;
}
 
Example 9
Project: idea-php-typo3-plugin   File: ConstantMatcherInspection.java   Source Code and License 6 votes vote down vote up
private Set<String> getRemovedConstantsFQNs(ConstantReference element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] constantMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "ConstantMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : constantMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream()
            .map(stringLiteral -> "\\" + ((StringLiteralExpression)stringLiteral).getContents())
            .collect(Collectors.toSet());
}
 
Example 10
Project: idea-php-typo3-plugin   File: ClassConstantMatcherInspection.java   Source Code and License 6 votes vote down vote up
private Set<String> getDeprecatedClassConstants(PhpPsiElement element) {
    Set<PsiElement> elements = new HashSet<>();
    PsiFile[] classConstantMatcherFiles = FilenameIndex.getFilesByName(element.getProject(), "ClassConstantMatcher.php", GlobalSearchScope.allScope(element.getProject()));
    for (PsiFile file : classConstantMatcherFiles) {

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(file, el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );
    }

    return elements.stream().map(stringLiteral -> ((StringLiteralExpression)stringLiteral).getContents()).collect(Collectors.toSet());
}
 
Example 11
Project: manifold-ij   File: RenameResourceElementProcessor.java   Source Code and License 6 votes vote down vote up
private static List<UsageInfo> findUsages( PsiElement element, PsiElement ctx )
  {
//    Module mod = ModuleUtilCore.findModuleForPsiElement( element );
//    if( mod == null )
//    {
//      return Collections.emptyList();
//    }

    Query<PsiReference> search = ReferencesSearch.search( element, GlobalSearchScope.moduleScope( ModuleUtilCore.findModuleForPsiElement( ctx ) ) );
    List<UsageInfo> usages = new ArrayList<>();
    for( PsiReference ref : search.findAll() )
    {
      MoveRenameUsageInfo usageInfo = new MoveRenameUsageInfo( ref.getElement(), ref, ref.getRangeInElement().getStartOffset(),
                                                               ref.getRangeInElement().getEndOffset(), element,
                                                               ref.resolve() == null && !(ref instanceof PsiPolyVariantReference && ((PsiPolyVariantReference)ref).multiResolve( true ).length > 0) );
      usages.add( usageInfo );
    }
    return usages;
  }
 
Example 12
Project: idea-php-typo3-plugin   File: TranslationUtil.java   Source Code and License 6 votes vote down vote up
public static PsiElement[] findDefinitionElements(@NotNull Project project, @NotNull String translationId) {
    Set<String> keys = new HashSet<>();
    keys.add(translationId);

    List<PsiElement> elements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(TranslationIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(TranslationIndex.KEY, translationId, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    elements.add(elementAt.getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements.toArray(new PsiElement[elements.size()]);
}
 
Example 13
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 6 votes vote down vote up
@Override
public boolean processPackageDirectories(@NotNull PsiPackage psiPackage,
                                         @NotNull final GlobalSearchScope scope,
                                         @NotNull final Processor<PsiDirectory> consumer,
                                         boolean includeLibrarySources) {
  //System.out.println( "processDirectories() : " + psiPackage + " : " + scope );

  final PsiManager psiManager = PsiManager.getInstance( _project );
  return PackageIndex.getInstance( _project )
    .getDirsByPackageName(psiPackage.getQualifiedName(), includeLibrarySources)
    .forEach(new ReadActionProcessor<VirtualFile>() {
      @Override
      public boolean processInReadAction(final VirtualFile dir) {
        if (!scope.contains(dir)) return true;
        PsiDirectory psiDir = psiManager.findDirectory(dir);
        return psiDir == null || consumer.process(psiDir);
      }
    });
}
 
Example 14
Project: manifold-ij   File: MoveTypeManifoldFileProcessor.java   Source Code and License 6 votes vote down vote up
@Nullable
private PsiClass findPsiClass( PsiFileSystemItem element )
{
  Module mod = ModuleUtilCore.findModuleForPsiElement( element );
  if( mod == null )
  {
    return null;
  }

  ManModule module = ManProject.getModule( mod );
  String[] fqns = module.getTypesForFile( FileUtil.toIFile( module.getProject(), element.getVirtualFile() ) );
  PsiClass psiClass = null;
  for( String fqn: fqns )
  {
    psiClass = ManifoldPsiClassCache.instance().getPsiClass( GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ), module, fqn );
    if( psiClass != null )
    {
      break;
    }
  }
  return psiClass;
}
 
Example 15
Project: idea-php-typo3-plugin   File: ControllerActionUtil.java   Source Code and License 6 votes vote down vote up
public static PsiElement[] getDefinitionElements(@NotNull Project project, @NotNull String actionName) {
    Set<String> keys = new HashSet<>();
    keys.add(actionName);

    List<PsiElement> elements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(ControllerActionIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(ControllerActionIndex.KEY, actionName, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    elements.add(elementAt.getParent().getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return elements.toArray(new PsiElement[elements.size()]);
}
 
Example 16
Project: idea-php-typo3-plugin   File: CoreServiceParser.java   Source Code and 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) {
            psiFile.accept(new CoreServiceDefinitionParserVisitor(serviceMap));
        }
    }
}
 
Example 17
Project: magento2-phpstorm-plugin   File: DiIndex.java   Source Code and License 6 votes vote down vote up
public Collection<PsiElement> getVirtualTypeElements(final String name, final GlobalSearchScope scope) {
    Collection<PsiElement> result = new ArrayList<>();

    Collection<VirtualFile> virtualFiles =
            FileBasedIndex.getInstance().getContainingFiles(VirtualTypeIndex.KEY, name, scope);

    for (VirtualFile virtualFile : virtualFiles) {
        XmlFile xmlFile = (XmlFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (xmlFile != null) {
            Collection<XmlAttributeValue> valueElements = XmlPsiTreeUtil
                    .findAttributeValueElements(xmlFile, "virtualType", "name", name);
            result.addAll(valueElements);
        }
    }
    return result;
}
 
Example 18
Project: magento2-phpstorm-plugin   File: DiIndex.java   Source Code and License 6 votes vote down vote up
@NotNull
private String getTopTypeOfVirtualType(@NonNull String name) {
    List<String> values;
    int parentNestingLevel = 0;
    int maxNestingLevel = 5;

    do {
        values = FileBasedIndex.getInstance()
                .getValues(VirtualTypeIndex.KEY, name, GlobalSearchScope.allScope(project));
        if (values.size() > 0 && values.get(0) != null) {
            name = values.get(0);
        }
    } while (values.size() > 0 || maxNestingLevel > parentNestingLevel++);

    return name;
}
 
Example 19
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 6 votes vote down vote up
@Override
public PsiClass findClass( String fqn, GlobalSearchScope globalSearchScope )
{
  //System.out.println( "findClass() : " + fqn + " : " + globalSearchScope );

  if( DumbService.getInstance( globalSearchScope.getProject() ).isDumb() )
  {
    // skip processing during index rebuild
    return null;
  }

  List<ManModule> modules = findModules( globalSearchScope );

  for( ManModule m : modules )
  {
    PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( globalSearchScope, m, fqn );
    if( psiClass != null )
    {
      return psiClass;
    }
  }
  return null;
}
 
Example 20
Project: magento2-phpstorm-plugin   File: FileBasedIndexUtil.java   Source Code and License 6 votes vote down vote up
private static Collection<VirtualFile> getValues(String moduleName, VirtualFile moduleVf, Project project)
{
    Collection<VirtualFile> viewVfs = new ArrayList<>();
    FileBasedIndex.getInstance()
            .processValues(
                    ModuleNameIndex.KEY, moduleName, moduleVf,
                    (file, value) -> {
                        VirtualFile viewVf = file.getParent().findFileByRelativePath(value.concat("/view"));
                        if (viewVf != null) {
                            viewVfs.add(viewVf);
                        }
                        return false;
                    },
                    GlobalSearchScope.fileScope(project, moduleVf)
            );
    return viewVfs;
}
 
Example 21
Project: magento2-phpstorm-plugin   File: PluginLineMarkerProvider.java   Source Code and License 6 votes vote down vote up
List<PhpClass> getPluginsForClass(@NotNull PhpClass phpClass, @NotNull String classFQN) {
    List<PhpClass> results = new ArrayList<>();

    if (classPluginsMap.containsKey(classFQN)) {
        return classPluginsMap.get(classFQN);
    }

    List<Set<String>> plugins = FileBasedIndex.getInstance()
        .getValues(PluginIndex.KEY, classFQN, GlobalSearchScope.allScope(phpClass.getProject()));

    if (plugins.size() == 0) {
        classPluginsMap.put(classFQN, results);
        return results;
    }

    PhpIndex phpIndex = PhpIndex.getInstance(phpClass.getProject());

    for (Set<String> pluginClassNames: plugins) {
        for (String pluginClassName: pluginClassNames) {
            results.addAll(phpIndex.getClassesByFQN(pluginClassName));
        }
    }
    classPluginsMap.put(classFQN, results);
    return results;
}
 
Example 22
Project: magento2-phpstorm-plugin   File: EventDispatchReferenceProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<PsiElement> targets = EventIndex.getInstance(element.getProject())
            .getEventElements(
                    value,
                    GlobalSearchScope.getScopeRestrictedByFileTypes(
                            GlobalSearchScope.allScope(element.getProject()),
                            XmlFileType.INSTANCE
                    )
    );

    if (targets.size() > 0) {
        return new PsiReference[] {new PolyVariantReferenceBase(element, targets)};
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 23
Project: magento2-phpstorm-plugin   File: EventNameReferenceProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    String value = StringUtil.unquoteString(element.getText());
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(EventNameIndex.KEY, value,
                GlobalSearchScope.getScopeRestrictedByFileTypes(
                        GlobalSearchScope.allScope(element.getProject()),
                        PhpFileType.INSTANCE
                )
        );

    PsiManager psiManager = PsiManager.getInstance(element.getProject());
    for (VirtualFile virtualFile: containingFiles) {
        PhpFile phpFile = (PhpFile) psiManager.findFile(virtualFile);
        if (phpFile != null) {
            List<PsiElement> psiElements = new ArrayList<>();
            recursiveFill(psiElements, phpFile, value);
            if (psiElements.size() > 0) {
                return new PsiReference[] {new PolyVariantReferenceBase(element, psiElements)};
            }
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 24
Project: bamboo-soy   File: TemplateNameUtils.java   Source Code and License 6 votes vote down vote up
/** Finds the matching SoyTemplateBlock by their exact name. */
public static List<SoyTemplateBlock> findTemplateDeclarations(
    PsiElement element, String identifier) {
  if (identifier.startsWith(".")) {
    identifier = ((SoyFile) element.getContainingFile()).getNamespace() + identifier;
  } else {
    AliasMapper mapper = new AliasMapper(element.getContainingFile());
    identifier = mapper.normalizeIdentifier(identifier);
  }

  Project project = element.getProject();
  return TemplateBlockIndex.INSTANCE
      .get(identifier, project, GlobalSearchScope.allScope(project))
      .stream()
      .filter((block) -> block.getDefinitionIdentifier() != null)
      .collect(Collectors.toList());
}
 
Example 25
Project: bamboo-soy   File: TemplateNameUtils.java   Source Code and License 6 votes vote down vote up
/** Finds all local template names in the given file. */
public static List<String> findLocalTemplateNames(PsiElement element) {
  PsiFile file = element.getContainingFile();
  return TemplateBlockIndex.INSTANCE
      .getAllKeys(file.getProject())
      .stream()
      .flatMap(
          (key) ->
              TemplateBlockIndex.INSTANCE
                  .get(
                      key, file.getProject(), GlobalSearchScope.fileScope(file.getOriginalFile()))
                  .stream()
                  .filter((block) -> !block.isDelegate())
                  .map(SoyTemplateBlock::getName))
      .collect(Collectors.toList());
}
 
Example 26
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 6 votes vote down vote up
@Override
public PsiClass[] findClasses( String fqn, GlobalSearchScope globalSearchScope )
{
  //System.out.println( "PsiClass[] findClasses() : " + fqn + " : " + globalSearchScope );

  if( DumbService.getInstance( globalSearchScope.getProject() ).isDumb() )
  {
    // skip processing during index rebuild
    return PsiClass.EMPTY_ARRAY;
  }

  List<PsiClass> psiClasses = new ArrayList<>();
  List<ManModule> modules = findModules( globalSearchScope );
  for( ManModule m : modules )
  {
    PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( globalSearchScope, m, fqn );
    if( psiClass != null )
    {
      psiClasses.add( psiClass );
    }
  }
  return psiClasses.toArray( new PsiClass[psiClasses.size()] );
}
 
Example 27
Project: idea-php-dotenv-plugin   File: EnvironmentVariablesApi.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param project project
 * @param key environment variable key
 * @return All key declarations, in .env files, Dockerfile, docker-compose.yml, etc
 */
@NotNull
public static PsiElement[] getKeyDeclarations(Project project, String key) {
    List<PsiElement> targets = new ArrayList<>();

    FileBasedIndex.getInstance().getFilesWithKey(DotEnvKeysIndex.KEY, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
        PsiFile psiFileTarget = PsiManager.getInstance(project).findFile(virtualFile);
        if(psiFileTarget == null) {
            return true;
        }

        for(EnvironmentVariablesProvider provider : EnvironmentVariablesProviderUtil.PROVIDERS) {
            if(provider.acceptFile(virtualFile)) {
                targets.addAll(EnvironmentVariablesUtil.getElementsByKey(key, provider.getElements(psiFileTarget)));
            }
        }

        return true;
    }, GlobalSearchScope.allScope(project));

    return targets.toArray(new PsiElement[0]);
}
 
Example 28
Project: idea-php-dotenv-plugin   File: EnvironmentVariablesApi.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param project project
 * @param key environment variable key
 * @return All key usages, like getenv('KEY')
 */
@NotNull
public static PsiElement[] getKeyUsages(Project project, String key) {
    List<PsiElement> targets = new ArrayList<>();

    FileBasedIndex.getInstance().getFilesWithKey(DotEnvUsagesIndex.KEY, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
        PsiFile psiFileTarget = PsiManager.getInstance(project).findFile(virtualFile);
        if(psiFileTarget == null) {
            return true;
        }

        for(EnvironmentVariablesUsagesProvider provider : EnvironmentVariablesProviderUtil.USAGES_PROVIDERS) {
            if(provider.acceptFile(virtualFile)) {
                targets.addAll(EnvironmentVariablesUtil.getUsagesElementsByKey(key, provider.getUsages(psiFileTarget)));
            }
        }

        return true;
    }, GlobalSearchScope.allScope(project));

    return targets.toArray(new PsiElement[0]);
}
 
Example 29
Project: idea-php-dotenv-plugin   File: DotEnvLightCodeInsightFixtureTestCase.java   Source Code and License 6 votes vote down vote up
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
    for (String key : keys) {

        final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();

        FileBasedIndexImpl.getInstance().getFilesWithKey(id, new HashSet<String>(Arrays.asList(key)), new Processor<VirtualFile>() {
            @Override
            public boolean process(VirtualFile virtualFile) {
                virtualFiles.add(virtualFile);
                return true;
            }
        }, GlobalSearchScope.allScope(getProject()));

        if(notCondition && virtualFiles.size() > 0) {
            fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
        } else if(!notCondition && virtualFiles.size() == 0) {
            fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
        }
    }
}
 
Example 30
Project: intellij-postfix-templates   File: CptUtil.java   Source Code and License 6 votes vote down vote up
public static List<CptMapping> findMappings(Project project, String key) {
	List<CptMapping> result = null;

	Collection<VirtualFile> virtualFiles =
		FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
			GlobalSearchScope.allScope(project));

	for (VirtualFile virtualFile : virtualFiles) {
		CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);

		if (cptFile != null) {
			CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
			if (mappings != null) {
				for (CptMapping mapping : mappings) {
					if (key.equals(mapping.getMatchingClass())) {
						if (result == null) {
							result = new ArrayList<>();
						}
						result.add(mapping);
					}
				}
			}
		}
	}
	return result != null ? result : Collections.emptyList();
}
 
Example 31
Project: hybris-integration-intellij-idea-plugin   File: HybrisEnumLiteralItemReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(final boolean incompleteCode) {
    Project project = myElement.getProject();
    final String enumLiteralJavaModelName = myElement.getText().replaceAll("\"", "").toUpperCase();

    final PsiShortNamesCache psiShortNamesCache = PsiShortNamesCache.getInstance(project);
    final PsiField[] javaEnumLiteralFields = psiShortNamesCache.getFieldsByName(
        enumLiteralJavaModelName, GlobalSearchScope.allScope(project)
    );

    final Set<PsiField> enumFields = stream(javaEnumLiteralFields)
        .filter(literal -> literal.getParent() != null)
        .filter(literal -> literal.getParent() instanceof ClsClassImpl)
        .filter(literal -> ((ClsClassImpl) literal.getParent()).isEnum())
        .collect(Collectors.toSet());

    return PsiElementResolveResult.createResults(enumFields);
}
 
Example 32
Project: hybris-integration-intellij-idea-plugin   File: HybrisModelItemReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(final boolean incompleteCode) {
    final Project project = myElement.getProject();
    final String modelName = PATTERN.matcher(myElement.getText()).replaceAll("");

    final String javaModelName = modelName + JAVA_MODEL_SUFFIX;
    final String jaloModelName = modelName;

    final PsiClass[] javaModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName(
        javaModelName, GlobalSearchScope.allScope(project)
    );

    final PsiClass[] jaloModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName(
        jaloModelName, GlobalSearchScope.projectScope(project)
    );

    final PsiClass[] psiClasses = ArrayUtil.mergeArrays(javaModelClasses, jaloModelClasses);
    return PsiElementResolveResult.createResults(psiClasses);
}
 
Example 33
Project: data-mediator   File: PropertyGenerator.java   Source Code and License 6 votes vote down vote up
private PsiField createConstantField(PsiClass mPsiClass, PsiElementFactory elementFactory, Property prop) {
    // Property PROP_student = SharedProperties.get("com.heaven7.data.mediator.demo.testpackage.TestBind", "student", 0);
    PsiType psiType = PsiType.getTypeByName("com.heaven7.java.data.mediator.Property",
            mPsiClass.getProject(), GlobalSearchScope.allScope(mPsiClass.getProject()));
    PsiField psiField = elementFactory.createField("PROP_" + prop.getName(), psiType);
    PsiExpression psiInitializer = elementFactory.createExpressionFromText(
            String.format("%s.get(%s.class.getName(), \"%s\" ,%d)",
                    "com.heaven7.java.data.mediator.internal.SharedProperties",
                    prop.getTypeString(), prop.getName(), prop.getComplexType()),
            psiField);
    psiField.setInitializer(psiInitializer);
    PsiModifierList modifierList = psiField.getModifierList();
    if (modifierList != null) {
        modifierList.setModifierProperty(PsiModifier.PUBLIC + " " + PsiModifier.STATIC, true);
    }
    return psiField;
}
 
Example 34
Project: intellij-plugin   File: CoffigDocumentationProvider.java   Source Code and License 6 votes vote down vote up
private Optional<PropertiesFile> findResourceBundle(Project project, PsiClass configClass) {
    String qualifiedName = configClass.getQualifiedName();
    if (qualifiedName != null) {
        int lastDotIndex = qualifiedName.lastIndexOf(".");
        String packageName = qualifiedName.substring(0, lastDotIndex);
        String className = qualifiedName.substring(lastDotIndex + 1);
        PsiPackage psiPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
        if (psiPackage != null) {
            return Arrays.stream(psiPackage.getFiles(GlobalSearchScope.allScope(project)))
                    .filter(psiFile -> psiFile instanceof PropertiesFile && psiFile.getVirtualFile().getNameWithoutExtension().equals(className))
                    .map(psiFile -> (PropertiesFile) psiFile)
                    .findFirst();
        }
    }
    return Optional.empty();
}
 
Example 35
Project: intellij-plugin   File: CoffigResolver.java   Source Code and License 6 votes vote down vote up
Stream<PsiClass> classStream() {
    if (context.isValid()) {
        Stream<PsiClass> stream = StreamSupport.stream(
                AnnotatedElementsSearch.searchPsiClasses(
                        context.getConfigAnnotationClass(),
                        GlobalSearchScope.allScope(context.getProject())).spliterator(),
                false);
        Predicate<PsiClass> filter = context.getFilter();
        if (filter != null) {
            stream = stream.filter(filter);
        }
        return stream;
    } else {
        return Stream.empty();
    }
}
 
Example 36
Project: intellij-plugin   File: AnnotatedInterfaceNode.java   Source Code and License 6 votes vote down vote up
@Override
protected MultiMap<PsiFile, T> computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, T> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass serviceAnnotation = javaPsiFacade.findClass(getAnnotationQName(), GlobalSearchScope.allScope(project));
        if (serviceAnnotation != null) {
            AnnotatedElementsSearch.searchPsiClasses(serviceAnnotation, GlobalSearchScope.allScope(project)).forEach(psiClass -> {
                if (psiClass.isInterface() && isSatisfying(psiClass)) {
                    children.putValue(psiClass.getContainingFile(), createChild(psiClass));
                }
                return true;
            });
        }
    }
    return children;
}
 
Example 37
Project: intellij-plugin   File: AggregateNode.java   Source Code and License 6 votes vote down vote up
@Override
protected MultiMap<PsiFile, ClassNode> computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, ClassNode> children = new MultiMap<>();
    children.putValue(aggregateRoot.getContainingFile(), new AggregateRootNode(this, aggregateRoot));
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass entityInterface = javaPsiFacade.findClass(ENTITY_INTERFACE, GlobalSearchScope.allScope(project));
        PsiClass valueObjectInterface = javaPsiFacade.findClass(VO_INTERFACE, GlobalSearchScope.allScope(project));
        if (entityInterface != null && valueObjectInterface != null) {
            for (PsiClass psiClass : psiPackage.getClasses(GlobalSearchScope.allScope(project))) {
                if (psiClass.isInheritor(entityInterface, true) && !psiClass.equals(aggregateRoot)) {
                    children.putValue(psiClass.getContainingFile(), new EntityNode(this, psiClass));
                } else if (psiClass.isInheritor(valueObjectInterface, true)) {
                    children.putValue(psiClass.getContainingFile(), new ValueObjectNode(this, psiClass));
                }
            }
        }
    }
    return children;
}
 
Example 38
Project: intellij-plugin   File: AggregatesNode.java   Source Code and License 6 votes vote down vote up
@Override
protected MultiMap computeChildren(@Nullable PsiFile psiFile) {
    MultiMap<PsiFile, AggregateNode> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass psiClass = javaPsiFacade.findClass(AGGREGATE_ROOT_INTERFACE, GlobalSearchScope.allScope(project));
        if (psiClass != null) {
            ClassInheritorsSearch.search(psiClass, GlobalSearchScope.allScope(project), true).forEach(candidate -> {
                String qualifiedName = candidate.getQualifiedName();
                if (qualifiedName != null && !qualifiedName.startsWith(BUSINESS_PACKAGE) && !isAbstract(candidate)) {
                    children.putValue(candidate.getContainingFile(), new AggregateNode(this, candidate));
                }
            });
        }

    }
    return children;
}
 
Example 39
Project: intellij-plugin   File: ResourcesNode.java   Source Code and License 6 votes vote down vote up
@Override
public MultiMap<PsiFile, ResourceNode> computeChildren(PsiFile psiFile) {
    Project project = getProject();
    MultiMap<PsiFile, ResourceNode> children = new MultiMap<>();
    if (project != null) {
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiClass pathAnnotation = javaPsiFacade.findClass(PATH_ANNOTATION, GlobalSearchScope.allScope(project));
        if (pathAnnotation != null) {
            AnnotatedElementsSearch.searchPsiClasses(pathAnnotation, GlobalSearchScope.allScope(project)).forEach(psiClass -> {
                if (!psiClass.isInterface() && !NavigatorUtil.isAbstract(psiClass)) {
                    children.putValue(psiClass.getContainingFile(), new ResourceNode(ResourcesNode.this, pathAnnotation, psiClass));
                }
                return true;
            });
        }
    }
    return children;
}
 
Example 40
Project: intellij-plugin   File: ToolsNode.java   Source Code and License 6 votes vote down vote up
protected MultiMap<PsiFile, ToolNode> computeChildren(PsiFile psiFile) {
    MultiMap<PsiFile, ToolNode> children = new MultiMap<>();
    Project project = getProject();
    if (project != null) {
        PsiClass toolInterface = JavaPsiFacade.getInstance(project).findClass(TOOL_INTERFACE, GlobalSearchScope.allScope(project));
        if (toolInterface != null) {
            ClassInheritorsSearch.search(toolInterface, GlobalSearchScope.allScope(project), true).forEach(psiClass -> {
                PsiFile containingFile = psiClass.getContainingFile();
                if (!isAbstract(psiClass)) {
                    children.putValue(containingFile, new ToolNode(this, psiClass));
                }
            });
        }
    }
    return children;
}
 
Example 41
Project: manifold-ij   File: TestFinder.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiClass[] getClasses(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
  String fqn = psiPackage.getQualifiedName();
  if (isShortCircuit(fqn)) {
    return PsiClass.EMPTY_ARRAY;
  }

  addShortCircuit(fqn);
  try {
    PsiClass[] classes = psiPackage.getClasses(scope);
    return Arrays.stream(classes).map(LightClass::new).toArray(PsiClass[]::new);
  } finally {
    removeShortCircuit(fqn);
  }
}
 
Example 42
Project: processing-idea   File: MigrationActions.java   Source Code and License 6 votes vote down vote up
public static PsiFile postProcessSelectedMainSketchClass(@NotNull Project project,
                                                         @NotNull PsiClass selectedMainClass,
                                                         @NotNull PsiImportList correspondingImportList) {
    // Construct a valid Java class from the selected main sketch class.
    selectedMainClass.getModifierList().setModifierProperty(PsiModifier.PUBLIC, true);

    PsiJavaCodeReferenceElement pAppletReference = JavaPsiFacade.getElementFactory(project)
            .createFQClassNameReferenceElement("processing.core.PApplet", GlobalSearchScope.projectScope(project));
    selectedMainClass.getExtendsList().add(pAppletReference);

    PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);

    StringJoiner mainFileJoiner = new StringJoiner("\n\n");
    StringJoiner importStatementJoiner = new StringJoiner("\n");

    for (PsiImportStatementBase importStatement : correspondingImportList.getAllImportStatements()) {
        importStatementJoiner.add(importStatement.getText());
    }

    mainFileJoiner.add(importStatementJoiner.toString());
    mainFileJoiner.add(selectedMainClass.getText());

    return psiFileFactory.createFileFromText(selectedMainClass.getName() + ".java", JavaFileType.INSTANCE, mainFileJoiner.toString());
}
 
Example 43
Project: Android-ORM-ASPlugin   File: Utils.java   Source Code and License 6 votes vote down vote up
public static void addJavaImport(Project project, @NotNull PsiJavaFile psiJavaFile, GlobalSearchScope scope, String... classQNames) {
    if (project == null) {
        project = psiJavaFile.getProject();
    }
    if (scope == null) {
        scope = GlobalSearchScope.allScope(project);
    }
    if (classQNames != null) {
        JavaCodeStyleManager factory = JavaCodeStyleManager.getInstance(project);
        for (String name : classQNames) {
            PsiClass clazz = JavaPsiFacade.getInstance(project).findClass(name, scope);
            if (clazz != null) {
                factory.addImport(psiJavaFile, clazz);
            }
        }
    }
}
 
Example 44
Project: manifold-ij   File: RenameResourceElementProcessor.java   Source Code and License 5 votes vote down vote up
private String findFeatureName( FeaturePath path )
{
  PsiClass root = path.getRoot();
  String fqn = root.getQualifiedName();
  PsiClass psiClass = JavaPsiFacade.getInstance( root.getProject() ).findClass( fqn, GlobalSearchScope.moduleScope( ModuleUtilCore.findModuleForPsiElement( root ) ) );
  if( psiClass == null )
  {
    return null;
  }
  PsiNamedElement renamedFeature = findFeatureElement( psiClass, path.getChild() );
  return renamedFeature == null ? null : renamedFeature.getName();
}
 
Example 45
Project: TS-IJ   File: TSFunctionCachedListGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public Set<TSFnDeclStmt> generate(Project project) {
    Set<TSFnDeclStmt> items = new HashSet<>();
    //Search every file in the project
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (tsFile != null) {
            TSFnDeclStmt[] functions = PsiTreeUtil.getChildrenOfType(tsFile, TSFnDeclStmt.class);
            if (functions != null) {
                Collections.addAll(items, functions);
            }

            TSPackageDecl[] packages = PsiTreeUtil.getChildrenOfType(tsFile, TSPackageDecl.class);
            if (packages != null) {
                for (TSPackageDecl pack : packages) {
                    functions = PsiTreeUtil.getChildrenOfType(pack, TSFnDeclStmt.class);
                    if (functions != null) {
                        Collections.addAll(items, functions);
                    }
                }
            }
            ProgressManager.progress("Loading Symbols");
        }
    }
    return items;
}
 
Example 46
Project: TS-IJ   File: TSObjectCachedListGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public Set<TSObjectExpr> generate(Project project) {
    Set<TSObjectExpr> items = new HashSet<>();
    //Search every file in the project
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (tsFile != null) {
            items.addAll(PsiTreeUtil.findChildrenOfType(tsFile, TSObjectExpr.class));
            items.addAll(PsiTreeUtil.findChildrenOfType(tsFile, TSDatablockDecl.class));
        }
        ProgressManager.progress("Loading Symbols");
    }
    return items;
}
 
Example 47
Project: jgiven-intellij-plugin   File: ScenarioStateReferenceProvider.java   Source Code and License 5 votes vote down vote up
public List<PsiReference> findReferences(PsiField field, int maxNumberOfResults) {
    PsiClass fieldClass = PsiTypesUtil.getPsiClass(field.getType());
    if (fieldClass == null) {
        return Collections.emptyList();
    }
    Project project = field.getProject();
    PsiManager manager = PsiManager.getInstance(project);
    JGivenUsageProvider usageProvider = new JGivenUsageProvider(scenarioStateProvider, resolutionHandler, new ReferenceFactory(manager));
    StateReferenceProcessor processor = new StateReferenceProcessor(field, maxNumberOfResults, usageProvider);

    SearchScope scope = GlobalSearchScope.everythingScope(project).intersectWith(javaFilesScope(project));

    findPsiFields(project, (GlobalSearchScope) scope, processor);
    return processor.getResults();
}
 
Example 48
Project: jgiven-intellij-plugin   File: JGivenUseScopeEnlarger.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public SearchScope getAdditionalUseScope(@NotNull PsiElement element) {
    return scenarioStateAnnotationProvider.isJGivenScenarioState(element)
            ? GlobalSearchScope.everythingScope(element.getProject())
            : null;
}
 
Example 49
Project: jgiven-intellij-plugin   File: ReferenceProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void processQuery(@NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull Processor<PsiReference> consumer) {
    final PsiElement element = queryParameters.getElementToSearch();

    ApplicationManager.getApplication().runReadAction(() -> {
        SearchScope scope = queryParameters.getEffectiveSearchScope();
        if (!scenarioStateProvider.isJGivenScenarioState(element)
                || !(scope instanceof GlobalSearchScope)) {
            return;
        }
        PsiField field = (PsiField) element;
        scenarioStateReferenceProvider.findReferences(field).forEach(consumer::process);
    });
}
 
Example 50
Project: jgiven-intellij-plugin   File: ReferenceProviderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_not_process_reference_if_element_is_not_a_JGiven_scenario_state() throws Exception {
    // given
    PsiField field = mock(PsiField.class);
    ReferencesSearch.SearchParameters searchParameters = mock(ReferencesSearch.SearchParameters.class);
    when(searchParameters.getElementToSearch()).thenReturn(field);
    when(searchParameters.getEffectiveSearchScope()).thenReturn(mock(GlobalSearchScope.class));
    when(scenarioStateProvider.isJGivenScenarioState(field)).thenReturn(false);

    // when
    referenceProvider.processQuery(searchParameters, processor);

    // then
    verifyZeroInteractions(processor);
}
 
Example 51
Project: idea-php-typo3-plugin   File: RouteHelper.java   Source Code and License 5 votes vote down vote up
@NotNull
public static PsiElement[] getRouteDefinitionElements(@NotNull Project project, @NotNull String routeName) {
    List<PsiElement> results = new ArrayList<>();

    for (PsiElement psiElement : RouteHelper.getTargetMethods(project, routeName)) {

        if (psiElement instanceof Method) {
            results.add(psiElement);
        }

    }

    // Route definition
    Set<String> keys = new HashSet<>();
    keys.add(routeName);
    FileBasedIndex.getInstance().getFilesWithKey(RouteIndex.KEY, keys, virtualFile -> {
        FileBasedIndex.getInstance().processValues(RouteIndex.KEY, routeName, virtualFile, (file, value) -> {
            PsiFile file1 = PsiManager.getInstance(project).findFile(file);
            if (file1 != null) {
                PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
                if (elementAt != null) {
                    results.add(elementAt.getParent());
                }
            }

            return true;
        }, GlobalSearchScope.allScope(project));

        return true;
    }, GlobalSearchScope.allScope(project));

    return results.toArray(new PsiElement[results.size()]);
}
 
Example 52
Project: idea-php-typo3-plugin   File: RouteHelper.java   Source Code and License 5 votes vote down vote up
@NotNull
public static Collection<LookupElement> getRoutesLookupElements(@NotNull Project project) {
    Collection<LookupElement> routeLookupElements = new ArrayList<>();

    Collection<String> routes = FileBasedIndex.getInstance().getAllKeys(RouteIndex.KEY, project);
    for (String routeName : routes) {
        List<RouteStub> values = FileBasedIndex.getInstance().getValues(RouteIndex.KEY, routeName, GlobalSearchScope.allScope(project));
        values.forEach(r -> routeLookupElements.add(new RouteLookupElement(r)));
    }

    return routeLookupElements;
}
 
Example 53
Project: manifold-ij   File: ResourceToManifoldUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Find the Manifold PisClass corresponding with a resource file.
 *
 * @param fileElem a psiFile, normally this should be a resource file
 *
 * @return The corresponding Manifold PsiClass or null
 */
public static PsiClass findPsiClass( PsiFileSystemItem fileElem )
{
  Project project = fileElem.getProject();
  ManProject manProject = ManProject.manProjectFrom( project );
  VirtualFile virtualFile = fileElem.getVirtualFile();
  if( virtualFile == null )
  {
    return null;
  }
  for( ManModule module : manProject.getModules() )
  {
    IjFile file = FileUtil.toIFile( manProject, virtualFile );
    Set<ITypeManifold> set = module.findTypeManifoldsFor( file );
    if( set != null )
    {
      for( ITypeManifold tf : set )
      {
        if( tf.getProducerKind() == ITypeManifold.ProducerKind.Primary )
        {
          String[] fqns = tf.getTypesForFile( file );
          for( String fqn : fqns )
          {
            PsiClass psiClass = ManifoldPsiClassCache.instance().getPsiClass( GlobalSearchScope.moduleWithDependenciesAndLibrariesScope( module.getIjModule() ), module, fqn );
            if( psiClass != null )
            {
              return psiClass;
            }
          }
        }
      }
    }
  }
  return null;
}
 
Example 54
Project: idea-php-typo3-plugin   File: IconIndex.java   Source Code and License 5 votes vote down vote up
@NotNull
public static IconStub[] getAllIcons(@NotNull Project project) {
    List<IconStub> iconStubs = new ArrayList<>();
    FileBasedIndex.getInstance().getAllKeys(IconIndex.KEY, project).forEach(k -> {
        List<IconStub> values = FileBasedIndex.getInstance().getValues(IconIndex.KEY, k, GlobalSearchScope.allScope(project));
        iconStubs.addAll(values);
    });

    return iconStubs.toArray(new IconStub[iconStubs.size()]);
}
 
Example 55
Project: idea-php-typo3-plugin   File: LegacyClassesForIDEIndex.java   Source Code and License 5 votes vote down vote up
@Nullable
public static String findReplacementClass(@NotNull Project project, @NotNull String fqn) {
    List<String> values = FileBasedIndex.getInstance().getValues(KEY, fqn, GlobalSearchScope.allScope(project));
    if (values.size() > 0) {
        return values.iterator().next();
    }

    return null;
}
 
Example 56
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 5 votes vote down vote up
public static List<ManModule> findModules( GlobalSearchScope scope )
{
  if( scope instanceof ModuleWithDependenciesScope )
  {
    Module module = ((ModuleWithDependenciesScope)scope).getModule();
    return Collections.singletonList( ManProject.getModule( module ) );
  }

  ManProject manProject = ManProject.manProjectFrom( scope.getProject() );
  List<ManModule> modules = new ArrayList<>( manProject.getModules() );
  modules.removeIf( module -> !scope.isSearchInModuleContent( module.getIjModule() ) );
  return modules;
}
 
Example 57
Project: idea-php-typo3-plugin   File: ExtensionScannerUtil.java   Source Code and License 5 votes vote down vote up
public static int getMaximumNumberOfArguments(@NotNull Project project, @NotNull String compiledClassMethodKey) {
    List<Integer> values = FileBasedIndex.getInstance().getValues(MethodArgumentDroppedIndex.KEY, compiledClassMethodKey, GlobalSearchScope.allScope(project));

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

    return values.iterator().next();
}
 
Example 58
Project: greycat-idea-plugin   File: GCMUtil.java   Source Code and License 5 votes vote down vote up
public static List<GCMTypeDeclaration> findProperties(Project project, final String key) {
    final List<GCMTypeDeclaration> result = new ArrayList<GCMTypeDeclaration>();
    Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, GCMLanguageType.INSTANCE,
            GlobalSearchScope.allScope(project));
    for (VirtualFile virtualFile : virtualFiles) {
        GCMFile simpleFile = (GCMFile) PsiManager.getInstance(project).findFile(virtualFile);
        if (simpleFile != null) {
            simpleFile.acceptChildren(new PsiElementVisitor() {
                @Override
                public void visitElement(PsiElement element) {
                    if (element instanceof GCMDeclaration) {
                        GCMDeclaration declaration = (GCMDeclaration) element;
                        if (declaration.getClassDeclaration() != null && declaration.getClassDeclaration().getTypeDeclaration() != null) {
                            if (key.equals(declaration.getClassDeclaration().getTypeDeclaration().getName())) {
                                result.add(declaration.getClassDeclaration().getTypeDeclaration());
                            }
                        }
                        if (declaration.getCustomTypeDeclaration() != null && declaration.getCustomTypeDeclaration().getIdent() != null) {
                            if (key.equals(declaration.getCustomTypeDeclaration().getIdent())) {
                                //result.add(declaration.getCustomTypeDeclaration().getIdent().getText());
                            }
                        }
                    }
                    super.visitElement(element);
                }
            });
        }
    }
    return result;
}
 
Example 59
Project: manifold-ij   File: ManTypeFinder.java   Source Code and License 5 votes vote down vote up
@Override
public PsiPackage[] getSubPackages( PsiPackage psiPackage, GlobalSearchScope scope )
{
  //System.out.println( "getSubPackages() : " + psiPackage + " : " + scope );

  List<ManModule> modules = findModules( scope );
  if( modules.isEmpty() )
  {
    return PsiPackage.EMPTY_ARRAY;
  }

  String parentPackage = psiPackage.getQualifiedName();
  Set<PsiPackage> children = new HashSet<>();
  PsiManager manager = PsiManagerImpl.getInstance( scope.getProject() );
  for( ManModule mm : modules )
  {
    for( ITypeManifold sp : mm.getTypeManifolds() )
    {
      if( sp.getProducerKind() == Supplemental )
      {
        continue;
      }

      Collection<TypeName> typeNames = sp.getTypeNames( parentPackage );
      for( TypeName child : typeNames )
      {
        if( child.kind == TypeName.Kind.NAMESPACE )
        {
          children.add( new NonDirectoryPackage( manager, parentPackage + '.' + child.name ) );
        }
      }
    }
  }
  if( !children.isEmpty() )
  {
    return children.toArray( new PsiPackage[children.size()] );
  }
  return PsiPackage.EMPTY_ARRAY;
}
 
Example 60
Project: magento2-phpstorm-plugin   File: EventIndex.java   Source Code and License 5 votes vote down vote up
public Collection<PsiElement> getEventElements(final String name, final GlobalSearchScope scope) {
    Collection<PsiElement> result = new ArrayList<>();

    Collection<VirtualFile> virtualFiles =
            FileBasedIndex.getInstance().getContainingFiles(EventNameIndex.KEY, name, scope);

    for (VirtualFile virtualFile : virtualFiles) {
        XmlFile xmlFile = (XmlFile) PsiManager.getInstance(project).findFile(virtualFile);
        Collection<XmlAttributeValue> valueElements = XmlPsiTreeUtil
                .findAttributeValueElements(xmlFile, "event", "name", name);
        result.addAll(valueElements);
    }
    return result;
}