Exemplo n.º 1
0
 public static boolean typesMatch(Class<?>[] usedTypes, Class<?>[] expectedTypes) {
   // expectedTypes is empty
   if (ArrayUtil.isEmpty(expectedTypes)) return ArrayUtil.isEmpty(usedTypes);
   Class<?> lastExpectedType = ArrayUtil.lastElementOf(expectedTypes);
   if (lastExpectedType.isArray()) {
     // process varargs parameter
     if (usedTypes.length < expectedTypes.length - 1) return false; // fault
     if (usedTypes.length == expectedTypes.length - 1)
       return typesMatch(
           usedTypes, ArrayUtil.copyOfRange(expectedTypes, 0, usedTypes.length)); // empty varargs
     // check if all used types match the varargs type
     if (usedTypes.length >= expectedTypes.length) {
       Class<?> componentType = lastExpectedType.getComponentType();
       for (int i = expectedTypes.length - 1; i < usedTypes.length; i++) {
         Class<?> foundType = usedTypes[i];
         if (!typeMatches(foundType, componentType)) return false;
       }
       return true;
     }
   }
   if (usedTypes.length != expectedTypes.length) return false;
   if (expectedTypes.length == 0 && usedTypes.length == 0) return true;
   for (int i = 0; i < usedTypes.length; i++) {
     Class<?> expectedType = expectedTypes[i];
     Class<?> foundType = usedTypes[i];
     if (!typeMatches(foundType, expectedType)) return false;
   }
   return true;
 }
Exemplo n.º 2
0
 /**
  * Finds a method by reflection. This iterates all methods of the class, comparing names and
  * parameter types. Unlike the method Class.getMethod(String, Class ...), this method is able to
  * match primitive and wrapper types. If no appropriate method is found, 'null' is returned
  *
  * @param type
  * @param methodName
  * @param paramTypes
  * @return a method with matching names and parameters
  */
 public static Method findMethod(Class<?> type, String methodName, Class<?>... paramTypes) {
   Method result = null;
   for (Method method : type.getMethods()) {
     if (!methodName.equals(method.getName())) continue;
     if (typesMatch(paramTypes, method.getParameterTypes())) {
       result = method;
       if ((ArrayUtil.isEmpty(paramTypes) && ArrayUtil.isEmpty(method.getParameterTypes()))
           || paramTypes.length == method.getParameterTypes().length)
         return method; // optimal match - return it immediately
       else
         result = method; // sub optimal match - store it, but keep on searching for better matches
     }
   }
   return result;
 }
  private void reportNullableReturns(
      DataFlowInstructionVisitor visitor,
      ProblemsHolder holder,
      Set<PsiElement> reportedAnchors,
      @NotNull PsiElement block) {
    final PsiMethod method = getScopeMethod(block);
    if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return;

    boolean notNullRequired = NullableNotNullManager.isNotNull(method);
    if (!notNullRequired && !SUGGEST_NULLABLE_ANNOTATIONS) return;

    PsiType returnType = method.getReturnType();
    // no warnings in void lambdas, where the expression is not returned anyway
    if (block instanceof PsiExpression
        && block.getParent() instanceof PsiLambdaExpression
        && returnType == PsiType.VOID) return;

    // no warnings for Void methods, where only null can be possibly returned
    if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return;

    for (PsiElement statement : visitor.getProblems(NullabilityProblem.nullableReturn)) {
      assert statement instanceof PsiExpression;
      final PsiExpression expr = (PsiExpression) statement;
      if (!reportedAnchors.add(expr)) continue;

      if (notNullRequired) {
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message("dataflow.message.return.null.from.notnull")
                : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull");
        holder.registerProblem(expr, text);
      } else if (AnnotationUtil.isAnnotatingApplicable(statement)) {
        final NullableNotNullManager manager =
            NullableNotNullManager.getInstance(expr.getProject());
        final String defaultNullable = manager.getDefaultNullable();
        final String presentableNullable = StringUtil.getShortName(defaultNullable);
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message(
                    "dataflow.message.return.null.from.notnullable", presentableNullable)
                : InspectionsBundle.message(
                    "dataflow.message.return.nullable.from.notnullable", presentableNullable);
        final LocalQuickFix[] fixes =
            PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class)
                    instanceof PsiLambdaExpression
                ? LocalQuickFix.EMPTY_ARRAY
                : new LocalQuickFix[] {
                  new AnnotateMethodFix(
                      defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls())) {
                    @Override
                    public int shouldAnnotateBaseMethod(
                        PsiMethod method, PsiMethod superMethod, Project project) {
                      return 1;
                    }
                  }
                };
        holder.registerProblem(expr, text, fixes);
      }
    }
  }
Exemplo n.º 4
0
  /**
   * Computes the standard packed array strides for a given shape.
   *
   * @param shape the shape of a matrix:
   * @param startValue the startValue for the strides
   * @return the strides for a matrix of n dimensions
   */
  public static int[] calcStrides(int[] shape, int startValue) {
    if (Shape.isColumnVectorShape(shape)) {
      int[] ret = new int[2];
      Arrays.fill(ret, startValue);
      return ret;
    }

    if (Shape.isRowVectorShape(shape)) {
      int[] ret = new int[2];
      ret[0] = 1;
      ret[1] = shape[0];
      return ret;
    }

    int dimensions = shape.length;
    int[] stride = new int[dimensions];

    int st = startValue;
    for (int j = dimensions - 1; j >= 0; j--) {
      stride[j] = st;
      st *= shape[j];
    }

    if (dimensions > 2 && shape[0] == 1) {
      stride = ArrayUtil.reverseCopy(stride);
    }

    return stride;
  }
Exemplo n.º 5
0
  @Override
  public int getId(
      @NotNull VirtualFile parent, @NotNull String childName, @NotNull NewVirtualFileSystem fs) {
    int parentId = getFileId(parent);
    int[] children = FSRecords.list(parentId);

    if (children.length > 0) {
      // fast path, check that some child has same nameId as given name, this avoid O(N) on
      // retrieving names for processing non-cached children
      int nameId = FSRecords.getNameId(childName);
      for (final int childId : children) {
        if (nameId == FSRecords.getNameId(childId)) {
          return childId;
        }
      }
      // for case sensitive system the above check is exhaustive in consistent state of vfs
    }

    for (final int childId : children) {
      if (namesEqual(fs, childName, FSRecords.getName(childId))) return childId;
    }

    final VirtualFile fake = new FakeVirtualFile(parent, childName);
    final FileAttributes attributes = fs.getAttributes(fake);
    if (attributes != null) {
      final int child = createAndFillRecord(fs, fake, parentId, attributes);
      FSRecords.updateList(parentId, ArrayUtil.append(children, child));
      return child;
    }

    return 0;
  }
Exemplo n.º 6
0
 @NotNull
 private static String[] listPersisted(@NotNull int[] childrenIds) {
   String[] names = ArrayUtil.newStringArray(childrenIds.length);
   for (int i = 0; i < childrenIds.length; i++) {
     names[i] = FSRecords.getName(childrenIds[i]);
   }
   return names;
 }
 @Override
 @NotNull
 public Document[] getUncommittedDocuments() {
   ApplicationManager.getApplication().assertIsDispatchThread();
   Document[] documents =
       myUncommittedDocuments.toArray(new Document[myUncommittedDocuments.size()]);
   return ArrayUtil.stripTrailingNulls(documents);
 }
 @NotNull
 private DetailedLogData loadSomeCommitsOnTaggedBranches(
     @NotNull VirtualFile root, int commitCount, @NotNull Collection<String> unmatchedTags)
     throws VcsException {
   List<String> params = new ArrayList<String>();
   params.add("--max-count=" + commitCount);
   params.addAll(unmatchedTags);
   return GitHistoryUtils.loadMetadata(myProject, root, true, ArrayUtil.toStringArray(params));
 }
Exemplo n.º 9
0
 @Nullable
 private static InjectionPlace[] dropKnownInvalidPlaces(InjectionPlace[] places) {
   InjectionPlace[] result = places;
   for (InjectionPlace place : places) {
     if (place.getText().contains("matches(\"[^${}/\\\\]+\")")) {
       result = ArrayUtil.remove(result, place);
     }
   }
   return places.length != 0 && result.length == 0 ? null : result;
 }
Exemplo n.º 10
0
 @NotNull
 private DetailedLogData loadSomeCommitsOnTaggedBranches(
     @NotNull VirtualFile root, int commitCount, @NotNull Collection<String> unmatchedTags)
     throws VcsException {
   StopWatch sw = StopWatch.start("loading commits on tagged branch in " + root.getName());
   List<String> params = new ArrayList<String>();
   params.add("--max-count=" + commitCount);
   params.addAll(unmatchedTags);
   sw.report();
   return GitHistoryUtils.loadMetadata(myProject, root, true, ArrayUtil.toStringArray(params));
 }
Exemplo n.º 11
0
  private static void removeIdFromParentList(
      final int parentId, final int id, @NotNull VirtualFile parent, VirtualFile file) {
    int[] childList = FSRecords.list(parentId);

    int index = ArrayUtil.indexOf(childList, id);
    if (index == -1) {
      throw new RuntimeException(
          "Cannot find child ("
              + id
              + ")"
              + file
              + "\n\tin ("
              + parentId
              + ")"
              + parent
              + "\n\tactual children:"
              + Arrays.toString(childList));
    }
    childList = ArrayUtil.remove(childList, index);
    FSRecords.updateList(parentId, childList);
  }
 private void removeFromArray(int index) {
   myChildren =
       ArrayUtil.remove(
           myChildren,
           index,
           new ArrayFactory<VirtualFileSystemEntry>() {
             @NotNull
             @Override
             public VirtualFileSystemEntry[] create(int count) {
               return new VirtualFileSystemEntry[count];
             }
           });
 }
Exemplo n.º 13
0
 @NotNull
 @Override
 public List<? extends VcsFullCommitDetails> readFullDetails(
     @NotNull VirtualFile root, @NotNull List<String> hashes) throws VcsException {
   String noWalk =
       GitVersionSpecialty.NO_WALK_UNSORTED.existsIn(myVcs.getVersion())
           ? "--no-walk=unsorted"
           : "--no-walk";
   List<String> params = new ArrayList<String>();
   params.add(noWalk);
   params.addAll(hashes);
   return GitHistoryUtils.history(myProject, root, ArrayUtil.toStringArray(params));
 }
  private boolean[][] getExclusiveMutations(Set<String> g1, Set<String> g2) {
    boolean[][] b = new boolean[2][];

    b[0] = getMutated(g1);
    b[1] = getMutated(g2);

    System.out.println("b[0].length = " + b[0].length);
    System.out.println("M1 = " + ArrayUtil.countValue(b[0], true));
    System.out.println("M2 = " + ArrayUtil.countValue(b[1], true));

    for (int i = 0; i < b[0].length; i++) {
      if (b[0][i] && b[1][i]) {
        b[0][i] = false;
        b[1][i] = false;
      }
    }

    System.out.println("After removing overlaps:");
    System.out.println("M1 = " + ArrayUtil.countValue(b[0], true));
    System.out.println("M2 = " + ArrayUtil.countValue(b[1], true));
    return b;
  }
  @NotNull
  public static String[] filterNames(@NotNull String[] names) {
    int filteredCount = 0;
    for (String string : names) {
      if (isBadName(string)) filteredCount++;
    }
    if (filteredCount == 0) return names;

    String[] result = ArrayUtil.newStringArray(names.length - filteredCount);
    int count = 0;
    for (String string : names) {
      if (isBadName(string)) continue;
      result[count++] = string;
    }

    return result;
  }
Exemplo n.º 16
0
  /**
   * Computes the standard packed array strides for a given shape.
   *
   * @param shape the shape of a matrix:
   * @param startNum the start number for the strides
   * @return the strides for a matrix of n dimensions
   */
  public static int[] calcStridesFortran(int[] shape, int startNum) {
    if (Shape.isColumnVectorShape(shape)) {
      int[] ret = new int[2];
      Arrays.fill(ret, startNum);
      return ret;
    }

    int dimensions = shape.length;
    int[] stride = new int[dimensions];
    int st = startNum;
    for (int j = 0; j < stride.length; j++) {
      stride[j] = st;
      st *= shape[j];
    }

    if (dimensions > 2 && shape[0] == 1) {
      stride = ArrayUtil.reverseCopy(stride);
    }

    return stride;
  }
  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);
              }
            }
          }
        }
      }
    }
  }
Exemplo n.º 18
0
 private static void appendIdToParentList(final int parentId, final int childId) {
   int[] childrenList = FSRecords.list(parentId);
   childrenList = ArrayUtil.append(childrenList, childId);
   FSRecords.updateList(parentId, childrenList);
 }
Exemplo n.º 19
0
 public static <T> T[] cloneAll(T[] input) {
   T[] output = ArrayUtil.newInstance(ArrayUtil.componentType(input), input.length);
   for (int i = 0; i < input.length; i++) output[i] = clone(input[i]);
   return output;
 }
  private ColumnInfo[] createInjectionColumnInfos() {
    final TableCellRenderer booleanCellRenderer = createBooleanCellRenderer();
    final TableCellRenderer displayNameCellRenderer = createDisplayNameCellRenderer();
    final TableCellRenderer languageCellRenderer = createLanguageCellRenderer();
    final Comparator<InjInfo> languageComparator =
        new Comparator<InjInfo>() {
          public int compare(final InjInfo o1, final InjInfo o2) {
            return Comparing.compare(
                o1.injection.getInjectedLanguageId(), o2.injection.getInjectedLanguageId());
          }
        };
    final Comparator<InjInfo> displayNameComparator =
        new Comparator<InjInfo>() {
          public int compare(final InjInfo o1, final InjInfo o2) {
            final int support =
                Comparing.compare(o1.injection.getSupportId(), o2.injection.getSupportId());
            if (support != 0) return support;
            return Comparing.compare(o1.injection.getDisplayName(), o2.injection.getDisplayName());
          }
        };
    final ColumnInfo[] columnInfos = {
      new ColumnInfo<InjInfo, Boolean>(" ") {
        @Override
        public Class getColumnClass() {
          return Boolean.class;
        }

        @Override
        public Boolean valueOf(final InjInfo o) {
          return o.injection.isEnabled();
        }

        @Override
        public boolean isCellEditable(final InjInfo injection) {
          return true;
        }

        @Override
        public void setValue(final InjInfo injection, final Boolean value) {
          injection.injection.setPlaceEnabled(null, value.booleanValue());
        }

        @Override
        public TableCellRenderer getRenderer(final InjInfo injection) {
          return booleanCellRenderer;
        }
      },
      new ColumnInfo<InjInfo, InjInfo>("Name") {
        @Override
        public InjInfo valueOf(final InjInfo info) {
          return info;
        }

        @Override
        public Comparator<InjInfo> getComparator() {
          return displayNameComparator;
        }

        @Override
        public TableCellRenderer getRenderer(final InjInfo injection) {
          return displayNameCellRenderer;
        }
      },
      new ColumnInfo<InjInfo, InjInfo>("Language") {
        @Override
        public InjInfo valueOf(final InjInfo info) {
          return info;
        }

        @Override
        public Comparator<InjInfo> getComparator() {
          return languageComparator;
        }

        @Override
        public TableCellRenderer getRenderer(final InjInfo info) {
          return languageCellRenderer;
        }
      }
    };
    if (myInfos.length > 1) {
      final TableCellRenderer typeRenderer = createTypeRenderer();
      return ArrayUtil.append(
          columnInfos,
          new ColumnInfo<InjInfo, String>("Scope") {
            @Override
            public String valueOf(final InjInfo info) {
              return info.bundled ? "Built-in" : info.cfgInfo.title;
            }

            @Override
            public TableCellRenderer getRenderer(final InjInfo injInfo) {
              return typeRenderer;
            }

            @Override
            public int getWidth(final JTable table) {
              return table
                  .getFontMetrics(table.getFont())
                  .stringWidth(StringUtil.repeatSymbol('m', 6));
            }

            @Override
            public Comparator<InjInfo> getComparator() {
              return new Comparator<InjInfo>() {
                @Override
                public int compare(final InjInfo o1, final InjInfo o2) {
                  return Comparing.compare(valueOf(o1), valueOf(o2));
                }
              };
            }
          });
    }
    return columnInfos;
  }