@Nullable
 private PsiElement resolveElement() {
   PsiElement element = getParent();
   while (element != null
       && (!(element instanceof PsiClass) || element instanceof PsiTypeParameter)) {
     if (element instanceof PsiMethod) {
       final PsiMethod method = (PsiMethod) element;
       final PsiTypeParameterList list = method.getTypeParameterList();
       if (list != null) {
         final PsiTypeParameter[] parameters = list.getTypeParameters();
         for (int i = 0; parameters != null && i < parameters.length; i++) {
           final PsiTypeParameter parameter = parameters[i];
           if (myQualifiedName.equals(parameter.getName())) return parameter;
         }
       }
     }
     element = element.getParent();
   }
   if (element == null) return null;
   for (PsiTypeParameter parameter :
       PsiUtil.typeParametersIterable((PsiTypeParameterListOwner) element)) {
     if (myQualifiedName.equals(parameter.getName())) return parameter;
   }
   return resolveClassPreferringMyJar();
 }
  public String calcGenerics(@NotNull PsiElement context, InsertionContext insertionContext) {
    if (insertionContext.getCompletionChar() == '<') {
      return "";
    }

    assert context.isValid();
    if (myDiamond) {
      return "<>";
    }

    if (getObject() instanceof PsiClass) {
      PsiClass psiClass = (PsiClass) getObject();
      PsiResolveHelper resolveHelper =
          JavaPsiFacade.getInstance(psiClass.getProject()).getResolveHelper();
      PsiSubstitutor substitutor = getSubstitutor();
      StringBuilder builder = new StringBuilder();
      for (PsiTypeParameter parameter : psiClass.getTypeParameters()) {
        PsiType substitute = substitutor.substitute(parameter);
        if (substitute == null
            || (PsiUtil.resolveClassInType(substitute) == parameter
                && resolveHelper.resolveReferencedClass(parameter.getName(), context)
                    != CompletionUtil.getOriginalOrSelf(parameter))) {
          return "";
        }
        if (builder.length() > 0) {
          builder.append(", ");
        }
        builder.append(substitute.getCanonicalText());
      }
      if (builder.length() > 0) {
        return "<" + builder + ">";
      }
    }
    return "";
  }
 public String toString() {
   @NonNls StringBuilder buffer = new StringBuilder();
   final Set<Map.Entry<PsiTypeParameter, PsiType>> set = mySubstitutionMap.entrySet();
   for (Map.Entry<PsiTypeParameter, PsiType> entry : set) {
     final PsiTypeParameter typeParameter = entry.getKey();
     buffer.append(typeParameter.getName());
     final PsiElement owner = typeParameter.getOwner();
     if (owner instanceof PsiClass) {
       buffer.append(" of ");
       buffer.append(((PsiClass) owner).getQualifiedName());
     } else if (owner instanceof PsiMethod) {
       buffer.append(" of ");
       buffer.append(((PsiMethod) owner).getName());
       buffer.append(" in ");
       buffer.append(((PsiMethod) owner).getContainingClass().getQualifiedName());
     }
     buffer.append(" -> ");
     if (entry.getValue() != null) {
       buffer.append(entry.getValue().getCanonicalText());
     } else {
       buffer.append("null");
     }
     buffer.append('\n');
   }
   return buffer.toString();
 }
 @Override
 public void visitTypeParameter(PsiTypeParameter parameter) {
   super.visitTypeParameter(parameter);
   final String name = parameter.getName();
   if (!PsiKeyword.ASSERT.equals(name)) {
     return;
   }
   registerTypeParameterError(parameter);
 }
  private void buildDelegate() {
    final PsiManager manager = sourceClass.getManager();
    final PsiElementFactory factory =
        JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    @NonNls final StringBuilder fieldBuffer = new StringBuilder();
    final String delegateVisibility = calculateDelegateVisibility();
    if (delegateVisibility.length() > 0) fieldBuffer.append(delegateVisibility).append(' ');
    fieldBuffer.append("final ");
    final String fullyQualifiedName = getQualifiedName();
    fieldBuffer.append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append(' ');
    fieldBuffer.append(delegateFieldName);
    fieldBuffer.append(" = new ").append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append('(');
    if (requiresBackpointer) {
      fieldBuffer.append("this");
    }

    fieldBuffer.append(");");
    try {
      final String fieldString = fieldBuffer.toString();
      final PsiField field = factory.createFieldFromText(fieldString, sourceClass);
      final PsiElement newField = sourceClass.add(field);
      codeStyleManager.reformat(
          JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newField));
    } catch (IncorrectOperationException e) {
      logger.error(e);
    }
  }
 private static void createTypeParamsListComment(
     final StringBuilder buffer,
     final Project project,
     final CodeDocumentationAwareCommenter commenter,
     final PsiTypeParameterList typeParameterList) {
   final PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters();
   for (PsiTypeParameter typeParameter : typeParameters) {
     buffer.append(CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, project, commenter));
     buffer.append("<").append(typeParameter.getName()).append(">");
     buffer.append(LINE_SEPARATOR);
   }
 }
Ejemplo n.º 7
0
  public SNode convertTypeParameter(PsiTypeParameter x) {
    SNode typeVar =
        SConceptOperations.createNewNode(
            "jetbrains.mps.baseLanguage.structure.TypeVariableDeclaration", null);
    SPropertyOperations.set(typeVar, "name", x.getName());

    if (x.getExtendsListTypes().length > 0) {
      Iterable<PsiClassType> extend = Sequence.fromArray(x.getExtendsListTypes());
      SLinkOperations.setTarget(
          typeVar, "bound", resolveClass(Sequence.fromIterable(extend).first()), true);
      ListSequence.fromList(SLinkOperations.getTargets(typeVar, "auxBounds", true))
          .addSequence(
              Sequence.fromIterable(extend)
                  .skip(1)
                  .select(
                      new ISelector<PsiClassType, SNode>() {
                        public SNode select(PsiClassType it) {
                          return resolveClass(it);
                        }
                      }));
    }

    return typeVar;
  }
Ejemplo n.º 8
0
  @Override
  public PsiReference getReference() {
    final PsiDocComment comment = PsiTreeUtil.getParentOfType(this, PsiDocComment.class);
    if (comment == null) return null;
    final PsiDocCommentOwner owner = comment.getOwner();
    if (!(owner instanceof PsiMethod) && !(owner instanceof PsiClass)) return null;
    final ASTNode valueToken = findChildByType(JavaDocTokenType.DOC_TAG_VALUE_TOKEN);
    if (valueToken == null) return null;
    final String name = valueToken.getText();
    PsiElement reference = null;
    final PsiElement firstChild = getFirstChild();
    if (firstChild instanceof PsiDocToken
        && ((PsiDocToken) firstChild).getTokenType().equals(JavaDocTokenType.DOC_TAG_VALUE_LT)) {
      final PsiTypeParameter[] typeParameters =
          ((PsiTypeParameterListOwner) owner).getTypeParameters();
      for (PsiTypeParameter typeParameter : typeParameters) {
        if (typeParameter.getName().equals(name)) {
          reference = typeParameter;
        }
      }
    } else if (owner instanceof PsiMethod) {
      final PsiParameter[] parameters = ((PsiMethod) owner).getParameterList().getParameters();
      for (PsiParameter parameter : parameters) {
        if (parameter.getName().equals(name)) {
          reference = parameter;
        }
      }
    }

    final PsiElement resultReference = reference;
    return new PsiJavaReference() {
      @Override
      public PsiElement resolve() {
        return resultReference;
      }

      @Override
      @NotNull
      public String getCanonicalText() {
        return valueToken.getText();
      }

      @Override
      public PsiElement handleElementRename(String newElementName) {
        final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(getNode());
        LeafElement newElement =
            Factory.createSingleLeafElement(
                JavaDocTokenType.DOC_TAG_VALUE_TOKEN,
                newElementName,
                charTableByTree,
                getManager());
        replaceChild(valueToken, newElement);
        return PsiDocParamRef.this;
      }

      @Override
      public PsiElement bindToElement(@NotNull PsiElement element)
          throws IncorrectOperationException {
        if (isReferenceTo(element)) return PsiDocParamRef.this;
        if (!(element instanceof PsiParameter)) {
          throw new IncorrectOperationException("Unsupported operation");
        }
        return handleElementRename(((PsiParameter) element).getName());
      }

      @Override
      public boolean isReferenceTo(PsiElement element) {
        if (!(element instanceof PsiNamedElement)) return false;
        PsiNamedElement namedElement = (PsiNamedElement) element;
        if (!getCanonicalText().equals(namedElement.getName())) return false;
        return getManager().areElementsEquivalent(resolve(), element);
      }

      @Override
      @NotNull
      public PsiElement[] getVariants() {
        final PsiElement firstChild = getFirstChild();

        Set<String> usedNames = new HashSet<String>();
        for (PsiDocTag tag : comment.getTags()) {
          if (tag.getName().equals("param")) {
            PsiDocTagValue valueElement = tag.getValueElement();
            if (valueElement != null) {
              usedNames.add(valueElement.getText());
            }
          }
        }

        PsiNamedElement[] result = PsiNamedElement.EMPTY_ARRAY;
        if (firstChild instanceof PsiDocToken
            && ((PsiDocToken) firstChild)
                .getTokenType()
                .equals(JavaDocTokenType.DOC_TAG_VALUE_LT)) {
          result = ((PsiTypeParameterListOwner) owner).getTypeParameters();
        } else if (owner instanceof PsiMethod) {
          result = ((PsiMethod) owner).getParameterList().getParameters();
        }
        List<PsiElement> filtered = new ArrayList<PsiElement>();
        for (PsiNamedElement namedElement : result) {
          if (!usedNames.contains(namedElement.getName())) {
            filtered.add(namedElement);
          }
        }
        return filtered.toArray(new PsiElement[filtered.size()]);
      }

      @Override
      public boolean isSoft() {
        return false;
      }

      @Override
      public TextRange getRangeInElement() {
        final int startOffsetInParent = valueToken.getPsi().getStartOffsetInParent();
        return new TextRange(startOffsetInParent, startOffsetInParent + valueToken.getTextLength());
      }

      @Override
      public PsiElement getElement() {
        return PsiDocParamRef.this;
      }

      @Override
      public void processVariants(PsiScopeProcessor processor) {
        for (final PsiElement element : getVariants()) {
          if (!processor.execute(element, ResolveState.initial())) {
            return;
          }
        }
      }

      @Override
      @NotNull
      public JavaResolveResult advancedResolve(boolean incompleteCode) {
        return resultReference == null
            ? JavaResolveResult.EMPTY
            : new CandidateInfo(resultReference, PsiSubstitutor.EMPTY);
      }

      @Override
      @NotNull
      public JavaResolveResult[] multiResolve(boolean incompleteCode) {
        return resultReference == null
            ? JavaResolveResult.EMPTY_ARRAY
            : new JavaResolveResult[] {new CandidateInfo(resultReference, PsiSubstitutor.EMPTY)};
      }
    };
  }
 @Override
 public int computeHashCode(PsiTypeParameter object) {
   String name = object.getName();
   return name == null ? 0 : name.hashCode();
 }
  @SuppressWarnings({"HardCodedStringLiteral"})
  private static String generateClassInfo(PsiClass aClass) {
    StringBuilder buffer = new StringBuilder();
    GroovyFile file = (GroovyFile) aClass.getContainingFile();

    String packageName = file.getPackageName();
    if (packageName.length() > 0) {
      buffer.append(packageName).append("\n");
    }

    final String classString =
        aClass.isInterface()
            ? "interface"
            : aClass instanceof PsiTypeParameter
                ? "type parameter"
                : aClass.isEnum() ? "enum" : "class";
    buffer.append(classString).append(" ").append(aClass.getName());

    if (aClass.hasTypeParameters()) {
      PsiTypeParameter[] typeParameters = aClass.getTypeParameters();

      buffer.append("<");

      for (int i = 0; i < typeParameters.length; i++) {
        if (i > 0) buffer.append(", ");

        PsiTypeParameter tp = typeParameters[i];

        buffer.append(tp.getName());

        PsiClassType[] refs = tp.getExtendsListTypes();

        if (refs.length > 0) {
          buffer.append(" extends ");

          for (int j = 0; j < refs.length; j++) {
            if (j > 0) buffer.append(" & ");
            appendTypeString(buffer, refs[j], aClass);
          }
        }
      }

      buffer.append(">");
    }

    PsiClassType[] refs = aClass.getExtendsListTypes();
    if (refs.length > 0
        || !aClass.isInterface()
            && !CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) {
      buffer.append(" extends ");
      if (refs.length == 0) {
        buffer.append("Object");
      } else {
        for (int i = 0; i < refs.length; i++) {
          if (i > 0) buffer.append(", ");
          appendTypeString(buffer, refs[i], aClass);
        }
      }
    }

    refs = aClass.getImplementsListTypes();
    if (refs.length > 0) {
      buffer.append("\nimplements ");
      for (int i = 0; i < refs.length; i++) {
        if (i > 0) buffer.append(", ");
        appendTypeString(buffer, refs[i], aClass);
      }
    }

    return buffer.toString();
  }