@NotNull
 public static PsiClassType createListType(@NotNull PsiClass elements) {
   JavaPsiFacade facade = JavaPsiFacade.getInstance(elements.getProject());
   GlobalSearchScope resolveScope = elements.getResolveScope();
   PsiClass listClass = facade.findClass(JAVA_UTIL_LIST, resolveScope);
   if (listClass == null) {
     return facade.getElementFactory().createTypeByFQClassName(JAVA_UTIL_LIST, resolveScope);
   }
   return facade
       .getElementFactory()
       .createType(listClass, facade.getElementFactory().createType(elements));
 }
  @NotNull
  public static PsiType createSetType(@NotNull PsiElement context, @NotNull PsiType type) {
    JavaPsiFacade facade = JavaPsiFacade.getInstance(context.getProject());
    GlobalSearchScope resolveScope = context.getResolveScope();

    PsiClass setClass = facade.findClass(JAVA_UTIL_SET, resolveScope);
    if (setClass != null && setClass.getTypeParameters().length == 1) {
      return facade.getElementFactory().createType(setClass, type);
    }

    return facade.getElementFactory().createTypeByFQClassName(JAVA_UTIL_SET, resolveScope);
  }
Exemple #3
0
 private void getVariantsFromQualifier(@NotNull GrExpression qualifier) {
   Project project = qualifier.getProject();
   PsiType qualifierType = qualifier.getType();
   final ResolveState state = ResolveState.initial();
   if (qualifierType == null || qualifierType == PsiType.VOID) {
     if (qualifier instanceof GrReferenceExpression) {
       PsiElement resolved = ((GrReferenceExpression) qualifier).resolve();
       if (resolved instanceof PsiPackage || resolved instanceof PsiVariable) {
         resolved.processDeclarations(myProcessor, state, null, myRefExpr);
         return;
       }
     }
     getVariantsFromQualifierType(TypesUtil.getJavaLangObject(qualifier), project);
   } else if (qualifierType instanceof PsiIntersectionType) {
     for (PsiType conjunct : ((PsiIntersectionType) qualifierType).getConjuncts()) {
       getVariantsFromQualifierType(conjunct, project);
     }
   } else if (qualifierType instanceof GrTraitType) {
     GrTypeDefinition definition = ((GrTraitType) qualifierType).getMockTypeDefinition();
     if (definition != null) {
       PsiClassType classType = JavaPsiFacade.getElementFactory(project).createType(definition);
       getVariantsFromQualifierType(classType, project);
     } else {
       getVariantsFromQualifierType(((GrTraitType) qualifierType).getExprType(), project);
       for (PsiClassType traitType : ((GrTraitType) qualifierType).getTraitTypes()) {
         getVariantsFromQualifierType(traitType, project);
       }
     }
   } else {
     getVariantsFromQualifierType(qualifierType, project);
     if (qualifier instanceof GrReferenceExpression
         && !PsiUtil.isSuperReference(qualifier)
         && !PsiUtil.isInstanceThisRef(qualifier)) {
       PsiElement resolved = ((GrReferenceExpression) qualifier).resolve();
       if (resolved instanceof PsiClass) { // //omitted .class
         GlobalSearchScope scope = myRefExpr.getResolveScope();
         PsiClass javaLangClass = PsiUtil.getJavaLangClass(resolved, scope);
         if (javaLangClass != null) {
           PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
           PsiTypeParameter[] typeParameters = javaLangClass.getTypeParameters();
           if (typeParameters.length == 1) {
             substitutor = substitutor.put(typeParameters[0], qualifierType);
           }
           PsiType javaLangClassType =
               JavaPsiFacade.getElementFactory(myRefExpr.getProject())
                   .createType(javaLangClass, substitutor);
           ResolveUtil.processAllDeclarations(javaLangClassType, myProcessor, state, myRefExpr);
         }
       }
     }
   }
 }
 private static boolean isIndexOfCall(@NotNull PsiMethodCallExpression expression) {
   final PsiReferenceExpression methodExpression = expression.getMethodExpression();
   final String methodName = methodExpression.getReferenceName();
   if (!HardcodedMethodConstants.INDEX_OF.equals(methodName)) {
     return false;
   }
   final PsiExpressionList argumentList = expression.getArgumentList();
   final PsiExpression[] arguments = argumentList.getExpressions();
   if (arguments.length != 1) {
     return false;
   }
   final PsiExpression qualifier = methodExpression.getQualifierExpression();
   if (qualifier == null) {
     return false;
   }
   final PsiType qualifierType = qualifier.getType();
   if (qualifierType == null) {
     return false;
   }
   final Project project = expression.getProject();
   final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project);
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass javaUtilListClass =
       psiFacade.findClass(CommonClassNames.JAVA_UTIL_LIST, projectScope);
   if (javaUtilListClass == null) {
     return false;
   }
   final PsiElementFactory factory = psiFacade.getElementFactory();
   final PsiClassType javaUtilListType = factory.createType(javaUtilListClass);
   return javaUtilListType.isAssignableFrom(qualifierType);
 }
  private static PsiAnnotationMemberValue[] readFromClass(
      @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) {
    PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName);
    PsiType fromClassType =
        fromClassAttr instanceof PsiClassObjectAccessExpression
            ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType()
            : null;
    PsiClass fromClass =
        fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null;
    if (fromClass == null) return null;
    String fqn = fromClass.getQualifiedName();
    if (fqn == null) return null;
    List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>();
    for (PsiField field : fromClass.getFields()) {
      if (!field.hasModifierProperty(PsiModifier.PUBLIC)
          || !field.hasModifierProperty(PsiModifier.STATIC)
          || !field.hasModifierProperty(PsiModifier.FINAL)) continue;
      PsiType fieldType = field.getType();
      if (!Comparing.equal(fieldType, type)) continue;
      PsiAssignmentExpression e =
          (PsiAssignmentExpression)
              JavaPsiFacade.getElementFactory(field.getProject())
                  .createExpressionFromText("x=" + fqn + "." + field.getName(), field);
      PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression();
      constants.add(refToField);
    }
    if (constants.isEmpty()) return null;

    return constants.toArray(new PsiAnnotationMemberValue[constants.size()]);
  }
  /* Guesswork
   */
  @Nullable
  private static PsiSubstitutor getInheritorSubstitutorForNewExpression(
      final PsiClass baseClass,
      final PsiClass inheritor,
      final PsiSubstitutor baseSubstitutor,
      final PsiElement context) {
    final Project project = baseClass.getProject();
    JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final PsiResolveHelper resolveHelper = facade.getResolveHelper();
    PsiSubstitutor superSubstitutor =
        TypeConversionUtil.getClassSubstitutor(baseClass, inheritor, PsiSubstitutor.EMPTY);
    if (superSubstitutor == null) return null;
    PsiSubstitutor inheritorSubstitutor = PsiSubstitutor.EMPTY;
    for (PsiTypeParameter inheritorParameter : PsiUtil.typeParametersIterable(inheritor)) {
      for (PsiTypeParameter baseParameter : PsiUtil.typeParametersIterable(baseClass)) {
        final PsiType substituted = superSubstitutor.substitute(baseParameter);
        PsiType arg = baseSubstitutor.substitute(baseParameter);
        if (arg instanceof PsiWildcardType) arg = ((PsiWildcardType) arg).getBound();
        PsiType substitution =
            resolveHelper.getSubstitutionForTypeParameter(
                inheritorParameter, substituted, arg, true, PsiUtil.getLanguageLevel(context));
        if (PsiType.NULL.equals(substitution)) continue;
        if (substitution == null) {
          return facade.getElementFactory().createRawSubstitutor(inheritor);
        }
        inheritorSubstitutor = inheritorSubstitutor.put(inheritorParameter, substitution);
        break;
      }
    }

    return inheritorSubstitutor;
  }
 protected PsiField createFieldToStartTemplateOn(final String[] names, final PsiType defaultType) {
   final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
   return ApplicationManager.getApplication()
       .runWriteAction(
           new Computable<PsiField>() {
             @Override
             public PsiField compute() {
               PsiField field =
                   elementFactory.createField(
                       getInputName() != null ? getInputName() : names[0], defaultType);
               field = (PsiField) myParentClass.add(field);
               if (myExprText != null) {
                 updateInitializer(elementFactory, field);
               }
               PsiUtil.setModifierProperty(
                   field, PsiModifier.FINAL, myIntroduceFieldPanel.isDeclareFinal());
               final String visibility = myIntroduceFieldPanel.getFieldVisibility();
               if (visibility != null) {
                 PsiUtil.setModifierProperty(field, visibility, true);
               }
               myFieldRangeStart = myEditor.getDocument().createRangeMarker(field.getTextRange());
               return field;
             }
           });
 }
Exemple #8
0
 public static @Nullable PsiType resolveMethod(
     Project proj,
     PsiElement context,
     String clas,
     String methodName,
     @NotNull PsiExpression... args) {
   StringBuilder sb = new StringBuilder();
   sb.append(clas).append(".").append(methodName).append("(");
   boolean comma = false;
   for (PsiExpression arg : args) {
     if (comma) sb.append(",");
     sb.append(arg.getText());
     comma = true;
   }
   sb.append(")");
   PsiExpression exp =
       JavaPsiFacade.getElementFactory(proj).createExpressionFromText(sb.toString(), context);
   return exp.getType();
   /*if (clas == null || methodName == null) return null;
   PsiType[] argTypes = new PsiType[args.length];
   for (int i = 0; i < args.length; i++) {
       if (args[i] == null) return null;
       argTypes[i] = args[i].getType();
   }
   return resolveMethod(clas.getType(), methodName, argTypes);*/
 }
 private static void addDefaultConstructor(
     JavaChangeInfo changeInfo, PsiClass aClass, final UsageInfo[] usages)
     throws IncorrectOperationException {
   if (!(aClass instanceof PsiAnonymousClass)) {
     PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject());
     PsiMethod defaultConstructor =
         factory.createMethodFromText(aClass.getName() + "(){}", aClass);
     defaultConstructor =
         (PsiMethod)
             CodeStyleManager.getInstance(aClass.getProject()).reformat(defaultConstructor);
     defaultConstructor = (PsiMethod) aClass.add(defaultConstructor);
     PsiUtil.setModifierProperty(
         defaultConstructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true);
     addSuperCall(changeInfo, defaultConstructor, null, usages);
   } else {
     final PsiElement parent = aClass.getParent();
     if (parent instanceof PsiNewExpression) {
       final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList();
       final PsiClass baseClass = changeInfo.getMethod().getContainingClass();
       final PsiSubstitutor substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
       fixActualArgumentsList(argumentList, changeInfo, true, substitutor);
     }
   }
 }
  @Override
  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element)
      throws IncorrectOperationException {
    final PsiNewExpression expression =
        PsiTreeUtil.getParentOfType(element, PsiNewExpression.class, false);
    if (expression == null) {
      return;
    }

    final PsiExpressionList arguments = expression.getArgumentList();
    if (arguments == null) {
      return;
    }

    final PsiMethod constructor = expression.resolveConstructor();
    if (constructor == null) {
      return;
    }

    final PsiExpressionList newArguments =
        createNewArguments(
            JavaPsiFacade.getElementFactory(project),
            constructor.getParameterList().getParameters(),
            arguments.getExpressions());

    if (newArguments == null) {
      return;
    }

    arguments.replace(newArguments);
  }
  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);
  }
 protected static void addStatementBefore(String newStatementText, PsiReturnStatement anchor) {
   final Project project = anchor.getProject();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   final PsiStatement newStatement = factory.createStatementFromText(newStatementText, anchor);
   final PsiElement addedStatement = anchor.getParent().addBefore(newStatement, anchor);
   CodeStyleManager.getInstance(project).reformat(addedStatement);
 }
 private static String compoundLambdaOrMethodReference(
     PsiParameter parameter,
     PsiExpression expression,
     String samQualifiedName,
     PsiType[] samParamTypes) {
   String result = "";
   final Project project = parameter.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass functionClass =
       psiFacade.findClass(samQualifiedName, GlobalSearchScope.allScope(project));
   for (int i = 0; i < samParamTypes.length; i++) {
     if (samParamTypes[i] instanceof PsiPrimitiveType) {
       samParamTypes[i] = ((PsiPrimitiveType) samParamTypes[i]).getBoxedType(expression);
     }
   }
   final PsiClassType functionalInterfaceType =
       functionClass != null
           ? psiFacade.getElementFactory().createType(functionClass, samParamTypes)
           : null;
   final PsiParameter[] parameters = {parameter};
   final String methodReferenceText =
       LambdaCanBeMethodReferenceInspection.convertToMethodReference(
           expression, parameters, functionalInterfaceType, null);
   if (methodReferenceText != null) {
     LOG.assertTrue(functionalInterfaceType != null);
     result += "(" + functionalInterfaceType.getCanonicalText() + ")" + methodReferenceText;
   } else {
     result += parameter.getName() + " -> " + expression.getText();
   }
   return result;
 }
    @Override
    public PsiType visitClassType(PsiClassType classType) {
      final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics();
      final PsiClass aClass = resolveResult.getElement();
      if (aClass == null) return classType;

      PsiUtilCore.ensureValid(aClass);
      if (aClass instanceof PsiTypeParameter) {
        final PsiTypeParameter typeParameter = (PsiTypeParameter) aClass;
        if (containsInMap(typeParameter)) {
          PsiType result = substituteTypeParameter(typeParameter);
          if (result != null) {
            PsiUtil.ensureValidType(result);
          }
          return result;
        }
        return classType;
      }
      final Map<PsiTypeParameter, PsiType> hashMap = new HashMap<PsiTypeParameter, PsiType>(2);
      if (!processClass(aClass, resolveResult.getSubstitutor(), hashMap)) {
        return null;
      }
      PsiClassType result =
          JavaPsiFacade.getElementFactory(aClass.getProject())
              .createType(aClass, createSubstitutor(hashMap), classType.getLanguageLevel());
      PsiUtil.ensureValidType(result);
      return result;
    }
 @NotNull
 @Override
 public PsiClassType rawType() {
   PsiClass psiClass = resolve();
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());
   return factory.createType(psiClass, factory.createRawSubstitutor(psiClass));
 }
  @NotNull
  private static PsiSubstitutor replaceVariables(Collection<InferenceVariable> inferenceVariables) {
    final List<InferenceVariable> targetVars = new ArrayList<InferenceVariable>();
    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    final InferenceVariable[] oldVars =
        inferenceVariables.toArray(new InferenceVariable[inferenceVariables.size()]);
    for (InferenceVariable variable : oldVars) {
      final InferenceVariable newVariable =
          new InferenceVariable(
              variable.getCallContext(), variable.getParameter(), variable.getName());
      substitutor =
          substitutor.put(
              variable,
              JavaPsiFacade.getElementFactory(variable.getProject()).createType(newVariable));
      targetVars.add(newVariable);
      if (variable.isThrownBound()) {
        newVariable.setThrownBound();
      }
    }

    for (int i = 0; i < targetVars.size(); i++) {
      InferenceVariable var = targetVars.get(i);
      for (InferenceBound boundType : InferenceBound.values()) {
        for (PsiType bound : oldVars[i].getBounds(boundType)) {
          var.addBound(substitutor.substitute(bound), boundType, null);
        }
      }
    }
    return substitutor;
  }
  private static boolean canBePrivate(
      PsiMethod method,
      Collection<PsiReference> references,
      Collection<? extends PsiElement> deleted,
      final PsiElement[] allElementsToDelete) {
    final PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) {
      return false;
    }

    PsiManager manager = method.getManager();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    final PsiElementFactory factory = facade.getElementFactory();
    final PsiModifierList privateModifierList;
    try {
      final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID);
      privateModifierList = newMethod.getModifierList();
      privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true);
    } catch (IncorrectOperationException e) {
      LOG.assertTrue(false);
      return false;
    }
    for (PsiReference reference : references) {
      final PsiElement element = reference.getElement();
      if (!isInside(element, allElementsToDelete)
          && !isInside(element, deleted)
          && !facade
              .getResolveHelper()
              .isAccessible(method, privateModifierList, element, null, null)) {
        return false;
      }
    }
    return true;
  }
  @Nullable
  public static PsiReferenceExpression createMockReference(
      final PsiElement place, @NotNull PsiType qualifierType, LookupElement qualifierItem) {
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getProject());
    if (qualifierItem.getObject() instanceof PsiClass) {
      final String qname = ((PsiClass) qualifierItem.getObject()).getQualifiedName();
      if (qname == null) return null;

      final String text = qname + ".xxx";
      try {
        final PsiExpression expr = factory.createExpressionFromText(text, place);
        if (expr instanceof PsiReferenceExpression) {
          return (PsiReferenceExpression) expr;
        }
        return null; // ignore ill-formed qualified names like "org.spark-project.jetty" that can't
                     // be used from Java code anyway
      } catch (IncorrectOperationException e) {
        LOG.info(e);
        return null;
      }
    }

    return (PsiReferenceExpression)
        factory.createExpressionFromText(
            "xxx.xxx", JavaCompletionUtil.createContextWithXxxVariable(place, qualifierType));
  }
 private void doMoveClass(PsiSubstitutor substitutor, MemberInfo info) {
   PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
   PsiClass aClass = (PsiClass) info.getMember();
   if (Boolean.FALSE.equals(info.getOverrides())) {
     final PsiReferenceList sourceReferenceList = info.getSourceReferenceList();
     LOG.assertTrue(sourceReferenceList != null);
     PsiJavaCodeReferenceElement ref =
         mySourceClass.equals(sourceReferenceList.getParent())
             ? RefactoringUtil.removeFromReferenceList(sourceReferenceList, aClass)
             : RefactoringUtil.findReferenceToClass(sourceReferenceList, aClass);
     if (ref != null && !myTargetSuperClass.isInheritor(aClass, false)) {
       RefactoringUtil.replaceMovedMemberTypeParameters(
           ref, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
       final PsiReferenceList referenceList =
           myIsTargetInterface
               ? myTargetSuperClass.getExtendsList()
               : myTargetSuperClass.getImplementsList();
       assert referenceList != null;
       referenceList.add(ref);
     }
   } else {
     RefactoringUtil.replaceMovedMemberTypeParameters(
         aClass, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
     fixReferencesToStatic(aClass);
     final PsiMember movedElement =
         (PsiMember)
             myTargetSuperClass.add(
                 convertClassToLanguage(aClass, myTargetSuperClass.getLanguage()));
     myMembersAfterMove.add(movedElement);
     aClass.delete();
   }
 }
 protected static void replaceExpressionWithNegatedExpression(
     @NotNull PsiExpression newExpression, @NotNull PsiExpression expression) {
   final Project project = expression.getProject();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   PsiExpression expressionToReplace = expression;
   final String newExpressionText = newExpression.getText();
   final String expString;
   if (BoolUtils.isNegated(expression)) {
     expressionToReplace = BoolUtils.findNegation(expression);
     expString = newExpressionText;
   } else if (ComparisonUtils.isComparison(newExpression)) {
     final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) newExpression;
     final String negatedComparison =
         ComparisonUtils.getNegatedComparison(binaryExpression.getOperationTokenType());
     final PsiExpression lhs = binaryExpression.getLOperand();
     final PsiExpression rhs = binaryExpression.getROperand();
     assert rhs != null;
     expString = lhs.getText() + negatedComparison + rhs.getText();
   } else {
     if (ParenthesesUtils.getPrecedence(newExpression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
       expString = "!(" + newExpressionText + ')';
     } else {
       expString = '!' + newExpressionText;
     }
   }
   final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
   assert expressionToReplace != null;
   final PsiElement insertedElement = expressionToReplace.replace(newCall);
   final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
   codeStyleManager.reformat(insertedElement);
 }
Exemple #21
0
 @Override
 protected PsiVariable createFieldToStartTemplateOn(
     final String[] names, final PsiType defaultType) {
   final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myMethod.getProject());
   return ApplicationManager.getApplication()
       .runWriteAction(
           new Computable<PsiParameter>() {
             @Override
             public PsiParameter compute() {
               final PsiParameter anchor =
                   JavaIntroduceParameterMethodUsagesProcessor.getAnchorParameter(myMethod);
               final PsiParameter psiParameter =
                   (PsiParameter)
                       myMethod
                           .getParameterList()
                           .addAfter(
                               elementFactory.createParameter(
                                   chooseName(names, myMethod.getLanguage()), defaultType),
                               anchor);
               PsiUtil.setModifierProperty(
                   psiParameter, PsiModifier.FINAL, myPanel.hasFinalModifier());
               myParameterIndex = myMethod.getParameterList().getParameterIndex(psiParameter);
               return psiParameter;
             }
           });
 }
Exemple #22
0
  private void specialCase(
      InferenceSession session,
      List<ConstraintFormula> constraints,
      PsiSubstitutor substitutor,
      PsiParameter[] targetParameters,
      boolean ignoreRaw) {
    final PsiElement qualifier = myExpression.getQualifier();
    PsiType qualifierType = null;
    if (qualifier instanceof PsiTypeElement) {
      qualifierType = ((PsiTypeElement) qualifier).getType();
      final PsiClass qualifierClass = PsiUtil.resolveClassInType(qualifierType);
      if (qualifierClass != null) {
        qualifierType =
            JavaPsiFacade.getElementFactory(myExpression.getProject())
                .createType(qualifierClass, PsiSubstitutor.EMPTY);
      }
    } else if (qualifier instanceof PsiExpression) {
      qualifierType = ((PsiExpression) qualifier).getType();
      if (qualifierType == null && qualifier instanceof PsiReferenceExpression) {
        final JavaResolveResult resolveResult =
            ((PsiReferenceExpression) qualifier).advancedResolve(false);
        final PsiElement res = resolveResult.getElement();
        if (res instanceof PsiClass) {
          PsiClass containingClass = (PsiClass) res;
          final boolean isRawSubst =
              !ignoreRaw
                  && !myExpression.isConstructor()
                  && PsiUtil.isRawSubstitutor(containingClass, resolveResult.getSubstitutor());
          qualifierType =
              JavaPsiFacade.getElementFactory(res.getProject())
                  .createType(
                      containingClass,
                      isRawSubst ? PsiSubstitutor.EMPTY : resolveResult.getSubstitutor());
        }
      }
    }

    final PsiClass qualifierClass = PsiUtil.resolveClassInType(qualifierType);
    if (qualifierClass != null) {
      session.initBounds(myExpression, qualifierClass.getTypeParameters());
      constraints.add(
          new StrictSubtypingConstraint(
              session.substituteWithInferenceVariables(qualifierType),
              session.substituteWithInferenceVariables(
                  substitutor.substitute(targetParameters[0].getType()))));
    }
  }
 private static PsiClassType createDefaultConsumerType(Project project, PsiParameter parameter) {
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass consumerClass =
       psiFacade.findClass("java.util.function.Consumer", GlobalSearchScope.allScope(project));
   return consumerClass != null
       ? psiFacade.getElementFactory().createType(consumerClass, parameter.getType())
       : null;
 }
 private static PsiType genNewListBy(PsiType genericOwner, PsiManager manager) {
   PsiClass list =
       JavaPsiFacade.getInstance(manager.getProject())
           .findClass(JAVA_UTIL_LIST, genericOwner.getResolveScope());
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject());
   if (list == null) return factory.createTypeFromText(JAVA_UTIL_LIST, null);
   return factory.createType(list, PsiUtil.extractIterableTypeParameter(genericOwner, false));
 }
 private static void notNull(Project project, PsiField field, PsiParameter parameter) {
   final String notNull = NullableNotNullManager.getInstance(field.getProject()).getNotNull(field);
   if (notNull != null) {
     final PsiAnnotation annotation =
         JavaPsiFacade.getElementFactory(project).createAnnotationFromText("@" + notNull, field);
     parameter.getModifierList().addBefore(annotation, null);
   }
 }
 public void testParamWithImplicitConstructors() throws Exception {
   final PsiMethod method = getPrimaryMethod();
   parameterPropagationTest(
       method,
       collectDefaultConstructorsToPropagate(method),
       JavaPsiFacade.getElementFactory(getProject())
           .createTypeByFQClassName("java.lang.Class", GlobalSearchScope.allScope(getProject())));
 }
 @Override
 protected void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement element = descriptor.getPsiElement();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   final PsiExpression newExpression =
       factory.createExpressionFromText("new java.lang.NullPointerException()", element);
   element.replace(newExpression);
 }
Exemple #28
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;
  }
  @Nullable
  @Override
  protected List<ClosureParameterInfo> getParameterInfos(
      InsertionContext context,
      PsiMethod method,
      PsiSubstitutor substitutor,
      Document document,
      int offset,
      PsiElement parent) {
    final String name = method.getName();
    if (!"eachWithIndex".equals(name)) return null;

    if (method instanceof GrGdkMethod) method = ((GrGdkMethod) method).getStaticMethod();

    final PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) return null;

    final String qname = containingClass.getQualifiedName();

    if (!GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(qname)) return null;

    final PsiParameter[] parameters = method.getParameterList().getParameters();
    if (parameters.length != 2) return null;

    final PsiType type = parameters[0].getType();
    final PsiType collection = substitutor.substitute(type);

    final PsiType iterable = getIteratedType(parent, collection);
    if (iterable != null) {
      return Arrays.asList(
          new ClosureParameterInfo(iterable.getCanonicalText(), "entry"),
          new ClosureParameterInfo("int", "i"));
    }

    if (InheritanceUtil.isInheritor(collection, CommonClassNames.JAVA_UTIL_MAP)) {
      final PsiType[] typeParams = ((PsiClassType) collection).getParameters();

      final Project project = context.getProject();

      final PsiClass entry =
          JavaPsiFacade.getInstance(project)
              .findClass("java.util.Map.Entry", parent.getResolveScope());
      if (entry == null) return null;

      final PsiClassType entryType =
          JavaPsiFacade.getElementFactory(project).createType(entry, typeParams);

      return Arrays.asList(
          new ClosureParameterInfo(entryType.getCanonicalText(), "entry"),
          new ClosureParameterInfo("int", "i"));
    }

    return Arrays.asList(
        new ClosureParameterInfo(collection.getCanonicalText(), "entry"),
        new ClosureParameterInfo("int", "i"));
  }
 private void exceptionPropagationTest(
     final PsiMethod method, final Set<PsiMethod> methodsToPropagateExceptions) throws Exception {
   PsiClassType newExceptionType =
       JavaPsiFacade.getElementFactory(getProject())
           .createTypeByFQClassName(
               "java.lang.Exception", GlobalSearchScope.allScope(getProject()));
   final ThrownExceptionInfo[] newExceptions =
       new ThrownExceptionInfo[] {new JavaThrownExceptionInfo(-1, newExceptionType)};
   doTest(new ParameterInfoImpl[0], newExceptions, null, methodsToPropagateExceptions, method);
 }