private static boolean isExtensionPointNameDeclarationField(PsiField psiField) {
    // *do* allow non-public
    if (!psiField.hasModifierProperty(PsiModifier.FINAL)
        || !psiField.hasModifierProperty(PsiModifier.STATIC)
        || psiField.hasModifierProperty(PsiModifier.ABSTRACT)) {
      return false;
    }

    if (!psiField.hasInitializer()) {
      return false;
    }

    final PsiExpression initializer = psiField.getInitializer();
    if (!(initializer instanceof PsiMethodCallExpression)
        && !(initializer instanceof PsiNewExpression)) {
      return false;
    }

    final PsiClass fieldClass = PsiTypesUtil.getPsiClass(psiField.getType());
    if (fieldClass == null) {
      return false;
    }

    return ExtensionPointName.class.getName().equals(fieldClass.getQualifiedName());
  }
  public static boolean runContributors(
      @NotNull PsiType qualifierType,
      @NotNull PsiScopeProcessor processor,
      @NotNull PsiElement place,
      @NotNull ResolveState state) {

    MyDelegatingScopeProcessor delegatingProcessor = new MyDelegatingScopeProcessor(processor);

    ensureInit();

    final PsiClass aClass = PsiTypesUtil.getPsiClass(qualifierType);

    if (aClass != null) {
      for (String superClassName : TypesUtil.getSuperClassesWithCache(aClass).keySet()) {
        for (NonCodeMembersContributor enhancer :
            ourClassSpecifiedContributors.get(superClassName)) {
          ProgressManager.checkCanceled();
          enhancer.processDynamicElements(qualifierType, aClass, delegatingProcessor, place, state);
          if (!delegatingProcessor.wantMore) {
            return false;
          }
        }
      }
    }

    for (NonCodeMembersContributor contributor : ourAllTypeContributors) {
      ProgressManager.checkCanceled();
      contributor.processDynamicElements(qualifierType, aClass, delegatingProcessor, place, state);
      if (!delegatingProcessor.wantMore) {
        return false;
      }
    }

    return GroovyDslFileIndex.processExecutors(qualifierType, place, processor, state);
  }
  protected void generatePsiElements(
      @NotNull PsiField psiField,
      @NotNull PsiAnnotation psiAnnotation,
      @NotNull List<? super PsiElement> target) {
    final String fieldName = psiField.getName();
    final PsiType psiFieldType = psiField.getType();

    final String methodName = getFindByName(psiField);

    PsiClass psiClass = psiField.getContainingClass();
    assert psiClass != null;

    UserMapKeys.addWriteUsageFor(psiField);

    LombokLightMethodBuilder method =
        new LombokLightMethodBuilder(psiField.getManager(), methodName)
            .withMethodReturnType(PsiTypesUtil.getClassType(psiClass))
            .withContainingClass(psiClass)
            .withParameter(fieldName, psiFieldType)
            .withNavigationElement(psiField);
    method.withModifier(PsiModifier.STATIC);
    method.withModifier(PsiModifier.PUBLIC);

    target.add(method);
  }
 private static void initialize(final PsiLocalVariable variable)
     throws IncorrectOperationException {
   PsiType type = variable.getType();
   String init = PsiTypesUtil.getDefaultValueOfType(type);
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(variable.getProject()).getElementFactory();
   PsiExpression initializer = factory.createExpressionFromText(init, variable);
   variable.setInitializer(initializer);
 }
Exemplo n.º 5
0
  private static boolean changeClassTypeArgument(
      PsiMethod myMethod,
      Project project,
      PsiType superReturnType,
      PsiClass superClass,
      Editor editor,
      PsiType returnType) {
    if (superClass == null || !superClass.hasTypeParameters()) return true;
    final PsiClass superReturnTypeClass = PsiUtil.resolveClassInType(superReturnType);
    if (superReturnTypeClass == null
        || !(superReturnTypeClass instanceof PsiTypeParameter
            || superReturnTypeClass.hasTypeParameters())) return true;

    final PsiClass derivedClass = myMethod.getContainingClass();
    if (derivedClass == null) return true;

    final PsiReferenceParameterList referenceParameterList =
        findTypeArgumentsList(superClass, derivedClass);
    if (referenceParameterList == null) return true;

    final PsiElement resolve =
        ((PsiJavaCodeReferenceElement) referenceParameterList.getParent()).resolve();
    if (!(resolve instanceof PsiClass)) return true;
    final PsiClass baseClass = (PsiClass) resolve;

    if (returnType instanceof PsiPrimitiveType) {
      returnType = ((PsiPrimitiveType) returnType).getBoxedType(derivedClass);
    }

    final PsiSubstitutor superClassSubstitutor =
        TypeConversionUtil.getSuperClassSubstitutor(superClass, baseClass, PsiSubstitutor.EMPTY);
    final PsiType superReturnTypeInBaseClassType =
        superClassSubstitutor.substitute(superReturnType);
    final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(project).getResolveHelper();
    final PsiSubstitutor psiSubstitutor =
        resolveHelper.inferTypeArguments(
            PsiTypesUtil.filterUnusedTypeParameters(
                superReturnTypeInBaseClassType, baseClass.getTypeParameters()),
            new PsiType[] {superReturnTypeInBaseClassType},
            new PsiType[] {returnType},
            PsiUtil.getLanguageLevel(superClass));

    final TypeMigrationRules rules = new TypeMigrationRules();
    final PsiSubstitutor compoundSubstitutor =
        TypeConversionUtil.getSuperClassSubstitutor(superClass, derivedClass, PsiSubstitutor.EMPTY)
            .putAll(psiSubstitutor);
    rules.setBoundScope(new LocalSearchScope(derivedClass));
    TypeMigrationProcessor.runHighlightingTypeMigration(
        project,
        editor,
        rules,
        referenceParameterList,
        JavaPsiFacade.getElementFactory(project).createType(baseClass, compoundSubstitutor));

    return false;
  }
 @Override
 public boolean setupDefaultValues(
     ChangeInfo changeInfo, Ref<UsageInfo[]> refUsages, Project project) {
   if (!(changeInfo instanceof JavaChangeInfo)) return true;
   for (UsageInfo usageInfo : refUsages.get()) {
     if (usageInfo instanceof GrMethodCallUsageInfo) {
       GrMethodCallUsageInfo methodCallUsageInfo = (GrMethodCallUsageInfo) usageInfo;
       if (methodCallUsageInfo.isToChangeArguments()) {
         final PsiElement element = methodCallUsageInfo.getElement();
         if (element == null) continue;
         final PsiMethod caller = RefactoringUtil.getEnclosingMethod(element);
         final boolean needDefaultValue =
             !((JavaChangeInfo) changeInfo).getMethodsToPropagateParameters().contains(caller);
         final PsiMethod referencedMethod = methodCallUsageInfo.getReferencedMethod();
         if (needDefaultValue
             && (caller == null
                 || referencedMethod == null
                 || !MethodSignatureUtil.isSuperMethod(referencedMethod, caller))) {
           final ParameterInfo[] parameters = changeInfo.getNewParameters();
           for (ParameterInfo parameter : parameters) {
             final String defaultValue = parameter.getDefaultValue();
             if (defaultValue == null && parameter.getOldIndex() == -1) {
               ((ParameterInfoImpl) parameter).setDefaultValue("");
               if (!ApplicationManager.getApplication().isUnitTestMode()) {
                 final PsiType type =
                     ((ParameterInfoImpl) parameter)
                         .getTypeWrapper()
                         .getType(element, element.getManager());
                 final DefaultValueChooser chooser =
                     new DefaultValueChooser(
                         project, parameter.getName(), PsiTypesUtil.getDefaultValueOfType(type));
                 chooser.show();
                 if (chooser.isOK()) {
                   if (chooser.feelLucky()) {
                     parameter.setUseAnySingleVariable(true);
                   } else {
                     ((ParameterInfoImpl) parameter).setDefaultValue(chooser.getDefaultValue());
                   }
                 } else {
                   return false;
                 }
               }
             }
           }
         }
       }
     }
   }
   return true;
 }
 private static void generateVariableNameByTypeInner(
     PsiType type, Set<String> possibleNames, NameValidator validator) {
   String unboxed = PsiTypesUtil.unboxIfPossible(type.getCanonicalText());
   if (unboxed != null && !unboxed.equals(type.getCanonicalText())) {
     String name = generateNameForBuiltInType(unboxed);
     name = validator.validateName(name, true);
     if (GroovyNamesUtil.isIdentifier(name)) {
       possibleNames.add(name);
     }
   } else if (type instanceof PsiIntersectionType) {
     for (PsiType psiType : ((PsiIntersectionType) type).getConjuncts()) {
       generateByType(psiType, possibleNames, validator);
     }
   } else {
     generateByType(type, possibleNames, validator);
   }
 }
  public static String checkReturnType(
      PsiMethodReferenceExpression expression,
      JavaResolveResult result,
      PsiType functionalInterfaceType) {
    final PsiElement resolve = result.getElement();
    if (resolve instanceof PsiMethod) {
      final PsiClass containingClass = ((PsiMethod) resolve).getContainingClass();
      LOG.assertTrue(containingClass != null);
      PsiSubstitutor subst = result.getSubstitutor();
      PsiClass qContainingClass = getQualifierResolveResult(expression).getContainingClass();
      if (qContainingClass != null
          && isReceiverType(functionalInterfaceType, containingClass, (PsiMethod) resolve)) {
        subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst);
        LOG.assertTrue(subst != null);
      }

      final PsiType interfaceReturnType =
          LambdaUtil.getFunctionalInterfaceReturnType(functionalInterfaceType);

      PsiType returnType =
          PsiTypesUtil.patchMethodGetClassReturnType(
              expression,
              expression,
              (PsiMethod) resolve,
              null,
              PsiUtil.getLanguageLevel(expression));
      if (returnType == null) {
        returnType = ((PsiMethod) resolve).getReturnType();
      }
      PsiType methodReturnType = subst.substitute(returnType);
      if (interfaceReturnType != null && interfaceReturnType != PsiType.VOID) {
        if (methodReturnType == null) {
          methodReturnType =
              JavaPsiFacade.getElementFactory(expression.getProject())
                  .createType(containingClass, subst);
        }
        if (!TypeConversionUtil.isAssignable(interfaceReturnType, methodReturnType, false)) {
          return "Bad return type in method reference: cannot convert "
              + methodReturnType.getCanonicalText()
              + " to "
              + interfaceReturnType.getCanonicalText();
        }
      }
    }
    return null;
  }
    @Nullable
    private static PsiType getResultType(
        PsiMethodCallExpression call,
        PsiReferenceExpression methodExpression,
        JavaResolveResult result,
        @NotNull final LanguageLevel languageLevel) {
      final PsiMethod method = (PsiMethod) result.getElement();
      if (method == null) return null;

      boolean is15OrHigher = languageLevel.compareTo(LanguageLevel.JDK_1_5) >= 0;
      final PsiType getClassReturnType =
          PsiTypesUtil.patchMethodGetClassReturnType(
              call,
              methodExpression,
              method,
              new Condition<IElementType>() {
                @Override
                public boolean value(IElementType type) {
                  return type != JavaElementType.CLASS;
                }
              },
              languageLevel);

      if (getClassReturnType != null) {
        return getClassReturnType;
      }

      PsiType ret = method.getReturnType();
      if (ret == null) return null;
      if (ret instanceof PsiClassType) {
        ret = ((PsiClassType) ret).setLanguageLevel(languageLevel);
      }
      if (is15OrHigher) {
        return captureReturnType(call, method, ret, result, languageLevel);
      }
      return TypeConversionUtil.erasure(ret);
    }
  private static PsiSubstitutor inferNested(
      final PsiTypeParameter[] typeParameters,
      @NotNull final PsiParameter[] parameters,
      @NotNull final PsiExpression[] arguments,
      final PsiSubstitutor partialSubstitutor,
      @NotNull final PsiCall parent,
      @NotNull final ParameterTypeInferencePolicy policy,
      final MethodCandidateInfo.CurrentCandidateProperties properties,
      final InferenceSession parentSession) {
    final CompoundInitialState compoundInitialState = createState(parentSession);
    InitialInferenceState initialInferenceState = compoundInitialState.getInitialState(parent);
    if (initialInferenceState != null) {
      final InferenceSession childSession = new InferenceSession(initialInferenceState);
      final List<String> errorMessages = parentSession.getIncompatibleErrorMessages();
      if (errorMessages != null) {
        return childSession.prepareSubstitution();
      }
      return childSession.collectAdditionalAndInfer(
          parameters, arguments, properties, compoundInitialState.getInitialSubstitutor());
    }

    // we do not investigate lambda return expressions when lambda's return type is already inferred
    // (proper)
    // this way all calls from lambda's return expressions won't appear in nested sessions
    else {
      PsiElement gParent = PsiUtil.skipParenthesizedExprUp(parent.getParent());
      // find the nearest parent which appears in the map and start inference with a provided target
      // type for a nested lambda
      while (true) {
        if (gParent instanceof PsiReturnStatement) { // process code block lambda
          final PsiElement returnContainer = gParent.getParent();
          if (returnContainer instanceof PsiCodeBlock) {
            gParent = returnContainer.getParent();
          }
        }
        if (gParent instanceof PsiLambdaExpression) {
          final PsiCall call = PsiTreeUtil.getParentOfType(gParent, PsiCall.class);
          if (call != null) {
            initialInferenceState = compoundInitialState.getInitialState(call);
            if (initialInferenceState != null) {
              final int idx = LambdaUtil.getLambdaIdx(call.getArgumentList(), gParent);
              final PsiMethod method = call.resolveMethod();
              if (method != null && idx > -1) {
                final PsiType parameterType =
                    PsiTypesUtil.getParameterType(
                        method.getParameterList().getParameters(), idx, true);
                final PsiType parameterTypeInTermsOfSession =
                    initialInferenceState.getInferenceSubstitutor().substitute(parameterType);
                final PsiType lambdaTargetType =
                    compoundInitialState
                        .getInitialSubstitutor()
                        .substitute(parameterTypeInTermsOfSession);
                return LambdaUtil.performWithLambdaTargetType(
                    (PsiLambdaExpression) gParent,
                    lambdaTargetType,
                    new Producer<PsiSubstitutor>() {
                      @Nullable
                      @Override
                      public PsiSubstitutor produce() {
                        if (call.equals(PsiTreeUtil.getParentOfType(parent, PsiCall.class, true))) {
                          // parent was mentioned in the top inference session
                          // just proceed with the target type
                          final InferenceSession inferenceSession =
                              new InferenceSession(
                                  typeParameters,
                                  partialSubstitutor,
                                  parent.getManager(),
                                  parent,
                                  policy);
                          inferenceSession.initExpressionConstraints(parameters, arguments, parent);
                          return inferenceSession.infer(parameters, arguments, parent);
                        }
                        // one of the grand parents were found in the top inference session
                        // start from it as it is the top level call
                        final InferenceSession sessionInsideLambda =
                            startTopLevelInference(call, policy);
                        return inferNested(
                            typeParameters,
                            parameters,
                            arguments,
                            partialSubstitutor,
                            parent,
                            policy,
                            properties,
                            sessionInsideLambda);
                      }
                    });
              }
            } else {
              gParent = PsiUtil.skipParenthesizedExprUp(call.getParent());
              continue;
            }
          }
        }
        break;
      }
    }
    return null;
  }