Пример #1
0
 @NotNull
 public static String getPropertyNameByGetter(PsiMethod getterMethod) {
   @NonNls String methodName = getterMethod.getName();
   return methodName.startsWith("get")
       ? StringUtil.decapitalize(methodName.substring(3))
       : StringUtil.decapitalize(methodName.substring(2));
 }
Пример #2
0
 private static void addCamelNames(
     ArrayList<String> result, String name, JetNameValidator validator) {
   if (name == "") return;
   String s = deleteNonLetterFromString(name);
   if (s.startsWith("get") || s.startsWith("set")) s = s.substring(3);
   else if (s.startsWith("is")) s = s.substring(2);
   for (int i = 0; i < s.length(); ++i) {
     if (i == 0) {
       addName(result, StringUtil.decapitalize(s), validator);
     } else if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') {
       addName(result, StringUtil.decapitalize(s.substring(i)), validator);
     }
   }
 }
  @Override
  public String handleEmptyLookup(
      @NotNull final CompletionParameters parameters, final Editor editor) {
    if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;

    final String ad = advertise(parameters);
    final String suffix = ad == null ? "" : "; " + StringUtil.decapitalize(ad);
    if (parameters.getCompletionType() == CompletionType.SMART) {
      if (!ApplicationManager.getApplication().isUnitTestMode()) {

        final Project project = parameters.getPosition().getProject();
        final PsiFile file = parameters.getOriginalFile();

        PsiExpression expression =
            PsiTreeUtil.getContextOfType(parameters.getPosition(), PsiExpression.class, true);
        if (expression != null && expression.getParent() instanceof PsiExpressionList) {
          int lbraceOffset = expression.getParent().getTextRange().getStartOffset();
          ShowParameterInfoHandler.invoke(project, editor, file, lbraceOffset, null);
        }

        if (expression instanceof PsiLiteralExpression) {
          return LangBundle.message("completion.no.suggestions") + suffix;
        }

        if (expression instanceof PsiInstanceOfExpression) {
          final PsiInstanceOfExpression instanceOfExpression = (PsiInstanceOfExpression) expression;
          if (PsiTreeUtil.isAncestor(
              instanceOfExpression.getCheckType(), parameters.getPosition(), false)) {
            return LangBundle.message("completion.no.suggestions") + suffix;
          }
        }
      }

      final Set<PsiType> expectedTypes = JavaCompletionUtil.getExpectedTypes(parameters);
      if (expectedTypes != null) {
        PsiType type = expectedTypes.size() == 1 ? expectedTypes.iterator().next() : null;
        if (type != null) {
          final PsiType deepComponentType = type.getDeepComponentType();
          if (deepComponentType instanceof PsiClassType) {
            if (((PsiClassType) deepComponentType).resolve() != null) {
              return CompletionBundle.message(
                      "completion.no.suggestions.of.type", type.getPresentableText())
                  + suffix;
            }
            return CompletionBundle.message("completion.unknown.type", type.getPresentableText())
                + suffix;
          }
          if (!PsiType.NULL.equals(type)) {
            return CompletionBundle.message(
                    "completion.no.suggestions.of.type", type.getPresentableText())
                + suffix;
          }
        }
      }
    }
    return LangBundle.message("completion.no.suggestions") + suffix;
  }
 @NotNull
 public static Collection<String> generateNames(@NotNull String name) {
   name =
       StringUtil.decapitalize(
           deleteNonLetterFromString(StringUtil.unquoteString(name.replace('.', '_'))));
   if (name.startsWith("get")) {
     name = name.substring(3);
   } else if (name.startsWith("is")) {
     name = name.substring(2);
   }
   while (name.startsWith("_")) {
     name = name.substring(1);
   }
   while (name.endsWith("_")) {
     name = name.substring(0, name.length() - 1);
   }
   final int length = name.length();
   final Collection<String> possibleNames = new LinkedHashSet<String>();
   for (int i = 0; i < length; i++) {
     if (Character.isLetter(name.charAt(i))
         && (i == 0
             || name.charAt(i - 1) == '_'
             || (Character.isLowerCase(name.charAt(i - 1))
                 && Character.isUpperCase(name.charAt(i))))) {
       final String candidate = StringUtil.decapitalize(name.substring(i));
       if (candidate.length() < 25) {
         possibleNames.add(candidate);
       }
     }
   }
   // prefer shorter names
   ArrayList<String> reversed = new ArrayList<String>(possibleNames);
   Collections.reverse(reversed);
   return ContainerUtil.map(
       reversed,
       name1 -> {
         if (name1.indexOf('_') == -1) {
           return name1;
         }
         name1 = StringUtil.capitalizeWords(name1, "_", true, true);
         return StringUtil.decapitalize(name1.replaceAll("_", ""));
       });
 }
  public static Collection<String> getSuggestedNames(
      final DartExpression expression, @Nullable Collection<String> additionalUsedNames) {
    Collection<String> candidates = new LinkedHashSet<String>();

    String text = expression.getText();
    if (expression instanceof DartReference) {
      DartClass dartClass = ((DartReference) expression).resolveDartClass().getDartClass();
      String dartClassName = dartClass == null ? null : dartClass.getName();
      if (dartClassName != null && !dartClassName.equals(StringUtil.decapitalize(dartClassName))) {
        candidates.add(StringUtil.decapitalize(dartClassName));
      }
    }

    if (expression instanceof DartCallExpression) {
      final DartExpression callee = ((DartCallExpression) expression).getExpression();
      text = callee.getText();
    }

    if (text != null) {
      candidates.addAll(generateNames(text));
    }

    final Set<String> usedNames = DartRefactoringUtil.collectUsedNames(expression);
    if (additionalUsedNames != null && !additionalUsedNames.isEmpty()) {
      usedNames.addAll(additionalUsedNames);
    }
    final Collection<String> result = new ArrayList<String>();

    for (String candidate : candidates) {
      int index = 0;
      String suffix = "";
      while (usedNames.contains(candidate + suffix)) {
        suffix = Integer.toString(++index);
      }
      result.add(candidate + suffix);
    }

    if (result.isEmpty()) {
      result.add("o"); // never empty
    }

    return result;
  }
  private String calculateDelegateFieldName() {
    final Project project = sourceClass.getProject();
    final CodeStyleSettingsManager settingsManager = CodeStyleSettingsManager.getInstance(project);
    final CodeStyleSettings settings = settingsManager.getCurrentSettings();

    final String baseName =
        settings.FIELD_NAME_PREFIX.length() == 0
            ? StringUtil.decapitalize(newClassName)
            : newClassName;
    String name = settings.FIELD_NAME_PREFIX + baseName + settings.FIELD_NAME_SUFFIX;
    if (!existsFieldWithName(name) && !PsiNameHelper.getInstance(project).isKeyword(name)) {
      return name;
    }
    int counter = 1;
    while (true) {
      name = settings.FIELD_NAME_PREFIX + baseName + counter + settings.FIELD_NAME_SUFFIX;
      if (!existsFieldWithName(name) && !PsiNameHelper.getInstance(project).isKeyword(name)) {
        return name;
      }
      counter++;
    }
  }
  @NotNull
  private static UsageViewPresentation createPresentation(
      @NotNull UsageViewDescriptor descriptor, @NotNull Usage[] usages) {
    UsageViewPresentation presentation = new UsageViewPresentation();
    presentation.setTabText(RefactoringBundle.message("usageView.tabText"));
    presentation.setTargetsNodeText(descriptor.getProcessedElementsHeader());
    presentation.setShowReadOnlyStatusAsRed(true);
    presentation.setShowCancelButton(true);
    presentation.setUsagesString(RefactoringBundle.message("usageView.usagesText"));
    int codeUsageCount = 0;
    int nonCodeUsageCount = 0;
    int dynamicUsagesCount = 0;
    Set<PsiFile> codeFiles = new HashSet<>();
    Set<PsiFile> nonCodeFiles = new HashSet<>();
    Set<PsiFile> dynamicUsagesCodeFiles = new HashSet<>();

    for (Usage usage : usages) {
      if (usage instanceof PsiElementUsage) {
        final PsiElementUsage elementUsage = (PsiElementUsage) usage;
        final PsiElement element = elementUsage.getElement();
        if (element == null) continue;
        final PsiFile containingFile = element.getContainingFile();
        if (elementUsage.isNonCodeUsage()) {
          nonCodeUsageCount++;
          nonCodeFiles.add(containingFile);
        } else {
          codeUsageCount++;
          codeFiles.add(containingFile);
        }
        if (usage instanceof UsageInfo2UsageAdapter) {
          final UsageInfo usageInfo = ((UsageInfo2UsageAdapter) usage).getUsageInfo();
          if (usageInfo instanceof MoveRenameUsageInfo && usageInfo.isDynamicUsage()) {
            dynamicUsagesCount++;
            dynamicUsagesCodeFiles.add(containingFile);
          }
        }
      }
    }
    codeFiles.remove(null);
    nonCodeFiles.remove(null);
    dynamicUsagesCodeFiles.remove(null);

    String codeReferencesText = descriptor.getCodeReferencesText(codeUsageCount, codeFiles.size());
    presentation.setCodeUsagesString(codeReferencesText);
    final String commentReferencesText =
        descriptor.getCommentReferencesText(nonCodeUsageCount, nonCodeFiles.size());
    if (commentReferencesText != null) {
      presentation.setNonCodeUsagesString(commentReferencesText);
    }
    presentation.setDynamicUsagesString(
        "Dynamic "
            + StringUtil.decapitalize(
                descriptor.getCodeReferencesText(
                    dynamicUsagesCount, dynamicUsagesCodeFiles.size())));
    String generatedCodeString;
    if (codeReferencesText.contains("in code")) {
      generatedCodeString = StringUtil.replace(codeReferencesText, "in code", "in generated code");
    } else {
      generatedCodeString = codeReferencesText + " in generated code";
    }
    presentation.setUsagesInGeneratedCodeString(generatedCodeString);
    return presentation;
  }
 @Override
 public String getName() {
   return myPsiClass.getName() + "." + StringUtil.decapitalize(myName.substring("set".length()));
 }
  private void findUsagesForMethod(
      PsiMethod overridingMethod, List<FixableUsageInfo> usages, boolean changeSignature) {
    final PsiCodeBlock body = overridingMethod.getBody();
    final String baseParameterName = StringUtil.decapitalize(className);
    final String fixedParamName =
        body != null
            ? JavaCodeStyleManager.getInstance(myProject)
                .suggestUniqueVariableName(baseParameterName, body.getLBrace(), true)
            : JavaCodeStyleManager.getInstance(myProject)
                .propertyNameToVariableName(baseParameterName, VariableKind.PARAMETER);

    usages.add(
        new MergeMethodArguments(
            overridingMethod,
            className,
            packageName,
            fixedParamName,
            paramsToMerge,
            typeParams,
            keepMethodAsDelegate,
            myCreateInnerClass ? method.getContainingClass() : null,
            changeSignature));

    final ParamUsageVisitor visitor = new ParamUsageVisitor(overridingMethod, paramsToMerge);
    overridingMethod.accept(visitor);
    final Set<PsiReferenceExpression> values = visitor.getParameterUsages();
    for (PsiReferenceExpression paramUsage : values) {
      final PsiParameter parameter = (PsiParameter) paramUsage.resolve();
      assert parameter != null;
      final PsiMethod containingMethod = (PsiMethod) parameter.getDeclarationScope();
      final int index = containingMethod.getParameterList().getParameterIndex(parameter);
      final PsiParameter replacedParameter = method.getParameterList().getParameters()[index];
      final ParameterChunk parameterChunk =
          ParameterChunk.getChunkByParameter(parameter, parameters);

      @NonNls String getter = parameterChunk != null ? parameterChunk.getter : null;
      final String paramName =
          parameterChunk != null ? parameterChunk.parameter.name : replacedParameter.getName();
      final PsiType paramType =
          parameterChunk != null ? parameterChunk.parameter.type : replacedParameter.getType();
      if (getter == null) {
        getter = GenerateMembersUtil.suggestGetterName(paramName, paramType, myProject);
        paramsNeedingGetters.add(replacedParameter);
      }
      @NonNls String setter = parameterChunk != null ? parameterChunk.setter : null;
      if (setter == null) {
        setter = GenerateMembersUtil.suggestSetterName(paramName, paramType, myProject);
      }
      if (RefactoringUtil.isPlusPlusOrMinusMinus(paramUsage.getParent())) {
        usages.add(
            new ReplaceParameterIncrementDecrement(paramUsage, fixedParamName, setter, getter));
        if (parameterChunk == null || parameterChunk.setter == null) {
          paramsNeedingSetters.add(replacedParameter);
        }
      } else if (RefactoringUtil.isAssignmentLHS(paramUsage)) {
        usages.add(
            new ReplaceParameterAssignmentWithCall(paramUsage, fixedParamName, setter, getter));
        if (parameterChunk == null || parameterChunk.setter == null) {
          paramsNeedingSetters.add(replacedParameter);
        }
      } else {
        usages.add(new ReplaceParameterReferenceWithCall(paramUsage, fixedParamName, getter));
      }
    }
  }
 protected String getProjectName() {
   return StringUtil.decapitalize(StringUtil.trimStart(getName(), "test"));
 }
  @Override
  public void invoke(final @NotNull Project project, Editor editor, @NotNull PsiElement element)
      throws IncorrectOperationException {
    final PyFunction srcFunction = PsiTreeUtil.getParentOfType(element, PyFunction.class);
    final PyClass srcClass = PsiTreeUtil.getParentOfType(element, PyClass.class);

    if (srcClass == null && srcFunction == null) return;

    final PsiDirectory dir = element.getContainingFile().getContainingDirectory();
    final CreateTestDialog d = new CreateTestDialog(project);
    if (srcClass != null) {
      d.setClassName("Test" + StringUtil.capitalize(srcClass.getName()));
      d.setFileName("test_" + StringUtil.decapitalize(srcClass.getName()) + ".py");

      if (dir != null) d.setTargetDir(dir.getVirtualFile().getPath());

      if (srcFunction != null) {
        d.methodsSize(1);
        d.addMethod("test_" + srcFunction.getName(), 0);
      } else {
        final List<PyFunction> methods = Lists.newArrayList();
        srcClass.visitMethods(
            new Processor<PyFunction>() {
              @Override
              public boolean process(PyFunction pyFunction) {
                if (pyFunction.getName() != null && !pyFunction.getName().startsWith("__"))
                  methods.add(pyFunction);
                return true;
              }
            },
            false);

        d.methodsSize(methods.size());
        int i = 0;
        for (PyFunction f : methods) {
          d.addMethod("test_" + f.getName(), i);
          ++i;
        }
      }
    } else {
      d.setClassName("Test" + StringUtil.capitalize(srcFunction.getName()));
      d.setFileName("test_" + StringUtil.decapitalize(srcFunction.getName()) + ".py");
      if (dir != null) d.setTargetDir(dir.getVirtualFile().getPath());

      d.methodsSize(1);
      d.addMethod("test_" + srcFunction.getName(), 0);
    }

    d.show();
    if (!d.isOK()) return;
    CommandProcessor.getInstance()
        .executeCommand(
            project,
            new Runnable() {
              @Override
              public void run() {
                PsiFile e = PyTestCreator.generateTest(project, d);
                final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
                documentManager.commitAllDocuments();
              }
            },
            CodeInsightBundle.message("intention.create.test"),
            this);
  }