private Variance calculateArgumentProjectionKindFromSuper(
      @NotNull TypeProjection argument,
      @NotNull List<TypeProjectionAndVariance> projectionsFromSuper) {
    Set<Variance> projectionKindsInSuper = Sets.newLinkedHashSet();
    for (TypeProjectionAndVariance projectionAndVariance : projectionsFromSuper) {
      projectionKindsInSuper.add(projectionAndVariance.typeProjection.getProjectionKind());
    }

    Variance defaultProjectionKind = argument.getProjectionKind();
    if (projectionKindsInSuper.size() == 0) {
      return defaultProjectionKind;
    } else if (projectionKindsInSuper.size() == 1) {
      Variance projectionKindInSuper = projectionKindsInSuper.iterator().next();
      if (defaultProjectionKind == INVARIANT || defaultProjectionKind == projectionKindInSuper) {
        return projectionKindInSuper;
      } else {
        reportError(
            "Incompatible projection kinds in type arguments of super methods' return types: "
                + projectionsFromSuper
                + ", defined in current: "
                + argument);
        return defaultProjectionKind;
      }
    } else {
      reportError(
          "Incompatible projection kinds in type arguments of super methods' return types: "
              + projectionsFromSuper);
      return defaultProjectionKind;
    }
  }
 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);
 }
Example #3
0
  protected void addLookupItem(
      Set<LookupElement> set,
      TailType tailType,
      @NotNull Object completion,
      final PsiFile file,
      final CompletionVariant variant) {
    LookupElement ret = objectToLookupItem(completion);
    if (ret == null) return;
    if (!(ret instanceof LookupItem)) {
      set.add(ret);
      return;
    }

    LookupItem item = (LookupItem) ret;

    final InsertHandler insertHandler = variant.getInsertHandler();
    if (insertHandler != null && item.getInsertHandler() == null) {
      item.setInsertHandler(insertHandler);
      item.setTailType(TailType.UNKNOWN);
    } else if (tailType != TailType.NONE) {
      item.setTailType(tailType);
    }
    final Map<Object, Object> itemProperties = variant.getItemProperties();
    for (final Object key : itemProperties.keySet()) {
      item.setAttribute(key, itemProperties.get(key));
    }

    set.add(ret);
  }
 private void handleBranchingInstruction(
     ProblemsHolder holder,
     StandardInstructionVisitor visitor,
     Set<Instruction> trueSet,
     Set<Instruction> falseSet,
     HashSet<PsiElement> reportedAnchors,
     BranchingInstruction instruction,
     final boolean onTheFly) {
   PsiElement psiAnchor = instruction.getPsiAnchor();
   boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor);
   if (instruction instanceof InstanceofInstruction
       && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) {
     if (visitor.canBeNull((BinopInstruction) instruction)) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message("dataflow.message.redundant.instanceof"),
           new RedundantInstanceofFix());
     } else {
       final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true);
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(true)),
           localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix});
     }
   } else if (psiAnchor instanceof PsiSwitchLabelStatement) {
     if (falseSet.contains(instruction)) {
       holder.registerProblem(
           psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label"));
     }
   } else if (psiAnchor != null
       && !reportedAnchors.contains(psiAnchor)
       && !isFlagCheck(psiAnchor)) {
     boolean evaluatesToTrue = trueSet.contains(instruction);
     final PsiElement parent = psiAnchor.getParent();
     if (parent instanceof PsiAssignmentExpression
         && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               "dataflow.message.pointless.assignment.expression",
               Boolean.toString(evaluatesToTrue)),
           createConditionalAssignmentFixes(
               evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly));
     } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) {
       final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue);
       String message =
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(evaluatesToTrue));
       holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix});
     }
     reportedAnchors.add(psiAnchor);
   }
 }
 public void readExternal(final Element element) throws InvalidDataException {
   PathMacroManager.getInstance(getProject()).expandPaths(element);
   super.readExternal(element);
   JavaRunConfigurationExtensionManager.getInstance().readExternal(this, element);
   readModule(element);
   DefaultJDOMExternalizer.readExternal(this, element);
   DefaultJDOMExternalizer.readExternal(getPersistentData(), element);
   EnvironmentVariablesComponent.readExternal(element, getPersistentData().getEnvs());
   final Element patternsElement = element.getChild(PATTERNS_EL_NAME);
   if (patternsElement != null) {
     final Set<String> tests = new LinkedHashSet<String>();
     for (Object o : patternsElement.getChildren(PATTERN_EL_NAME)) {
       Element patternElement = (Element) o;
       tests.add(patternElement.getAttributeValue(TEST_CLASS_ATT_NAME));
     }
     myData.setPatterns(tests);
   }
   final Element forkModeElement = element.getChild("fork_mode");
   if (forkModeElement != null) {
     final String mode = forkModeElement.getAttributeValue("value");
     if (mode != null) {
       setForkMode(mode);
     }
   }
   final Element dirNameElement = element.getChild("dir");
   if (dirNameElement != null) {
     final String dirName = dirNameElement.getAttributeValue("value");
     getPersistentData().setDirName(FileUtil.toSystemDependentName(dirName));
   }
 }
    public String getGeneratedName(final JavaRunConfigurationModule configurationModule) {
      if (TEST_PACKAGE.equals(TEST_OBJECT) || TEST_DIRECTORY.equals(TEST_OBJECT)) {
        final String moduleName =
            TEST_SEARCH_SCOPE.getScope() == TestSearchScope.WHOLE_PROJECT
                ? ""
                : configurationModule.getModuleName();
        final String packageName = getPackageName();
        if (packageName.length() == 0) {
          if (moduleName.length() > 0) {
            return ExecutionBundle.message("default.junit.config.name.all.in.module", moduleName);
          }
          return DEFAULT_PACKAGE_NAME;
        }
        if (moduleName.length() > 0) {
          return ExecutionBundle.message(
              "default.junit.config.name.all.in.package.in.module", packageName, moduleName);
        }
        return packageName;
      }
      if (TEST_PATTERN.equals(TEST_OBJECT)) {
        final int size = myPattern.size();
        if (size == 0) return "Temp suite";
        return StringUtil.getShortName(myPattern.iterator().next())
            + (size > 1 ? " and " + (size - 1) + " more" : "");
      }
      final String className =
          JavaExecutionUtil.getPresentableClassName(getMainClassName(), configurationModule);
      if (TEST_METHOD.equals(TEST_OBJECT)) {
        return className + '.' + getMethodName();
      }

      return className;
    }
  private static void reportOptionalOfNullableImprovements(
      ProblemsHolder holder, Set<PsiElement> reportedAnchors, Instruction[] instructions) {
    for (Instruction instruction : instructions) {
      if (instruction instanceof MethodCallInstruction) {
        final PsiExpression[] args = ((MethodCallInstruction) instruction).getArgs();
        if (args.length != 1) continue;

        final PsiExpression expr = args[0];

        if (((MethodCallInstruction) instruction).isOptionalAlwaysNullProblem()) {
          if (!reportedAnchors.add(expr)) continue;
          holder.registerProblem(
              expr,
              "Passing <code>null</code> argument to <code>Optional</code>",
              DfaOptionalSupport.createReplaceOptionalOfNullableWithEmptyFix(expr));
        } else if (((MethodCallInstruction) instruction).isOptionalAlwaysNotNullProblem()) {
          if (!reportedAnchors.add(expr)) continue;
          holder.registerProblem(
              expr,
              "Passing a non-null argument to <code>Optional</code>",
              DfaOptionalSupport.createReplaceOptionalOfNullableWithOfFix());
        }
      }
    }
  }
 public void bePatternConfiguration(List<PsiClass> classes, PsiMethod method) {
   myData.TEST_OBJECT = TEST_PATTERN;
   final Set<String> patterns = new HashSet<String>();
   final String methodSufiix;
   if (method != null) {
     myData.METHOD_NAME = method.getName();
     methodSufiix = "," + myData.METHOD_NAME;
   } else {
     methodSufiix = "";
   }
   for (PsiClass pattern : classes) {
     patterns.add(JavaExecutionUtil.getRuntimeQualifiedName(pattern) + methodSufiix);
   }
   myData.setPatterns(patterns);
   final Module module =
       PatternConfigurationProducer.findModule(
           this, getConfigurationModule().getModule(), patterns);
   if (module == null) {
     myData.setScope(TestSearchScope.WHOLE_PROJECT);
     setModule(null);
   } else {
     setModule(module);
   }
   setGeneratedName();
 }
  /**
   * Find a string return value of a method context "function() { return 'foo'}" First match wins
   */
  @Nullable
  public static String getMethodReturnAsString(
      @NotNull PhpClass phpClass, @NotNull String methodName) {

    Method method = phpClass.findMethodByName(methodName);
    if (method == null) {
      return null;
    }

    final Set<String> values = new HashSet<String>();
    method.acceptChildren(
        new PsiRecursiveElementWalkingVisitor() {
          @Override
          public void visitElement(PsiElement element) {

            if (PhpElementsUtil.getMethodReturnPattern().accepts(element)) {
              String value = PhpElementsUtil.getStringValue(element);
              if (value != null && StringUtils.isNotBlank(value)) {
                values.add(value);
              }
            }

            super.visitElement(element);
          }
        });

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

    // we support only first item
    return values.iterator().next();
  }
Example #10
0
    @Override
    public void consume(Object o) {
      if (!(o instanceof GroovyResolveResult)) {
        LOG.error(o);
        return;
      }

      GroovyResolveResult result = (GroovyResolveResult) o;
      if (!result.isStaticsOK()) {
        if (myInapplicable == null) myInapplicable = ContainerUtil.newArrayList();
        myInapplicable.add(result);
        return;
      }
      if (!result.isAccessible() && myParameters.getInvocationCount() < 2) return;

      if (mySkipPackages && result.getElement() instanceof PsiPackage) return;

      PsiElement element = result.getElement();
      if (element instanceof PsiVariable
          && !myMatcher.prefixMatches(((PsiVariable) element).getName())) {
        return;
      }

      if (element instanceof GrReflectedMethod) {
        element = ((GrReflectedMethod) element).getBaseMethod();
        if (!myProcessedMethodWithOptionalParams.add((GrMethod) element)) return;

        result =
            new GroovyResolveResultImpl(
                element,
                result.getCurrentFileResolveContext(),
                result.getSpreadState(),
                result.getSubstitutor(),
                result.isAccessible(),
                result.isStaticsOK(),
                result.isInvokedOnProperty(),
                result.isValidResult());
      }

      if (myFieldPointerOperator && !(element instanceof PsiVariable)) {
        return;
      }
      if (myMethodPointerOperator && !(element instanceof PsiMethod)) {
        return;
      }
      addCandidate(result);

      if (!myFieldPointerOperator && !myMethodPointerOperator) {
        if (element instanceof PsiMethod) {
          processProperty((PsiMethod) element, result);
        } else if (element instanceof GrField) {
          if (((GrField) element).isProperty()) {
            processPropertyFromField((GrField) element, result);
          }
        }
      }
      if (element instanceof GrVariable && !(element instanceof GrField)) {
        myLocalVars.add(((GrVariable) element).getName());
      }
    }
  private static PsiSubstitutor obtainFinalSubstitutor(
      PsiClass superClass,
      PsiSubstitutor superSubstitutor,
      PsiSubstitutor derivedSubstitutor,
      boolean inRawContext) {
    if (inRawContext) {
      Set<PsiTypeParameter> typeParams = superSubstitutor.getSubstitutionMap().keySet();
      PsiElementFactory factory = JavaPsiFacade.getElementFactory(superClass.getProject());
      superSubstitutor =
          factory.createRawSubstitutor(
              derivedSubstitutor, typeParams.toArray(new PsiTypeParameter[typeParams.size()]));
    }
    Map<PsiTypeParameter, PsiType> map = null;
    for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(superClass)) {
      PsiType type = superSubstitutor.substitute(typeParameter);
      final PsiType t = derivedSubstitutor.substitute(type);
      if (map == null) {
        map = new THashMap<PsiTypeParameter, PsiType>();
      }
      map.put(typeParameter, t);
    }

    return map == null
        ? PsiSubstitutor.EMPTY
        : JavaPsiFacade.getInstance(superClass.getProject())
            .getElementFactory()
            .createSubstitutor(map);
  }
Example #12
0
 @Override
 public DfaInstructionState[] visitPush(
     PushInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
   if (myContext == instruction.getPlace()) {
     final Map<DfaVariableValue, DfaVariableState> map =
         ((ValuableDataFlowRunner.MyDfaMemoryState) memState).getVariableStates();
     for (Map.Entry<DfaVariableValue, DfaVariableState> entry : map.entrySet()) {
       ValuableDataFlowRunner.ValuableDfaVariableState state =
           (ValuableDataFlowRunner.ValuableDfaVariableState) entry.getValue();
       DfaVariableValue variableValue = entry.getKey();
       final PsiExpression psiExpression = state.myExpression;
       if (psiExpression != null && variableValue.getQualifier() == null) {
         myValues.put(variableValue.getPsiVariable(), psiExpression);
       }
     }
     DfaValue value = instruction.getValue();
     if (value instanceof DfaVariableValue
         && ((DfaVariableValue) value).getQualifier() == null) {
       if (memState.isNotNull((DfaVariableValue) value)) {
         myNotNulls.add(((DfaVariableValue) value).getPsiVariable());
       }
       if (memState.isNull(value)) {
         myNulls.add(((DfaVariableValue) value).getPsiVariable());
       }
     }
   }
   return super.visitPush(instruction, runner, memState);
 }
  public Set<InferenceVariable> getDependencies(InferenceSession session) {
    final Set<InferenceVariable> dependencies = new LinkedHashSet<InferenceVariable>();
    for (List<PsiType> boundTypes : myBounds.values()) {
      if (boundTypes != null) {
        for (PsiType bound : boundTypes) {
          session.collectDependencies(bound, dependencies);
        }
      }
    }

    if (!session.hasCapture(this) && dependencies.isEmpty()) {
      return dependencies;
    }

    if (!session.hasCapture(this)) {
      return dependencies;
    }

    for (Iterator<InferenceVariable> iterator = dependencies.iterator(); iterator.hasNext(); ) {
      if (!session.hasCapture(iterator.next())) {
        iterator.remove();
      }
    }
    session.collectCaptureDependencies(this, dependencies);
    return dependencies;
  }
  @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;
  }
 /** @return were javadoc params used */
 public static void collectAnnotationValues(
     final Map<String, Collection<String>> results, PsiMethod[] psiMethods, PsiClass... classes) {
   final Set<String> test = new HashSet<>(1);
   test.add(TEST_ANNOTATION_FQN);
   ContainerUtil.addAll(test, CONFIG_ANNOTATIONS_FQN);
   if (psiMethods != null) {
     for (final PsiMethod psiMethod : psiMethods) {
       ApplicationManager.getApplication()
           .runReadAction(
               () ->
                   appendAnnotationAttributeValues(
                       results, AnnotationUtil.findAnnotation(psiMethod, test), psiMethod));
     }
   } else {
     for (final PsiClass psiClass : classes) {
       ApplicationManager.getApplication()
           .runReadAction(
               () -> {
                 if (psiClass != null && hasTest(psiClass)) {
                   appendAnnotationAttributeValues(
                       results, AnnotationUtil.findAnnotation(psiClass, test), psiClass);
                   PsiMethod[] methods = psiClass.getMethods();
                   for (PsiMethod method : methods) {
                     if (method != null) {
                       appendAnnotationAttributeValues(
                           results, AnnotationUtil.findAnnotation(method, test), method);
                     }
                   }
                 }
               });
     }
   }
 }
Example #16
0
  // TODO: Make it work for properties
  public Collection<DeclarationDescriptor> getJetCallableExtensions(
      @NotNull Condition<String> acceptedNameCondition,
      @NotNull JetSimpleNameExpression expression,
      @NotNull ResolveSession resolveSession,
      @NotNull GlobalSearchScope searchScope) {
    Collection<DeclarationDescriptor> resultDescriptors = new ArrayList<DeclarationDescriptor>();

    BindingContext context = ResolveSessionUtils.resolveToExpression(resolveSession, expression);
    JetExpression receiverExpression = expression.getReceiverExpression();

    if (receiverExpression != null) {
      JetType expressionType = context.get(BindingContext.EXPRESSION_TYPE, receiverExpression);
      JetScope scope = context.get(BindingContext.RESOLUTION_SCOPE, receiverExpression);

      if (expressionType != null && scope != null) {
        Collection<String> extensionFunctionsNames = getAllJetExtensionFunctionsNames(searchScope);

        Set<FqName> functionFQNs = new java.util.HashSet<FqName>();

        // Collect all possible extension function qualified names
        for (String name : extensionFunctionsNames) {
          if (acceptedNameCondition.value(name)) {
            Collection<PsiElement> extensionFunctions =
                getJetExtensionFunctionsByName(name, searchScope);

            for (PsiElement extensionFunction : extensionFunctions) {
              if (extensionFunction instanceof JetNamedFunction) {
                functionFQNs.add(JetPsiUtil.getFQName((JetNamedFunction) extensionFunction));
              } else if (extensionFunction instanceof PsiMethod) {
                FqName functionFQN =
                    JetFromJavaDescriptorHelper.getJetTopLevelDeclarationFQN(
                        (PsiMethod) extensionFunction);
                if (functionFQN != null) {
                  functionFQNs.add(functionFQN);
                }
              }
            }
          }
        }

        // Iterate through the function with attempt to resolve found functions
        for (FqName functionFQN : functionFQNs) {
          for (CallableDescriptor functionDescriptor :
              ExpressionTypingUtils.canFindSuitableCall(
                  functionFQN,
                  project,
                  receiverExpression,
                  expressionType,
                  scope,
                  resolveSession.getModuleConfiguration())) {

            resultDescriptors.add(functionDescriptor);
          }
        }
      }
    }

    return resultDescriptors;
  }
  /**
   * Filter the specified collection of classes to return only ones that contain any of the
   * specified values in the specified annotation parameter. For example, this method can be used to
   * return all classes that contain all tesng annotations that are in the groups 'foo' or 'bar'.
   */
  public static Map<PsiClass, Collection<PsiMethod>> filterAnnotations(
      String parameter, Set<String> values, Collection<PsiClass> classes) {
    Map<PsiClass, Collection<PsiMethod>> results = new HashMap<>();
    Set<String> test = new HashSet<>(1);
    test.add(TEST_ANNOTATION_FQN);
    ContainerUtil.addAll(test, CONFIG_ANNOTATIONS_FQN);
    for (PsiClass psiClass : classes) {
      if (isBrokenPsiClass(psiClass)) continue;

      PsiAnnotation annotation;
      try {
        annotation = AnnotationUtil.findAnnotation(psiClass, test);
      } catch (Exception e) {
        LOGGER.error(
            "Exception trying to findAnnotation on "
                + psiClass.getClass().getName()
                + ".\n\n"
                + e.getMessage());
        annotation = null;
      }
      if (annotation != null) {
        if (isAnnotatedWithParameter(annotation, parameter, values)) {
          results.put(psiClass, new LinkedHashSet<>());
        }
      } else {
        Collection<String> matches =
            extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter);
        for (String s : matches) {
          if (values.contains(s)) {
            results.put(psiClass, new LinkedHashSet<>());
            break;
          }
        }
      }

      // we already have the class, no need to look through its methods
      PsiMethod[] methods = psiClass.getMethods();
      for (PsiMethod method : methods) {
        if (method != null) {
          annotation = AnnotationUtil.findAnnotation(method, test);
          if (annotation != null) {
            if (isAnnotatedWithParameter(annotation, parameter, values)) {
              if (results.get(psiClass) == null) results.put(psiClass, new LinkedHashSet<>());
              results.get(psiClass).add(method);
            }
          } else {
            Collection<String> matches =
                extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter);
            for (String s : matches) {
              if (values.contains(s)) {
                results.get(psiClass).add(method);
              }
            }
          }
        }
      }
    }
    return results;
  }
 @Override
 @NotNull
 public Document[] getUncommittedDocuments() {
   ApplicationManager.getApplication().assertIsDispatchThread();
   Document[] documents =
       myUncommittedDocuments.toArray(new Document[myUncommittedDocuments.size()]);
   return ArrayUtil.stripTrailingNulls(documents);
 }
 @NotNull
 private static GlobalSearchScope forDirectory(
     @NotNull Project project, boolean withSubdirectories, @NotNull VirtualFile directory) {
   Set<VirtualFile> result = new LinkedHashSet<>();
   result.add(directory);
   addSourceDirectoriesFromLibraries(project, directory, result);
   VirtualFile[] array = result.toArray(new VirtualFile[result.size()]);
   return GlobalSearchScopesCore.directoriesScope(project, withSubdirectories, array);
 }
  private void markTypeParameterUsages(
      final PsiClass psiClass,
      PsiClassType migrationType,
      PsiReferenceParameterList referenceParameterList,
      final Map<PsiElement, Pair<PsiReference[], PsiType>> roots) {

    final PsiSubstitutor[] fullHierarchySubstitutor = {
      migrationType.resolveGenerics().getSubstitutor()
    };
    RefactoringHierarchyUtil.processSuperTypes(
        migrationType,
        new RefactoringHierarchyUtil.SuperTypeVisitor() {
          @Override
          public void visitType(PsiType aType) {
            fullHierarchySubstitutor[0] =
                fullHierarchySubstitutor[0].putAll(
                    ((PsiClassType) aType).resolveGenerics().getSubstitutor());
          }

          @Override
          public void visitClass(PsiClass aClass) {
            // do nothing
          }
        });

    final PsiClass resolvedClass =
        (PsiClass) ((PsiJavaCodeReferenceElement) referenceParameterList.getParent()).resolve();
    ;
    LOG.assertTrue(resolvedClass != null);
    final Set<PsiClass> superClasses = new HashSet<PsiClass>();
    superClasses.add(resolvedClass);
    InheritanceUtil.getSuperClasses(resolvedClass, superClasses, true);
    for (PsiClass superSuperClass : superClasses) {
      final TypeParameterSearcher parameterSearcher =
          new TypeParameterSearcher(superSuperClass.getTypeParameters());
      superSuperClass.accept(
          new JavaRecursiveElementVisitor() {
            @Override
            public void visitMethod(final PsiMethod method) {
              super.visitMethod(method);
              processMemberType(
                  method, parameterSearcher, psiClass, fullHierarchySubstitutor[0], roots);
              for (PsiParameter parameter : method.getParameterList().getParameters()) {
                processMemberType(
                    parameter, parameterSearcher, psiClass, fullHierarchySubstitutor[0], roots);
              }
            }

            @Override
            public void visitField(final PsiField field) {
              super.visitField(field);
              processMemberType(
                  field, parameterSearcher, psiClass, fullHierarchySubstitutor[0], roots);
            }
          });
    }
  }
  @Override
  public String handleEmptyLookup(
      @NotNull final CompletionParameters parameters, final Editor editor) {
    if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;

    final String ad = advertise(parameters);
    final String suffix = ad == null ? "" : "; " + StringUtil.decapitalize(ad);
    if (parameters.getCompletionType() == CompletionType.SMART) {
      if (!ApplicationManager.getApplication().isUnitTestMode()) {

        final Project project = parameters.getPosition().getProject();
        final PsiFile file = parameters.getOriginalFile();

        PsiExpression expression =
            PsiTreeUtil.getContextOfType(parameters.getPosition(), PsiExpression.class, true);
        if (expression != null && expression.getParent() instanceof PsiExpressionList) {
          int lbraceOffset = expression.getParent().getTextRange().getStartOffset();
          ShowParameterInfoHandler.invoke(project, editor, file, lbraceOffset, null);
        }

        if (expression instanceof PsiLiteralExpression) {
          return LangBundle.message("completion.no.suggestions") + suffix;
        }

        if (expression instanceof PsiInstanceOfExpression) {
          final PsiInstanceOfExpression instanceOfExpression = (PsiInstanceOfExpression) expression;
          if (PsiTreeUtil.isAncestor(
              instanceOfExpression.getCheckType(), parameters.getPosition(), false)) {
            return LangBundle.message("completion.no.suggestions") + suffix;
          }
        }
      }

      final Set<PsiType> expectedTypes = JavaCompletionUtil.getExpectedTypes(parameters);
      if (expectedTypes != null) {
        PsiType type = expectedTypes.size() == 1 ? expectedTypes.iterator().next() : null;
        if (type != null) {
          final PsiType deepComponentType = type.getDeepComponentType();
          if (deepComponentType instanceof PsiClassType) {
            if (((PsiClassType) deepComponentType).resolve() != null) {
              return CompletionBundle.message(
                      "completion.no.suggestions.of.type", type.getPresentableText())
                  + suffix;
            }
            return CompletionBundle.message("completion.unknown.type", type.getPresentableText())
                + suffix;
          }
          if (!PsiType.NULL.equals(type)) {
            return CompletionBundle.message(
                    "completion.no.suggestions.of.type", type.getPresentableText())
                + suffix;
          }
        }
      }
    }
    return LangBundle.message("completion.no.suggestions") + suffix;
  }
Example #22
0
 /**
  * Get jet non-extension top-level function names. Method is allowed to give invalid names - all
  * result should be checked with getTopLevelFunctionDescriptorsByName().
  *
  * @return
  */
 @NotNull
 public Collection<String> getAllTopLevelFunctionNames() {
   Set<String> functionNames = new HashSet<String>();
   functionNames.addAll(JetShortFunctionNameIndex.getInstance().getAllKeys(project));
   functionNames.addAll(
       JetFromJavaDescriptorHelper.getPossiblePackageDeclarationsNames(
           project, GlobalSearchScope.allScope(project)));
   return functionNames;
 }
Example #23
0
  /**
   * Get jet extensions top-level function names. Method is allowed to give invalid names - all
   * result should be checked with getAllJetExtensionFunctionsByName().
   *
   * @return
   */
  @NotNull
  public Collection<String> getAllJetExtensionFunctionsNames(@NotNull GlobalSearchScope scope) {
    Set<String> extensionFunctionNames = new HashSet<String>();

    extensionFunctionNames.addAll(JetExtensionFunctionNameIndex.getInstance().getAllKeys(project));
    extensionFunctionNames.addAll(
        JetFromJavaDescriptorHelper.getTopExtensionFunctionNames(project, scope));

    return extensionFunctionNames;
  }
  protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
    final UsageInfo[] usages = refUsages.get();
    MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    final Set<PsiMember> members = new HashSet<PsiMember>();
    members.add(myMethod);
    if (myTargetVariable instanceof PsiField) members.add((PsiMember) myTargetVariable);
    if (!myTargetClass.isInterface()) {
      RefactoringConflictsUtil.analyzeAccessibilityConflicts(
          members, myTargetClass, conflicts, myNewVisibility);
    } else {
      for (final UsageInfo usage : usages) {
        if (usage instanceof InheritorUsageInfo) {
          RefactoringConflictsUtil.analyzeAccessibilityConflicts(
              members, ((InheritorUsageInfo) usage).getInheritor(), conflicts, myNewVisibility);
        }
      }
    }

    if (myTargetVariable instanceof PsiParameter) {
      PsiParameter parameter = (PsiParameter) myTargetVariable;
      for (final UsageInfo usageInfo : usages) {
        if (usageInfo instanceof MethodCallUsageInfo) {
          final PsiElement methodCall = ((MethodCallUsageInfo) usageInfo).getMethodCallExpression();
          if (methodCall instanceof PsiMethodCallExpression) {
            final PsiExpression[] expressions =
                ((PsiMethodCallExpression) methodCall).getArgumentList().getExpressions();
            final int index = myMethod.getParameterList().getParameterIndex(parameter);
            if (index < expressions.length) {
              PsiExpression instanceValue = expressions[index];
              instanceValue = RefactoringUtil.unparenthesizeExpression(instanceValue);
              if (instanceValue instanceof PsiLiteralExpression
                  && ((PsiLiteralExpression) instanceValue).getValue() == null) {
                String message =
                    RefactoringBundle.message(
                        "0.contains.call.with.null.argument.for.parameter.1",
                        RefactoringUIUtil.getDescription(
                            ConflictsUtil.getContainer(methodCall), true),
                        CommonRefactoringUtil.htmlEmphasize(parameter.getName()));
                conflicts.putValue(instanceValue, message);
              }
            }
          } else if (methodCall instanceof PsiMethodReferenceExpression) {
            conflicts.putValue(methodCall, "Method reference would be broken after move");
          }
        }
      }
    }

    try {
      ConflictsUtil.checkMethodConflicts(myTargetClass, myMethod, getPatternMethod(), conflicts);
    } catch (IncorrectOperationException e) {
    }

    return showConflicts(conflicts, usages);
  }
 public ExtractClassProcessor(
     PsiClass sourceClass,
     List<PsiField> fields,
     List<PsiMethod> methods,
     List<PsiClass> classes,
     String packageName,
     MoveDestination moveDestination,
     String newClassName,
     String newVisibility,
     boolean generateAccessors,
     List<MemberInfo> enumConstants) {
   super(sourceClass.getProject());
   this.sourceClass = sourceClass;
   this.newPackageName = packageName;
   myMoveDestination = moveDestination;
   myNewVisibility = newVisibility;
   myGenerateAccessors = generateAccessors;
   this.enumConstants = new ArrayList<PsiField>();
   for (MemberInfo constant : enumConstants) {
     if (constant.isChecked()) {
       this.enumConstants.add((PsiField) constant.getMember());
     }
   }
   this.fields = new ArrayList<PsiField>(fields);
   this.methods = new ArrayList<PsiMethod>(methods);
   this.innerClasses = new ArrayList<PsiClass>(classes);
   this.newClassName = newClassName;
   delegateFieldName = calculateDelegateFieldName();
   requiresBackpointer =
       new BackpointerUsageVisitor(fields, innerClasses, methods, sourceClass)
           .backpointerRequired();
   if (requiresBackpointer) {
     ContainerUtil.addAll(typeParams, sourceClass.getTypeParameters());
   } else {
     final Set<PsiTypeParameter> typeParamSet = new HashSet<PsiTypeParameter>();
     final TypeParametersVisitor visitor = new TypeParametersVisitor(typeParamSet);
     for (PsiField field : fields) {
       field.accept(visitor);
     }
     for (PsiMethod method : methods) {
       method.accept(visitor);
       // do not include method's type parameters in class signature
       typeParamSet.removeAll(Arrays.asList(method.getTypeParameters()));
     }
     typeParams.addAll(typeParamSet);
   }
   myClass =
       new WriteCommandAction<PsiClass>(myProject, getCommandName()) {
         @Override
         protected void run(@NotNull Result<PsiClass> result) throws Throwable {
           result.setResult(buildClass());
         }
       }.execute().getResultObject();
   myExtractEnumProcessor = new ExtractEnumProcessor(myProject, this.enumConstants, myClass);
 }
  @Override
  @NotNull
  public Object[] getVariants() {
    Set<PsiPackage> subPackages = new HashSet<>();
    for (PsiPackage psiPackage : getContext()) {
      subPackages.addAll(
          Arrays.asList(psiPackage.getSubPackages(myReferenceSet.getResolveScope())));
    }

    return subPackages.toArray();
  }
 public synchronized void createNewList(
     @NotNull String name, boolean readOnly, boolean allowsTree) {
   myName2FavoritesRoots.put(name, new ArrayList<TreeItem<Pair<AbstractUrl, String>>>());
   if (readOnly) {
     myReadOnlyLists.add(name);
   }
   if (allowsTree) {
     myAllowsTreeLists.add(name);
   }
   fireListeners.listAdded(name);
 }
  @Override
  public void run() {
    while (!myDisposed) {
      boolean isEmpty;
      synchronized (filesToResolve) {
        isEmpty = filesToResolve.isEmpty();
      }
      if (enableVetoes.get() > 0
          || isEmpty
          || !resolveProcess.isDone()
          || HeavyProcessLatch.INSTANCE.isRunning()
          || PsiDocumentManager.getInstance(myProject).hasUncommitedDocuments()) {
        try {
          waitForQueue();
        } catch (InterruptedException e) {
          break;
        }
        continue;
      }
      final Set<VirtualFile> files = pollFilesToResolve();
      if (files.isEmpty()) continue;

      upToDate = false;

      myApplication.invokeLater(
          () -> {
            if (!resolveProcess.isDone()) return;
            log("Started to resolve " + files.size() + " files");

            Task.Backgroundable backgroundable =
                new Task.Backgroundable(myProject, "Resolving files...", false) {
                  @Override
                  public void run(@NotNull final ProgressIndicator indicator) {
                    if (!myApplication.isDisposed()) {
                      processBatch(indicator, files);
                    }
                  }
                };
            ProgressIndicator indicator;
            if (files.size() > 1) {
              // show progress
              indicator = new BackgroundableProcessIndicator(backgroundable);
            } else {
              indicator = new MyProgress();
            }
            resolveProcess =
                ((ProgressManagerImpl) ProgressManager.getInstance())
                    .runProcessWithProgressAsynchronously(backgroundable, indicator, null);
          },
          myProject.getDisposed());

      flushLog();
    }
  }
 @NotNull
 private Set<PsiPackage> getContext() {
   if (myIndex == 0) return myReferenceSet.getInitialContext();
   Set<PsiPackage> psiPackages = new HashSet<>();
   for (ResolveResult resolveResult : myReferenceSet.getReference(myIndex - 1).doMultiResolve()) {
     PsiElement psiElement = resolveResult.getElement();
     if (psiElement instanceof PsiPackage) {
       psiPackages.add((PsiPackage) psiElement);
     }
   }
   return psiPackages;
 }
Example #30
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);
 }