@NotNull
 private static SearchScope notNullizeScope(
     @NotNull FindUsagesOptions options, @NotNull Project project) {
   SearchScope scope = options.searchScope;
   if (scope == null) return ProjectScope.getAllScope(project);
   return scope;
 }
Пример #2
0
  public ReplInterpreter(
      @NotNull Disposable disposable, @NotNull CompilerConfiguration configuration) {
    KotlinCoreEnvironment environment =
        KotlinCoreEnvironment.createForProduction(
            disposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
    Project project = environment.getProject();
    this.psiFileFactory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project);
    this.trace = new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace();
    MutableModuleContext moduleContext =
        TopDownAnalyzerFacadeForJVM.createContextWithSealedModule(project);
    this.module = moduleContext.getModule();

    scriptDeclarationFactory = new ScriptMutableDeclarationProviderFactory();

    FileScopeProvider.AdditionalScopes scopeProvider =
        new FileScopeProvider.AdditionalScopes() {
          @NotNull
          @Override
          public List<JetScope> scopes(@NotNull JetFile file) {
            return lastLineScope != null
                ? new SmartList<JetScope>(lastLineScope)
                : Collections.<JetScope>emptyList();
          }
        };

    ContainerForReplWithJava container =
        DiPackage.createContainerForReplWithJava(
            moduleContext,
            trace,
            scriptDeclarationFactory,
            ProjectScope.getAllScope(project),
            scopeProvider);

    this.topDownAnalysisContext =
        new TopDownAnalysisContext(
            TopDownAnalysisMode.LocalDeclarations,
            DataFlowInfo.EMPTY,
            container.getResolveSession().getDeclarationScopeProvider());
    this.topDownAnalyzer = container.getLazyTopDownAnalyzerForTopLevel();
    this.resolveSession = container.getResolveSession();

    moduleContext.initializeModuleContents(
        new CompositePackageFragmentProvider(
            Arrays.asList(
                container.getResolveSession().getPackageFragmentProvider(),
                container.getJavaDescriptorResolver().getPackageFragmentProvider())));

    List<URL> classpath = Lists.newArrayList();
    for (File file : getJvmClasspathRoots(configuration)) {
      try {
        classpath.add(file.toURI().toURL());
      } catch (MalformedURLException e) {
        throw UtilsPackage.rethrow(e);
      }
    }

    this.classLoader =
        new ReplClassLoader(new URLClassLoader(classpath.toArray(new URL[classpath.size()]), null));
  }
 @Override
 protected SearchScope getReferencesSearchScope(VirtualFile file) {
   PsiFile currentFile =
       PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
   return currentFile != null
       ? new LocalSearchScope(currentFile)
       : ProjectScope.getProjectScope(myProject);
 }
  @Nullable
  public PsiClass getContainingClassElement() {
    final PsiClassType containingClassType =
        JavaPsiFacade.getInstance(getProject())
            .getElementFactory()
            .createTypeByFQClassName(myContainingClassName, ProjectScope.getAllScope(getProject()));

    return containingClassType.resolve();
  }
 public static List<PsiFile> findFxmlWithController(final Project project, String className) {
   return findFxmlWithController(
       project,
       className,
       new Function<VirtualFile, PsiFile>() {
         @Override
         public PsiFile fun(VirtualFile file) {
           return PsiManager.getInstance(project).findFile(file);
         }
       },
       ProjectScope.getAllScope(project));
 }
  private static List<LanguageDefinition> collectLanguageDefinitions(final ConvertContext context) {
    final Project project = context.getProject();
    final Collection<PsiClass> allLanguages =
        CachedValuesManager.getManager(project)
            .getCachedValue(
                project,
                () -> {
                  final PsiClass languageClass =
                      JavaPsiFacade.getInstance(project)
                          .findClass(Language.class.getName(), GlobalSearchScope.allScope(project));
                  if (languageClass == null) {
                    return Result.create(
                        Collections.emptyList(),
                        PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
                  }

                  final GlobalSearchScope projectProductionScope =
                      GlobalSearchScopesCore.projectProductionScope(project);
                  GlobalSearchScope allScope =
                      projectProductionScope.union(ProjectScope.getLibrariesScope(project));
                  final Collection<PsiClass> allInheritors =
                      ClassInheritorsSearch.search(languageClass, allScope, true).findAll();
                  return Result.create(
                      allInheritors, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
                });
    if (allLanguages.isEmpty()) {
      return Collections.emptyList();
    }

    final List<LanguageDefinition> libraryDefinitions =
        collectLibraryLanguages(context, allLanguages);

    final GlobalSearchScope projectProductionScope =
        GlobalSearchScopesCore.projectProductionScope(project);
    final Collection<PsiClass> projectLanguages =
        ContainerUtil.filter(
            allLanguages, aClass -> PsiSearchScopeUtil.isInScope(projectProductionScope, aClass));
    final List<LanguageDefinition> projectDefinitions =
        collectProjectLanguages(projectLanguages, libraryDefinitions);

    final List<LanguageDefinition> all = ContainerUtil.newArrayList(libraryDefinitions);
    all.addAll(projectDefinitions);
    return all;
  }
  private void createUIComponents() {
    myMainPanel = new JPanel();

    myWithBrowseButtonReference = createPackageChooser();
    myClassPackageChooser = createPackageChooser();

    GlobalSearchScope scope =
        JavaProjectRootsUtil.getScopeWithoutGeneratedSources(
            ProjectScope.getProjectScope(myProject), myProject);
    myInnerClassChooser = new ClassNameReferenceEditor(myProject, null, scope);
    myInnerClassChooser.addDocumentListener(
        new DocumentAdapter() {
          public void documentChanged(DocumentEvent e) {
            validateButtons();
          }
        });

    // override CardLayout sizing behavior
    myCardPanel =
        new JPanel() {
          public Dimension getMinimumSize() {
            return myHavePackages
                ? myMovePackagePanel.getMinimumSize()
                : myMoveClassPanel.getMinimumSize();
          }

          public Dimension getPreferredSize() {
            return myHavePackages
                ? myMovePackagePanel.getPreferredSize()
                : myMoveClassPanel.getPreferredSize();
          }
        };

    myDestinationFolderCB =
        new DestinationFolderComboBox() {
          @Override
          public String getTargetPackage() {
            return MoveClassesOrPackagesDialog.this.getTargetPackage();
          }
        };
  }
  @NotNull
  @Override
  public Set<UsageDescriptor> getProjectUsages(@NotNull final Project project)
      throws CollectUsagesException {
    final LibraryJarDescriptor[] descriptors =
        LibraryJarStatisticsService.getInstance().getTechnologyDescriptors();
    final Set<UsageDescriptor> result = new HashSet<>(descriptors.length);

    ApplicationManager.getApplication()
        .runReadAction(
            () -> {
              for (LibraryJarDescriptor descriptor : descriptors) {
                String className = descriptor.myClass;
                if (className == null) continue;

                PsiClass[] psiClasses =
                    JavaPsiFacade.getInstance(project)
                        .findClasses(className, ProjectScope.getLibrariesScope(project));
                for (PsiClass psiClass : psiClasses) {
                  if (psiClass == null) continue;

                  VirtualFile jarFile =
                      JarFileSystem.getInstance()
                          .getLocalVirtualFileFor(psiClass.getContainingFile().getVirtualFile());
                  if (jarFile == null) continue;

                  String version = getVersionByJarManifest(jarFile);
                  if (version == null) {
                    version = getVersionByJarFileName(jarFile.getName());
                  }

                  if (version == null || !StringUtil.containsChar(version, '.')) {
                    continue;
                  }

                  result.add(new UsageDescriptor(descriptor.myName + "_" + version, 1));
                }
              }
            });
    return result;
  }
  @Override
  public boolean shouldInspect(@NotNull PsiElement psiRoot) {
    if (ApplicationManager.getApplication().isUnitTestMode()) return true;

    final FileHighlightingSetting settingForRoot = getHighlightingSettingForRoot(psiRoot);
    if (settingForRoot == FileHighlightingSetting.SKIP_HIGHLIGHTING
        || settingForRoot == FileHighlightingSetting.SKIP_INSPECTION) {
      return false;
    }
    final Project project = psiRoot.getProject();
    final VirtualFile virtualFile = psiRoot.getContainingFile().getVirtualFile();
    if (virtualFile == null || !virtualFile.isValid()) return false;

    if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return false;

    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    if (ProjectScope.getLibrariesScope(project).contains(virtualFile)
        && !fileIndex.isInContent(virtualFile)) return false;

    return !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile);
  }
 @NotNull
 static SearchScope getScopeFromModel(@NotNull Project project, @NotNull FindModel findModel) {
   SearchScope customScope = findModel.getCustomScope();
   VirtualFile directory = getDirectory(findModel);
   Module module =
       findModel.getModuleName() == null
           ? null
           : ModuleManager.getInstance(project).findModuleByName(findModel.getModuleName());
   return findModel.isCustomScope() && customScope != null
       ? customScope.intersectWith(GlobalSearchScope.allScope(project))
       :
       // we don't have to check for myProjectFileIndex.isExcluded(file) here like
       // FindInProjectTask.collectFilesInScope() does
       // because all found usages are guaranteed to be not in excluded dir
       directory != null
           ? forDirectory(project, findModel.isWithSubdirectories(), directory)
           : module != null
               ? module.getModuleContentScope()
               : findModel.isProjectScope()
                   ? ProjectScope.getContentScope(project)
                   : GlobalSearchScope.allScope(project);
 }
Пример #11
0
  @NotNull
  private Object[] getSubclassVariants(
      @NotNull PsiPackage context, @NotNull String[] extendClasses) {
    HashSet<Object> lookups = new HashSet<Object>();
    GlobalSearchScope packageScope = PackageScope.packageScope(context, true);
    GlobalSearchScope scope = myJavaClassReferenceSet.getProvider().getScope();
    if (scope != null) {
      packageScope = packageScope.intersectWith(scope);
    }
    final GlobalSearchScope allScope = ProjectScope.getAllScope(context.getProject());
    final boolean instantiatable =
        JavaClassReferenceProvider.INSTANTIATABLE.getBooleanValue(getOptions());
    final boolean notInterface =
        JavaClassReferenceProvider.NOT_INTERFACE.getBooleanValue(getOptions());
    final boolean notEnum = JavaClassReferenceProvider.NOT_ENUM.getBooleanValue(getOptions());
    final boolean concrete = JavaClassReferenceProvider.CONCRETE.getBooleanValue(getOptions());

    final ClassKind classKind = getClassKind();

    for (String extendClassName : extendClasses) {
      final PsiClass extendClass =
          JavaPsiFacade.getInstance(context.getProject()).findClass(extendClassName, allScope);
      if (extendClass != null) {
        // add itself
        if (packageScope.contains(extendClass.getContainingFile().getVirtualFile())) {
          if (isClassAccepted(
              extendClass, classKind, instantiatable, concrete, notInterface, notEnum)) {
            ContainerUtil.addIfNotNull(createSubclassLookupValue(context, extendClass), lookups);
          }
        }
        for (final PsiClass clazz : ClassInheritorsSearch.search(extendClass, packageScope, true)) {
          if (isClassAccepted(clazz, classKind, instantiatable, concrete, notInterface, notEnum)) {
            ContainerUtil.addIfNotNull(createSubclassLookupValue(context, clazz), lookups);
          }
        }
      }
    }
    return lookups.toArray();
  }
 @Nullable
 private PsiClass findTargetClass() {
   String name = myInnerClassChooser.getText().trim();
   return JavaPsiFacade.getInstance(myManager.getProject())
       .findClass(name, ProjectScope.getProjectScope(myProject));
 }
  @NotNull
  public static VirtualFile getTargetDirectoryFor(
      @NotNull Project project,
      @NotNull VirtualFile sourceFile,
      @Nullable String targetFile,
      @Nullable String targetPackage,
      boolean returnRoot) {
    boolean hasPackage = StringUtil.isNotEmpty(targetPackage);
    ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
    ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(project);
    Collection<VirtualFile> files =
        targetFile == null
            ? Collections.<VirtualFile>emptyList()
            : FilenameIndex.getVirtualFilesByName(
                project, targetFile, ProjectScope.getAllScope(project));

    VirtualFile existingFile = null;
    for (VirtualFile file : files) {
      String existingFilePackage = fileIndex.getPackageNameByDirectory(file.getParent());
      if (!hasPackage || existingFilePackage == null || targetPackage.equals(existingFilePackage)) {
        existingFile = file;
        break;
      }
    }

    VirtualFile existingFileRoot =
        existingFile == null
            ? null
            : fileIndex.isInSourceContent(existingFile)
                ? fileIndex.getSourceRootForFile(existingFile)
                : fileIndex.isInContent(existingFile)
                    ? fileIndex.getContentRootForFile(existingFile)
                    : null;

    boolean preferGenRoot =
        sourceFile.getFileType() == BnfFileType.INSTANCE
            || sourceFile.getFileType() == JFlexFileType.INSTANCE;
    boolean preferSourceRoot = hasPackage && !preferGenRoot;
    VirtualFile[] sourceRoots = rootManager.getContentSourceRoots();
    VirtualFile[] contentRoots = rootManager.getContentRoots();
    final VirtualFile virtualRoot =
        existingFileRoot != null
            ? existingFileRoot
            : preferSourceRoot && fileIndex.isInSource(sourceFile)
                ? fileIndex.getSourceRootForFile(sourceFile)
                : fileIndex.isInContent(sourceFile)
                    ? fileIndex.getContentRootForFile(sourceFile)
                    : getFirstElement(
                        preferSourceRoot && sourceRoots.length > 0 ? sourceRoots : contentRoots);
    if (virtualRoot == null) {
      fail(project, sourceFile, "Unable to guess target source root");
      throw new ProcessCanceledException();
    }
    try {
      String genDirName = Options.GEN_DIR.get();
      boolean newGenRoot = !fileIndex.isInSourceContent(virtualRoot);
      final String relativePath =
          (hasPackage && newGenRoot
                  ? genDirName + "/" + targetPackage
                  : hasPackage ? targetPackage : newGenRoot ? genDirName : "")
              .replace('.', '/');
      if (relativePath.isEmpty()) {
        return virtualRoot;
      } else {
        VirtualFile result =
            new WriteAction<VirtualFile>() {
              @Override
              protected void run(@NotNull Result<VirtualFile> result) throws Throwable {
                result.setResult(VfsUtil.createDirectoryIfMissing(virtualRoot, relativePath));
              }
            }.execute().throwException().getResultObject();
        VfsUtil.markDirtyAndRefresh(false, true, true, result);
        return returnRoot && newGenRoot
            ? ObjectUtils.assertNotNull(virtualRoot.findChild(genDirName))
            : returnRoot ? virtualRoot : result;
      }
    } catch (ProcessCanceledException ex) {
      throw ex;
    } catch (Exception ex) {
      fail(project, sourceFile, ex.getMessage());
      throw new ProcessCanceledException();
    }
  }
  @NotNull
  private Set<PsiFile> getFilesForFastWordSearch() {
    String stringToFind = myFindModel.getStringToFind();
    if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) {
      return Collections.emptySet();
    }

    SearchScope customScope = myFindModel.getCustomScope();
    GlobalSearchScope scope =
        myPsiDirectory != null
            ? GlobalSearchScopesCore.directoryScope(myPsiDirectory, true)
            : myModule != null
                ? myModule.getModuleContentScope()
                : customScope instanceof GlobalSearchScope
                    ? (GlobalSearchScope) customScope
                    : toGlobal(customScope);
    if (scope == null) {
      scope = ProjectScope.getContentScope(myProject);
    }

    final Set<PsiFile> resultFiles = new LinkedHashSet<PsiFile>();

    if (TrigramIndex.ENABLED) {
      final Set<Integer> keys = ContainerUtil.newTroveSet();
      TrigramBuilder.processTrigrams(
          stringToFind,
          new TrigramBuilder.TrigramProcessor() {
            @Override
            public boolean execute(int value) {
              keys.add(value);
              return true;
            }
          });

      if (!keys.isEmpty()) {
        final List<VirtualFile> hits = new ArrayList<VirtualFile>();
        final GlobalSearchScope finalScope = scope;
        ApplicationManager.getApplication()
            .runReadAction(
                new Runnable() {
                  @Override
                  public void run() {
                    FileBasedIndex.getInstance()
                        .getFilesWithKey(
                            TrigramIndex.INDEX_ID,
                            keys,
                            new CommonProcessors.CollectProcessor<VirtualFile>(hits),
                            finalScope);
                  }
                });

        for (VirtualFile hit : hits) {
          if (myFileMask.value(hit)) {
            PsiFile file = findFile(hit);
            if (file != null) {
              resultFiles.add(file);
            }
          }
        }

        return resultFiles;
      }
    }

    PsiSearchHelperImpl helper =
        (PsiSearchHelperImpl) PsiSearchHelper.SERVICE.getInstance(myProject);
    helper.processFilesWithText(
        scope,
        UsageSearchContext.ANY,
        myFindModel.isCaseSensitive(),
        stringToFind,
        new Processor<VirtualFile>() {
          @Override
          public boolean process(VirtualFile file) {
            if (myFileMask.value(file)) {
              ContainerUtil.addIfNotNull(resultFiles, findFile(file));
            }
            return true;
          }
        });

    // in case our word splitting is incorrect
    CacheManager cacheManager = CacheManager.SERVICE.getInstance(myProject);
    PsiFile[] filesWithWord =
        cacheManager.getFilesWithWord(
            stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive());
    for (PsiFile file : filesWithWord) {
      if (myFileMask.value(file.getVirtualFile())) {
        resultFiles.add(file);
      }
    }

    return resultFiles;
  }
 public static List<VirtualFile> findFxmlsWithController(
     final Project project, @NotNull String className) {
   return findFxmlWithController(
       project, className, Function.ID, ProjectScope.getAllScope(project));
 }