@NotNull
  public static Collection<PsiFileSystemItem> getAbsoluteTopLevelDirLocations(
      final @NotNull PsiFile file) {

    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) {
      return Collections.emptyList();
    }
    final Project project = file.getProject();
    PsiDirectory parent = file.getParent();
    final Module module = ModuleUtil.findModuleForPsiElement(parent == null ? file : parent);
    if (module == null) {
      return Collections.emptyList();
    }
    final FileReferenceHelper[] helpers = FileReferenceHelperRegistrar.getHelpers();
    final ArrayList<PsiFileSystemItem> list = new ArrayList<PsiFileSystemItem>();
    for (FileReferenceHelper helper : helpers) {
      if (helper.isMine(project, virtualFile)) {
        final Collection<PsiFileSystemItem> roots = helper.getRoots(module);
        for (PsiFileSystemItem root : roots) {
          LOG.assertTrue(root != null, "Helper " + helper + " produced a null root for " + file);
        }
        list.addAll(roots);
      }
    }

    if (list.size() == 0) {
      list.addAll(FileReferenceHelperRegistrar.getNotNullHelper(file).getRoots(module));
    }
    return list;
  }
Exemplo n.º 2
0
 public static boolean filterEquals(ClassFilter[] filters1, ClassFilter[] filters2) {
   if (filters1.length != filters2.length) {
     return false;
   }
   final Set<ClassFilter> f1 =
       new HashSet<ClassFilter>(Math.max((int) (filters1.length / .75f) + 1, 16));
   final Set<ClassFilter> f2 =
       new HashSet<ClassFilter>(Math.max((int) (filters2.length / .75f) + 1, 16));
   Collections.addAll(f1, filters1);
   Collections.addAll(f2, filters2);
   return f2.equals(f1);
 }
 @Override
 public void loadState(Element state) {
   try {
     DefaultJDOMExternalizer.readExternal(this, state);
     if (myNullables.isEmpty()) {
       Collections.addAll(myNullables, DEFAULT_NULLABLES);
     }
     if (myNotNulls.isEmpty()) {
       Collections.addAll(myNotNulls, DEFAULT_NOT_NULLS);
     }
   } catch (InvalidDataException e) {
     LOG.error(e);
   }
 }
  @Nullable
  private static Map<PsiExpression, PsiType> buildDataflowTypeMap(PsiExpression forPlace) {
    PsiElement scope = DfaPsiUtil.getTopmostBlockInSameClass(forPlace);
    if (scope == null) {
      PsiFile file = forPlace.getContainingFile();
      if (!(file instanceof PsiCodeFragment)) {
        return Collections.emptyMap();
      }

      scope = file;
    }

    DataFlowRunner runner =
        new DataFlowRunner() {
          @NotNull
          @Override
          protected DfaMemoryState createMemoryState() {
            return new ExpressionTypeMemoryState(getFactory());
          }
        };

    final ExpressionTypeInstructionVisitor visitor = new ExpressionTypeInstructionVisitor(forPlace);
    if (runner.analyzeMethod(scope, visitor) == RunnerResult.OK) {
      return visitor.getResult();
    }
    return null;
  }
  @NotNull
  private static Set<PsiClassType> filterInProjectExceptions(
      @Nullable PsiMethod targetMethod, @NotNull List<PsiClassType> unhandledExceptions) {
    if (targetMethod == null) return Collections.emptySet();

    Set<PsiClassType> result = new HashSet<PsiClassType>();

    if (targetMethod.getManager().isInProject(targetMethod)) {
      PsiMethod[] superMethods = targetMethod.findSuperMethods();
      for (PsiMethod superMethod : superMethods) {
        Set<PsiClassType> classTypes = filterInProjectExceptions(superMethod, unhandledExceptions);
        result.addAll(classTypes);
      }

      if (superMethods.length == 0) {
        result.addAll(unhandledExceptions);
      }
    } else {
      PsiClassType[] referencedTypes = targetMethod.getThrowsList().getReferencedTypes();
      for (PsiClassType referencedType : referencedTypes) {
        PsiClass psiClass = referencedType.resolve();
        if (psiClass == null) continue;
        for (PsiClassType exception : unhandledExceptions) {
          if (referencedType.isAssignableFrom(exception)) result.add(exception);
        }
      }
    }

    return result;
  }
  private Collection<AbstractTreeNode> createGeneralList() {
    ArrayList<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();

    PsiFile psiFile = getValue();
    final TodoItem[] items =
        findAllTodos(psiFile, myBuilder.getTodoTreeStructure().getSearchHelper());
    final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);

    if (document != null) {
      for (final TodoItem todoItem : items) {
        if (todoItem.getTextRange().getEndOffset() < document.getTextLength() + 1) {
          final SmartTodoItemPointer pointer = new SmartTodoItemPointer(todoItem, document);
          TodoFilter todoFilter = getToDoFilter();
          if (todoFilter != null) {
            if (todoFilter.contains(todoItem.getPattern())) {
              children.add(new TodoItemNode(getProject(), pointer, myBuilder));
            }
          } else {
            children.add(new TodoItemNode(getProject(), pointer, myBuilder));
          }
        }
      }
    }
    Collections.sort(children, SmartTodoItemPointerComparator.ourInstance);
    return children;
  }
Exemplo n.º 7
0
  @NotNull
  private List<PsiMethod> changeReturnType(
      final PsiMethod method, @NotNull final PsiType returnType) {
    final PsiMethod[] methods = getChangeRoots(method, returnType);
    if (methods == null) {
      // canceled
      return Collections.emptyList();
    }

    final MethodSignatureChangeVisitor methodSignatureChangeVisitor =
        new MethodSignatureChangeVisitor();
    for (PsiMethod targetMethod : methods) {
      methodSignatureChangeVisitor.addBase(targetMethod);
      ChangeSignatureProcessor processor =
          new UsagesAwareChangeSignatureProcessor(
              method.getProject(),
              targetMethod,
              false,
              null,
              myName,
              returnType,
              RemoveUnusedParameterFix.getNewParametersInfo(targetMethod, null),
              methodSignatureChangeVisitor);
      processor.run();
    }

    return methodSignatureChangeVisitor.getAffectedMethods();
  }
  private ClassMapCachingNulls<MultiHostInjector> getInjectorMap() {
    ClassMapCachingNulls<MultiHostInjector> cached = cachedInjectors;
    if (cached != null) {
      return cached;
    }

    Map<Class, MultiHostInjector[]> injectors = ContainerUtil.newHashMap();

    List<MultiHostInjector> allInjectors = ContainerUtil.newArrayList();
    allInjectors.addAll(myManualInjectors);
    Collections.addAll(
        allInjectors, MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME.getExtensions(myProject));
    if (LanguageInjector.EXTENSION_POINT_NAME.getExtensions().length > 0) {
      allInjectors.add(PsiManagerRegisteredInjectorsAdapter.INSTANCE);
    }

    for (MultiHostInjector injector : allInjectors) {
      for (Class<? extends PsiElement> place : injector.elementsToInjectIn()) {
        LOG.assertTrue(place != null, injector);
        MultiHostInjector[] existing = injectors.get(place);
        injectors.put(
            place,
            existing == null
                ? new MultiHostInjector[] {injector}
                : ArrayUtil.append(existing, injector));
      }
    }

    ClassMapCachingNulls<MultiHostInjector> result =
        new ClassMapCachingNulls<>(injectors, new MultiHostInjector[0], allInjectors);
    cachedInjectors = result;
    return result;
  }
Exemplo n.º 9
0
 public String[] knownNamespaces() {
   final PsiElement parentElement = getParent();
   BidirectionalMap<String, String> map = initNamespaceMaps(parentElement);
   Set<String> known = Collections.emptySet();
   if (map != null) {
     known = new HashSet<String>(map.values());
   }
   if (parentElement instanceof XmlTag) {
     if (known.isEmpty()) return ((XmlTag) parentElement).knownNamespaces();
     ContainerUtil.addAll(known, ((XmlTag) parentElement).knownNamespaces());
   } else {
     XmlExtension xmlExtension = XmlExtension.getExtensionByElement(this);
     if (xmlExtension != null) {
       final XmlFile xmlFile = xmlExtension.getContainingFile(this);
       if (xmlFile != null) {
         final XmlTag rootTag = xmlFile.getRootTag();
         if (rootTag != null && rootTag != this) {
           if (known.isEmpty()) return rootTag.knownNamespaces();
           ContainerUtil.addAll(known, rootTag.knownNamespaces());
         }
       }
     }
   }
   return ArrayUtil.toStringArray(known);
 }
 @NotNull
 private static List<PsiMethod> findMethodsBySignature(
     @NotNull PsiClass aClass,
     @NotNull PsiMethod patternMethod,
     boolean checkBases,
     boolean stopOnFirst) {
   final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases);
   if (methodsByName.length == 0) return Collections.emptyList();
   final List<PsiMethod> methods = new SmartList<PsiMethod>();
   final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY);
   for (final PsiMethod method : methodsByName) {
     final PsiClass superClass = method.getContainingClass();
     final PsiSubstitutor substitutor;
     if (checkBases && !aClass.equals(superClass)) {
       substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY);
     } else {
       substitutor = PsiSubstitutor.EMPTY;
     }
     final MethodSignature signature = method.getSignature(substitutor);
     if (signature.equals(patternSignature)) {
       methods.add(method);
       if (stopOnFirst) {
         break;
       }
     }
   }
   return methods;
 }
Exemplo n.º 11
0
  private static List<FunctionDescriptor> getSuperFunctionsForMethod(
      @NotNull PsiMethodWrapper method,
      @NotNull BindingTrace trace,
      @NotNull ClassDescriptor containingClass) {
    List<FunctionDescriptor> superFunctions = Lists.newArrayList();

    Map<ClassDescriptor, JetType> superclassToSupertype =
        getSuperclassToSupertypeMap(containingClass);

    Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>> superclassToFunctions =
        getSuperclassToFunctionsMultimap(method, trace.getBindingContext(), containingClass);

    for (HierarchicalMethodSignature superSignature :
        method.getPsiMethod().getHierarchicalMethodSignature().getSuperSignatures()) {
      PsiMethod superMethod = superSignature.getMethod();

      PsiClass psiClass = superMethod.getContainingClass();
      assert psiClass != null;
      String classFqNameString = psiClass.getQualifiedName();
      assert classFqNameString != null;
      FqName classFqName = new FqName(classFqNameString);

      if (!JavaToKotlinClassMap.getInstance().mapPlatformClass(classFqName).isEmpty()) {
        for (FunctionDescriptor superFun :
            JavaToKotlinMethodMap.INSTANCE.getFunctions(superMethod, containingClass)) {
          superFunctions.add(substituteSuperFunction(superclassToSupertype, superFun));
        }
        continue;
      }

      DeclarationDescriptor superFun =
          superMethod instanceof JetClsMethod
              ? trace.get(
                  BindingContext.DECLARATION_TO_DESCRIPTOR,
                  ((JetClsMethod) superMethod).getOrigin())
              : findSuperFunction(superclassToFunctions.get(classFqName), superMethod);
      if (superFun == null) {
        reportCantFindSuperFunction(method);
        continue;
      }

      assert superFun instanceof FunctionDescriptor : superFun.getClass().getName();

      superFunctions.add(
          substituteSuperFunction(superclassToSupertype, (FunctionDescriptor) superFun));
    }

    // sorting for diagnostic stability
    Collections.sort(
        superFunctions,
        new Comparator<FunctionDescriptor>() {
          @Override
          public int compare(FunctionDescriptor fun1, FunctionDescriptor fun2) {
            FqNameUnsafe fqName1 = getFQName(fun1.getContainingDeclaration());
            FqNameUnsafe fqName2 = getFQName(fun2.getContainingDeclaration());
            return fqName1.getFqName().compareTo(fqName2.getFqName());
          }
        });
    return superFunctions;
  }
Exemplo n.º 12
0
  private static void logStats(Collection<PsiFile> otherFiles, long start) {
    long time = System.currentTimeMillis() - start;

    final Multiset<String> stats = HashMultiset.create();
    for (PsiFile file : otherFiles) {
      stats.add(
          StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension())
              .toLowerCase());
    }

    List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
    Collections.sort(
        extensions,
        new Comparator<String>() {
          @Override
          public int compare(String o1, String o2) {
            return stats.count(o2) - stats.count(o1);
          }
        });

    String message =
        "Search in "
            + otherFiles.size()
            + " files with unknown types took "
            + time
            + "ms.\n"
            + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n"
            + "Most frequent non-indexed file extensions: ";
    for (int i = 0; i < Math.min(10, extensions.size()); i++) {
      String extension = extensions.get(i);
      message += extension + "(" + stats.count(extension) + ") ";
    }
    LOG.info(message);
  }
  /**
   * Get array string values mapped with their PsiElements
   *
   * <p>["value", "value2"]
   */
  @NotNull
  public static Map<String, PsiElement> getArrayValuesAsMap(
      @NotNull ArrayCreationExpression arrayCreationExpression) {

    List<PsiElement> arrayValues =
        PhpPsiUtil.getChildren(
            arrayCreationExpression,
            new Condition<PsiElement>() {
              @Override
              public boolean value(PsiElement psiElement) {
                return psiElement.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE;
              }
            });

    if (arrayValues == null) {
      return Collections.emptyMap();
    }

    Map<String, PsiElement> keys = new HashMap<String, PsiElement>();
    for (PsiElement child : arrayValues) {
      String stringValue = PhpElementsUtil.getStringValue(child.getFirstChild());
      if (stringValue != null && StringUtils.isNotBlank(stringValue)) {
        keys.put(stringValue, child);
      }
    }

    return keys;
  }
 public static void findUsages(
     @NotNull FindModel findModel,
     @NotNull final Project project,
     @NotNull final Processor<UsageInfo> consumer,
     @NotNull FindUsagesProcessPresentation processPresentation) {
   findUsages(findModel, project, consumer, processPresentation, Collections.emptySet());
 }
Exemplo n.º 15
0
  /**
   * @param type
   * @param min
   * @param createDef
   * @param manager - must not be null if min is not null
   * @param scope - must not be null if min is not null
   */
  private GrTypeComboBox(
      @Nullable PsiType type,
      @Nullable PsiType min,
      boolean createDef,
      @Nullable PsiManager manager,
      @Nullable GlobalSearchScope scope) {
    LOG.assertTrue(min == null || manager != null);
    LOG.assertTrue(min == null || scope != null);

    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    Map<String, PsiType> types = Collections.emptyMap();
    if (type != null) {
      types = getCompatibleTypeNames(type, min, manager, scope);
    }

    if (createDef || types.isEmpty()) {
      addItem(new PsiTypeItem(null));
    }

    for (String typeName : types.keySet()) {
      addItem(new PsiTypeItem(types.get(typeName)));
    }

    if (createDef && getItemCount() > 1) {
      setSelectedIndex(1);
    }
  }
  public PostprocessReformattingAspect(
      Project project, PsiManager psiManager, TreeAspect treeAspect) {
    myProject = project;
    myPsiManager = psiManager;
    myTreeAspect = treeAspect;
    PomManager.getModel(psiManager.getProject())
        .registerAspect(
            PostprocessReformattingAspect.class,
            this,
            Collections.singleton((PomModelAspect) treeAspect));

    ApplicationListener applicationListener =
        new ApplicationAdapter() {
          public void writeActionStarted(final Object action) {
            final CommandProcessor processor = CommandProcessor.getInstance();
            if (processor != null) {
              final Project project = processor.getCurrentCommandProject();
              if (project == myProject) {
                myPostponedCounter++;
              }
            }
          }

          public void writeActionFinished(final Object action) {
            final CommandProcessor processor = CommandProcessor.getInstance();
            if (processor != null) {
              final Project project = processor.getCurrentCommandProject();
              if (project == myProject) {
                decrementPostponedCounter();
              }
            }
          }
        };
    ApplicationManager.getApplication().addApplicationListener(applicationListener, this);
  }
  public void doClone(PsiElement element) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
    PsiClass[] classes = getTopLevelClasses(element);
    if (classes == null) {
      CopyFilesOrDirectoriesHandler.doCloneFile(element);
      return;
    }
    Project project = element.getProject();

    CopyClassDialog dialog = new CopyClassDialog(classes[0], null, project, true);
    dialog.setTitle(RefactoringBundle.message("copy.handler.clone.class"));
    dialog.show();
    if (dialog.isOK()) {
      String className = dialog.getClassName();
      PsiDirectory targetDirectory = element.getContainingFile().getContainingDirectory();
      copyClassesImpl(
          className,
          project,
          Collections.singletonMap(classes[0].getContainingFile(), classes),
          null,
          targetDirectory,
          targetDirectory,
          RefactoringBundle.message("copy.handler.clone.class"),
          true,
          true);
    }
  }
  @NotNull
  public Collection<PsiFileSystemItem> computeDefaultContexts() {
    final PsiFile file = getContainingFile();
    if (file == null) return Collections.emptyList();

    if (myOptions != null) {
      final Function<PsiFile, Collection<PsiFileSystemItem>> value =
          DEFAULT_PATH_EVALUATOR_OPTION.getValue(myOptions);

      if (value != null) {
        final Collection<PsiFileSystemItem> roots = value.fun(file);
        if (roots != null) {
          for (PsiFileSystemItem root : roots) {
            if (root == null) {
              LOG.error("Default path evaluator " + value + " produced a null root for " + file);
            }
          }
          return roots;
        }
      }
    }
    if (isAbsolutePathReference()) {
      return getAbsoluteTopLevelDirLocations(file);
    }

    return getContextByFile(file);
  }
  private List<HighlightInfo> getHighlights() {
    if (myReadAccessRanges.isEmpty() && myWriteAccessRanges.isEmpty()) {
      return Collections.emptyList();
    }
    Set<Pair<Object, TextRange>> existingMarkupTooltips = new HashSet<Pair<Object, TextRange>>();
    for (RangeHighlighter highlighter : myEditor.getMarkupModel().getAllHighlighters()) {
      existingMarkupTooltips.add(
          Pair.create(
              highlighter.getErrorStripeTooltip(),
              new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset())));
    }

    List<HighlightInfo> result =
        new ArrayList<HighlightInfo>(myReadAccessRanges.size() + myWriteAccessRanges.size());
    for (TextRange range : myReadAccessRanges) {
      ContainerUtil.addIfNotNull(
          createHighlightInfo(
              range, HighlightInfoType.ELEMENT_UNDER_CARET_READ, existingMarkupTooltips),
          result);
    }
    for (TextRange range : myWriteAccessRanges) {
      ContainerUtil.addIfNotNull(
          createHighlightInfo(
              range, HighlightInfoType.ELEMENT_UNDER_CARET_WRITE, existingMarkupTooltips),
          result);
    }
    return result;
  }
Exemplo n.º 20
0
  @Nullable
  private Collection<DfaMemoryState> createInitialStates(
      @NotNull PsiElement psiBlock, @NotNull InstructionVisitor visitor) {
    PsiElement container =
        PsiTreeUtil.getParentOfType(psiBlock, PsiClass.class, PsiLambdaExpression.class);
    if (container != null
        && (!(container instanceof PsiClass)
            || PsiUtil.isLocalOrAnonymousClass((PsiClass) container))) {
      final PsiElement parent = container.getParent();
      final PsiCodeBlock block = DfaPsiUtil.getTopmostBlockInSameClass(parent);
      if (block != null) {
        final RunnerResult result = analyzeMethod(block, visitor);
        if (result == RunnerResult.OK) {
          final Collection<DfaMemoryState> closureStates =
              myNestedClosures.get(DfaPsiUtil.getTopmostBlockInSameClass(psiBlock));
          if (!closureStates.isEmpty()) {
            return closureStates;
          }
        }
        return null;
      }
    }

    return Collections.singletonList(createMemoryState());
  }
 /**
  * intersection may spread over several injected fragments
  *
  * @param rangeToEdit range in encoded(raw) PSI
  * @return list of ranges in encoded (raw) PSI
  */
 @Override
 @SuppressWarnings({"ConstantConditions", "unchecked"})
 @NotNull
 public List<TextRange> intersectWithAllEditableFragments(
     @NotNull PsiFile injectedPsi, @NotNull TextRange rangeToEdit) {
   Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
   if (shreds == null) return Collections.emptyList();
   Object result = null; // optimization: TextRange or ArrayList
   int count = 0;
   int offset = 0;
   for (PsiLanguageInjectionHost.Shred shred : shreds) {
     TextRange encodedRange =
         TextRange.from(
             offset + shred.getPrefix().length(), shred.getRangeInsideHost().getLength());
     TextRange intersection = encodedRange.intersection(rangeToEdit);
     if (intersection != null) {
       count++;
       if (count == 1) {
         result = intersection;
       } else if (count == 2) {
         TextRange range = (TextRange) result;
         if (range.isEmpty()) {
           result = intersection;
           count = 1;
         } else if (intersection.isEmpty()) {
           count = 1;
         } else {
           List<TextRange> list = new ArrayList<TextRange>();
           list.add(range);
           list.add(intersection);
           result = list;
         }
       } else if (intersection.isEmpty()) {
         count--;
       } else {
         ((List<TextRange>) result).add(intersection);
       }
     }
     offset +=
         shred.getPrefix().length()
             + shred.getRangeInsideHost().getLength()
             + shred.getSuffix().length();
   }
   return count == 0
       ? Collections.<TextRange>emptyList()
       : count == 1 ? Collections.singletonList((TextRange) result) : (List<TextRange>) result;
 }
 public Collection<String> getAdditionalAnnotations() {
   List<String> annos = ADDITIONAL_ANNOS;
   if (annos == null) {
     annos = new ArrayList<String>();
     Collections.addAll(annos, STANDARD_ANNOS);
     final EntryPoint[] extensions =
         Extensions.getExtensions(ToolExtensionPoints.DEAD_CODE_TOOL, null);
     for (EntryPoint extension : extensions) {
       final String[] ignoredAnnotations = extension.getIgnoreAnnotations();
       if (ignoredAnnotations != null) {
         ContainerUtil.addAll(annos, ignoredAnnotations);
       }
     }
     ADDITIONAL_ANNOS = annos = Collections.unmodifiableList(annos);
   }
   return annos;
 }
 @Nullable
 public static List<? extends PsiElement> getAllPsiElements(final LookupElement item) {
   List<PsiMethod> allMethods = getAllMethods(item);
   if (allMethods != null) return allMethods;
   if (item.getObject() instanceof PsiElement)
     return Collections.singletonList((PsiElement) item.getObject());
   return null;
 }
  public static List<Match> hasDuplicates(final PsiFile file, final PsiMember member) {
    final DuplicatesFinder duplicatesFinder = createDuplicatesFinder(member);
    if (duplicatesFinder == null) {
      return Collections.emptyList();
    }

    return duplicatesFinder.findDuplicates(file);
  }
  public Collection<PsiElement> getAdditionalElementsToDelete(
      @NotNull final PsiElement element,
      @NotNull final Collection<PsiElement> allElementsToDelete,
      final boolean askUser) {
    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      final Project project = element.getProject();
      String propertyName =
          JavaCodeStyleManager.getInstance(project)
              .variableNameToPropertyName(field.getName(), VariableKind.FIELD);

      PsiClass aClass = field.getContainingClass();
      if (aClass != null) {
        boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
        PsiMethod[] getters =
            GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);
        if (getters != null) {
          final List<PsiMethod> validGetters = new ArrayList<>(1);
          for (PsiMethod getter : getters) {
            if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) {
              validGetters.add(getter);
            }
          }
          getters =
              validGetters.isEmpty()
                  ? null
                  : validGetters.toArray(new PsiMethod[validGetters.size()]);
        }

        PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);
        if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical())
          setter = null;
        if (askUser && (getters != null || setter != null)) {
          final String message =
              RefactoringMessageUtil.getGetterSetterMessage(
                  field.getName(),
                  RefactoringBundle.message("delete.title"),
                  getters != null ? getters[0] : null,
                  setter);
          if (!ApplicationManager.getApplication().isUnitTestMode()
              && Messages.showYesNoDialog(
                      project,
                      message,
                      RefactoringBundle.message("safe.delete.title"),
                      Messages.getQuestionIcon())
                  != Messages.YES) {
            getters = null;
            setter = null;
          }
        }
        List<PsiElement> elements = new ArrayList<>();
        if (setter != null) elements.add(setter);
        if (getters != null) Collections.addAll(elements, getters);
        return elements;
      }
    }
    return null;
  }
  private boolean processFilesConcurrently(
      @NotNull Set<VirtualFile> files,
      @NotNull final ProgressIndicator indicator,
      @NotNull final Processor<VirtualFile> processor) {
    final List<VirtualFile> fileList = new ArrayList<VirtualFile>(files);
    // fine but grabs all CPUs
    // return JobLauncher.getInstance().invokeConcurrentlyUnderProgress(fileList, indicator, false,
    // false, processor);

    int parallelism = CacheUpdateRunner.indexingThreadCount();
    final Callable<Boolean> processFileFromSet =
        () -> {
          final boolean[] result = {true};
          ProgressManager.getInstance()
              .executeProcessUnderProgress(
                  () -> {
                    while (true) {
                      ProgressManager.checkCanceled();
                      VirtualFile file;
                      synchronized (fileList) {
                        file = fileList.isEmpty() ? null : fileList.remove(fileList.size() - 1);
                      }
                      if (file == null) {
                        break;
                      }
                      if (!processor.process(file)) {
                        result[0] = false;
                        break;
                      }
                    }
                  },
                  indicator);
          return result[0];
        };
    List<Future<Boolean>> futures =
        ContainerUtil.map(
            Collections.nCopies(parallelism, ""),
            s -> myApplication.executeOnPooledThread(processFileFromSet));

    List<Boolean> results =
        ContainerUtil.map(
            futures,
            future -> {
              try {
                return future.get();
              } catch (Exception e) {
                LOG.error(e);
              }
              return false;
            });

    return !ContainerUtil.exists(
        results,
        result -> {
          return result != null && !result; // null means PCE
        });
  }
 @Override
 public void doApplyInformationToEditor() {
   final boolean virtSpace =
       TargetElementUtil.inVirtualSpace(myEditor, myEditor.getCaretModel().getOffset());
   final List<HighlightInfo> infos =
       virtSpace ? Collections.<HighlightInfo>emptyList() : getHighlights();
   UpdateHighlightersUtil.setHighlightersToEditor(
       myProject, myDocument, 0, myFile.getTextLength(), infos, getColorsScheme(), getId());
 }
 @NotNull
 private Collection<DefaultMutableTreeNode> getSelectedNodes() {
   if (!isValid()) {
     return Collections.emptyList();
   }
   JTree tree = myStructureViewComponent.getTree();
   if (tree == null) return Collections.emptyList();
   TreePath[] selected = tree.getSelectionModel().getSelectionPaths();
   if (selected == null || selected.length == 0) return Collections.emptyList();
   return ContainerUtil.map(
       selected,
       new Function<TreePath, DefaultMutableTreeNode>() {
         @Override
         public DefaultMutableTreeNode fun(TreePath treePath) {
           return (DefaultMutableTreeNode) treePath.getLastPathComponent();
         }
       });
 }
Exemplo n.º 29
0
  private static void createValueRootNode(
      NullAnalysisResult result,
      SliceRootNode oldRoot,
      final Map<SliceNode, NullAnalysisResult> map,
      SliceRootNode root,
      SliceNode oldRootStart,
      String nodeName,
      final int group) {
    Collection<PsiElement> groupedByValue = result.groupedByValue[group];
    if (groupedByValue.isEmpty()) {
      return;
    }
    SliceLeafValueClassNode valueRoot =
        new SliceLeafValueClassNode(root.getProject(), root, nodeName);
    root.myCachedChildren.add(valueRoot);

    Set<PsiElement> uniqueValues =
        new THashSet<PsiElement>(groupedByValue, SliceLeafAnalyzer.LEAF_ELEMENT_EQUALITY);
    for (final PsiElement expression : uniqueValues) {
      SliceNode newRoot =
          SliceLeafAnalyzer.filterTree(
              oldRootStart,
              new NullableFunction<SliceNode, SliceNode>() {
                @Override
                public SliceNode fun(SliceNode oldNode) {
                  if (oldNode.getDuplicate() != null) {
                    return null;
                  }

                  for (PsiElement nullSuspect : group(oldNode, map, group)) {
                    if (PsiEquivalenceUtil.areElementsEquivalent(nullSuspect, expression)) {
                      return oldNode.copy();
                    }
                  }
                  return null;
                }
              },
              new PairProcessor<SliceNode, List<SliceNode>>() {
                @Override
                public boolean process(SliceNode node, List<SliceNode> children) {
                  if (!children.isEmpty()) return true;
                  PsiElement element = node.getValue().getElement();
                  if (element == null) return false;
                  return PsiEquivalenceUtil.areElementsEquivalent(
                      element, expression); // leaf can be there only if it's filtering expression
                }
              });
      valueRoot.myCachedChildren.add(
          new SliceLeafValueRootNode(
              root.getProject(),
              expression,
              valueRoot,
              Collections.singletonList(newRoot),
              oldRoot.getValue().params));
    }
  }
  private static List<PsiElement> getTopLevelRegExpChars(String regExpText, Project project) {
    @SuppressWarnings("deprecation")
    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText("A.regexp", regExpText);
    List<PsiElement> result = null;
    final PsiElement[] children = file.getChildren();

    for (PsiElement child : children) {
      PsiElement[] grandChildren = child.getChildren();
      if (grandChildren.length != 1)
        return Collections
            .emptyList(); // a | b, more than one branch, can not predict in current way

      for (PsiElement grandGrandChild : grandChildren[0].getChildren()) {
        if (result == null) result = new ArrayList<>();
        result.add(grandGrandChild);
      }
    }
    return result != null ? result : Collections.<PsiElement>emptyList();
  }