@Override
 protected String buildErrorString(Object... args) {
   PsiType ltype = (PsiType) args[0];
   PsiType rtype = (PsiType) args[1];
   return GroovyInspectionBundle.message(
       "rtype.cannot.contain.ltype", ltype.getPresentableText(), rtype.getPresentableText());
 }
  @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;
  }
示例#3
0
 @Nullable
 private static String getLongTypeName(PsiType type) {
   if (type instanceof PsiClassType) {
     PsiClass aClass = ((PsiClassType) type).resolve();
     if (aClass == null) {
       return null;
     } else if (aClass instanceof PsiAnonymousClass) {
       PsiClass baseClass = ((PsiAnonymousClass) aClass).getBaseClassType().resolve();
       return baseClass != null ? baseClass.getQualifiedName() : null;
     } else {
       return aClass.getQualifiedName();
     }
   } else if (type instanceof PsiArrayType) {
     return getLongTypeName(((PsiArrayType) type).getComponentType()) + "[]";
   } else if (type instanceof PsiPrimitiveType) {
     return type.getPresentableText();
   } else if (type instanceof PsiWildcardType) {
     final PsiType bound = ((PsiWildcardType) type).getBound();
     return bound != null ? getLongTypeName(bound) : CommonClassNames.JAVA_LANG_OBJECT;
   } else if (type instanceof PsiCapturedWildcardType) {
     final PsiType bound = ((PsiCapturedWildcardType) type).getWildcard().getBound();
     return bound != null ? getLongTypeName(bound) : CommonClassNames.JAVA_LANG_OBJECT;
   } else if (type instanceof PsiIntersectionType) {
     return getLongTypeName(((PsiIntersectionType) type).getRepresentative());
   } else if (type instanceof PsiDisjunctionType) {
     return getLongTypeName(((PsiDisjunctionType) type).getLeastUpperBound());
   } else {
     return null;
   }
 }
  private static void generateNamesForCollectionType(
      PsiType type, Set<String> possibleNames, NameValidator validator) {
    PsiType componentType = getCollectionComponentType(type, validator.getProject());
    if (!(type instanceof PsiClassType) || componentType == null) return;
    PsiClass clazz = ((PsiClassType) type).resolve();
    if (clazz == null) return;
    String collectionName = clazz.getName();
    assert collectionName != null;

    String componentName = cleanTypeName(componentType.getPresentableText());
    if (componentType instanceof PsiClassType) {
      PsiClassType classType = (PsiClassType) componentType;
      PsiClass psiClass = classType.resolve();
      if (psiClass == null) return;
      componentName = psiClass.getName();
    }

    assert componentName != null;
    String candidateName = StringUtil.pluralize(GroovyNamesUtil.fromLowerLetter(componentName));
    generateCamelNames(possibleNames, validator, candidateName);

    ArrayList<String> camelizedName = GroovyNamesUtil.camelizeString(candidateName);
    candidateName = camelizedName.get(camelizedName.size() - 1);
    candidateName = collectionName.toLowerCase() + "Of" + fromUpperLetter(candidateName);
    possibleNames.add(validator.validateName(candidateName, true));
  }
  @Nullable
  private static String formatTypeParameters(
      @NotNull final PsiSubstitutor substitutor, final PsiTypeParameter[] params) {
    final boolean space = showSpaceAfterComma(params[0]);
    StringBuilder buffer = new StringBuilder();
    buffer.append("<");
    for (int i = 0; i < params.length; i++) {
      final PsiTypeParameter param = params[i];
      final PsiType type = substitutor.substitute(param);
      if (type == null) {
        return "";
      }
      if (type instanceof PsiClassType && ((PsiClassType) type).getParameters().length > 0) {
        buffer.append(((PsiClassType) type).rawType().getPresentableText()).append("<...>");
      } else {
        buffer.append(type.getPresentableText());
      }

      if (i < params.length - 1) {
        buffer.append(",");
        if (space) {
          buffer.append(" ");
        }
      }
    }
    buffer.append(">");
    return buffer.toString();
  }
  public static String[] getParameterString(ExtractInfoHelper helper, boolean useCanonicalText) {
    int i = 0;
    ParameterInfo[] infos = helper.getParameterInfos();
    int number = 0;
    for (ParameterInfo info : infos) {
      if (info.passAsParameter()) number++;
    }
    ArrayList<String> params = new ArrayList<String>();
    for (ParameterInfo info : infos) {
      if (info.passAsParameter()) {
        PsiType paramType = info.getType();
        final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(paramType);
        if (unboxed != null) paramType = unboxed;
        String paramTypeText;

        if (paramType == null || paramType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
          paramTypeText = "";
        } else {
          paramTypeText =
              (useCanonicalText ? paramType.getCanonicalText() : paramType.getPresentableText())
                  + " ";
        }
        params.add(paramTypeText + info.getName() + (i < number - 1 ? ", " : ""));
        i++;
      }
    }
    return ArrayUtil.toStringArray(params);
  }
  private static Map<String, PsiType> getCompatibleTypeNames(
      @NotNull PsiType type, @Nullable PsiType min, PsiManager manager, GlobalSearchScope scope) {
    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    // if initial type is not assignable to min type we don't take into consideration min type.
    if (min != null && !TypesUtil.isAssignable(min, type, manager, scope)) {
      min = null;
    }

    Map<String, PsiType> map = new LinkedHashMap<String, PsiType>();
    final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type);
    if (unboxed != null) type = unboxed;
    final Set<PsiType> set = new LinkedHashSet<PsiType>();
    set.add(type);
    while (!set.isEmpty()) {
      PsiType cur = set.iterator().next();
      set.remove(cur);
      if (!map.containsValue(cur)
          && (min == null || TypesUtil.isAssignable(min, cur, manager, scope))) {
        if (isPartiallySubstituted(cur)) {
          LOG.assertTrue(cur instanceof PsiClassType);
          PsiClassType rawType = ((PsiClassType) cur).rawType();
          map.put(rawType.getPresentableText(), rawType);
        } else {
          map.put(cur.getPresentableText(), cur);
        }
        for (PsiType superType : cur.getSuperTypes()) {
          if (!map.containsValue(superType)) {
            set.add(superType);
          }
        }
      }
    }
    return map;
  }
示例#8
0
 @Nullable
 private static String getTypeName(PsiType type, boolean withIndices) {
   type = type.getDeepComponentType();
   if (type instanceof PsiClassType) {
     final PsiClassType classType = (PsiClassType) type;
     final String className = classType.getClassName();
     if (className != null || !withIndices) return className;
     final PsiClass aClass = classType.resolve();
     return aClass instanceof PsiAnonymousClass
         ? ((PsiAnonymousClass) aClass).getBaseClassType().getClassName()
         : null;
   } else if (type instanceof PsiPrimitiveType) {
     return type.getPresentableText();
   } else if (type instanceof PsiWildcardType) {
     return getTypeName(((PsiWildcardType) type).getExtendsBound(), withIndices);
   } else if (type instanceof PsiIntersectionType) {
     return getTypeName(((PsiIntersectionType) type).getRepresentative(), withIndices);
   } else if (type instanceof PsiCapturedWildcardType) {
     return getTypeName(((PsiCapturedWildcardType) type).getWildcard(), withIndices);
   } else if (type instanceof PsiDisjunctionType) {
     return getTypeName(((PsiDisjunctionType) type).getLeastUpperBound(), withIndices);
   } else {
     return null;
   }
 }
 @Override
 @NotNull
 protected String buildErrorString(Object... infos) {
   final PsiType expectedType = (PsiType) infos[0];
   final String typeText = expectedType.getPresentableText();
   return InspectionGadgetsBundle.message("overly.strong.type.cast.problem.descriptor", typeText);
 }
 @Override
 @NotNull
 public String buildErrorString(Object... infos) {
   final PsiType type = (PsiType) infos[0];
   final String typeName = type.getPresentableText();
   return InspectionGadgetsBundle.message("stringbuffer.field.problem.descriptor", typeName);
 }
 @Override
 @NotNull
 public String getText() {
   return QuickFixBundle.message(
       "change.new.operator.type.text",
       new PsiExpressionTrimRenderer.RenderFunction().fun(myExpression),
       myType.getPresentableText(),
       myType instanceof PsiArrayType ? "" : "()");
 }
示例#12
0
 @NotNull
 public static LookupElementBuilder createPropertyLookupElement(
     @NotNull String name, @Nullable PsiType type) {
   LookupElementBuilder res =
       LookupElementBuilder.create(name).withIcon(JetgroovyIcons.Groovy.Property);
   if (type != null) {
     res = res.withTypeText(type.getPresentableText());
   }
   return res;
 }
  @Override
  @NotNull
  public Map<String, NamedArgumentDescriptor> getNamedParameters() {
    final GrMethodStub stub = getStub();
    if (stub != null) {
      String[] namedParameters = stub.getNamedParameters();
      if (namedParameters.length == 0) return Collections.emptyMap();

      Map<String, NamedArgumentDescriptor> result = ContainerUtil.newHashMap();

      for (String parameter : namedParameters) {
        result.put(parameter, GrNamedArgumentSearchVisitor.CODE_NAMED_ARGUMENTS_DESCR);
      }
      return result;
    }

    GrOpenBlock body = getBlock();
    if (body == null) return Collections.emptyMap();

    GrParameter[] parameters = getParameters();
    if (parameters.length == 0) return Collections.emptyMap();
    GrParameter firstParameter = parameters[0];

    PsiType type = firstParameter.getTypeGroovy();
    GrTypeElement typeElement = firstParameter.getTypeElementGroovy();
    // equalsToText can't be called here because of stub creating

    if (type != null
        && typeElement != null
        && type.getPresentableText() != null
        && !type.getPresentableText().endsWith("Map")) {
      return Collections.emptyMap();
    }

    GrNamedArgumentSearchVisitor visitor =
        new GrNamedArgumentSearchVisitor(firstParameter.getNameIdentifierGroovy().getText());

    body.accept(visitor);
    return visitor.getResult();
  }
 public static boolean isInjectable(@Nullable final PsiType type, final Project project) {
   if (type == null) return false;
   if (type instanceof PsiPrimitiveType) return false;
   if (project.isDefault()) {
     @NonNls final String text = type.getPresentableText();
     if (text == null) return false;
     return text.equals("java.lang.String")
         || text.equals("java.lang.String...")
         || text.equals("java.lang.String[]");
   } else {
     return type.equalsToText("java.lang.String")
         || type.equalsToText("java.lang.String...")
         || type.equalsToText("java.lang.String[]");
   }
 }
 @Nullable
 private static String formatTypesList(ParameterInfoImpl[] infos, PsiElement context) {
   if (infos == null) return null;
   StringBuilder result = new StringBuilder();
   try {
     for (ParameterInfoImpl info : infos) {
       PsiType type = info.createType(context);
       if (type == null) return null;
       if (result.length() != 0) result.append(", ");
       result.append(type.getPresentableText());
     }
     return result.toString();
   } catch (IncorrectOperationException e) {
     return null;
   }
 }
  private static PsiTypeLookupItem doCreateItem(
      final PsiType type,
      PsiElement context,
      int bracketsCount,
      boolean diamond,
      InsertHandler<PsiTypeLookupItem> importFixer) {
    if (type instanceof PsiClassType) {
      PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType) type).resolveGenerics();
      final PsiClass psiClass = classResolveResult.getElement();

      if (psiClass != null) {
        String name = psiClass.getName();
        if (name != null) {
          final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();

          PsiClass resolved =
              JavaPsiFacade.getInstance(psiClass.getProject())
                  .getResolveHelper()
                  .resolveReferencedClass(name, context);

          Set<String> allStrings = new HashSet<String>();
          allStrings.add(name);
          if (!psiClass.getManager().areElementsEquivalent(resolved, psiClass)
              && !PsiUtil.isInnerClass(psiClass)) {
            // inner class name should be shown qualified if its not accessible by single name
            PsiClass aClass = psiClass.getContainingClass();
            while (aClass != null && !PsiUtil.isInnerClass(aClass) && aClass.getName() != null) {
              name = aClass.getName() + '.' + name;
              allStrings.add(name);
              aClass = aClass.getContainingClass();
            }
          }

          PsiTypeLookupItem item =
              new PsiTypeLookupItem(
                  psiClass, name, diamond, bracketsCount, importFixer, substitutor);
          item.addLookupStrings(ArrayUtil.toStringArray(allStrings));
          return item;
        }
      }
    }
    return new PsiTypeLookupItem(
        type, type.getPresentableText(), false, bracketsCount, importFixer, PsiSubstitutor.EMPTY);
  }
  public static String getTypeString(
      ExtractMethodInfoHelper helper, boolean forPresentation, String modifier) {
    PsiType type = helper.getOutputType();
    final PsiPrimitiveType outUnboxed = PsiPrimitiveType.getUnboxedType(type);
    if (outUnboxed != null) type = outUnboxed;

    String typeText = forPresentation ? type.getPresentableText() : type.getCanonicalText();
    String returnType = typeText == null || !helper.specifyType() ? "" : typeText;

    if (StringUtil.isEmptyOrSpaces(returnType) || "null".equals(returnType)) {
      if (modifier.length() == 0) {
        return "def ";
      } else {
        return "";
      }
    } else {
      return returnType + " ";
    }
  }
 @Override
 public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element)
     throws IncorrectOperationException {
   if (!FileModificationService.getInstance().preparePsiElementsForWrite(element)) return;
   final XmlAttribute attr = (XmlAttribute) element.getParent();
   final String name = attr.getName();
   final XmlAttributeDescriptor descriptor = attr.getDescriptor();
   LOG.assertTrue(descriptor != null);
   String value = attr.getValue();
   final PsiElement declaration = descriptor.getDeclaration();
   if (declaration instanceof PsiField) {
     final PsiType fieldType = ((PsiField) declaration).getType();
     final PsiType itemType =
         JavaGenericsUtil.getCollectionItemType(fieldType, declaration.getResolveScope());
     if (itemType != null) {
       final String typeNode = itemType.getPresentableText();
       JavaFxPsiUtil.insertImportWhenNeeded(
           (XmlFile) attr.getContainingFile(), typeNode, itemType.getCanonicalText());
       final String[] vals = value.split(",");
       value =
           StringUtil.join(
               vals,
               new Function<String, String>() {
                 @Override
                 public String fun(String s) {
                   return "<"
                       + typeNode
                       + " "
                       + FxmlConstants.FX_VALUE
                       + "=\""
                       + s.trim()
                       + "\"/>";
                 }
               },
               "\n");
     }
   }
   final XmlTag childTag =
       XmlElementFactory.getInstance(project)
           .createTagFromText("<" + name + ">" + value + "</" + name + ">");
   attr.getParent().add(childTag);
   attr.delete();
 }
示例#19
0
    public String toString() {
      final StringBuffer buffer = new StringBuffer();

      for (PsiTypeVariable boundVariable : myBoundVariables) {
        final int i = boundVariable.getIndex();
        final PsiType binding = myBindings.get(i);

        if (binding != null) {
          buffer
              .append("#")
              .append(i)
              .append(" -> ")
              .append(binding.getPresentableText())
              .append("; ");
        }
      }

      return buffer.toString();
    }
  private static void generateNamesForArrayType(
      PsiType type, Set<String> possibleNames, NameValidator validator) {
    int arrayDim = type.getArrayDimensions();
    if (arrayDim == 0) return;
    PsiType deepType = type.getDeepComponentType();
    String candidateName = cleanTypeName(deepType.getPresentableText());
    if (deepType instanceof PsiClassType) {
      PsiClass clazz = ((PsiClassType) deepType).resolve();
      if (clazz == null) return;
      candidateName = GroovyNamesUtil.fromLowerLetter(clazz.getName());
    }
    candidateName = StringUtil.pluralize(GroovyNamesUtil.fromLowerLetter(candidateName));
    generateCamelNames(possibleNames, validator, candidateName);

    ArrayList<String> camelizedName = GroovyNamesUtil.camelizeString(candidateName);
    candidateName = camelizedName.get(camelizedName.size() - 1);
    candidateName = "arrayOf" + fromUpperLetter(candidateName);
    possibleNames.add(validator.validateName(candidateName, true));
  }
示例#21
0
  @Nullable
  public static LookupElementBuilder createPropertyLookupElement(
      @NotNull PsiMethod accessor,
      @Nullable GroovyResolveResult resolveResult,
      @Nullable PrefixMatcher matcher) {
    String propName;
    PsiType propType;
    final boolean getter = GroovyPropertyUtils.isSimplePropertyGetter(accessor, null);
    if (getter) {
      propName = GroovyPropertyUtils.getPropertyNameByGetter(accessor);
    } else if (GroovyPropertyUtils.isSimplePropertySetter(accessor, null)) {
      propName = GroovyPropertyUtils.getPropertyNameBySetter(accessor);
    } else {
      return null;
    }
    assert propName != null;
    if (!PsiUtil.isValidReferenceName(propName)) {
      propName = "'" + propName + "'";
    }

    if (matcher != null && !matcher.prefixMatches(propName)) {
      return null;
    }

    if (getter) {
      propType = PsiUtil.getSmartReturnType(accessor);
    } else {
      propType = accessor.getParameterList().getParameters()[0].getType();
    }

    final PsiType substituted =
        resolveResult != null ? resolveResult.getSubstitutor().substitute(propType) : propType;

    LookupElementBuilder builder =
        LookupElementBuilder.create(
                generatePropertyResolveResult(propName, accessor, propType, resolveResult),
                propName)
            .withIcon(JetgroovyIcons.Groovy.Property);
    if (substituted != null) {
      builder = builder.withTypeText(substituted.getPresentableText());
    }
    return builder;
  }
  @NotNull
  public static String getTypeString(
      @NotNull ExtractMethodInfoHelper helper, boolean forPresentation, @NotNull String modifier) {
    if (!helper.specifyType()) {
      return modifier.isEmpty() ? "def " : "";
    }

    PsiType type = helper.getOutputType();
    final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type);
    if (unboxed != null) type = unboxed;

    final String returnType =
        StringUtil.notNullize(
            forPresentation ? type.getPresentableText() : type.getCanonicalText());

    if (StringUtil.isEmptyOrSpaces(returnType) || "null".equals(returnType)) {
      return modifier.isEmpty() ? "def " : "";
    } else {
      return returnType + " ";
    }
  }
  private static PsiField createField(
      PsiLocalVariable local, PsiType forcedType, String fieldName, boolean includeInitializer) {
    @NonNls StringBuilder pattern = new StringBuilder();
    pattern.append("var ");
    pattern.append(fieldName);

    PsiType type = local.getType();
    if (local.getInitializer() == null) {
      includeInitializer = false;
    } else {
      type = local.getInitializer().getType();
    }

    pattern.append(": ").append(type.getPresentableText());
    if (includeInitializer) {
      pattern.append(" = ").append(local.getInitializer().getText());
    }

    final PsiElement psiElement =
        GosuPsiParseUtil.parseProgramm(
            pattern.toString(), PsiManager.getInstance(local.getProject()), null);

    final GosuFieldImpl field = PsiTreeUtil.findChildOfType(psiElement, GosuFieldImpl.class);

    GeneratedMarkerVisitor.markGenerated(field);

    try {
      final PsiModifierList modifierList = local.getModifierList();
      if (modifierList != null) {
        for (PsiAnnotation annotation : modifierList.getAnnotations()) {
          field.getModifierList().add(annotation.copy());
        }
      }
      return field;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
 private static void generateByType(
     PsiType type, Set<String> possibleNames, NameValidator validator) {
   String typeName = type.getPresentableText();
   generateNamesForCollectionType(type, possibleNames, validator);
   generateNamesForArrayType(type, possibleNames, validator);
   generateNamesForExceptions(type, possibleNames, validator);
   typeName = cleanTypeName(typeName);
   if (typeName.equals("String")) {
     possibleNames.add(validator.validateName("s", true));
   }
   if (typeName.equals("Closure")) {
     possibleNames.add(validator.validateName("cl", true));
   }
   if (typeName.toUpperCase().equals(typeName)) {
     possibleNames.add(
         validator.validateName(
             GroovyNamesUtil.deleteNonLetterFromString(typeName.toLowerCase()), true));
   } else if (!typeName.equals(typeName.toLowerCase())) {
     generateCamelNames(possibleNames, validator, typeName);
     possibleNames.remove(typeName);
   }
 }
  private static LookupItem doCreateItem(PsiType type, PsiElement context) {
    if (type instanceof PsiClassType) {
      PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType) type).resolveGenerics();
      final PsiClass psiClass = classResolveResult.getElement();
      final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
      final String text = type.getCanonicalText();
      String typeString = text;
      String typeParams = "";
      if (text.indexOf('<') > 0 && text.endsWith(">")) {
        typeString = text.substring(0, text.indexOf('<'));
        typeParams = text.substring(text.indexOf('<'));
      }

      String lookupString = text.substring(typeString.lastIndexOf('.') + 1);
      if (psiClass != null) {
        PsiClass resolved =
            JavaPsiFacade.getInstance(psiClass.getProject())
                .getResolveHelper()
                .resolveReferencedClass(psiClass.getName(), context);
        if (!psiClass.getManager().areElementsEquivalent(resolved, psiClass)) {
          // inner class name should be shown qualified if its not accessible by single name
          PsiClass aClass = psiClass;
          lookupString = "";
          while (aClass != null) {
            lookupString = aClass.getName() + (lookupString == "" ? "" : ".") + lookupString;
            aClass = aClass.getContainingClass();
          }
          lookupString += typeParams;
        }
        LookupItem item = new PsiTypeLookupItem(psiClass, lookupString);
        item.setAttribute(SUBSTITUTOR, substitutor);
        return item;
      }
    }
    return new LookupItem(type, type.getPresentableText());
  }
  private static LookupElementBuilder createGenerateMethodElement(
      PsiMethod prototype,
      PsiSubstitutor substitutor,
      Icon icon,
      String typeText,
      InsertHandler<LookupElement> insertHandler) {
    String methodName = prototype.getName();

    String visibility = VisibilityUtil.getVisibilityModifier(prototype.getModifierList());
    String modifiers = (visibility == PsiModifier.PACKAGE_LOCAL ? "" : visibility + " ");

    PsiType type = substitutor.substitute(prototype.getReturnType());
    String signature =
        modifiers + (type == null ? "" : type.getPresentableText() + " ") + methodName;

    String parameters =
        PsiFormatUtil.formatMethod(
            prototype, substitutor, PsiFormatUtilBase.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_NAME);

    String overrideSignature =
        " @Override "
            + signature; // leading space to make it a middle match, under all annotation
                         // suggestions
    LookupElementBuilder element =
        LookupElementBuilder.create(prototype, signature)
            .withLookupString(methodName)
            .withLookupString(signature)
            .withLookupString(overrideSignature)
            .withInsertHandler(insertHandler)
            .appendTailText(parameters, false)
            .appendTailText(" {...}", true)
            .withTypeText(typeText)
            .withIcon(icon);
    element.putUserData(GENERATE_ELEMENT, true);
    return element;
  }
示例#27
0
 @Override
 public String toString() {
   return myExpression.getText() + " -> " + myT.getPresentableText();
 }
  private void buildText(
      @NotNull PsiClass aClass,
      @NotNull PsiSubstitutor substitutor,
      @NotNull StringBuilder buffer,
      @NotNull TextType textType,
      boolean annotated) {
    if (aClass instanceof PsiAnonymousClass) {
      ClassResolveResult baseResolveResult =
          ((PsiAnonymousClass) aClass).getBaseClassType().resolveGenerics();
      PsiClass baseClass = baseResolveResult.getElement();
      if (baseClass != null) {
        buildText(baseClass, baseResolveResult.getSubstitutor(), buffer, textType, false);
      }
      return;
    }

    boolean qualified = textType != TextType.PRESENTABLE;

    PsiClass enclosingClass = null;
    if (!aClass.hasModifierProperty(PsiModifier.STATIC)) {
      PsiElement parent = aClass.getParent();
      if (parent instanceof PsiClass && !(parent instanceof PsiAnonymousClass)) {
        enclosingClass = (PsiClass) parent;
      }
    }
    if (enclosingClass != null) {
      buildText(enclosingClass, substitutor, buffer, textType, false);
      buffer.append('.');
    } else if (qualified) {
      String fqn = aClass.getQualifiedName();
      if (fqn != null) {
        String prefix = StringUtil.getPackageName(fqn);
        if (!StringUtil.isEmpty(prefix)) {
          buffer.append(prefix);
          buffer.append('.');
        }
      }
    }

    if (annotated) {
      PsiNameHelper.appendAnnotations(buffer, getAnnotations(), qualified);
    }

    buffer.append(aClass.getName());

    PsiTypeParameter[] typeParameters = aClass.getTypeParameters();
    if (typeParameters.length > 0) {
      int pos = buffer.length();
      buffer.append('<');

      for (int i = 0; i < typeParameters.length; i++) {
        PsiTypeParameter typeParameter = typeParameters[i];
        PsiUtilCore.ensureValid(typeParameter);

        if (i > 0) {
          buffer.append(',');
          if (textType == TextType.PRESENTABLE) buffer.append(' ');
        }

        PsiType substitutionResult = substitutor.substitute(typeParameter);
        if (substitutionResult == null) {
          buffer.setLength(pos);
          pos = -1;
          break;
        }
        PsiUtil.ensureValidType(substitutionResult);

        if (textType == TextType.PRESENTABLE) {
          buffer.append(substitutionResult.getPresentableText());
        } else if (textType == TextType.CANONICAL) {
          buffer.append(substitutionResult.getCanonicalText(annotated));
        } else {
          buffer.append(substitutionResult.getInternalCanonicalText());
        }
      }

      if (pos >= 0) {
        buffer.append('>');
      }
    }
  }
  private void buildText(
      @NotNull PsiClass aClass,
      @NotNull PsiSubstitutor substitutor,
      @NotNull StringBuilder buffer,
      boolean canonical,
      boolean internal) {
    if (aClass instanceof PsiAnonymousClass) {
      ClassResolveResult baseResolveResult =
          ((PsiAnonymousClass) aClass).getBaseClassType().resolveGenerics();
      PsiClass baseClass = baseResolveResult.getElement();
      PsiSubstitutor baseSub = baseResolveResult.getSubstitutor();
      if (baseClass != null) {
        buildText(baseClass, baseSub, buffer, canonical, internal);
      }
      return;
    }

    if (canonical == internal) {
      buffer.append(getAnnotationsTextPrefix(internal, false, true));
    }

    PsiClass enclosingClass = null;
    if (!aClass.hasModifierProperty(PsiModifier.STATIC)) {
      final PsiElement parent = aClass.getParent();
      if (parent instanceof PsiClass && !(parent instanceof PsiAnonymousClass)) {
        enclosingClass = (PsiClass) parent;
      }
    }
    if (enclosingClass != null) {
      buildText(enclosingClass, substitutor, buffer, canonical, false);
      buffer.append('.');
      buffer.append(aClass.getName());
    } else {
      final String name;
      if (!canonical) {
        name = aClass.getName();
      } else {
        final String qualifiedName = aClass.getQualifiedName();
        if (qualifiedName == null) {
          name = aClass.getName();
        } else {
          name = qualifiedName;
        }
      }
      buffer.append(name);
    }

    PsiTypeParameter[] typeParameters = aClass.getTypeParameters();
    if (typeParameters.length > 0) {
      StringBuilder pineBuffer = new StringBuilder();
      pineBuffer.append('<');
      for (int i = 0; i < typeParameters.length; i++) {
        PsiTypeParameter typeParameter = typeParameters[i];
        assert typeParameter.isValid();
        if (i > 0) pineBuffer.append(',');
        final PsiType substitutionResult = substitutor.substitute(typeParameter);
        if (substitutionResult == null) {
          pineBuffer = null;
          break;
        }
        assert substitutionResult.isValid();
        if (canonical) {
          if (internal) {
            pineBuffer.append(substitutionResult.getInternalCanonicalText());
          } else {
            pineBuffer.append(substitutionResult.getCanonicalText());
          }
        } else {
          pineBuffer.append(substitutionResult.getPresentableText());
        }
      }
      if (pineBuffer != null) {
        buffer.append(pineBuffer);
        buffer.append('>');
      }
    }
  }
  @Override
  public String advertise(@NotNull final CompletionParameters parameters) {
    if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;

    if (parameters.getCompletionType() == CompletionType.BASIC
        && parameters.getInvocationCount() > 0) {
      PsiElement position = parameters.getPosition();
      if (psiElement()
          .withParent(
              psiReferenceExpression()
                  .withFirstChild(psiReferenceExpression().referencing(psiClass())))
          .accepts(position)) {
        if (CompletionUtil.shouldShowFeature(
            parameters, JavaCompletionFeatures.GLOBAL_MEMBER_NAME)) {
          final String shortcut = getActionShortcut(IdeActions.ACTION_CODE_COMPLETION);
          if (shortcut != null) {
            return "Pressing "
                + shortcut
                + " twice without a class qualifier would show all accessible static methods";
          }
        }
      }
    }

    if (parameters.getCompletionType() != CompletionType.SMART
        && shouldSuggestSmartCompletion(parameters.getPosition())) {
      if (CompletionUtil.shouldShowFeature(
          parameters, CodeCompletionFeatures.EDITING_COMPLETION_SMARTTYPE_GENERAL)) {
        final String shortcut = getActionShortcut(IdeActions.ACTION_SMART_TYPE_COMPLETION);
        if (shortcut != null) {
          return CompletionBundle.message("completion.smart.hint", shortcut);
        }
      }
    }

    if (parameters.getCompletionType() == CompletionType.SMART
        && parameters.getInvocationCount() == 1) {
      final PsiType[] psiTypes =
          ExpectedTypesGetter.getExpectedTypes(parameters.getPosition(), true);
      if (psiTypes.length > 0) {
        if (CompletionUtil.shouldShowFeature(
            parameters, JavaCompletionFeatures.SECOND_SMART_COMPLETION_TOAR)) {
          final String shortcut = getActionShortcut(IdeActions.ACTION_SMART_TYPE_COMPLETION);
          if (shortcut != null) {
            for (final PsiType psiType : psiTypes) {
              final PsiType type = PsiUtil.extractIterableTypeParameter(psiType, false);
              if (type != null) {
                return CompletionBundle.message(
                    "completion.smart.aslist.hint", shortcut, type.getPresentableText());
              }
            }
          }
        }
        if (CompletionUtil.shouldShowFeature(
            parameters, JavaCompletionFeatures.SECOND_SMART_COMPLETION_ASLIST)) {
          final String shortcut = getActionShortcut(IdeActions.ACTION_SMART_TYPE_COMPLETION);
          if (shortcut != null) {
            for (final PsiType psiType : psiTypes) {
              if (psiType instanceof PsiArrayType) {
                final PsiType componentType = ((PsiArrayType) psiType).getComponentType();
                if (!(componentType instanceof PsiPrimitiveType)) {
                  return CompletionBundle.message(
                      "completion.smart.toar.hint", shortcut, componentType.getPresentableText());
                }
              }
            }
          }
        }

        if (CompletionUtil.shouldShowFeature(
            parameters, JavaCompletionFeatures.SECOND_SMART_COMPLETION_CHAIN)) {
          final String shortcut = getActionShortcut(IdeActions.ACTION_SMART_TYPE_COMPLETION);
          if (shortcut != null) {
            return CompletionBundle.message("completion.smart.chain.hint", shortcut);
          }
        }
      }
    }
    return null;
  }