Exemple #1
0
  @NotNull
  private static String buildImportListText(
      @NotNull String[] names,
      @NotNull final Set<String> packagesOrClassesToImportOnDemand,
      @NotNull final Set<String> namesToUseSingle,
      @NotNull Set<String> namesToImportStaticly) {
    final Set<String> importedPackagesOrClasses = new THashSet<String>();
    @NonNls final StringBuilder buffer = new StringBuilder();
    for (String name : names) {
      String packageOrClassName = getPackageOrClassName(name);
      final boolean implicitlyImported = JAVA_LANG_PACKAGE.equals(packageOrClassName);
      boolean useOnDemand =
          implicitlyImported || packagesOrClassesToImportOnDemand.contains(packageOrClassName);
      if (useOnDemand && namesToUseSingle.contains(name)) {
        useOnDemand = false;
      }
      if (useOnDemand
          && (importedPackagesOrClasses.contains(packageOrClassName) || implicitlyImported))
        continue;
      buffer.append("import ");
      if (namesToImportStaticly.contains(name)) buffer.append("static ");
      if (useOnDemand) {
        importedPackagesOrClasses.add(packageOrClassName);
        buffer.append(packageOrClassName);
        buffer.append(".*");
      } else {
        buffer.append(name);
      }
      buffer.append(";\n");
    }

    return buffer.toString();
  }
Exemple #2
0
    @NotNull
    @Override
    public GroovyResolveResult[] getCandidates() {
      if (!hasCandidates()) return GroovyResolveResult.EMPTY_ARRAY;
      final GroovyResolveResult[] results =
          ResolveUtil.filterSameSignatureCandidates(getCandidatesInternal());
      List<GroovyResolveResult> list = new ArrayList<GroovyResolveResult>(results.length);
      myPropertyNames.removeAll(myPreferredFieldNames);

      Set<String> usedFields = ContainerUtil.newHashSet();
      for (GroovyResolveResult result : results) {
        final PsiElement element = result.getElement();
        if (element instanceof PsiField) {
          final String name = ((PsiField) element).getName();
          if (myPropertyNames.contains(name)
              || myLocalVars.contains(name)
              || usedFields.contains(name)) {
            continue;
          } else {
            usedFields.add(name);
          }
        }

        list.add(result);
      }
      return list.toArray(new GroovyResolveResult[list.size()]);
    }
 private void handleBranchingInstruction(
     ProblemsHolder holder,
     StandardInstructionVisitor visitor,
     Set<Instruction> trueSet,
     Set<Instruction> falseSet,
     HashSet<PsiElement> reportedAnchors,
     BranchingInstruction instruction,
     final boolean onTheFly) {
   PsiElement psiAnchor = instruction.getPsiAnchor();
   boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor);
   if (instruction instanceof InstanceofInstruction
       && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) {
     if (visitor.canBeNull((BinopInstruction) instruction)) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message("dataflow.message.redundant.instanceof"),
           new RedundantInstanceofFix());
     } else {
       final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true);
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(true)),
           localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix});
     }
   } else if (psiAnchor instanceof PsiSwitchLabelStatement) {
     if (falseSet.contains(instruction)) {
       holder.registerProblem(
           psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label"));
     }
   } else if (psiAnchor != null
       && !reportedAnchors.contains(psiAnchor)
       && !isFlagCheck(psiAnchor)) {
     boolean evaluatesToTrue = trueSet.contains(instruction);
     final PsiElement parent = psiAnchor.getParent();
     if (parent instanceof PsiAssignmentExpression
         && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               "dataflow.message.pointless.assignment.expression",
               Boolean.toString(evaluatesToTrue)),
           createConditionalAssignmentFixes(
               evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly));
     } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) {
       final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue);
       String message =
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(evaluatesToTrue));
       holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix});
     }
     reportedAnchors.add(psiAnchor);
   }
 }
  /**
   * Filter the specified collection of classes to return only ones that contain any of the
   * specified values in the specified annotation parameter. For example, this method can be used to
   * return all classes that contain all tesng annotations that are in the groups 'foo' or 'bar'.
   */
  public static Map<PsiClass, Collection<PsiMethod>> filterAnnotations(
      String parameter, Set<String> values, Collection<PsiClass> classes) {
    Map<PsiClass, Collection<PsiMethod>> results = new HashMap<>();
    Set<String> test = new HashSet<>(1);
    test.add(TEST_ANNOTATION_FQN);
    ContainerUtil.addAll(test, CONFIG_ANNOTATIONS_FQN);
    for (PsiClass psiClass : classes) {
      if (isBrokenPsiClass(psiClass)) continue;

      PsiAnnotation annotation;
      try {
        annotation = AnnotationUtil.findAnnotation(psiClass, test);
      } catch (Exception e) {
        LOGGER.error(
            "Exception trying to findAnnotation on "
                + psiClass.getClass().getName()
                + ".\n\n"
                + e.getMessage());
        annotation = null;
      }
      if (annotation != null) {
        if (isAnnotatedWithParameter(annotation, parameter, values)) {
          results.put(psiClass, new LinkedHashSet<>());
        }
      } else {
        Collection<String> matches =
            extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter);
        for (String s : matches) {
          if (values.contains(s)) {
            results.put(psiClass, new LinkedHashSet<>());
            break;
          }
        }
      }

      // we already have the class, no need to look through its methods
      PsiMethod[] methods = psiClass.getMethods();
      for (PsiMethod method : methods) {
        if (method != null) {
          annotation = AnnotationUtil.findAnnotation(method, test);
          if (annotation != null) {
            if (isAnnotatedWithParameter(annotation, parameter, values)) {
              if (results.get(psiClass) == null) results.put(psiClass, new LinkedHashSet<>());
              results.get(psiClass).add(method);
            }
          } else {
            Collection<String> matches =
                extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter);
            for (String s : matches) {
              if (values.contains(s)) {
                results.get(psiClass).add(method);
              }
            }
          }
        }
      }
    }
    return results;
  }
  private static void processClassInner(
      PsiClassType type,
      PsiSubstitutor superClassSubstitutor,
      boolean shouldProcessDeprecated,
      List<PsiMethod> result,
      GrTypeDefinition classToDelegateTo,
      Set<PsiClass> processedWithoutDeprecated,
      Set<PsiClass> processedAll,
      boolean keepParameterAnnotationsNew) {
    final PsiClassType.ClassResolveResult resolveResult = type.resolveGenerics();
    final PsiClass psiClass = resolveResult.getElement();
    if (psiClass == null) return;

    final String qname = psiClass.getQualifiedName();
    if (CommonClassNames.JAVA_LANG_OBJECT.equals(qname)) return;
    if (GroovyCommonClassNames.GROOVY_OBJECT.equals(qname)) return;
    if (GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT.equals(qname)) return;

    final PsiSubstitutor substitutor =
        TypesUtil.composeSubstitutors(resolveResult.getSubstitutor(), superClassSubstitutor);

    if (processedAll.contains(psiClass)) return;
    if (!shouldProcessDeprecated && processedWithoutDeprecated.contains(psiClass)) return;

    if (shouldProcessDeprecated) {
      processedAll.add(psiClass);
    } else {
      processedWithoutDeprecated.add(psiClass);
    }

    collectMethods(
        psiClass,
        substitutor,
        shouldProcessDeprecated,
        classToDelegateTo,
        result,
        keepParameterAnnotationsNew);
    process(
        psiClass,
        substitutor,
        shouldProcessDeprecated,
        processedWithoutDeprecated,
        processedAll,
        result,
        classToDelegateTo,
        keepParameterAnnotationsNew);
  }
 private void updateDocumentFromPropertyValue(
     final String value, final Document document, final PropertiesFile propertiesFile) {
   @NonNls String text = value;
   if (myBackSlashPressed.contains(propertiesFile)) {
     text += "\\";
   }
   document.replaceString(0, document.getTextLength(), text);
 }
Exemple #7
0
  protected boolean isScopeFinal(Class scopeClass) {
    if (myFinalScopes.contains(scopeClass)) return true;

    for (final Class myFinalScope : myFinalScopes) {
      if (ReflectionCache.isAssignable(myFinalScope, scopeClass)) {
        return true;
      }
    }
    return false;
  }
 @Override
 protected void visitClassMemberReferenceElement(
     GrMember classMember, GrReferenceElement classMemberReference) {
   if (classMember.hasModifierProperty(
       PsiModifier.STATIC) /*&& classMemberReference.isQualified()*/) {
     if (!myMovedMembers.contains(classMember)
         && RefactoringHierarchyUtil.isMemberBetween(
             myTargetSuperClass, mySourceClass, classMember)) {
       myReferences.add(classMemberReference);
       myReferees.add(classMember);
       myRefereeClasses.add(classMember.getContainingClass());
     } else if (myMovedMembers.contains(classMember)
         || myMembersAfterMove.contains(classMember)) {
       myReferences.add(classMemberReference);
       myReferees.add(classMember);
       myRefereeClasses.add(myTargetSuperClass);
     }
   }
 }
    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
 public QualifiedResolveResult followAssignmentsChain(PyResolveContext resolveContext) {
   PyReferenceExpression seeker = this;
   QualifiedResolveResult ret = null;
   List<PyExpression> qualifiers = new ArrayList<PyExpression>();
   PyExpression qualifier = seeker.getQualifier();
   if (qualifier != null) {
     qualifiers.add(qualifier);
   }
   Set<PsiElement> visited = new HashSet<PsiElement>();
   visited.add(this);
   SEARCH:
   while (ret == null) {
     ResolveResult[] targets = seeker.getReference(resolveContext).multiResolve(false);
     for (ResolveResult target : targets) {
       PsiElement elt = target.getElement();
       if (elt instanceof PyTargetExpression) {
         PsiElement assigned_from = null;
         final PyTargetExpression expr = (PyTargetExpression) elt;
         final TypeEvalContext context = resolveContext.getTypeEvalContext();
         if (context.maySwitchToAST(expr) || expr.getStub() == null) {
           assigned_from = expr.findAssignedValue();
         }
         // TODO: Maybe findAssignedValueByStub() should become a part of the PyTargetExpression
         // interface
         else if (elt instanceof PyTargetExpressionImpl) {
           assigned_from = ((PyTargetExpressionImpl) elt).findAssignedValueByStub(context);
         }
         if (assigned_from instanceof PyReferenceExpression) {
           if (visited.contains(assigned_from)) {
             break;
           }
           visited.add(assigned_from);
           seeker = (PyReferenceExpression) assigned_from;
           if (seeker.getQualifier() != null) {
             qualifiers.add(seeker.getQualifier());
           }
           continue SEARCH;
         } else if (assigned_from != null)
           ret = new QualifiedResolveResultImpl(assigned_from, qualifiers, false);
       } else if (ret == null && elt instanceof PyElement && target.isValidResult()) {
         // remember this result, but a further reference may be the next resolve result
         ret =
             new QualifiedResolveResultImpl(
                 elt, qualifiers, target instanceof ImplicitResolveResult);
       }
     }
     // all resolve results checked, reassignment not detected, nothing more to do
     break;
   }
   if (ret == null) ret = EMPTY_RESULT;
   return ret;
 }
Exemple #11
0
 @NotNull
 private static List<Import> importsToImportList(@NotNull PsiImportStatementBase[] imports) {
   List<Import> result = new LinkedList<Import>();
   for (PsiImportStatementBase i : imports) {
     Import anImport = importToImport(i);
     String name = anImport.getName();
     if (!name.isEmpty() && !NOT_NULL_ANNOTATIONS.contains(name)) {
       result.add(anImport);
     }
   }
   return result;
 }
 public synchronized boolean renameFavoritesList(
     @NotNull String oldName, @NotNull String newName) {
   if (myReadOnlyLists.contains(oldName)) return false;
   List<TreeItem<Pair<AbstractUrl, String>>> list = myName2FavoritesRoots.remove(oldName);
   if (list != null && newName.length() > 0) {
     myName2FavoritesRoots.put(newName, list);
     fireListeners.listRemoved(oldName);
     fireListeners.listAdded(newName);
     return true;
   }
   return false;
 }
 /**
  * Returns true if the given associated activity class is either found in the given set of
  * classes, or (less likely) extends any of the classes in that set
  */
 private static boolean containsOrExtends(
     @NotNull Set<PsiClass> resolvedClasses, @NotNull PsiClass relatedActivity) {
   if (resolvedClasses.contains(relatedActivity)) {
     return true;
   }
   for (PsiClass resolvedClass : resolvedClasses) {
     if (relatedActivity.isInheritor(resolvedClass, false)) {
       return true;
     }
   }
   return false;
 }
 @Override
 public void visitReferenceExpression(final PsiReferenceExpression reference) {
   if (myLineRange.intersects(reference.getTextRange())) {
     final PsiElement psiElement = reference.resolve();
     if (psiElement instanceof PsiVariable) {
       final PsiVariable var = (PsiVariable) psiElement;
       if (var instanceof PsiField) {
         if (myCollectExpressions
             && !DebuggerUtils.hasSideEffectsOrReferencesMissingVars(
                 reference, myVisibleLocals)) {
           /*
           if (var instanceof PsiEnumConstant && reference.getQualifier() == null) {
             final PsiClass enumClass = ((PsiEnumConstant)var).getContainingClass();
             if (enumClass != null) {
               final PsiExpression expression = JavaPsiFacade.getInstance(var.getProject()).getParserFacade().createExpressionFromText(enumClass.getName() + "." + var.getName(), var);
               final PsiReference ref = expression.getReference();
               if (ref != null) {
                 ref.bindToElement(var);
                 myExpressions.add(new TextWithImportsImpl(expression));
               }
             }
           }
           else {
             myExpressions.add(new TextWithImportsImpl(reference));
           }
           */
           final PsiModifierList modifierList = var.getModifierList();
           boolean isConstant =
               (var instanceof PsiEnumConstant)
                   || (modifierList != null
                       && modifierList.hasModifierProperty(PsiModifier.STATIC)
                       && modifierList.hasModifierProperty(PsiModifier.FINAL));
           if (!isConstant) {
             myExpressions.add(new TextWithImportsImpl(reference));
           }
         }
       } else {
         if (myVisibleLocals.contains(var.getName())) {
           myVars.add(var.getName());
         } else {
           // fix for variables used in inner classes
           if (!Comparing.equal(
               PsiTreeUtil.getParentOfType(reference, PsiClass.class),
               PsiTreeUtil.getParentOfType(var, PsiClass.class))) {
             myExpressions.add(new TextWithImportsImpl(reference));
           }
         }
       }
     }
   }
   super.visitReferenceExpression(reference);
 }
 @Override
 public void visitReferenceExpression(PsiReferenceExpression expression) {
   final PsiExpression qualifierExpression = expression.getQualifierExpression();
   if (qualifierExpression != null && !(qualifierExpression instanceof PsiThisExpression)) {
     return;
   }
   final PsiElement resolved = expression.resolve();
   if (resolved instanceof PsiParameter) {
     myUsedParameters.add((PsiParameter) resolved);
   } else if (myMovedFields.contains(resolved)) {
     myUsedFields.add((PsiField) resolved);
   }
 }
  private List<PsiElement> _process(final Matcher matcher, final boolean resolve) {
    final XmlTag root = matcher.getRoot();
    if (root == null || myHistory.contains(root)) {
      return Collections.emptyList();
    }
    myHistory.add(root);
    final List<PsiElement> found = new ArrayList<PsiElement>();

    try {
      if (matcher.isRecursive()) {
        root.accept(
            new XmlRecursiveElementVisitor() {
              @Override
              public void visitXmlTag(XmlTag tag) {
                final Matcher.Result match = matcher.match(tag);
                if (match != null) {
                  if (match.chain != null) {
                    found.addAll(_process(match.chain, resolve));
                  } else {
                    assert match.result != null;
                    found.add(match.result);
                    if (resolve) throw Stop.DONE;
                  }
                }
                super.visitXmlTag(tag);
              }
            });
      } else {
        root.acceptChildren(
            new XmlElementVisitor() {

              @Override
              public void visitXmlTag(XmlTag tag) {
                final Matcher.Result match = matcher.match(tag);
                if (match != null) {
                  if (match.chain != null) {
                    found.addAll(_process(match.chain, resolve));
                  } else {
                    assert match.result != null;
                    found.add(match.result);
                    if (resolve) throw Stop.DONE;
                  }
                }
              }
            });
      }
    } catch (Stop e) {
      /* processing stopped */
    }
    return found;
  }
  private static void addParameters(
      @NotNull PsiClass psiClass,
      GrLightMethodBuilder fieldsConstructor,
      boolean includeProperties,
      boolean includeFields,
      boolean optional,
      Set<String> excludes) {

    PsiMethod[] methods = CollectClassMembersUtil.getMethods(psiClass, false);
    if (includeProperties) {
      for (PsiMethod method : methods) {
        if (!method.hasModifierProperty(PsiModifier.STATIC)
            && PropertyUtil.isSimplePropertySetter(method)) {
          final String name = PropertyUtil.getPropertyNameBySetter(method);
          if (!excludes.contains(name)) {
            final PsiType type = PropertyUtil.getPropertyType(method);
            assert type != null : method;
            fieldsConstructor.addParameter(
                new GrLightParameter(name, type, fieldsConstructor).setOptional(optional));
          }
        }
      }
    }

    final Map<String, PsiMethod> properties = PropertyUtil.getAllProperties(true, false, methods);
    for (PsiField field : CollectClassMembersUtil.getFields(psiClass, false)) {
      final String name = field.getName();
      if (includeFields
          || includeProperties && field instanceof GrField && ((GrField) field).isProperty()) {
        if (!excludes.contains(name)
            && !field.hasModifierProperty(PsiModifier.STATIC)
            && !properties.containsKey(name)) {
          fieldsConstructor.addParameter(
              new GrLightParameter(name, field.getType(), fieldsConstructor).setOptional(optional));
        }
      }
    }
  }
 public static boolean isAnnotatedWithParameter(
     PsiAnnotation annotation, String parameter, Set<String> values) {
   final PsiAnnotationMemberValue attributeValue =
       annotation.findDeclaredAttributeValue(parameter);
   if (attributeValue != null) {
     Collection<String> matches = extractValuesFromParameter(attributeValue);
     for (String s : matches) {
       if (values.contains(s)) {
         return true;
       }
     }
   }
   return false;
 }
Exemple #19
0
  @SuppressWarnings({"HardCodedStringLiteral"})
  public static boolean isCharOrIntegerArray(Value value) {
    if (value == null) return false;
    if (myCharOrIntegers == null) {
      myCharOrIntegers = new HashSet<String>();
      myCharOrIntegers.add("C");
      myCharOrIntegers.add("B");
      myCharOrIntegers.add("S");
      myCharOrIntegers.add("I");
      myCharOrIntegers.add("J");
    }

    String signature = value.type().signature();
    int i;
    for (i = 0; signature.charAt(i) == '['; i++) ;
    if (i == 0) return false;
    signature = signature.substring(i, signature.length());
    return myCharOrIntegers.contains(signature);
  }
  public static boolean processDeclarationsInClass(
      @NotNull PsiClass aClass,
      @NotNull final PsiScopeProcessor processor,
      @NotNull ResolveState state,
      @Nullable Set<PsiClass> visited,
      PsiElement last,
      @NotNull PsiElement place,
      boolean isRaw) {
    if (last instanceof PsiTypeParameterList || last instanceof PsiModifierList) {
      return true; // TypeParameterList and ModifierList do not see our declarations
    }
    if (visited != null && visited.contains(aClass)) return true;

    PsiSubstitutor substitutor = state.get(PsiSubstitutor.KEY);
    isRaw = isRaw || PsiUtil.isRawSubstitutor(aClass, substitutor);

    ParameterizedCachedValue<MembersMap, PsiClass> cache =
        getValues(aClass); // aClass.getUserData(MAP_IN_CLASS_KEY);
    boolean upToDate = cache.hasUpToDateValue();
    LanguageLevel languageLevel = PsiUtil.getLanguageLevel(place);
    if (
    /*true || */ upToDate) {
      final NameHint nameHint = processor.getHint(NameHint.KEY);
      if (nameHint != null) {
        String name = nameHint.getName(state);
        return processCachedMembersByName(
            aClass,
            processor,
            state,
            visited,
            last,
            place,
            isRaw,
            substitutor,
            cache.getValue(aClass),
            name,
            languageLevel);
      }
    }
    return processDeclarationsInClassNotCached(
        aClass, processor, state, visited, last, place, isRaw, languageLevel);
  }
  public boolean execute(PsiElement element, ResolveState state) {
    //noinspection SuspiciousMethodCalls
    if (myNonInitializedFields.contains(element)) {
      return true;
    }

    if (!(element instanceof PsiClass) && element instanceof PsiModifierListOwner) {
      PsiModifierListOwner modifierListOwner = (PsiModifierListOwner) element;
      if (myStatic) {
        if (!modifierListOwner.hasModifierProperty(PsiModifier.STATIC)) {
          // we don't need non static method in static context.
          return true;
        }
      } else {
        if (!mySettings.SHOW_STATIC_AFTER_INSTANCE
            && modifierListOwner.hasModifierProperty(PsiModifier.STATIC)
            && !myMembersFlag) {
          // according settings we don't need to process such fields/methods
          return true;
        }
      }
    }
    final PsiElement elementParent = myElement.getParent();
    if (element instanceof PsiPackage && myScope instanceof PsiClass) {
      if (!(elementParent instanceof PsiQualifiedReference
          && ((PsiQualifiedReference) elementParent).getQualifier() != null)) {
        return true;
      }
    }

    if (satisfies(element, state) && isAccessible(element)) {
      CompletionElement element1 =
          new CompletionElement(
              myQualifierType, element, state.get(PsiSubstitutor.KEY), myQualifierClass);
      if (myResultNames.add(element1.getUniqueId())) {
        myResults.add(element1);
      }
    }
    return true;
  }
  private void reportNullableArgumentsPassedToNonAnnotated(
      DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) {
    for (PsiElement expr :
        visitor.getProblems(NullabilityProblem.passingNullableArgumentToNonAnnotatedParameter)) {
      if (reportedAnchors.contains(expr)) continue;

      final String text =
          isNullLiteralExpression(expr)
              ? "Passing <code>null</code> argument to non annotated parameter"
              : "Argument <code>#ref</code> #loc might be null but passed to non annotated parameter";
      LocalQuickFix[] fixes =
          createNPEFixes((PsiExpression) expr, (PsiExpression) expr, holder.isOnTheFly());
      final PsiElement parent = expr.getParent();
      if (parent instanceof PsiExpressionList) {
        final int idx = ArrayUtilRt.find(((PsiExpressionList) parent).getExpressions(), expr);
        if (idx > -1) {
          final PsiElement gParent = parent.getParent();
          if (gParent instanceof PsiCallExpression) {
            final PsiMethod psiMethod = ((PsiCallExpression) gParent).resolveMethod();
            if (psiMethod != null
                && psiMethod.getManager().isInProject(psiMethod)
                && AnnotationUtil.isAnnotatingApplicable(psiMethod)) {
              final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
              if (idx < parameters.length) {
                final AddNullableAnnotationFix addNullableAnnotationFix =
                    new AddNullableAnnotationFix(parameters[idx]);
                fixes =
                    fixes == null
                        ? new LocalQuickFix[] {addNullableAnnotationFix}
                        : ArrayUtil.append(fixes, addNullableAnnotationFix);
                holder.registerProblem(expr, text, fixes);
                reportedAnchors.add(expr);
              }
            }
          }
        }
      }
    }
  }
Exemple #23
0
  private static void addNamesFromStatistics(
      Set<String> names,
      VariableKind variableKind,
      @Nullable String propertyName,
      @Nullable PsiType type) {
    String[] allNames =
        JavaStatisticsManager.getAllVariableNamesUsed(variableKind, propertyName, type);

    int maxFrequency = 0;
    for (String name : allNames) {
      int count =
          JavaStatisticsManager.getVariableNameUseCount(name, variableKind, propertyName, type);
      maxFrequency = Math.max(maxFrequency, count);
    }

    int frequencyLimit = Math.max(5, maxFrequency / 2);

    for (String name : allNames) {
      if (names.contains(name)) {
        continue;
      }
      int count =
          JavaStatisticsManager.getVariableNameUseCount(name, variableKind, propertyName, type);
      if (LOG.isDebugEnabled()) {
        LOG.debug("new name:" + name + " count:" + count);
        LOG.debug("frequencyLimit:" + frequencyLimit);
      }
      if (count >= frequencyLimit) {
        names.add(name);
      }
    }

    if (propertyName != null && type != null) {
      addNamesFromStatistics(names, variableKind, propertyName, null);
      addNamesFromStatistics(names, variableKind, null, type);
    }
  }
  static boolean isSideEffectFreeConstructor(PsiNewExpression newExpression) {
    PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
    PsiClass aClass = classReference == null ? null : (PsiClass) classReference.resolve();
    String qualifiedName = aClass == null ? null : aClass.getQualifiedName();
    if (qualifiedName == null) return false;
    if (ourSideEffectFreeClasses.contains(qualifiedName)) return true;

    PsiFile file = aClass.getContainingFile();
    PsiDirectory directory = file.getContainingDirectory();
    PsiPackage classPackage = JavaDirectoryService.getInstance().getPackage(directory);
    String packageName = classPackage == null ? null : classPackage.getQualifiedName();

    // all Throwable descendants from java.lang are side effects free
    if ("java.lang".equals(packageName) || "java.io".equals(packageName)) {
      PsiClass throwableClass =
          JavaPsiFacade.getInstance(aClass.getProject())
              .findClass("java.lang.Throwable", aClass.getResolveScope());
      if (throwableClass != null
          && InheritanceUtil.isInheritorOrSelf(aClass, throwableClass, true)) {
        return true;
      }
    }
    return false;
  }
Exemple #25
0
  @NotNull
  public static Set<JetElement> findRootExpressions(
      @NotNull Collection<JetElement> unreachableElements) {
    Set<JetElement> rootElements = new HashSet<JetElement>();
    final Set<JetElement> shadowedElements = new HashSet<JetElement>();
    JetVisitorVoid shadowAllChildren =
        new JetVisitorVoid() {
          @Override
          public void visitJetElement(@NotNull JetElement element) {
            if (shadowedElements.add(element)) {
              element.acceptChildren(this);
            }
          }
        };

    for (JetElement element : unreachableElements) {
      if (shadowedElements.contains(element)) continue;
      element.acceptChildren(shadowAllChildren);

      rootElements.removeAll(shadowedElements);
      rootElements.add(element);
    }
    return rootElements;
  }
 @Override
 public boolean isCommitted(@NotNull Document document) {
   if (getSynchronizer().isInSynchronization(document)) return true;
   return !((DocumentEx) document).isInEventsHandling()
       && !myUncommittedDocuments.contains(document);
 }
    @Override
    public void visitXmlAttributeValue(XmlAttributeValue value) {
      for (PsiReference reference : value.getReferences()) {
        if (!(reference instanceof OnClickConverter.MyReference)) {
          continue;
        }
        final OnClickConverter.MyReference ref = (OnClickConverter.MyReference) reference;
        final String methodName = ref.getValue();

        if (methodName.isEmpty()) {
          continue;
        }
        final ResolveResult[] results = ref.multiResolve(false);
        final Set<PsiClass> resolvedClasses = new HashSet<PsiClass>();
        final Set<PsiClass> resolvedClassesWithMistake = new HashSet<PsiClass>();

        for (ResolveResult result : results) {
          if (result instanceof OnClickConverter.MyResolveResult) {
            final PsiElement element = result.getElement();

            if (element != null) {
              final PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);

              if (aClass != null) {
                resolvedClasses.add(aClass);

                if (!((OnClickConverter.MyResolveResult) result).hasCorrectSignature()) {
                  resolvedClassesWithMistake.add(aClass);
                }
              }
            }
          }
        }
        PsiClass activity = null;
        for (PsiClass relatedActivity : myRelatedActivities) {
          if (!containsOrExtends(resolvedClasses, relatedActivity)) {
            activity = relatedActivity;
            break;
          } else if (activity == null
              && containsOrExtends(resolvedClassesWithMistake, relatedActivity)) {
            activity = relatedActivity;
          }
        }

        if (activity != null) {
          reportMissingOnClickProblem(
              ref, activity, methodName, resolvedClassesWithMistake.contains(activity));
        } else if (results.length == 0) {
          myResult.add(
              myInspectionManager.createProblemDescriptor(
                  value,
                  reference.getRangeInElement(),
                  ProblemsHolder.unresolvedReferenceMessage(reference),
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                  myOnTheFly));
        } else if (resolvedClassesWithMistake.size() > 0) {
          reportMissingOnClickProblem(
              ref, resolvedClassesWithMistake.iterator().next(), methodName, true);
        }
      }
    }
Exemple #28
0
  public PsiImportList prepareOptimizeImportsResult(@NotNull final PsiJavaFile file) {
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(file.getProject());

    final Set<String> namesToImportStaticly = new THashSet<String>();
    String[] names =
        collectNamesToImport(
            file,
            namesToImportStaticly); // Note: this array may contain "<packageOrClassName>.*" for
                                    // unresolved imports!
    Arrays.sort(names);

    ArrayList<String> namesList = new ArrayList<String>();
    ImportLayoutTable table = mySettings.IMPORT_LAYOUT_TABLE;
    if (table != null) {
      int[] entriesForName = ArrayUtil.newIntArray(names.length);
      for (int i = 0; i < names.length; i++) {
        entriesForName[i] = findEntryIndex(names[i]);
      }

      Entry[] entries = table.getEntries();
      for (int i = 0; i < entries.length; i++) {
        Entry entry = entries[i];
        if (entry instanceof PackageEntry) {
          for (int j = 0; j < names.length; j++) {
            if (entriesForName[j] == i) {
              namesList.add(names[j]);
              names[j] = null;
            }
          }
        }
      }
    }
    for (String name : names) {
      if (name != null) namesList.add(name);
    }
    names = ArrayUtil.toStringArray(namesList);

    TObjectIntHashMap<String> packageToCountMap = new TObjectIntHashMap<String>();
    TObjectIntHashMap<String> classToCountMap = new TObjectIntHashMap<String>();
    for (String name : names) {
      String packageOrClassName = getPackageOrClassName(name);
      if (packageOrClassName.length() == 0) continue;
      if (namesToImportStaticly.contains(name)) {
        int count = classToCountMap.get(packageOrClassName);
        classToCountMap.put(packageOrClassName, count + 1);
      } else {
        int count = packageToCountMap.get(packageOrClassName);
        packageToCountMap.put(packageOrClassName, count + 1);
      }
    }

    final Set<String> classesOrPackagesToImportOnDemand = new THashSet<String>();
    class MyVisitorProcedure implements TObjectIntProcedure<String> {
      private final boolean myIsVisitingPackages;

      MyVisitorProcedure(boolean isVisitingPackages) {
        myIsVisitingPackages = isVisitingPackages;
      }

      public boolean execute(final String packageOrClassName, final int count) {
        if (isToUseImportOnDemand(packageOrClassName, count, !myIsVisitingPackages)) {
          classesOrPackagesToImportOnDemand.add(packageOrClassName);
        }
        return true;
      }
    }
    classToCountMap.forEachEntry(new MyVisitorProcedure(false));
    packageToCountMap.forEachEntry(new MyVisitorProcedure(true));

    Set<String> classesToUseSingle =
        findSingleImports(file, names, classesOrPackagesToImportOnDemand, namesToImportStaticly);

    try {
      final String text =
          buildImportListText(
              names, classesOrPackagesToImportOnDemand, classesToUseSingle, namesToImportStaticly);
      String ext = StdFileTypes.JAVA.getDefaultExtension();
      final PsiJavaFile dummyFile =
          (PsiJavaFile)
              PsiFileFactory.getInstance(file.getProject())
                  .createFileFromText("_Dummy_." + ext, StdFileTypes.JAVA, text);
      codeStyleManager.reformat(dummyFile);

      PsiImportList resultList = dummyFile.getImportList();
      PsiImportList oldList = file.getImportList();
      if (oldList.isReplaceEquivalent(resultList)) return null;
      return resultList;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  @Nullable
  private static PsiExpression createDefaultValue(
      JavaChangeInfo changeInfo,
      final PsiElementFactory factory,
      final JavaParameterInfo info,
      final PsiExpressionList list)
      throws IncorrectOperationException {
    if (info.isUseAnySingleVariable()) {
      final PsiResolveHelper resolveHelper =
          JavaPsiFacade.getInstance(list.getProject()).getResolveHelper();
      final PsiType type = info.getTypeWrapper().getType(changeInfo.getMethod(), list.getManager());
      final VariablesProcessor processor =
          new VariablesProcessor(false) {
            protected boolean check(PsiVariable var, ResolveState state) {
              if (var instanceof PsiField
                  && !resolveHelper.isAccessible((PsiField) var, list, null)) return false;
              if (var instanceof PsiLocalVariable
                  && list.getTextRange().getStartOffset() <= var.getTextRange().getStartOffset())
                return false;
              if (PsiTreeUtil.isAncestor(var, list, false)) return false;
              final PsiType varType = state.get(PsiSubstitutor.KEY).substitute(var.getType());
              return type.isAssignableFrom(varType);
            }

            public boolean execute(PsiElement pe, ResolveState state) {
              super.execute(pe, state);
              return size() < 2;
            }
          };
      PsiScopesUtil.treeWalkUp(processor, list, null);
      if (processor.size() == 1) {
        final PsiVariable result = processor.getResult(0);
        return factory.createExpressionFromText(result.getName(), list);
      }
      if (processor.size() == 0) {
        final PsiClass parentClass = PsiTreeUtil.getParentOfType(list, PsiClass.class);
        if (parentClass != null) {
          PsiClass containingClass = parentClass;
          final Set<PsiClass> containingClasses = new HashSet<PsiClass>();
          while (containingClass != null) {
            if (type.isAssignableFrom(factory.createType(containingClass, PsiSubstitutor.EMPTY))) {
              containingClasses.add(containingClass);
            }
            containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class);
          }
          if (containingClasses.size() == 1) {
            return RefactoringUtil.createThisExpression(
                parentClass.getManager(),
                containingClasses.contains(parentClass)
                    ? null
                    : containingClasses.iterator().next());
          }
        }
      }
    }
    final PsiCallExpression callExpression =
        PsiTreeUtil.getParentOfType(list, PsiCallExpression.class);
    final String defaultValue = info.getDefaultValue();
    return callExpression != null
        ? info.getValue(callExpression)
        : defaultValue.length() > 0 ? factory.createExpressionFromText(defaultValue, list) : null;
  }
Exemple #30
0
  @NotNull
  private static Set<String> findSingleImports(
      @NotNull final PsiJavaFile file,
      @NotNull String[] names,
      @NotNull final Set<String> onDemandImports,
      @NotNull Set<String> namesToImportStaticly) {
    final GlobalSearchScope resolveScope = file.getResolveScope();
    Set<String> namesToUseSingle = new THashSet<String>();
    final String thisPackageName = file.getPackageName();
    final Set<String> implicitlyImportedPackages =
        new THashSet<String>(Arrays.asList(file.getImplicitlyImportedPackages()));
    final PsiManager manager = file.getManager();
    for (String name : names) {
      String prefix = getPackageOrClassName(name);
      if (prefix.length() == 0) continue;
      final boolean isImplicitlyImported = implicitlyImportedPackages.contains(prefix);
      if (!onDemandImports.contains(prefix) && !isImplicitlyImported) continue;
      String shortName = PsiNameHelper.getShortClassName(name);

      String thisPackageClass =
          thisPackageName.length() > 0 ? thisPackageName + "." + shortName : shortName;
      if (JavaPsiFacade.getInstance(manager.getProject()).findClass(thisPackageClass, resolveScope)
          != null) {
        namesToUseSingle.add(name);
        continue;
      }
      if (!isImplicitlyImported) {
        String langPackageClass = JAVA_LANG_PACKAGE + "." + shortName; // TODO : JSP!
        if (JavaPsiFacade.getInstance(manager.getProject())
                .findClass(langPackageClass, resolveScope)
            != null) {
          namesToUseSingle.add(name);
          continue;
        }
      }
      for (String onDemandName : onDemandImports) {
        if (prefix.equals(onDemandName)) continue;
        if (namesToImportStaticly.contains(name)) {
          PsiClass aClass =
              JavaPsiFacade.getInstance(manager.getProject()).findClass(onDemandName, resolveScope);
          if (aClass != null) {
            PsiField field = aClass.findFieldByName(shortName, true);
            if (field != null && field.hasModifierProperty(PsiModifier.STATIC)) {
              namesToUseSingle.add(name);
            } else {
              PsiClass inner = aClass.findInnerClassByName(shortName, true);
              if (inner != null && inner.hasModifierProperty(PsiModifier.STATIC)) {
                namesToUseSingle.add(name);
              } else {
                PsiMethod[] methods = aClass.findMethodsByName(shortName, true);
                for (PsiMethod method : methods) {
                  if (method.hasModifierProperty(PsiModifier.STATIC)) {
                    namesToUseSingle.add(name);
                  }
                }
              }
            }
          }
        } else {
          PsiClass aClass =
              JavaPsiFacade.getInstance(manager.getProject())
                  .findClass(onDemandName + "." + shortName, resolveScope);
          if (aClass != null) {
            namesToUseSingle.add(name);
          }
        }
      }
    }
    return namesToUseSingle;
  }