Beispiel #1
0
  public SNode resolveClass(PsiClassType t) {
    PsiClass cls = t.resolve();

    // TODO q: handle this case? create dynamic reference?
    if (cls == null) {
      return null;
    }

    System.out.println("Class resolved: " + cls.getQualifiedName());

    PsiElement e = cls;
    do {
      e = e.getParent();
      if (!(e instanceof PsiClass) && !(e instanceof PsiJavaFile)) {
        return null;
      }
    } while (!(e instanceof PsiJavaFile));

    PsiJavaFile file = (PsiJavaFile) e;
    String packageName = file.getPackageName();
    SModelReference modelRef = SModelReference.fromString(packageName);

    SNode clsType =
        SConceptOperations.createNewNode(
            "jetbrains.mps.baseLanguage.structure.ClassifierType", null);
    clsType.setReference(
        "classifier", new DynamicReference("classifier", clsType, modelRef, t.getClassName()));

    System.out.println("Class type: " + t.getClassName());

    return clsType;
  }
  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));
  }
  @NotNull
  private static Set<PsiClassType> filterInProjectExceptions(
      @Nullable PsiMethod targetMethod, @NotNull List<PsiClassType> unhandledExceptions) {
    if (targetMethod == null) return Collections.emptySet();

    Set<PsiClassType> result = new HashSet<PsiClassType>();

    if (targetMethod.getManager().isInProject(targetMethod)) {
      PsiMethod[] superMethods = targetMethod.findSuperMethods();
      for (PsiMethod superMethod : superMethods) {
        Set<PsiClassType> classTypes = filterInProjectExceptions(superMethod, unhandledExceptions);
        result.addAll(classTypes);
      }

      if (superMethods.length == 0) {
        result.addAll(unhandledExceptions);
      }
    } else {
      PsiClassType[] referencedTypes = targetMethod.getThrowsList().getReferencedTypes();
      for (PsiClassType referencedType : referencedTypes) {
        PsiClass psiClass = referencedType.resolve();
        if (psiClass == null) continue;
        for (PsiClassType exception : unhandledExceptions) {
          if (referencedType.isAssignableFrom(exception)) result.add(exception);
        }
      }
    }

    return result;
  }
    @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;
    }
  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;
  }
  /**
   * Adds all code methods of clazz add its super classes to signatures. Doesn't walk into
   * interfaces because all methods from them will be overloaded in any case. Besides Some of
   * interfaces came from delegates and they should be visited during the following processing.
   *
   * @param clazz current class
   * @param substitutor super class substitutor of clazz
   * @param signatures map to initialize
   * @param classes already visited classes
   */
  private static void initializeSignatures(
      PsiClass clazz,
      PsiSubstitutor substitutor,
      Map<MethodSignature, PsiMethod> signatures,
      Set<PsiClass> classes) {
    if (clazz.isInterface()) return;

    if (classes.add(clazz)) {
      final List<PsiMethod> methods;
      if (clazz instanceof GrTypeDefinition) {
        methods = new ArrayList<PsiMethod>();
        GrClassImplUtil.collectMethodsFromBody((GrTypeDefinition) clazz, methods);
      } else {
        methods = Arrays.asList(clazz.getMethods());
      }

      for (PsiMethod method : methods) {
        addMethodChecked(signatures, method, substitutor, null);
      }

      for (PsiClassType type : getSuperTypes(clazz)) {
        final PsiClassType.ClassResolveResult result = type.resolveGenerics();
        final PsiClass superClass = result.getElement();
        if (superClass == null) continue;
        final PsiSubstitutor superClassSubstitutor =
            TypeConversionUtil.getSuperClassSubstitutor(superClass, clazz, substitutor);
        initializeSignatures(superClass, superClassSubstitutor, signatures, classes);
      }
    }
  }
  private void collectUncaughtExceptions(@NotNull PsiMethod method) {
    if (isExternalOverride()) return;
    if (getRefManager().isOfflineView()) return;
    @NonNls final String name = method.getName();
    if (getOwnerClass().isTestCase() && name.startsWith("test")) return;

    if (getSuperMethods().isEmpty()) {
      PsiClassType[] throwsList = method.getThrowsList().getReferencedTypes();
      if (throwsList.length > 0) {
        myUnThrownExceptions =
            throwsList.length == 1
                ? new SmartList<String>()
                : new ArrayList<String>(throwsList.length);
        for (final PsiClassType type : throwsList) {
          PsiClass aClass = type.resolve();
          String fqn = aClass == null ? null : aClass.getQualifiedName();
          if (fqn != null) {
            myUnThrownExceptions.add(fqn);
          }
        }
      }
    }

    final PsiCodeBlock body = method.getBody();
    if (body == null) return;

    final Collection<PsiClassType> exceptionTypes =
        ExceptionUtil.collectUnhandledExceptions(body, method, false);
    for (final PsiClassType exceptionType : exceptionTypes) {
      updateThrowsList(exceptionType);
    }
  }
 @Nullable
 private PsiType extractContentTypeFromType(PsiType collectionType) {
   if (!(collectionType instanceof PsiClassType)) {
     return null;
   }
   final PsiClassType classType = (PsiClassType) collectionType;
   final PsiType[] parameterTypes = classType.getParameters();
   if (parameterTypes.length == 0) {
     return null;
   }
   final PsiType parameterType = parameterTypes[0];
   if (parameterType == null) {
     return null;
   }
   if (parameterType instanceof PsiWildcardType) {
     final PsiWildcardType wildcardType = (PsiWildcardType) parameterType;
     return wildcardType.getExtendsBound();
   } else if (parameterType instanceof PsiCapturedWildcardType) {
     final PsiCapturedWildcardType capturedWildcardType =
         (PsiCapturedWildcardType) parameterType;
     final PsiWildcardType wildcardType = capturedWildcardType.getWildcard();
     return wildcardType.getExtendsBound();
   }
   return parameterType;
 }
Beispiel #9
0
    private void processListenerProperties(@NotNull PsiMethod method) {
      if (!method.getName().startsWith("add")
          || method.getParameterList().getParametersCount() != 1) return;

      final PsiParameter parameter = method.getParameterList().getParameters()[0];
      final PsiType type = parameter.getType();
      if (!(type instanceof PsiClassType)) return;

      final PsiClassType classType = (PsiClassType) type;
      final PsiClass listenerClass = classType.resolve();
      if (listenerClass == null) return;

      final PsiMethod[] listenerMethods = listenerClass.getMethods();
      if (!InheritanceUtil.isInheritorOrSelf(listenerClass, myEventListener, true)) return;

      for (PsiMethod listenerMethod : listenerMethods) {
        final String name = listenerMethod.getName();
        if (myPropertyNames.add(name)) {
          LookupElementBuilder builder =
              LookupElementBuilder.create(
                      generatePropertyResolveResult(name, listenerMethod, null, null), name)
                  .withIcon(JetgroovyIcons.Groovy.Property);
          myConsumer.consume(builder);
        }
      }
    }
 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(final PsiClassType classType) {
    PsiClassType alreadyComputed = myResultMap.get(classType);
    if (alreadyComputed != null) {
      return alreadyComputed;
    }

    final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
    final PsiClass psiClass = classResolveResult.getElement();
    final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
    if (psiClass == null) return classType;

    PsiUtilCore.ensureValid(psiClass);

    final PsiClass mappedClass = mapClass(psiClass);
    if (mappedClass == null) return classType;

    PsiClassType mappedType =
        new PsiCorrectedClassType(
            classType.getLanguageLevel(),
            classType,
            new CorrectedResolveResult(psiClass, mappedClass, substitutor, classResolveResult));
    myResultMap.put(classType, mappedType);
    return mappedType;
  }
 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);
 }
  @NotNull
  private static PsiClass[] resolveClassReferenceList(
      @NotNull PsiClassType[] listOfTypes,
      @NotNull PsiManager manager,
      @NotNull GlobalSearchScope resolveScope,
      boolean includeObject) {
    PsiClass objectClass =
        JavaPsiFacade.getInstance(manager.getProject())
            .findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
    if (objectClass == null) includeObject = false;
    if (listOfTypes.length == 0) {
      if (includeObject) return new PsiClass[] {objectClass};
      return PsiClass.EMPTY_ARRAY;
    }

    int referenceCount = listOfTypes.length;
    if (includeObject) referenceCount++;

    PsiClass[] resolved = new PsiClass[referenceCount];
    int resolvedCount = 0;

    if (includeObject) resolved[resolvedCount++] = objectClass;
    for (PsiClassType reference : listOfTypes) {
      PsiClass refResolved = reference.resolve();
      if (refResolved != null) resolved[resolvedCount++] = refResolved;
    }

    if (resolvedCount < referenceCount) {
      PsiClass[] shorter = new PsiClass[resolvedCount];
      System.arraycopy(resolved, 0, shorter, 0, resolvedCount);
      resolved = shorter;
    }

    return resolved;
  }
    public void merge(final Binding b, final boolean removeObject) {
      for (final PsiTypeVariable var : b.getBoundVariables()) {
        final int index = var.getIndex();

        if (myBindings.get(index) != null) {
          LOG.error("Oops... Binding conflict...");
        } else {
          final PsiType type = b.apply(var);
          final PsiClassType javaLangObject =
              PsiType.getJavaLangObject(
                  PsiManager.getInstance(myProject), GlobalSearchScope.allScope(myProject));

          if (removeObject && javaLangObject.equals(type)) {
            final HashSet<PsiTypeVariable> cluster = myFactory.getClusterOf(var.getIndex());

            if (cluster != null) {
              for (final PsiTypeVariable war : cluster) {
                final PsiType wtype = b.apply(war);

                if (!javaLangObject.equals(wtype)) {
                  myBindings.put(index, type);
                  break;
                }
              }
            }
          } else {
            myBindings.put(index, type);
          }
        }
      }
    }
  @NotNull
  public static PsiClassType[] getExtendsListTypes(GrTypeDefinition grType) {
    final PsiClassType[] extendsTypes = getReferenceListTypes(grType.getExtendsClause());
    if (grType.isInterface()) {
      return extendsTypes;
    }

    for (PsiClassType type : extendsTypes) {
      final PsiClass superClass = type.resolve();
      if (superClass instanceof GrTypeDefinition && !superClass.isInterface()
          || superClass != null
              && GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT.equals(
                  superClass.getQualifiedName())) {
        return extendsTypes;
      }
    }

    PsiClass grObSupport =
        GroovyPsiManager.getInstance(grType.getProject())
            .findClassWithCache(
                GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT, grType.getResolveScope());
    if (grObSupport != null) {
      final PsiClassType type =
          JavaPsiFacade.getInstance(grType.getProject())
              .getElementFactory()
              .createType(grObSupport);
      return ArrayUtil.append(extendsTypes, type, PsiClassType.ARRAY_FACTORY);
    }
    return extendsTypes;
  }
  @Nullable
  public static PsiClass getSuperClass(@NotNull PsiClass psiClass) {
    PsiManager manager = psiClass.getManager();
    GlobalSearchScope resolveScope = psiClass.getResolveScope();

    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    if (psiClass.isInterface()) {
      return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
    }
    if (psiClass.isEnum()) {
      return facade.findClass(CommonClassNames.JAVA_LANG_ENUM, resolveScope);
    }

    if (psiClass instanceof PsiAnonymousClass) {
      PsiClassType baseClassReference = ((PsiAnonymousClass) psiClass).getBaseClassType();
      PsiClass baseClass = baseClassReference.resolve();
      if (baseClass == null || baseClass.isInterface())
        return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);
      return baseClass;
    }

    if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName())) return null;

    final PsiClassType[] referenceElements = psiClass.getExtendsListTypes();

    if (referenceElements.length == 0)
      return facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope);

    PsiClass psiResoved = referenceElements[0].resolve();
    return psiResoved == null
        ? facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope)
        : psiResoved;
  }
Beispiel #17
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;
   }
 }
 private static boolean isIndexedListLoopStatement(PsiForStatement forStatement, boolean ignoreUntypedCollections) {
   final PsiStatement initialization = forStatement.getInitialization();
   if (!(initialization instanceof PsiDeclarationStatement)) {
     return false;
   }
   final PsiDeclarationStatement declaration = (PsiDeclarationStatement)initialization;
   final PsiElement[] declaredElements = declaration.getDeclaredElements();
   final PsiElement secondDeclaredElement;
   if (declaredElements.length == 1) {
     secondDeclaredElement = null;
   }
   else if (declaredElements.length == 2) {
     secondDeclaredElement = declaredElements[1];
   }
   else {
     return false;
   }
   final PsiElement declaredElement = declaredElements[0];
   if (!(declaredElement instanceof PsiVariable)) {
     return false;
   }
   final PsiVariable indexVariable = (PsiVariable)declaredElement;
   final PsiExpression initialValue = indexVariable.getInitializer();
   if (initialValue == null) {
     return false;
   }
   final Object constant = ExpressionUtils.computeConstantExpression(initialValue);
   if (!(constant instanceof Number)) {
     return false;
   }
   final Number number = (Number)constant;
   if (number.intValue() != 0) {
     return false;
   }
   final PsiExpression condition = forStatement.getCondition();
   final Holder collectionHolder = getCollectionFromSizeComparison(condition, indexVariable, secondDeclaredElement);
   if (collectionHolder == null) {
     return false;
   }
   final PsiStatement update = forStatement.getUpdate();
   if (!VariableAccessUtils.variableIsIncremented(indexVariable, update)) {
     return false;
   }
   final PsiStatement body = forStatement.getBody();
   if (!isIndexVariableOnlyUsedAsListIndex(collectionHolder, indexVariable, body)) {
     return false;
   }
   if (collectionHolder != Holder.DUMMY) {
     final PsiVariable collection = collectionHolder.getVariable();
     final PsiClassType collectionType = (PsiClassType)collection.getType();
     final PsiType[] parameters = collectionType.getParameters();
     if (ignoreUntypedCollections && parameters.length == 0) {
       return false;
     }
     return !VariableAccessUtils.variableIsAssigned(collection, body);
   }
   return true;
 }
  @Nullable
  public PsiClass getContainingClassElement() {
    final PsiClassType containingClassType =
        JavaPsiFacade.getInstance(getProject())
            .getElementFactory()
            .createTypeByFQClassName(myContainingClassName, ProjectScope.getAllScope(getProject()));

    return containingClassType.resolve();
  }
 public static PsiClass[] getInterfaces(GrTypeDefinition grType) {
   final PsiClassType[] implementsListTypes = grType.getImplementsListTypes();
   List<PsiClass> result = new ArrayList<PsiClass>(implementsListTypes.length);
   for (PsiClassType type : implementsListTypes) {
     final PsiClass psiClass = type.resolve();
     if (psiClass != null) result.add(psiClass);
   }
   return result.toArray(new PsiClass[result.size()]);
 }
  @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"));
  }
 @Override
 public void visitThrowStatement(PsiThrowStatement statement) {
   super.visitThrowStatement(statement);
   final PsiCatchSection catchSection =
       PsiTreeUtil.getParentOfType(statement, PsiCatchSection.class, true, PsiClass.class);
   if (catchSection == null) {
     return;
   }
   final PsiParameter parameter = catchSection.getParameter();
   if (parameter == null) {
     return;
   }
   @NonNls final String parameterName = parameter.getName();
   if (PsiUtil.isIgnoredName(parameterName)) {
     return;
   }
   final PsiExpression exception = statement.getException();
   if (exception == null) {
     return;
   }
   if (ignoreCantWrap) {
     final PsiType thrownType = exception.getType();
     if (thrownType instanceof PsiClassType) {
       final PsiClassType classType = (PsiClassType) thrownType;
       final PsiClass exceptionClass = classType.resolve();
       if (exceptionClass != null) {
         final PsiMethod[] constructors = exceptionClass.getConstructors();
         final PsiClassType throwableType =
             TypeUtils.getType(CommonClassNames.JAVA_LANG_THROWABLE, statement);
         boolean canWrap = false;
         outer:
         for (PsiMethod constructor : constructors) {
           final PsiParameterList parameterList = constructor.getParameterList();
           final PsiParameter[] parameters = parameterList.getParameters();
           for (PsiParameter constructorParameter : parameters) {
             final PsiType type = constructorParameter.getType();
             if (throwableType.equals(type)) {
               canWrap = true;
               break outer;
             }
           }
         }
         if (!canWrap) {
           return;
         }
       }
     }
   }
   final ReferenceFinder visitor = new ReferenceFinder(parameter);
   exception.accept(visitor);
   if (visitor.usesParameter()) {
     return;
   }
   registerStatementError(statement);
 }
 @Nullable
 private static PsiType getGenericElementType(PsiType collectionType) {
   if (collectionType instanceof PsiClassType) {
     PsiClassType classType = (PsiClassType) collectionType;
     PsiType[] parameters = classType.getParameters();
     if (parameters.length == 1) {
       return parameters[0];
     }
   }
   return null;
 }
    public Boolean visitClassType(final PsiClassType classType) {
      final PsiClass aClass = classType.resolve();
      if (aClass instanceof PsiTypeParameter && myTypeParams.contains((PsiTypeParameter) aClass))
        return true;

      final PsiType[] types = classType.getParameters();
      for (final PsiType psiType : types) {
        if (psiType.accept(this).booleanValue()) return true;
      }
      return false;
    }
  @NotNull
  private static PsiClass[] getSupersInner(@NotNull PsiClass psiClass) {
    PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes();
    PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes();

    if (psiClass.isInterface()) {
      return resolveClassReferenceList(
          extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), true);
    }

    if (psiClass instanceof PsiAnonymousClass) {
      PsiAnonymousClass psiAnonymousClass = (PsiAnonymousClass) psiClass;
      PsiClassType baseClassReference = psiAnonymousClass.getBaseClassType();
      PsiClass baseClass = baseClassReference.resolve();
      if (baseClass != null) {
        if (baseClass.isInterface()) {
          PsiClass objectClass =
              JavaPsiFacade.getInstance(psiClass.getProject())
                  .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope());
          return objectClass != null
              ? new PsiClass[] {objectClass, baseClass}
              : new PsiClass[] {baseClass};
        }
        return new PsiClass[] {baseClass};
      }

      PsiClass objectClass =
          JavaPsiFacade.getInstance(psiClass.getProject())
              .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope());
      return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY;
    }
    if (psiClass instanceof PsiTypeParameter) {
      if (extendsListTypes.length == 0) {
        final PsiClass objectClass =
            JavaPsiFacade.getInstance(psiClass.getProject())
                .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope());
        return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY;
      }
      return resolveClassReferenceList(
          extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false);
    }

    PsiClass[] interfaces =
        resolveClassReferenceList(
            implementsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false);

    PsiClass superClass = getSuperClass(psiClass);
    if (superClass == null) return interfaces;
    PsiClass[] types = new PsiClass[interfaces.length + 1];
    types[0] = superClass;
    System.arraycopy(interfaces, 0, types, 1, interfaces.length);

    return types;
  }
 private boolean isTypeParameter(PsiType type) {
   if (!(type instanceof PsiClassType)) {
     return false;
   }
   final PsiClassType classType = (PsiClassType) type;
   final PsiClass aClass = classType.resolve();
   if (aClass == null) {
     return false;
   }
   return aClass instanceof PsiTypeParameter;
 }
Beispiel #27
0
 @Override
 public boolean process(PsiClass inheritor) {
   ProgressManager.checkCanceled();
   for (PsiClassType interfaceType : inheritor.getImplementsListTypes()) {
     ProgressManager.checkCanceled();
     PsiClass anInterface = interfaceType.resolveGenerics().getElement();
     if (anInterface != null && myCheckedInterfaces.add(PsiAnchor.create(anInterface))) {
       processInterface(inheritor, anInterface);
     }
   }
   return !myRemainingMethods.isEmpty();
 }
  @NotNull
  public static PsiClass[] getSupers(GrTypeDefinition grType) {
    PsiClassType[] superTypes = grType.getSuperTypes();
    List<PsiClass> result = new ArrayList<PsiClass>();
    for (PsiClassType superType : superTypes) {
      PsiClass superClass = superType.resolve();
      if (superClass != null) {
        result.add(superClass);
      }
    }

    return result.toArray(new PsiClass[result.size()]);
  }
Beispiel #29
0
 private boolean caseForObject(@NotNull PsiMethod method) {
   PsiClass containing = method.getContainingClass();
   if (containing != null) {
     for (PsiClassType s : containing.getSuperTypes()) {
       String canonicalText = s.getCanonicalText();
       if (!canonicalText.equals(JAVA_LANG_OBJECT)
           && !getClassIdentifiers().contains(canonicalText)) {
         return true;
       }
     }
   }
   return false;
 }
 @Nullable
 private PsiType extractListTypeFromContainingClass(
   PsiElement element) {
   PsiClass listClass = PsiTreeUtil.getParentOfType(element,
                                                    PsiClass.class);
   if (listClass == null) {
     return null;
   }
   final PsiMethod[] getMethods =
     listClass.findMethodsByName("get", true);
   if (getMethods.length == 0) {
     return null;
   }
   final PsiType type = getMethods[0].getReturnType();
   if (!(type instanceof PsiClassType)) {
     return null;
   }
   final PsiClassType classType = (PsiClassType)type;
   final PsiClass parameterClass = classType.resolve();
   if (parameterClass == null) {
     return null;
   }
   PsiClass subClass = null;
   while (listClass != null && !listClass.hasTypeParameters()) {
     subClass = listClass;
     listClass = listClass.getSuperClass();
   }
   if (listClass == null || subClass == null) {
     return TypeUtils.getObjectType(element);
   }
   final PsiTypeParameter[] typeParameters =
     listClass.getTypeParameters();
   if (!parameterClass.equals(typeParameters[0])) {
     return TypeUtils.getObjectType(element);
   }
   final PsiReferenceList extendsList = subClass.getExtendsList();
   if (extendsList == null) {
     return null;
   }
   final PsiJavaCodeReferenceElement[] referenceElements =
     extendsList.getReferenceElements();
   if (referenceElements.length == 0) {
     return null;
   }
   final PsiType[] types =
     referenceElements[0].getTypeParameters();
   if (types.length == 0) {
     return TypeUtils.getObjectType(element);
   }
   return types[0];
 }