Example #1
0
  private static boolean isParameterUsedRecursively(
      @NotNull PsiElement element, @NotNull List<PsiReference> array) {
    if (!(element instanceof PsiParameter)) return false;
    PsiParameter parameter = (PsiParameter) element;
    PsiElement scope = parameter.getDeclarationScope();
    if (!(scope instanceof PsiMethod)) return false;
    PsiMethod method = (PsiMethod) scope;
    int paramIndex = ArrayUtilRt.find(method.getParameterList().getParameters(), parameter);

    for (PsiReference reference : array) {
      if (!(reference instanceof PsiElement)) return false;
      PsiElement argument = (PsiElement) reference;

      PsiMethodCallExpression methodCallExpression =
          (PsiMethodCallExpression)
              new PsiMatcherImpl(argument)
                  .dot(PsiMatchers.hasClass(PsiReferenceExpression.class))
                  .parent(PsiMatchers.hasClass(PsiExpressionList.class))
                  .parent(PsiMatchers.hasClass(PsiMethodCallExpression.class))
                  .getElement();
      if (methodCallExpression == null) return false;
      PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
      if (method != methodExpression.resolve()) return false;
      PsiExpressionList argumentList = methodCallExpression.getArgumentList();
      PsiExpression[] arguments = argumentList.getExpressions();
      int argumentIndex = ArrayUtilRt.find(arguments, argument);
      if (paramIndex != argumentIndex) return false;
    }

    return true;
  }
  private static boolean isTailAfterIf(
      @NotNull GrIfStatement ifStatement, @NotNull GrStatementOwner owner) {
    final GrControlFlowOwner flowOwner = ControlFlowUtils.findControlFlowOwner(ifStatement);
    if (flowOwner == null) return false;

    final Instruction[] flow = flowOwner.getControlFlow();

    final GrStatement[] statements = owner.getStatements();
    final int index = ArrayUtilRt.find(statements, ifStatement);
    if (index == statements.length - 1) return false;

    final GrStatement then = ifStatement.getThenBranch();

    for (Instruction i : flow) {
      final PsiElement element = i.getElement();
      if (element == null || !PsiTreeUtil.isAncestor(then, element, true)) continue;

      for (Instruction succ : i.allSuccessors()) {
        if (succ instanceof IfEndInstruction) {
          return false;
        }
      }
    }

    return true;
  }
 @Override
 protected int getSelectedIndex() {
   if (myCanExpand) {
     return ArrayUtilRt.find(getAllElements(), myComponent.getSelectionPath());
   }
   int[] selectionRows = myComponent.getSelectionRows();
   return selectionRows == null || selectionRows.length == 0 ? -1 : selectionRows[0];
 }
    @Nullable
    @Override
    public HighlightInfo create() {
      HighlightInfo info = createUnconditionally();
      LOG.assertTrue(
          psiElement != null
              || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY
              || severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY
              || ArrayUtilRt.find(HighlightSeverity.DEFAULT_SEVERITIES, severity) != -1,
          "Custom type requires not-null element to detect its text attributes");

      if (!isAcceptedByFilters(info, psiElement)) return null;

      return info;
    }
  private static boolean isLastStatementInCaseSection(
      GrCaseSection caseSection, GrSwitchStatement switchStatement) {
    final GrCaseSection[] sections = switchStatement.getCaseSections();
    final int i = ArrayUtilRt.find(sections, caseSection);
    if (i == sections.length - 1) {
      return true;
    }

    for (int j = i + 1; j < sections.length; j++) {
      GrCaseSection section = sections[j];
      for (GrStatement statement : section.getStatements()) {
        if (!(statement instanceof GrBreakStatement)) {
          return false;
        }
      }
    }
    return true;
  }
    @Nullable
    @Override
    public HighlightInfo create() {
      HighlightInfo info = createUnconditionally();
      LOG.assertTrue(
          psiElement != null
              || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY
              || severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY
              || ArrayUtilRt.find(HighlightSeverity.DEFAULT_SEVERITIES, severity) != -1,
          "Custom type demands element to detect its text attributes");

      PsiFile file = psiElement == null ? null : psiElement.getContainingFile();
      for (HighlightInfoFilter filter : getFilters()) {
        if (!filter.accept(info, file)) {
          return null;
        }
      }

      return info;
    }
  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);
              }
            }
          }
        }
      }
    }
  }
 /**
  * @deprecated To be removed in idea 13. Use {@link
  *     HighlightInfo#newHighlightInfo(HighlightInfoType)} instead.
  */
 @Deprecated
 @Nullable
 public static HighlightInfo createHighlightInfo(
     @NotNull HighlightInfoType type,
     @Nullable PsiElement element,
     int start,
     int end,
     @Nullable String description,
     @Nullable String toolTip,
     boolean isEndOfLine,
     @Nullable TextAttributes forcedAttributes) {
   LOG.assertTrue(
       element != null
           || ArrayUtilRt.find(HighlightSeverity.DEFAULT_SEVERITIES, type.getSeverity(element))
               != -1,
       "Custom type demands element to detect its text attributes");
   HighlightInfo highlightInfo =
       new HighlightInfo(
           forcedAttributes,
           null,
           type,
           start,
           end,
           description,
           toolTip,
           type.getSeverity(element),
           isEndOfLine,
           null,
           false,
           0);
   PsiFile file = element == null ? null : element.getContainingFile();
   for (HighlightInfoFilter filter : getFilters()) {
     if (!filter.accept(highlightInfo, file)) {
       return null;
     }
   }
   return highlightInfo;
 }
  @Nullable
  private DependencyOnPlugin editPluginDependency(
      @NotNull JComponent parent, @NotNull final DependencyOnPlugin original) {
    List<String> pluginIds = new ArrayList<String>(getPluginNameByIdMap().keySet());
    if (!original.getPluginId().isEmpty() && !pluginIds.contains(original.getPluginId())) {
      pluginIds.add(original.getPluginId());
    }
    Collections.sort(
        pluginIds,
        new Comparator<String>() {
          @Override
          public int compare(String o1, String o2) {
            return getPluginNameById(o1).compareToIgnoreCase(getPluginNameById(o2));
          }
        });

    final ComboBox pluginChooser = new ComboBox(ArrayUtilRt.toStringArray(pluginIds), 250);
    pluginChooser.setRenderer(
        new ListCellRendererWrapper<String>() {
          @Override
          public void customize(
              JList list, String value, int index, boolean selected, boolean hasFocus) {
            setText(getPluginNameById(value));
          }
        });
    new ComboboxSpeedSearch(pluginChooser) {
      @Override
      protected String getElementText(Object element) {
        return getPluginNameById((String) element);
      }
    };
    pluginChooser.setSelectedItem(original.getPluginId());

    final JBTextField minVersionField =
        new JBTextField(StringUtil.notNullize(original.getMinVersion()));
    final JBTextField maxVersionField =
        new JBTextField(StringUtil.notNullize(original.getMaxVersion()));
    final JBTextField channelField = new JBTextField(StringUtil.notNullize(original.getChannel()));
    minVersionField.getEmptyText().setText("<any>");
    minVersionField.setColumns(10);
    maxVersionField.getEmptyText().setText("<any>");
    maxVersionField.setColumns(10);
    channelField.setColumns(10);
    JPanel panel =
        FormBuilder.createFormBuilder()
            .addLabeledComponent("Plugin:", pluginChooser)
            .addLabeledComponent("Minimum version:", minVersionField)
            .addLabeledComponent("Maximum version:", maxVersionField)
            .addLabeledComponent("Channel:", channelField)
            .getPanel();
    final DialogBuilder dialogBuilder =
        new DialogBuilder(parent).title("Required Plugin").centerPanel(panel);
    dialogBuilder.setPreferredFocusComponent(pluginChooser);
    pluginChooser.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            dialogBuilder.setOkActionEnabled(
                !StringUtil.isEmpty((String) pluginChooser.getSelectedItem()));
          }
        });
    if (dialogBuilder.show() == DialogWrapper.OK_EXIT_CODE) {
      return new DependencyOnPlugin(
          ((String) pluginChooser.getSelectedItem()),
          StringUtil.nullize(minVersionField.getText().trim()),
          StringUtil.nullize(maxVersionField.getText().trim()),
          StringUtil.nullize(channelField.getText().trim()));
    }
    return null;
  }
Example #10
0
 public void doCopy(PsiElement[] elements, PsiDirectory defaultTargetDirectory) {
   FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
   final HashMap<PsiFile, String> relativePathsMap = new HashMap<>();
   final Map<PsiFile, PsiClass[]> classes =
       convertToTopLevelClasses(elements, false, "", relativePathsMap);
   assert classes != null;
   if (defaultTargetDirectory == null) {
     final PsiFile psiFile = classes.keySet().iterator().next();
     defaultTargetDirectory = psiFile.getContainingDirectory();
     LOG.assertTrue(defaultTargetDirectory != null, psiFile);
   }
   Project project = defaultTargetDirectory.getProject();
   VirtualFile sourceRootForFile =
       ProjectRootManager.getInstance(project)
           .getFileIndex()
           .getSourceRootForFile(defaultTargetDirectory.getVirtualFile());
   if (sourceRootForFile == null) {
     final List<PsiElement> files = new ArrayList<>();
     for (PsiElement element : elements) {
       PsiFile containingFile = element.getContainingFile();
       if (containingFile != null) {
         files.add(containingFile);
       } else if (element instanceof PsiDirectory) {
         files.add(element);
       }
     }
     CopyFilesOrDirectoriesHandler.copyAsFiles(
         files.toArray(new PsiElement[files.size()]), defaultTargetDirectory, project);
     return;
   }
   Object targetDirectory = null;
   String className = null;
   boolean openInEditor = true;
   if (copyOneClass(classes)) {
     final String commonPath =
         ArrayUtilRt.find(elements, classes.values().iterator().next()) == -1
             ? normalizeRelativeMap(relativePathsMap)
             : null;
     CopyClassDialog dialog =
         new CopyClassDialog(
             classes.values().iterator().next()[0], defaultTargetDirectory, project, false) {
           @Override
           protected String getQualifiedName() {
             final String qualifiedName = super.getQualifiedName();
             if (commonPath != null
                 && !commonPath.isEmpty()
                 && !qualifiedName.endsWith(commonPath)) {
               return StringUtil.getQualifiedName(qualifiedName, commonPath.replaceAll("/", "."));
             }
             return qualifiedName;
           }
         };
     dialog.setTitle(RefactoringBundle.message("copy.handler.copy.class"));
     if (dialog.showAndGet()) {
       openInEditor = dialog.openInEditor();
       targetDirectory = dialog.getTargetDirectory();
       className = dialog.getClassName();
       if (className == null || className.length() == 0) return;
     }
   } else {
     if (ApplicationManager.getApplication().isUnitTestMode()) {
       targetDirectory = defaultTargetDirectory;
     } else {
       defaultTargetDirectory =
           CopyFilesOrDirectoriesHandler.resolveDirectory(defaultTargetDirectory);
       if (defaultTargetDirectory == null) return;
       PsiElement[] files = PsiUtilCore.toPsiFileArray(classes.keySet());
       if (classes.keySet().size() == 1) {
         // do not choose a new name for a file when multiple classes exist in one file
         final PsiClass[] psiClasses = classes.values().iterator().next();
         if (psiClasses != null) {
           files = psiClasses;
         }
       }
       final CopyFilesOrDirectoriesDialog dialog =
           new CopyFilesOrDirectoriesDialog(files, defaultTargetDirectory, project, false);
       if (dialog.showAndGet()) {
         targetDirectory = dialog.getTargetDirectory();
         className = dialog.getNewName();
         openInEditor = dialog.openInEditor();
       }
     }
   }
   if (targetDirectory != null) {
     copyClassesImpl(
         className,
         project,
         classes,
         relativePathsMap,
         targetDirectory,
         defaultTargetDirectory,
         RefactoringBundle.message("copy.handler.copy.class"),
         false,
         openInEditor);
   }
 }