@Override
 public void visitReferenceExpression(GrReferenceExpression expression) {
   super.visitReferenceExpression(expression);
   if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isSuperReference(expression)) {
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         expression.putCopyableUserData(SUPER_REF, Boolean.TRUE);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   } else if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isThisReference(expression)) {
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         expression.putCopyableUserData(THIS_REF, Boolean.TRUE);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   }
 }
예제 #2
0
 private void getVariantsFromQualifier(@NotNull GrExpression qualifier) {
   Project project = qualifier.getProject();
   PsiType qualifierType = qualifier.getType();
   final ResolveState state = ResolveState.initial();
   if (qualifierType == null || qualifierType == PsiType.VOID) {
     if (qualifier instanceof GrReferenceExpression) {
       PsiElement resolved = ((GrReferenceExpression) qualifier).resolve();
       if (resolved instanceof PsiPackage || resolved instanceof PsiVariable) {
         resolved.processDeclarations(myProcessor, state, null, myRefExpr);
         return;
       }
     }
     getVariantsFromQualifierType(TypesUtil.getJavaLangObject(qualifier), project);
   } else if (qualifierType instanceof PsiIntersectionType) {
     for (PsiType conjunct : ((PsiIntersectionType) qualifierType).getConjuncts()) {
       getVariantsFromQualifierType(conjunct, project);
     }
   } else if (qualifierType instanceof GrTraitType) {
     GrTypeDefinition definition = ((GrTraitType) qualifierType).getMockTypeDefinition();
     if (definition != null) {
       PsiClassType classType = JavaPsiFacade.getElementFactory(project).createType(definition);
       getVariantsFromQualifierType(classType, project);
     } else {
       getVariantsFromQualifierType(((GrTraitType) qualifierType).getExprType(), project);
       for (PsiClassType traitType : ((GrTraitType) qualifierType).getTraitTypes()) {
         getVariantsFromQualifierType(traitType, project);
       }
     }
   } else {
     getVariantsFromQualifierType(qualifierType, project);
     if (qualifier instanceof GrReferenceExpression
         && !PsiUtil.isSuperReference(qualifier)
         && !PsiUtil.isInstanceThisRef(qualifier)) {
       PsiElement resolved = ((GrReferenceExpression) qualifier).resolve();
       if (resolved instanceof PsiClass) { // //omitted .class
         GlobalSearchScope scope = myRefExpr.getResolveScope();
         PsiClass javaLangClass = PsiUtil.getJavaLangClass(resolved, scope);
         if (javaLangClass != null) {
           PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
           PsiTypeParameter[] typeParameters = javaLangClass.getTypeParameters();
           if (typeParameters.length == 1) {
             substitutor = substitutor.put(typeParameters[0], qualifierType);
           }
           PsiType javaLangClassType =
               JavaPsiFacade.getElementFactory(myRefExpr.getProject())
                   .createType(javaLangClass, substitutor);
           ResolveUtil.processAllDeclarations(javaLangClassType, myProcessor, state, myRefExpr);
         }
       }
     }
   }
 }
 private static void deleteOverrideAnnotationIfFound(PsiMethod oMethod) {
   final PsiAnnotation annotation =
       AnnotationUtil.findAnnotation(oMethod, CommonClassNames.JAVA_LANG_OVERRIDE);
   if (annotation != null) {
     PsiElement prev = annotation.getPrevSibling();
     PsiElement next = annotation.getNextSibling();
     if ((prev == null || org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isLineFeed(prev))
         && org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isLineFeed(next)) {
       next.delete();
     }
     annotation.delete();
   }
 }
 @Override
 public void visitReferenceExpression(GrReferenceExpression expression) {
   super.visitReferenceExpression(expression);
   if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isSuperReference(
       expression.getQualifierExpression())) {
     PsiElement resolved = expression.resolve();
     if (resolved == null
         || resolved instanceof PsiMethod && shouldFixSuper((PsiMethod) resolved)) {
       mySupersToDelete.add(expression.getQualifierExpression());
     }
   } else if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isSuperReference(expression)) {
     mySupersToChangeToThis.add(expression);
   }
 }
  @NotNull
  private GroovyResolveResult[] doPolyResolve(boolean incompleteCode, boolean genericsMatter) {
    String name = getReferenceName();
    if (name == null) return GroovyResolveResult.EMPTY_ARRAY;

    if (incompleteCode) {
      ResolverProcessor processor = CompletionProcessor.createRefSameNameProcessor(this, name);
      new GrReferenceResolveRunner(this).resolveImpl(processor);
      GroovyResolveResult[] propertyCandidates = processor.getCandidates();
      if (propertyCandidates.length > 0 && !PsiUtil.isSingleBindingVariant(propertyCandidates))
        return propertyCandidates;
    }

    try {
      ResolveProfiler.start();
      switch (getKind()) {
        case METHOD_OR_PROPERTY:
          return resolveMethodOrProperty(false, null, genericsMatter);
        case TYPE_OR_PROPERTY:
          return resolveTypeOrProperty();
        case METHOD_OR_PROPERTY_OR_TYPE:
          GroovyResolveResult[] results = resolveMethodOrProperty(false, null, genericsMatter);
          if (results.length == 0) results = resolveTypeOrProperty();
          return results;
        default:
          return GroovyResolveResult.EMPTY_ARRAY;
      }
    } finally {
      final long time = ResolveProfiler.finish();
      ResolveProfiler.write("ref", this, time);
    }
  }
    @Override
    public void visitMethodCallExpression(GrMethodCallExpression grMethodCallExpression) {
      super.visitMethodCallExpression(grMethodCallExpression);
      final GrArgumentList args = grMethodCallExpression.getArgumentList();
      if (args.getExpressionArguments().length != 1) {
        return;
      }
      if (PsiImplUtil.hasNamedArguments(args)) {
        return;
      }
      final GrExpression methodExpression = grMethodCallExpression.getInvokedExpression();
      if (!(methodExpression instanceof GrReferenceExpression)) {
        return;
      }
      final GrReferenceExpression referenceExpression = (GrReferenceExpression) methodExpression;
      final String name = referenceExpression.getReferenceName();
      if (!"get".equals(name)) {
        return;
      }
      final GrExpression qualifier = referenceExpression.getQualifierExpression();

      if (qualifier == null || PsiUtil.isThisOrSuperRef(qualifier)) {
        return;
      }

      if (referenceExpression.getDotTokenType() == GroovyTokenTypes.mOPTIONAL_DOT) return;
      final PsiType type = qualifier.getType();
      if (!InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_MAP)) {
        return;
      }
      registerMethodCallError(grMethodCallExpression);
    }
  static PsiElement[] getOccurrences(GrIntroduceParameterSettings settings) {
    final GrParametersOwner scope = settings.getToReplaceIn();

    final GrExpression expression = settings.getExpression();
    if (expression != null) {
      final PsiElement expr = PsiUtil.skipParentheses(expression, false);
      if (expr == null) return PsiElement.EMPTY_ARRAY;

      final PsiElement[] occurrences = GroovyRefactoringUtil.getExpressionOccurrences(expr, scope);
      if (occurrences == null || occurrences.length == 0) {
        throw new GrRefactoringError(GroovyRefactoringBundle.message("no.occurrences.found"));
      }
      return occurrences;
    } else {
      final GrVariable var = settings.getVar();
      LOG.assertTrue(var != null);
      final List<PsiElement> list = Collections.synchronizedList(new ArrayList<PsiElement>());
      ReferencesSearch.search(var, new LocalSearchScope(scope))
          .forEach(
              new Processor<PsiReference>() {
                @Override
                public boolean process(PsiReference psiReference) {
                  final PsiElement element = psiReference.getElement();
                  if (element != null) {
                    list.add(element);
                  }
                  return true;
                }
              });
      return list.toArray(new PsiElement[list.size()]);
    }
  }
예제 #8
0
 @Override
 public void visitReferenceExpression(@NotNull GrReferenceExpression referenceExpression) {
   super.visitReferenceExpression(referenceExpression);
   if (PsiUtil.isSuperReference(referenceExpression)) {
     myContainsSupers = true;
   }
 }
  public void visitReferenceExpression(GrReferenceExpression refExpr) {
    super.visitReferenceExpression(refExpr);

    if (myPolicy.isReferenceAccepted(refExpr)) {
      String name = refExpr.getReferenceName();
      if (name == null) return;

      if (ControlFlowUtils.isIncOrDecOperand(refExpr)) {
        final InstructionImpl i = new ReadWriteVariableInstruction(name, refExpr, READ);
        addNodeAndCheckPending(i);
        addNode(new ReadWriteVariableInstruction(name, refExpr, WRITE));
      } else {
        final int type = PsiUtil.isLValue(refExpr) ? WRITE : READ;
        addNodeAndCheckPending(new ReadWriteVariableInstruction(name, refExpr, type));
        if (refExpr.getParent() instanceof GrArgumentList
            && refExpr.getParent().getParent() instanceof GrCall) {
          addNodeAndCheckPending(new ArgumentInstruction(refExpr));
        }
      }
    }

    if (refExpr.isQualified() && !(refExpr.getParent() instanceof GrCall)) {
      visitCall(refExpr);
    }
  }
예제 #10
0
 public boolean isProperty() {
   final GrFieldStub stub = getStub();
   if (stub != null) {
     return stub.isProperty();
   }
   return PsiUtil.isProperty(this);
 }
예제 #11
0
  @Nullable
  private static PsiType doNormalizeWildcardByPosition(
      final PsiType type, final GrExpression expression, final GrExpression toplevel) {
    if (type instanceof PsiCapturedWildcardType) {
      return doNormalizeWildcardByPosition(
          ((PsiCapturedWildcardType) type).getWildcard(), expression, toplevel);
    }

    if (type instanceof PsiWildcardType) {
      final PsiWildcardType wildcardType = (PsiWildcardType) type;

      if (PsiUtil.isAccessedForWriting(toplevel)) {
        return wildcardType.isSuper()
            ? wildcardType.getBound()
            : PsiCapturedWildcardType.create(wildcardType, expression);
      } else {
        if (wildcardType.isExtends()) {
          return wildcardType.getBound();
        } else {
          return PsiType.getJavaLangObject(expression.getManager(), expression.getResolveScope());
        }
      }
    } else if (type instanceof PsiArrayType) {
      final PsiType componentType = ((PsiArrayType) type).getComponentType();
      final PsiType normalizedComponentType =
          doNormalizeWildcardByPosition(componentType, expression, toplevel);
      if (normalizedComponentType != componentType) {
        assert normalizedComponentType != null;
        return normalizedComponentType.createArrayType();
      }
    }

    return type;
  }
  @Override
  public boolean checkApplicability(
      @NotNull AnnotationHolder holder, @NotNull GrAnnotation annotation) {
    final String qname = annotation.getQualifiedName();
    if (!GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD.equals(qname)) return false;

    checkScriptField(holder, annotation);

    PsiElement annoParent = annotation.getParent();
    PsiElement ownerToUse =
        annoParent instanceof PsiModifierList ? annoParent.getParent() : annoParent;
    if (!(ownerToUse instanceof GrVariableDeclaration)
        || !PsiUtil.isLocalVariable(((GrVariableDeclaration) ownerToUse).getVariables()[0])) {
      return false;
    }

    if (!GrAnnotationImpl.isAnnotationApplicableTo(
        annotation, PsiAnnotation.TargetType.LOCAL_VARIABLE)) {
      GrCodeReferenceElement ref = annotation.getClassReference();
      String target = JavaErrorMessages.message("annotation.target.LOCAL_VARIABLE");
      String description =
          JavaErrorMessages.message("annotation.not.applicable", ref.getText(), target);
      holder.createErrorAnnotation(ref, description);
    }

    return true;
  }
  private static void qualify(PsiMember member, PsiElement renamed, String name) {
    if (!(renamed instanceof GrReferenceExpression)) return;

    final PsiClass clazz = member.getContainingClass();
    if (clazz == null) return;

    final GrReferenceExpression refExpr = (GrReferenceExpression) renamed;
    final PsiElement replaced;
    if (member.hasModifierProperty(GrModifier.STATIC)) {
      final GrReferenceExpression newRefExpr =
          GroovyPsiElementFactory.getInstance(member.getProject())
              .createReferenceExpressionFromText(clazz.getQualifiedName() + "." + name);
      replaced = refExpr.replace(newRefExpr);
    } else {
      final PsiClass containingClass = PsiTreeUtil.getParentOfType(renamed, PsiClass.class);
      if (member.getManager().areElementsEquivalent(containingClass, clazz)) {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText("this." + name);
        replaced = refExpr.replace(newRefExpr);
      } else {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText(clazz.getQualifiedName() + ".this." + name);
        replaced = refExpr.replace(newRefExpr);
      }
    }
    PsiUtil.shortenReferences((GroovyPsiElement) replaced);
  }
  private static void addDynamicAnnotation(
      HighlightInfo info, GrReferenceExpression referenceExpression, HighlightDisplayKey key) {
    final PsiFile containingFile = referenceExpression.getContainingFile();
    if (containingFile != null) {
      VirtualFile file = containingFile.getVirtualFile();
      if (file == null) return;
    } else {
      return;
    }

    if (isCall(referenceExpression)) {
      PsiType[] argumentTypes = PsiUtil.getArgumentTypes(referenceExpression, false);
      if (argumentTypes != null) {
        QuickFixAction.registerQuickFixAction(
            info,
            referenceExpression.getTextRange(),
            new DynamicMethodFix(referenceExpression, argumentTypes),
            key);
      }
    } else {
      QuickFixAction.registerQuickFixAction(
          info,
          referenceExpression.getTextRange(),
          new DynamicPropertyFix(referenceExpression),
          key);
    }
  }
 public static boolean isClassReference(GrReferenceExpression ref) {
   GrExpression qualifier = ref.getQualifier();
   return "class".equals(ref.getReferenceName())
       && qualifier instanceof GrReferenceExpression
       && ((GrReferenceExpression) qualifier).resolve() instanceof PsiClass
       && !PsiUtil.isThisReference(qualifier);
 }
예제 #16
0
  public static PsiElement findTailingSemicolon(@NotNull GrStatement statement) {
    final PsiElement nextNonSpace = PsiUtil.skipWhitespaces(statement.getNextSibling(), true);
    if (nextNonSpace != null && nextNonSpace.getNode().getElementType() == mSEMI) {
      return nextNonSpace;
    }

    return null;
  }
  private PsiElement findSuitableModifier() {
    final GrModifierList list = getModifierList();

    PsiElement modifier = PsiUtil.findModifierInList(list, GrModifier.DEF);
    if (modifier != null) return modifier;

    modifier = PsiUtil.findModifierInList(list, PsiModifier.FINAL);
    if (modifier != null) return modifier;

    for (PsiElement element : list.getModifiers()) {
      if (!(element instanceof GrAnnotation)) {
        return element;
      }
    }

    return null;
  }
  @Nullable
  private static HighlightInfo checkRefInner(GrReferenceExpression ref) {
    PsiElement refNameElement = ref.getReferenceNameElement();
    if (refNameElement == null) return null;

    boolean cannotBeDynamic = PsiUtil.isCompileStatic(ref) || isPropertyAccessInStaticMethod(ref);
    GroovyResolveResult resolveResult = getBestResolveResult(ref);

    if (resolveResult.getElement() != null) {
      if (!isInspectionEnabled(ref.getContainingFile(), ref.getProject())) return null;

      if (isStaticOk(resolveResult)) return null;
      String message = GroovyBundle.message("cannot.reference.non.static", ref.getReferenceName());
      return createAnnotationForRef(ref, cannotBeDynamic, message);
    }

    if (ResolveUtil.isKeyOfMap(ref) || isClassReference(ref)) {
      return null;
    }

    if (!cannotBeDynamic) {
      if (!isInspectionEnabled(ref.getContainingFile(), ref.getProject())) return null;
      GrUnresolvedAccessInspection inspection =
          getInstance(ref.getContainingFile(), ref.getProject());

      if (!inspection.myHighlightIfGroovyObjectOverridden && areGroovyObjectMethodsOverridden(ref))
        return null;
      if (!inspection.myHighlightIfMissingMethodsDeclared && areMissingMethodsDeclared(ref))
        return null;

      if (GroovySuppressableInspectionTool.isElementToolSuppressedIn(ref, SHORT_NAME)) return null;
    }

    if (cannotBeDynamic || shouldHighlightAsUnresolved(ref)) {
      HighlightInfo info =
          createAnnotationForRef(
              ref, cannotBeDynamic, GroovyBundle.message("cannot.resolve", ref.getReferenceName()));
      LOG.assertTrue(info != null);

      HighlightDisplayKey displayKey = HighlightDisplayKey.find(SHORT_NAME);
      if (ref.getParent() instanceof GrMethodCall) {
        registerStaticImportFix(ref, info, displayKey);
      } else {
        registerCreateClassByTypeFix(ref, info, displayKey);
        registerAddImportFixes(ref, info, displayKey);
      }

      registerReferenceFixes(ref, info, cannotBeDynamic, displayKey);
      UnresolvedReferenceQuickFixProvider.registerReferenceFixes(
          ref, new QuickFixActionRegistrarAdapter(info, displayKey));
      OrderEntryFix.registerFixes(new QuickFixActionRegistrarAdapter(info, displayKey), ref);
      return info;
    }

    return null;
  }
예제 #19
0
  @Nullable
  public static LookupElementBuilder createPropertyLookupElement(
      @NotNull PsiMethod accessor,
      @Nullable GroovyResolveResult resolveResult,
      @Nullable PrefixMatcher matcher) {
    String propName;
    PsiType propType;
    final boolean getter = GroovyPropertyUtils.isSimplePropertyGetter(accessor, null);
    if (getter) {
      propName = GroovyPropertyUtils.getPropertyNameByGetter(accessor);
    } else if (GroovyPropertyUtils.isSimplePropertySetter(accessor, null)) {
      propName = GroovyPropertyUtils.getPropertyNameBySetter(accessor);
    } else {
      return null;
    }
    assert propName != null;
    if (!PsiUtil.isValidReferenceName(propName)) {
      propName = "'" + propName + "'";
    }

    if (matcher != null && !matcher.prefixMatches(propName)) {
      return null;
    }

    if (getter) {
      propType = PsiUtil.getSmartReturnType(accessor);
    } else {
      propType = accessor.getParameterList().getParameters()[0].getType();
    }

    final PsiType substituted =
        resolveResult != null ? resolveResult.getSubstitutor().substitute(propType) : propType;

    LookupElementBuilder builder =
        LookupElementBuilder.create(
                generatePropertyResolveResult(propName, accessor, propType, resolveResult),
                propName)
            .withIcon(JetgroovyIcons.Groovy.Property);
    if (substituted != null) {
      builder = builder.withTypeText(substituted.getPresentableText());
    }
    return builder;
  }
    private static PsiType doFun(GrReferenceExpression refExpr) {
      if (ResolveUtil.isClassReference(refExpr)) {
        GrExpression qualifier = refExpr.getQualifier();
        LOG.assertTrue(qualifier != null);
        return TypesUtil.createJavaLangClassType(
            qualifier.getType(), refExpr.getProject(), refExpr.getResolveScope());
      }

      if (PsiUtil.isCompileStatic(refExpr)) {
        final GroovyResolveResult resolveResult = refExpr.advancedResolve();
        final PsiElement resolvedF = resolveResult.getElement();
        final PsiType type;
        if (resolvedF instanceof GrField) {
          type = ((GrField) resolvedF).getType();
        } else if (resolvedF instanceof GrAccessorMethod) {
          type = ((GrAccessorMethod) resolvedF).getProperty().getType();
        } else {
          type = null;
        }
        if (type != null) {
          return resolveResult.getSubstitutor().substitute(type);
        }
      }

      final PsiElement resolved = refExpr.resolve();
      final PsiType nominal = refExpr.getNominalType();

      Boolean reassigned = GrReassignedLocalVarsChecker.isReassignedVar(refExpr);
      if (reassigned != null && reassigned.booleanValue()) {
        return GrReassignedLocalVarsChecker.getReassignedVarType(refExpr, true);
      }

      final PsiType inferred = getInferredTypes(refExpr, resolved);
      if (inferred == null) {
        if (nominal == null) {
          // inside nested closure we could still try to infer from variable initializer. Not sound,
          // but makes sense
          if (resolved instanceof GrVariable) {
            LOG.assertTrue(resolved.isValid());
            return ((GrVariable) resolved).getTypeGroovy();
          }
        }

        return nominal;
      }

      if (nominal == null) return inferred;
      if (!TypeConversionUtil.isAssignable(TypeConversionUtil.erasure(nominal), inferred, false)) {
        if (resolved instanceof GrVariable
            && ((GrVariable) resolved).getTypeElementGroovy() != null) {
          return nominal;
        }
      }
      return inferred;
    }
  public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
    final GroovyResolveResult result = advancedResolve();
    if (result.isInvokedOnProperty()) {
      final String name = GroovyPropertyUtils.getPropertyNameByAccessorName(newElementName);
      if (name != null) {
        newElementName = name;
      }
    }
    if (PsiUtil.isThisOrSuperRef(this)) return this;

    return handleElementRenameSimple(newElementName);
  }
 @Override
 public GrTypeElement getTypeElementGroovyForVariable(GrVariable var) {
   if (isTuple()) {
     final PsiElement psiElement = PsiUtil.skipWhitespacesAndComments(var.getPrevSibling(), false);
     if (psiElement instanceof GrTypeElement) {
       return (GrTypeElement) psiElement;
     }
     return null;
   } else {
     return getTypeElementGroovy();
   }
 }
 private static void generateNameByExpr(
     GrExpression expr,
     Set<String> possibleNames,
     NameValidator validator,
     boolean forStaticVariable) {
   if (expr instanceof GrReferenceExpression
       && ((GrReferenceExpression) expr).getReferenceName() != null) {
     if (PsiUtil.isThisReference(expr)) {
       possibleNames.add(validator.validateName("thisInstance", true));
     }
     if (PsiUtil.isSuperReference(expr)) {
       possibleNames.add(validator.validateName("superInstance", true));
     }
     GrReferenceExpression refExpr = (GrReferenceExpression) expr;
     String name = refExpr.getReferenceName();
     if (name != null && name.toUpperCase().equals(name)) {
       possibleNames.add(validator.validateName(name.toLowerCase(), true));
     } else {
       generateCamelNames(possibleNames, validator, name);
     }
     if (expr.getText().equals(name)) {
       possibleNames.remove(name);
     }
   }
   if (expr instanceof GrMethodCallExpression) {
     generateNameByExpr(
         ((GrMethodCallExpression) expr).getInvokedExpression(),
         possibleNames,
         validator,
         forStaticVariable);
   }
   if (expr instanceof GrLiteral) {
     final Object value = ((GrLiteral) expr).getValue();
     if (value instanceof String) {
       generateNameByString(
           possibleNames, (String) value, validator, forStaticVariable, expr.getProject());
     }
   }
 }
    @Override
    public void visitReferenceExpression(GrReferenceExpression ref) {
      super.visitReferenceExpression(ref);
      final GrExpression qualifier = ref.getQualifier();
      if (!PsiUtil.isThisReference(qualifier)) return;

      final PsiElement resolved = ref.resolve();
      if (!(resolved instanceof PsiField)) return;
      final PsiMethod getter = GroovyPropertyUtils.findGetterForField((PsiField) resolved);
      if (getter != null) {
        result.add((PsiField) resolved);
      }
    }
예제 #25
0
    private static PsiReference[] createReferencesForNamedArgument(
        @NotNull PsiElement element,
        GrNamedArgument namedArgument,
        @NotNull ProcessingContext context) {
      String labelName = namedArgument.getLabelName();
      if (labelName == null) return PsiReference.EMPTY_ARRAY;

      if (!GroovyMethodInfo.getAllSupportedNamedArguments().contains(labelName)) {
        // Optimization: avoid unnecessary resolve.
        return PsiReference.EMPTY_ARRAY;
      }

      PsiElement call = PsiUtil.getCallByNamedParameter(namedArgument);

      if (!(call instanceof GrMethodCall)) return PsiReference.EMPTY_ARRAY;

      GrExpression invokedExpression = ((GrMethodCall) call).getInvokedExpression();
      if (!(invokedExpression instanceof GrReferenceExpression)) return PsiReference.EMPTY_ARRAY;

      for (GroovyResolveResult result :
          ((GrReferenceExpression) invokedExpression).multiResolve(false)) {
        PsiElement eMethod = result.getElement();
        if (!(eMethod instanceof PsiMethod)) continue;

        PsiMethod method = (PsiMethod) eMethod;

        for (GroovyMethodInfo info : GroovyMethodInfo.getInfos(method)) {
          Object referenceProvider = info.getNamedArgReferenceProvider(labelName);
          if (referenceProvider != null) {
            PsiReference[] refs;

            if (referenceProvider instanceof GroovyNamedArgumentReferenceProvider) {
              refs =
                  ((GroovyNamedArgumentReferenceProvider) referenceProvider)
                      .createRef(element, namedArgument, result, context);
            } else {
              refs =
                  ((PsiReferenceProvider) referenceProvider)
                      .getReferencesByElement(element, context);
            }

            if (refs.length > 0) {
              return refs;
            }
          }
        }
      }

      return PsiReference.EMPTY_ARRAY;
    }
  @Override
  public PsiType getNominalType() {
    if (getParent() instanceof GrThrowStatement) return super.getNominalType();

    LOG.assertTrue(
        PsiUtil.isLValue(this),
        "it is assumed that nominal type is invoked only for assignment lhs");

    GroovyResolveResult[] candidates = multiResolve(true);
    if (candidates.length == 1) {
      return extractLastParameterType(candidates[0]);
    }
    return null;
  }
예제 #27
0
  @Nullable
  public static PsiType inferExpectedTypeForDiamond(GrExpression diamondNew) {
    PsiElement skipped = PsiUtil.skipParentheses(diamondNew, true);
    assert skipped != null;
    PsiElement pparent = skipped.getParent();
    if (pparent instanceof GrAssignmentExpression
        && PsiTreeUtil.isAncestor(
            ((GrAssignmentExpression) pparent).getRValue(), diamondNew, false)) {
      GrExpression lValue = ((GrAssignmentExpression) pparent).getLValue();
      if (PsiUtil.mightBeLValue(lValue)) {
        return lValue.getNominalType();
      }
    } else if (pparent instanceof GrVariable
        && ((GrVariable) pparent).getInitializerGroovy() == diamondNew) {
      return ((GrVariable) pparent).getDeclaredType();
    } else if (pparent instanceof GrListOrMap) {
      PsiElement ppparent = PsiUtil.skipParentheses(pparent.getParent(), true);

      if (ppparent instanceof GrAssignmentExpression
          && PsiTreeUtil.isAncestor(
              ((GrAssignmentExpression) ppparent).getRValue(), pparent, false)) {

        PsiElement lValue =
            PsiUtil.skipParentheses(((GrAssignmentExpression) ppparent).getLValue(), false);
        if (lValue instanceof GrTupleExpression) {
          GrExpression[] initializers = ((GrListOrMap) pparent).getInitializers();
          int index = ArrayUtil.find(initializers, diamondNew);
          GrExpression[] expressions = ((GrTupleExpression) lValue).getExpressions();
          if (index < expressions.length) {
            return expressions[index].getNominalType();
          }
        }
      }
    }

    return null;
  }
  public PsiElement handleElementRenameSimple(String newElementName)
      throws IncorrectOperationException {
    if (!PsiUtil.isValidReferenceName(newElementName)) {
      final PsiElement old = getReferenceNameElement();
      if (old == null) throw new IncorrectOperationException("ref has no name element");

      PsiElement element =
          GroovyPsiElementFactory.getInstance(getProject())
              .createStringLiteralForReference(newElementName);
      old.replace(element);
      return this;
    }

    return super.handleElementRenameSimple(newElementName);
  }
  @Nullable
  public static PsiType checkReassignedVar(
      GrReferenceExpression refExpr, boolean honorCompileStatic) {
    if (honorCompileStatic && !PsiUtil.isCompileStatic(refExpr) || refExpr.getQualifier() != null) {
      return null;
    }

    final PsiElement resolved = refExpr.resolve();
    if (!GroovyRefactoringUtil.isLocalVariable(resolved)) {
      return null;
    }

    assert resolved != null;
    return getLeastUpperBoundByVar((GrVariable) resolved);
  }
예제 #30
0
  private void getVariantsImpl() {
    GrExpression qualifier = myRefExpr.getQualifierExpression();
    if (qualifier == null) {
      ResolveUtil.treeWalkUp(myRefExpr, myProcessor, true);

      for (PsiElement e = myRefExpr.getParent(); e != null; e = e.getParent()) {
        if (e instanceof GrClosableBlock) {
          ResolveState state = ResolveState.initial().put(ClassHint.RESOLVE_CONTEXT, e);
          for (ClosureMissingMethodContributor contributor :
              ClosureMissingMethodContributor.EP_NAME.getExtensions()) {
            contributor.processMembers((GrClosableBlock) e, myProcessor, myRefExpr, state);
          }
        }
      }

      GrExpression runtimeQualifier = PsiImplUtil.getRuntimeQualifier(myRefExpr);
      if (runtimeQualifier != null) {
        getVariantsFromQualifier(runtimeQualifier);
      }

      getBindings();
    } else {
      if (myRefExpr.getDotTokenType() != GroovyTokenTypes.mSPREAD_DOT) {
        getVariantsFromQualifier(qualifier);

        if (qualifier instanceof GrReferenceExpression
            && ("class".equals(((GrReferenceExpression) qualifier).getReferenceName())
                || PsiUtil.isThisReference(qualifier) && !PsiUtil.isInstanceThisRef(qualifier))) {
          processIfJavaLangClass(qualifier.getType());
        }
      } else {
        getVariantsFromQualifierForSpreadOperator(qualifier);
      }
    }
    ResolveUtil.processCategoryMembers(myRefExpr, myProcessor, ResolveState.initial());
  }