コード例 #1
0
  @NotNull
  @Override
  public Collection<PsiReference> findReferences(PsiElement element) {
    assert element instanceof GrField;

    ArrayList<PsiReference> refs = new ArrayList<>();

    GrField field = (GrField) element;
    GlobalSearchScope projectScope = GlobalSearchScope.projectScope(element.getProject());
    PsiMethod setter = field.getSetter();
    if (setter != null) {
      refs.addAll(
          RenameAliasedUsagesUtil.filterAliasedRefs(
              MethodReferencesSearch.search(setter, projectScope, true).findAll(), setter));
    }
    GrAccessorMethod[] getters = field.getGetters();
    for (GrAccessorMethod getter : getters) {
      refs.addAll(
          RenameAliasedUsagesUtil.filterAliasedRefs(
              MethodReferencesSearch.search(getter, projectScope, true).findAll(), getter));
    }
    refs.addAll(
        RenameAliasedUsagesUtil.filterAliasedRefs(
            ReferencesSearch.search(field, projectScope, false).findAll(), field));
    return refs;
  }
コード例 #2
0
  @NotNull
  @Override
  public Collection<PsiReference> findReferences(final PsiElement element) {
    if (element instanceof GrField) {
      ArrayList<PsiReference> refs = new ArrayList<PsiReference>();

      GrField field = (GrField) element;
      PsiMethod setter = GroovyPropertyUtils.findSetterForField(field);
      GlobalSearchScope projectScope = GlobalSearchScope.projectScope(element.getProject());
      if (setter != null && setter instanceof GrAccessorMethod) {
        refs.addAll(
            RenameAliasedUsagesUtil.filterAliasedRefs(
                MethodReferencesSearch.search(setter, projectScope, true).findAll(), setter));
      }
      GrAccessorMethod[] getters = field.getGetters();
      for (GrAccessorMethod getter : getters) {
        refs.addAll(
            RenameAliasedUsagesUtil.filterAliasedRefs(
                MethodReferencesSearch.search(getter, projectScope, true).findAll(), getter));
      }
      refs.addAll(
          RenameAliasedUsagesUtil.filterAliasedRefs(
              ReferencesSearch.search(field, projectScope, true).findAll(), field));
      return refs;
    }
    return super.findReferences(element);
  }
    public boolean satisfiedBy(PsiElement element) {
      if (element.getLanguage() != GroovyFileType.GROOVY_LANGUAGE) return false;
      final PsiReference ref = element.getReference();
      GrField field;
      if (ref != null) {
        PsiElement resolved = ref.resolve();
        if (resolved instanceof GrAccessorMethod) {
          resolved = ((GrAccessorMethod) resolved).getProperty();
        }
        if (!(resolved instanceof GrField)) return false;
        field = (GrField) resolved;
      } else {
        final PsiElement parent = element.getParent();
        if (!(parent instanceof GrField)) return false;
        field = (GrField) parent;
        if (field.getNameIdentifierGroovy() != element) return false;
      }

      final PsiElement varDeclaration = field.getParent();
      if (!(varDeclaration instanceof GrVariableDeclaration)) return false;
      if (((GrVariableDeclaration) varDeclaration).getVariables().length != 1) return false;

      final GrExpression expression = field.getInitializerGroovy();
      return expression instanceof GrClosableBlock;
    }
コード例 #4
0
  public static void collectMethodsFromBody(
      @NotNull GrTypeDefinition definition, List<PsiMethod> result) {
    for (GrMethod method : definition.getCodeMethods()) {
      addExpandingReflectedMethods(result, method);
    }

    for (GrField field : definition.getFields()) {
      if (!field.isProperty()) continue;
      ContainerUtil.addAll(result, field.getGetters());
      ContainerUtil.addIfNotNull(result, field.getSetter());
    }
  }
コード例 #5
0
    private void processPropertyFromField(
        @NotNull GrField field, @NotNull GroovyResolveResult resolveResult) {
      if (field.getGetters().length != 0
          || field.getSetter() != null
          || !myPropertyNames.add(field.getName())
          || myIsMap) return;

      for (LookupElement element :
          GroovyCompletionUtil.createLookupElements(resolveResult, false, myMatcher, null)) {
        myConsumer.consume(
            ((LookupElementBuilder) element).withIcon(JetgroovyIcons.Groovy.Property));
      }
    }
コード例 #6
0
  @Override
  public void processDynamicElements(
      @NotNull PsiType qualifierType,
      PsiClass aClass,
      PsiScopeProcessor processor,
      GroovyPsiElement place,
      ResolveState state) {
    ClassHint classHint = processor.getHint(ClassHint.KEY);
    if (classHint != null && !classHint.shouldProcess(ClassHint.ResolveKind.PROPERTY)) return;

    String nameHint = ResolveUtil.getNameHint(processor);

    Map<String, PsiClass> supers = TypesUtil.getSuperClassesWithCache(aClass);

    PsiElement grCall = place.getParent();
    if (grCall instanceof GrMethodCall) {
      PsiElement grClosure = grCall.getParent();
      if (grClosure instanceof GrClosableBlock) {
        PsiElement contentField = grClosure.getParent();
        if (contentField instanceof GrField) {
          GrField f = (GrField) contentField;
          if ("content".equals(f.getName())
              && f.hasModifierProperty(PsiModifier.STATIC)
              && f.getContainingClass() == aClass) {
            Map<String, PsiField> elements = GebUtil.getContentElements(aClass);
            for (PsiField field : elements.values()) {
              if (field.getNavigationElement() == place) {
                return; // Don't resolve variable definition.
              }
            }
          }
        }
      }
    }

    for (PsiClass psiClass : supers.values()) {
      Map<String, PsiField> contentFields = GebUtil.getContentElements(psiClass);

      if (nameHint == null) {
        for (Map.Entry<String, PsiField> entry : contentFields.entrySet()) {
          if (!processor.execute(entry.getValue(), state)) return;
        }
      } else {
        PsiField field = contentFields.get(nameHint);
        if (field != null) {
          processor.execute(field, state);
          return;
        }
      }
    }
  }
コード例 #7
0
    public void putNewElements(@NotNull GrField field) {
      myNewElements.put(field.getName(), field);

      if (field.isProperty()) {
        for (GrAccessorMethod newGetter : field.getGetters()) {
          myNewElements.put(newGetter.getName(), newGetter);
        }

        final GrAccessorMethod newSetter = field.getSetter();
        if (newSetter != null) {
          myNewElements.put(newSetter.getName(), newSetter);
        }
      }
    }
コード例 #8
0
    public NameProvider(GrField field, String newName) {
      myNameMap.put(field, newName);

      if (field.isProperty()) {
        for (GrAccessorMethod getter : field.getGetters()) {
          myNameMap.put(
              getter, RenamePropertyUtil.getGetterNameByOldName(newName, getter.getName()));
        }
        final GrAccessorMethod setter = field.getSetter();
        if (setter != null) {
          myNameMap.put(setter, GroovyPropertyUtils.getSetterName(newName));
        }
      }
    }
コード例 #9
0
 private void doMoveField(PsiSubstitutor substitutor, GrMemberInfo info) {
   GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(myProject);
   GrField field = (GrField) info.getMember();
   field.normalizeDeclaration();
   replaceMovedMemberTypeParameters(
       field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
   // fixReferencesToStatic(field, movedMembers);
   if (myTargetSuperClass.isInterface()) {
     PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true);
   }
   final PsiMember movedElement = (PsiMember) myTargetSuperClass.add(field);
   myMembersAfterMove.add(movedElement);
   deleteMemberWithDocComment(field);
 }
コード例 #10
0
  /**
   * The key method of contributor. It collects all delegating methods of clazz
   *
   * @param clazz class to process
   * @param processedWithoutDeprecated already visited classes which deprecated methods were not
   *     processsed
   * @param processedAll already visited classes which all methods were processed
   * @param collector result collection
   */
  private static void process(
      PsiClass clazz,
      PsiSubstitutor superClassSubstitutor,
      boolean shouldProcessDeprecated,
      Set<PsiClass> processedWithoutDeprecated,
      Set<PsiClass> processedAll,
      List<PsiMethod> collector,
      GrTypeDefinition classToDelegateTo,
      boolean keepParameterAnnotations) {
    final List<PsiMethod> result = new ArrayList<PsiMethod>();

    // process super methods before delegated methods
    for (PsiClassType superType : getSuperTypes(clazz)) {
      processClassInner(
          superType,
          superClassSubstitutor,
          shouldProcessDeprecated,
          result,
          classToDelegateTo,
          processedWithoutDeprecated,
          processedAll,
          keepParameterAnnotations);
    }

    if (clazz instanceof GrTypeDefinition) {
      // search for @Delegate fields and collect methods from them
      for (GrField field : ((GrTypeDefinition) clazz).getFields()) {
        final PsiAnnotation delegate =
            PsiImplUtil.getAnnotation(field, GroovyCommonClassNames.GROOVY_LANG_DELEGATE);
        if (delegate == null) continue;

        final PsiType type = field.getDeclaredType();
        if (!(type instanceof PsiClassType)) continue;

        processClassInner(
            (PsiClassType) type,
            superClassSubstitutor,
            shouldDelegateDeprecated(delegate),
            result,
            classToDelegateTo,
            processedWithoutDeprecated,
            processedAll,
            shouldKeepParameterAnnotations(delegate));
      }
    }

    collector.addAll(result);
  }
コード例 #11
0
  @Override
  public void findExistingNameConflicts(
      PsiElement element, String newName, MultiMap<PsiElement, String> conflicts) {
    super.findExistingNameConflicts(element, newName, conflicts);

    GrField field = (GrField) element;
    final PsiClass containingClass = field.getContainingClass();
    if (containingClass == null) return;

    final PsiMethod getter = GroovyPropertyUtils.findGetterForField(field);
    if (getter instanceof GrAccessorMethod) {
      final PsiMethod newGetter =
          PropertyUtil.findPropertyGetter(
              containingClass, newName, field.hasModifierProperty(PsiModifier.STATIC), true);
      if (newGetter != null && !(newGetter instanceof GrAccessorMethod)) {
        conflicts.putValue(
            newGetter,
            GroovyRefactoringBundle.message(
                "implicit.getter.will.by.overriden.by.method",
                field.getName(),
                newGetter.getName()));
      }
    }
    final PsiMethod setter = GroovyPropertyUtils.findSetterForField(field);
    if (setter instanceof GrAccessorMethod) {
      final PsiMethod newSetter =
          PropertyUtil.findPropertySetter(
              containingClass, newName, field.hasModifierProperty(PsiModifier.STATIC), true);
      if (newSetter != null && !(newSetter instanceof GrAccessorMethod)) {
        conflicts.putValue(
            newSetter,
            GroovyRefactoringBundle.message(
                "implicit.setter.will.by.overriden.by.method",
                field.getName(),
                newSetter.getName()));
      }
    }
  }
コード例 #12
0
  @Override
  public void renameElement(
      final PsiElement psiElement,
      final String newName,
      final UsageInfo[] usages,
      final RefactoringElementListener listener)
      throws IncorrectOperationException {

    final GrField field = (GrField) psiElement;
    final PsiMethod getter = GroovyPropertyUtils.findGetterForField(field);
    final PsiMethod setter = GroovyPropertyUtils.findSetterForField(field);
    final String newGetterName =
        (getter != null && getter.getName().startsWith("is") ? "is" : "get")
            + StringUtil.capitalize(newName);
    final String newSetterName = "set" + StringUtil.capitalize(newName);

    final PsiManager manager = field.getManager();

    List<PsiReference> getterRefs = new ArrayList<PsiReference>();
    List<PsiReference> setterRefs = new ArrayList<PsiReference>();
    List<PsiReference> fieldRefs = new ArrayList<PsiReference>();

    for (UsageInfo usage : usages) {
      final PsiElement element = usage.getElement();
      if (element == null) continue;

      PsiReference ref = element.findReferenceAt(usage.startOffset);
      if (ref == null) continue;

      PsiElement resolved = ref.resolve();
      if (manager.areElementsEquivalent(resolved, getter)) {
        if (isPropertyAccess(element)) {
          fieldRefs.add(ref);
        } else {
          getterRefs.add(ref);
        }
      } else if (manager.areElementsEquivalent(resolved, setter)) {
        if (isPropertyAccess(element)) {
          fieldRefs.add(ref);
        } else {
          setterRefs.add(ref);
        }
      } else if (manager.areElementsEquivalent(resolved, field)) {
        fieldRefs.add(ref);
      } else {
        ref.handleElementRename(newName);
      }
    }

    field.setName(newName);

    final PsiMethod newGetter = GroovyPropertyUtils.findGetterForField(field);
    doRename(newGetterName, manager, getterRefs, newGetter);

    final PsiMethod newSetter = GroovyPropertyUtils.findSetterForField(field);
    doRename(newSetterName, manager, setterRefs, newSetter);

    doRename(newName, manager, fieldRefs, field);

    listener.elementRenamed(field);
  }
コード例 #13
0
  @Override
  public void renameElement(
      final PsiElement psiElement,
      String newName,
      final UsageInfo[] usages,
      @Nullable RefactoringElementListener listener)
      throws IncorrectOperationException {
    final GrField field = (GrField) psiElement;
    String fieldName = field.getName();

    NameProvider nameProvider = new NameProvider(field, newName);

    MultiMap<PsiNamedElement, UsageInfo> propertyUsages = MultiMap.createLinked();
    MultiMap<PsiNamedElement, UsageInfo> simpleUsages = MultiMap.createLinked();

    List<PsiReference> unknownUsages = new ArrayList<>();

    for (UsageInfo usage : usages) {
      final PsiReference ref = usage.getReference();
      if (ref instanceof GrReferenceExpression) {
        final GroovyResolveResult resolveResult = ((GrReferenceExpression) ref).advancedResolve();
        final PsiElement element = resolveResult.getElement();
        if (resolveResult.isInvokedOnProperty()) {
          propertyUsages.putValue((PsiNamedElement) element, usage);
        } else {
          simpleUsages.putValue((PsiNamedElement) element, usage);
        }
      } else if (ref != null) {
        unknownUsages.add(ref);
      }
    }

    for (PsiReference ref : unknownUsages) {
      handleElementRename(newName, ref, fieldName);
    }

    field.setName(newName);

    nameProvider.putNewElements(field);

    PsiManager manager = field.getManager();
    for (PsiNamedElement element : simpleUsages.keySet()) {
      for (UsageInfo info : simpleUsages.get(element)) {
        final String name = nameProvider.getNewName(element);
        rename(
            nameProvider.getNewElement(element),
            info,
            name == null ? newName : name,
            name != null,
            manager);
      }
    }
    for (PsiNamedElement element : propertyUsages.keySet()) {
      for (UsageInfo info : propertyUsages.get(element)) {
        rename(element, info, newName, true, manager);
      }
    }
    if (listener != null) {
      listener.elementRenamed(field);
    }
  }
コード例 #14
0
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    final GrField field;
    if (element.getParent() instanceof GrField) {
      field = (GrField) element.getParent();
    } else {
      final PsiReference ref = element.getReference();
      LOG.assertTrue(ref != null);
      PsiElement resolved = ref.resolve();
      if (resolved instanceof GrAccessorMethod) {
        resolved = ((GrAccessorMethod) resolved).getProperty();
      }
      LOG.assertTrue(resolved instanceof GrField);
      field = (GrField) resolved;
    }

    final HashSet<PsiReference> usages = new HashSet<PsiReference>();
    usages.addAll(ReferencesSearch.search(field).findAll());
    final GrAccessorMethod[] getters = field.getGetters();
    for (GrAccessorMethod getter : getters) {
      usages.addAll(MethodReferencesSearch.search(getter).findAll());
    }
    final GrAccessorMethod setter = field.getSetter();
    if (setter != null) {
      usages.addAll(MethodReferencesSearch.search(setter).findAll());
    }

    final String fieldName = field.getName();
    LOG.assertTrue(fieldName != null);
    final Collection<PsiElement> fieldUsages = new HashSet<PsiElement>();
    MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    for (PsiReference usage : usages) {
      final PsiElement psiElement = usage.getElement();
      if (PsiUtil.isMethodUsage(psiElement)) continue;
      if (!GroovyFileType.GROOVY_LANGUAGE.equals(psiElement.getLanguage())) {
        conflicts.putValue(
            psiElement,
            GroovyIntentionsBundle.message("closure.is.accessed.outside.of.groovy", fieldName));
      } else {
        if (psiElement instanceof GrReferenceExpression) {
          fieldUsages.add(psiElement);
          if (PsiUtil.isAccessedForWriting((GrExpression) psiElement)) {
            conflicts.putValue(
                psiElement,
                GroovyIntentionsBundle.message("write.access.to.closure.variable", fieldName));
          }
        } else if (psiElement instanceof GrArgumentLabel) {
          conflicts.putValue(
              psiElement,
              GroovyIntentionsBundle.message("field.is.used.in.argument.label", fieldName));
        }
      }
    }
    final PsiClass containingClass = field.getContainingClass();
    final GrExpression initializer = field.getInitializerGroovy();
    LOG.assertTrue(initializer != null);
    final PsiType type = initializer.getType();
    LOG.assertTrue(type instanceof GrClosureType);
    final GrSignature signature = ((GrClosureType) type).getSignature();
    final List<MethodSignature> signatures =
        GrClosureSignatureUtil.generateAllMethodSignaturesBySignature(fieldName, signature);
    for (MethodSignature s : signatures) {
      final PsiMethod method = MethodSignatureUtil.findMethodBySignature(containingClass, s, true);
      if (method != null) {
        conflicts.putValue(
            method,
            GroovyIntentionsBundle.message(
                "method.with.signature.already.exists",
                GroovyPresentationUtil.getSignaturePresentation(s)));
      }
    }
    if (conflicts.size() > 0) {
      final ConflictsDialog conflictsDialog =
          new ConflictsDialog(
              project,
              conflicts,
              new Runnable() {
                @Override
                public void run() {
                  execute(field, fieldUsages);
                }
              });
      conflictsDialog.show();
      if (conflictsDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return;
    }
    execute(field, fieldUsages);
  }
コード例 #15
0
  private static void execute(final GrField field, final Collection<PsiElement> fieldUsages) {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(field.getProject());

    final StringBuilder builder = new StringBuilder(field.getTextLength());
    final GrClosableBlock block = (GrClosableBlock) field.getInitializerGroovy();

    final GrModifierList modifierList = field.getModifierList();
    if (modifierList.getModifiers().length > 0 || modifierList.getAnnotations().length > 0) {
      builder.append(modifierList.getText());
    } else {
      builder.append(GrModifier.DEF);
    }
    builder.append(' ').append(field.getName());

    builder.append('(');
    if (block.hasParametersSection()) {
      builder.append(block.getParameterList().getText());
    } else {
      builder.append("def it = null");
    }
    builder.append(") {");

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                block.getParameterList().delete();
                block.getLBrace().delete();
                final PsiElement psiElement =
                    PsiUtil.skipWhitespacesAndComments(block.getFirstChild(), true);
                if (psiElement != null && "->".equals(psiElement.getText())) {
                  psiElement.delete();
                }
                builder.append(block.getText());
                final GrMethod method =
                    GroovyPsiElementFactory.getInstance(field.getProject())
                        .createMethodFromText(builder.toString());
                field.getParent().replace(method);
                for (PsiElement usage : fieldUsages) {
                  if (usage instanceof GrReferenceExpression) {
                    final PsiElement parent = usage.getParent();
                    StringBuilder newRefText = new StringBuilder();
                    if (parent instanceof GrReferenceExpression
                        && usage == ((GrReferenceExpression) parent).getQualifier()
                        && "call".equals(((GrReferenceExpression) parent).getReferenceName())) {
                      newRefText.append(usage.getText());
                      usage = parent;
                    } else {
                      PsiElement qualifier = ((GrReferenceExpression) usage).getQualifier();
                      if (qualifier == null) {
                        if (parent instanceof GrReferenceExpression
                            && ((GrReferenceExpression) parent).getQualifier() != null
                            && usage != ((GrReferenceExpression) parent).getQualifier()) {
                          qualifier = ((GrReferenceExpression) parent).getQualifier();
                          usage = parent;
                        }
                      }

                      if (qualifier != null) {
                        newRefText.append(qualifier.getText()).append('.');
                        ((GrReferenceExpression) usage).setQualifier(null);
                      } else {
                        newRefText.append("this.");
                      }
                      newRefText.append('&').append(usage.getText());
                    }
                    usage.replace(factory.createReferenceExpressionFromText(newRefText.toString()));
                  }
                }
              }
            });
  }