private void findUsagesForStaticMethod(PsiMethod method, List<FixableUsageInfo> usages) {
    final PsiManager psiManager = method.getManager();
    final Project project = psiManager.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope);
    final String fullyQualifiedName = getQualifiedName();
    for (PsiReference reference : calls) {
      final PsiElement referenceElement = reference.getElement();

      final PsiElement parent = referenceElement.getParent();
      if (parent instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression call = (PsiMethodCallExpression) parent;
        if (!isInMovedElement(call)) {
          usages.add(new RetargetStaticMethodCall(call, fullyQualifiedName));
        }
      } else if (parent instanceof PsiImportStaticStatement) {
        final PsiJavaCodeReferenceElement importReference =
            ((PsiImportStaticStatement) parent).getImportReference();
        if (importReference != null) {
          final PsiElement qualifier = importReference.getQualifier();
          if (qualifier instanceof PsiJavaCodeReferenceElement) {
            usages.add(
                new ReplaceClassReference(
                    (PsiJavaCodeReferenceElement) qualifier, fullyQualifiedName));
          }
        }
      }
    }
    usages.add(new RemoveMethod(method));
  }
Ejemplo n.º 2
0
  private static boolean isAnnotated(ASTNode element) {
    PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) element.getPsi();

    PsiElement qualifier = ref.getQualifier();
    if (qualifier instanceof PsiJavaCodeReferenceElement) {
      if (((PsiJavaCodeReferenceElement) qualifier).resolve() instanceof PsiPackage) {
        return false;
      }
      if (PsiTreeUtil.getChildOfType(qualifier, PsiAnnotation.class) != null) {
        return true;
      }
    }

    PsiModifierList modifierList = PsiImplUtil.findNeighbourModifierList(ref);
    if (modifierList != null) {
      for (PsiAnnotation annotation : modifierList.getAnnotations()) {
        if (PsiImplUtil.findApplicableTarget(annotation, PsiAnnotation.TargetType.TYPE_USE)
            != null) {
          return true;
        }
      }
    }

    return false;
  }
  protected PsiType processLocalVariableInitializer(PsiExpression initializer) {
    PsiType result = null;
    if (null != initializer && !(initializer instanceof PsiArrayInitializerExpression)) {
      if (!recursionBreaker.get().contains(initializer)) {
        recursionBreaker.get().add(initializer);
        try {
          result = initializer.getType();
        } finally {
          recursionBreaker.get().remove(initializer);
        }

        if (initializer instanceof PsiNewExpression) {
          final PsiJavaCodeReferenceElement reference =
              ((PsiNewExpression) initializer).getClassOrAnonymousClassReference();
          if (reference != null) {
            final PsiReferenceParameterList parameterList = reference.getParameterList();
            if (parameterList != null) {
              final PsiTypeElement[] elements = parameterList.getTypeParameterElements();
              if (elements.length == 1 && elements[0].getType() instanceof PsiDiamondType) {
                result = TypeConversionUtil.erasure(result);
              }
            }
          }
        }
      }
    }
    return result;
  }
 @Override
 public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
   super.visitReferenceElement(reference);
   if (referenceFound) {
     return;
   }
   final String text = reference.getText();
   if (text.indexOf((int) '.') >= 0 || !name.equals(text)) {
     return;
   }
   final PsiElement element = reference.resolve();
   if (!(element instanceof PsiClass) || element instanceof PsiTypeParameter) {
     return;
   }
   final PsiClass aClass = (PsiClass) element;
   final String testClassName = aClass.getName();
   final String testClassQualifiedName = aClass.getQualifiedName();
   if (testClassQualifiedName == null
       || testClassName == null
       || testClassQualifiedName.equals(fullyQualifiedName)
       || !testClassName.equals(name)) {
     return;
   }
   referenceFound = true;
 }
 @Override
 public void visitAnonymousClass(@NotNull PsiAnonymousClass anonymousClass) {
   if (anonymousClass instanceof PsiEnumConstantInitializer) {
     return;
   }
   final PsiMember containingMember =
       PsiTreeUtil.getParentOfType(anonymousClass, PsiMember.class);
   if (containingMember == null || containingMember.hasModifierProperty(PsiModifier.STATIC)) {
     return;
   }
   final PsiJavaCodeReferenceElement reference = anonymousClass.getBaseClassReference();
   if (reference.resolve() == null) {
     // don't warn on broken code
     return;
   }
   final PsiClass containingClass = PsiTreeUtil.getParentOfType(anonymousClass, PsiClass.class);
   if (containingClass == null) {
     return;
   }
   if (containingClass.getContainingClass() != null
       && !containingClass.hasModifierProperty(PsiModifier.STATIC)) {
     // strictly speaking can be named static inner class but not when part of the current
     // containing class
     return;
   }
   final InnerClassReferenceVisitor visitor = new InnerClassReferenceVisitor(anonymousClass);
   anonymousClass.accept(visitor);
   if (!visitor.canInnerClassBeStatic()) {
     return;
   }
   if (hasReferenceToLocalClass(anonymousClass)) {
     return;
   }
   registerClassError(anonymousClass);
 }
  @Override
  protected void invokeImpl(final PsiClass targetClass) {
    PsiNewExpression newExpression = getNewExpression();
    PsiJavaCodeReferenceElement ref = newExpression.getClassOrAnonymousClassReference();
    assert ref != null;
    String refName = ref.getReferenceName();
    LOG.assertTrue(refName != null);
    PsiElementFactory elementFactory =
        JavaPsiFacade.getInstance(newExpression.getProject()).getElementFactory();
    PsiClass created = elementFactory.createClass(refName);
    final PsiModifierList modifierList = created.getModifierList();
    LOG.assertTrue(modifierList != null);
    if (PsiTreeUtil.isAncestor(targetClass, newExpression, true)) {
      if (targetClass.isInterface()) {
        modifierList.setModifierProperty(PsiModifier.PACKAGE_LOCAL, true);
      } else {
        modifierList.setModifierProperty(PsiModifier.PRIVATE, true);
      }
    }

    if (!PsiTreeUtil.isAncestor(targetClass, newExpression, true)
        || PsiUtil.getEnclosingStaticElement(newExpression, targetClass) != null
        || isInThisOrSuperCall(newExpression)) {
      modifierList.setModifierProperty(PsiModifier.STATIC, true);
    }
    created = (PsiClass) targetClass.add(created);

    setupClassFromNewExpression(created, newExpression);

    setupGenericParameters(created, ref);
  }
  private static boolean shouldInsertParentheses(PsiClass psiClass, PsiElement position) {
    final PsiJavaCodeReferenceElement ref =
        PsiTreeUtil.getParentOfType(position, PsiJavaCodeReferenceElement.class);
    if (ref == null) {
      return false;
    }

    final PsiReferenceParameterList parameterList = ref.getParameterList();
    if (parameterList != null && parameterList.getTextLength() > 0) {
      return false;
    }

    final PsiElement prevElement = FilterPositionUtil.searchNonSpaceNonCommentBack(ref);
    if (prevElement != null && prevElement.getParent() instanceof PsiNewExpression) {

      Set<PsiType> expectedTypes = new HashSet<PsiType>();
      for (ExpectedTypeInfo info :
          ExpectedTypesProvider.getExpectedTypes((PsiExpression) prevElement.getParent(), true)) {
        expectedTypes.add(info.getType());
      }

      return JavaCompletionUtil.isDefinitelyExpected(psiClass, expectedTypes, position);
    }

    return false;
  }
Ejemplo n.º 8
0
  private void fixReferencesToStatic(PsiElement classMember) throws IncorrectOperationException {
    final StaticReferencesCollector collector = new StaticReferencesCollector();
    classMember.accept(collector);
    ArrayList<PsiJavaCodeReferenceElement> refs = collector.getReferences();
    ArrayList<PsiElement> members = collector.getReferees();
    ArrayList<PsiClass> classes = collector.getRefereeClasses();
    PsiElementFactory factory =
        JavaPsiFacade.getInstance(classMember.getProject()).getElementFactory();

    for (int i = 0; i < refs.size(); i++) {
      PsiJavaCodeReferenceElement ref = refs.get(i);
      PsiElement namedElement = members.get(i);
      PsiClass aClass = classes.get(i);

      if (namedElement instanceof PsiNamedElement) {
        PsiReferenceExpression newRef =
            (PsiReferenceExpression)
                factory.createExpressionFromText(
                    "a." + ((PsiNamedElement) namedElement).getName(), null);
        PsiExpression qualifierExpression = newRef.getQualifierExpression();
        assert qualifierExpression != null;
        qualifierExpression =
            (PsiExpression) qualifierExpression.replace(factory.createReferenceExpression(aClass));
        qualifierExpression.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified());
        ref.replace(newRef);
      }
    }
  }
 public InspectionGadgetsFix buildFix(Object... infos) {
   final PsiNewExpression expression = (PsiNewExpression) infos[0];
   final PsiJavaCodeReferenceElement classReference = expression.getClassReference();
   assert classReference != null;
   final String className = classReference.getText();
   return new CachedNumberConstructorCallFix(className);
 }
  private static Set<LookupElement> suggestQualifierItems(
      CompletionParameters parameters,
      PsiJavaCodeReferenceElement qualifier,
      ElementFilter filter) {
    String referenceName = qualifier.getReferenceName();
    if (referenceName == null) {
      return Collections.emptySet();
    }

    PrefixMatcher qMatcher = new CamelHumpMatcher(referenceName);
    Set<LookupElement> plainVariants =
        JavaSmartCompletionContributor.completeReference(
            qualifier, qualifier, filter, true, true, parameters, qMatcher);

    for (PsiClass aClass :
        PsiShortNamesCache.getInstance(qualifier.getProject())
            .getClassesByName(referenceName, qualifier.getResolveScope())) {
      plainVariants.add(JavaClassNameCompletionContributor.createClassLookupItem(aClass, true));
    }

    if (!plainVariants.isEmpty()) {
      return plainVariants;
    }

    final Set<LookupElement> allClasses = new LinkedHashSet<LookupElement>();
    PsiElement qualifierName = qualifier.getReferenceNameElement();
    if (qualifierName != null) {
      JavaClassNameCompletionContributor.addAllClasses(
          parameters.withPosition(qualifierName, qualifierName.getTextRange().getEndOffset()),
          true,
          qMatcher,
          new CollectConsumer<LookupElement>(allClasses));
    }
    return allClasses;
  }
 private static String buildAnnotationText(PsiAnnotation annotation) {
   final StringBuilder out = new StringBuilder("@");
   final PsiJavaCodeReferenceElement nameReferenceElement = annotation.getNameReferenceElement();
   assert nameReferenceElement != null;
   out.append(nameReferenceElement.getText());
   final PsiAnnotationParameterList parameterList = annotation.getParameterList();
   final PsiNameValuePair[] attributes = parameterList.getAttributes();
   if (attributes.length == 0) {
     return out.toString();
   }
   out.append('(');
   if (attributes.length == 1) {
     final PsiNameValuePair attribute = attributes[0];
     @NonNls final String name = attribute.getName();
     if (name != null && !PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(name)) {
       out.append(name).append('=');
     }
     buildAttributeValueText(attribute.getValue(), out);
   } else {
     for (int i = 0; i < attributes.length; i++) {
       final PsiNameValuePair attribute = attributes[i];
       if (i > 0) {
         out.append(',');
       }
       out.append(attribute.getName()).append('=');
       buildAttributeValueText(attribute.getValue(), out);
     }
   }
   out.append(')');
   return out.toString();
 }
  @Nullable
  private ProblemDescriptor[] checkMember(
      final PsiDocCommentOwner docCommentOwner,
      final InspectionManager manager,
      final boolean isOnTheFly) {
    final ArrayList<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
    final PsiDocComment docComment = docCommentOwner.getDocComment();
    if (docComment == null) return null;

    final Set<PsiJavaCodeReferenceElement> references = new HashSet<PsiJavaCodeReferenceElement>();
    docComment.accept(getVisitor(references, docCommentOwner, problems, manager, isOnTheFly));
    for (PsiJavaCodeReferenceElement reference : references) {
      final List<PsiClass> classesToImport = new ImportClassFix(reference).getClassesToImport();
      final PsiElement referenceNameElement = reference.getReferenceNameElement();
      problems.add(
          manager.createProblemDescriptor(
              referenceNameElement != null ? referenceNameElement : reference,
              cannotResolveSymbolMessage("<code>" + reference.getText() + "</code>"),
              !isOnTheFly || classesToImport.isEmpty() ? null : new AddImportFix(classesToImport),
              ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
              isOnTheFly));
    }

    return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]);
  }
 @Override
 public void visitNewExpression(PsiNewExpression expression) {
   super.visitNewExpression(expression);
   final PsiJavaCodeReferenceElement classReference = expression.getClassReference();
   if (classReference == null) {
     return;
   }
   final String name = classReference.getReferenceName();
   if (!"BigDecimal".equals(name)) {
     return;
   }
   final PsiMethod constructor = expression.resolveConstructor();
   if (constructor == null) {
     return;
   }
   final PsiParameterList parameterList = constructor.getParameterList();
   final int length = parameterList.getParametersCount();
   if (length != 1 && length != 2) {
     return;
   }
   final PsiParameter[] parameters = parameterList.getParameters();
   final PsiParameter firstParameter = parameters[0];
   final PsiType type = firstParameter.getType();
   if (type != PsiType.DOUBLE) {
     return;
   }
   registerNewExpressionError(expression);
 }
  @Nullable
  static Pair<PsiClass, Integer> getTypeParameterInfo(PsiElement context) {
    final PsiReferenceParameterList parameterList =
        PsiTreeUtil.getContextOfType(context, PsiReferenceParameterList.class, true);
    if (parameterList == null) return null;

    PsiElement parent = parameterList.getParent();
    if (!(parent instanceof PsiJavaCodeReferenceElement)) return null;

    final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) parent;
    final int parameterIndex;

    int index = 0;
    final PsiTypeElement typeElement =
        PsiTreeUtil.getContextOfType(context, PsiTypeElement.class, true);
    if (typeElement != null) {
      final PsiTypeElement[] elements =
          referenceElement.getParameterList().getTypeParameterElements();
      while (index < elements.length) {
        final PsiTypeElement element = elements[index++];
        if (element == typeElement) break;
      }
    }
    parameterIndex = index - 1;

    if (parameterIndex < 0) return null;
    final PsiElement target = referenceElement.resolve();
    if (!(target instanceof PsiClass)) return null;

    final PsiClass referencedClass = (PsiClass) target;
    final PsiTypeParameter[] typeParameters = referencedClass.getTypeParameters();
    if (typeParameters.length <= parameterIndex) return null;

    return Pair.create(referencedClass, parameterIndex);
  }
 /**
  * The parameter <code>allowIndirect</code> determines if the method should look for indirect
  * annotations, i.e. annotations which have themselves been annotated by the supplied annotation
  * name. Currently, this only allows one level of indirection and returns an array of
  * [base-annotation, indirect annotation]
  *
  * <p>The <code>annotationName</code> parameter is a pair of the target annotation class' fully
  * qualified name as a String and as a Set. This is done for performance reasons because the Set
  * is required by the {@link com.intellij.codeInsight.AnnotationUtil} utility class and allows to
  * avoid unnecessary object constructions.
  */
 public static PsiAnnotation[] getAnnotationsFromImpl(
     PsiModifierListOwner owner,
     Pair<String, ? extends Set<String>> annotationName,
     boolean allowIndirect,
     boolean inHierarchy) {
   final PsiAnnotation directAnnotation =
       inHierarchy
           ? AnnotationUtil.findAnnotationInHierarchy(owner, annotationName.second)
           : AnnotationUtil.findAnnotation(owner, annotationName.second);
   if (directAnnotation != null) {
     return new PsiAnnotation[] {directAnnotation};
   }
   if (allowIndirect) {
     final PsiAnnotation[] annotations = getAnnotations(owner, inHierarchy);
     for (PsiAnnotation annotation : annotations) {
       PsiJavaCodeReferenceElement nameReference = annotation.getNameReferenceElement();
       if (nameReference == null) continue;
       PsiElement resolved = nameReference.resolve();
       if (resolved instanceof PsiClass) {
         final PsiAnnotation psiAnnotation =
             AnnotationUtil.findAnnotationInHierarchy(
                 (PsiModifierListOwner) resolved, annotationName.second);
         if (psiAnnotation != null) {
           return new PsiAnnotation[] {psiAnnotation, annotation};
         }
       }
     }
   }
   return PsiAnnotation.EMPTY_ARRAY;
 }
 private static void checkMethodReference(
     PsiMethodReferenceExpression expression,
     InspectionManager inspectionManager,
     List<ProblemDescriptor> problems) {
   final PsiTypeElement qualifierTypeElement = expression.getQualifierType();
   if (qualifierTypeElement != null) {
     final PsiType psiType = qualifierTypeElement.getType();
     if (psiType instanceof PsiClassType && !(((PsiClassType) psiType).isRaw())) {
       final JavaResolveResult result = expression.advancedResolve(false);
       final PsiElement element = result.getElement();
       if (element instanceof PsiTypeParameterListOwner) {
         final PsiMethodReferenceExpression copy =
             createMethodReference(expression, qualifierTypeElement);
         final JavaResolveResult simplifiedResolve = copy.advancedResolve(false);
         final PsiElement candidate = simplifiedResolve.getElement();
         if (candidate == element) {
           final PsiJavaCodeReferenceElement referenceElement =
               qualifierTypeElement.getInnermostComponentReferenceElement();
           LOG.assertTrue(referenceElement != null, qualifierTypeElement);
           final PsiReferenceParameterList parameterList = referenceElement.getParameterList();
           LOG.assertTrue(parameterList != null);
           final ProblemDescriptor descriptor =
               inspectionManager.createProblemDescriptor(
                   parameterList,
                   InspectionsBundle.message("inspection.redundant.type.problem.descriptor"),
                   new MyMethodReferenceFixAction(),
                   ProblemHighlightType.LIKE_UNUSED_SYMBOL,
                   false);
           problems.add(descriptor);
         }
       }
     }
   }
 }
  private static void autoImport(final PsiFile file, int offset, final Editor editor) {
    final CharSequence text = editor.getDocument().getCharsSequence();
    while (offset > 0 && Character.isJavaIdentifierPart(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0 || text.charAt(offset) != '.') return;

    offset--;

    while (offset > 0 && Character.isWhitespace(text.charAt(offset))) offset--;
    if (offset <= 0) return;

    PsiJavaCodeReferenceElement element =
        extractReference(
            PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiExpression.class, false));
    if (element == null) return;

    while (true) {
      final PsiJavaCodeReferenceElement qualifier = extractReference(element.getQualifier());
      if (qualifier == null) break;

      element = qualifier;
    }
    if (!(element.getParent() instanceof PsiMethodCallExpression)
        && element.multiResolve(true).length == 0) {
      new ImportClassFix(element).doFix(editor, false, false);
    }
  }
Ejemplo n.º 18
0
  public ASTNode getDefaultAnchor(
      @NotNull PsiImportList list, @NotNull PsiImportStatementBase statement) {
    PsiJavaCodeReferenceElement ref = statement.getImportReference();
    if (ref == null) return null;

    int entryIndex = findEntryIndex(statement);
    PsiImportStatementBase[] allStatements = list.getAllImportStatements();
    int[] entries = ArrayUtil.newIntArray(allStatements.length);
    List<PsiImportStatementBase> statements = new ArrayList<PsiImportStatementBase>();
    for (int i = 0; i < allStatements.length; i++) {
      PsiImportStatementBase statement1 = allStatements[i];
      int entryIndex1 = findEntryIndex(statement1);
      entries[i] = entryIndex1;
      if (entryIndex1 == entryIndex) {
        statements.add(statement1);
      }
    }

    if (statements.isEmpty()) {
      int index;
      for (index = entries.length - 1; index >= 0; index--) {
        if (entries[index] < entryIndex) break;
      }
      index++;
      return index < entries.length
          ? SourceTreeToPsiMap.psiElementToTree(allStatements[index])
          : null;
    } else {
      String refText = ref.getCanonicalText();
      if (statement.isOnDemand()) {
        refText += ".";
      }

      PsiImportStatementBase insertBefore = null;
      PsiImportStatementBase insertAfter = null;
      for (PsiImportStatementBase statement1 : statements) {
        PsiJavaCodeReferenceElement ref1 = statement1.getImportReference();
        if (ref1 == null) {
          continue;
        }
        String refTextThis = ref1.getCanonicalText();
        if (statement1.isOnDemand()) {
          refTextThis += ".";
        }

        int comp = Comparing.compare(refText, refTextThis);
        if (comp < 0 && insertBefore == null) {
          insertBefore = statement1;
        }
        if (comp > 0) {
          insertAfter = statement1;
        }
      }

      if (insertBefore != null) return insertBefore.getNode();
      if (insertAfter != null) return insertAfter.getNode().getTreeNext();
      return null;
    }
  }
Ejemplo n.º 19
0
 @NotNull
 private static Import importToImport(@NotNull PsiImportStatementBase i) {
   PsiJavaCodeReferenceElement reference = i.getImportReference();
   if (reference != null) {
     return new Import(quoteKeywords(reference.getQualifiedName()) + (i.isOnDemand() ? ".*" : ""));
   }
   return new Import("");
 }
  private int substituteToTypeParameters(
      PsiTypeElement typeElement,
      PsiTypeElement inplaceTypeElement,
      PsiType[] paramVals,
      PsiTypeParameter[] params,
      TemplateBuilder builder,
      PsiSubstitutor rawingSubstitutor,
      boolean toplevel) {
    PsiType type = inplaceTypeElement.getType();
    List<PsiType> types = new ArrayList<>();
    for (int i = 0; i < paramVals.length; i++) {
      PsiType val = paramVals[i];
      if (val == null) return SUBSTITUTED_NONE;
      if (type.equals(val)) {
        types.add(myFactory.createType(params[i]));
      }
    }

    if (!types.isEmpty()) {
      Project project = typeElement.getProject();
      PsiType substituted = rawingSubstitutor.substitute(type);
      if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText())
          && (toplevel || substituted.equals(type))) {
        types.add(substituted);
      }

      builder.replaceElement(
          typeElement,
          new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
      return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS;
    }

    boolean substituted = false;
    PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement();
    PsiJavaCodeReferenceElement inplaceRef =
        inplaceTypeElement.getInnermostComponentReferenceElement();
    if (ref != null) {
      LOG.assertTrue(inplaceRef != null);
      PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements();
      PsiTypeElement[] inplaceInnerTypeElements =
          inplaceRef.getParameterList().getTypeParameterElements();
      for (int i = 0; i < innerTypeElements.length; i++) {
        substituted |=
            substituteToTypeParameters(
                    innerTypeElements[i],
                    inplaceInnerTypeElements[i],
                    paramVals,
                    params,
                    builder,
                    rawingSubstitutor,
                    false)
                != SUBSTITUTED_NONE;
      }
    }

    return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE;
  }
  public JavaCompletionProcessor(
      PsiElement element,
      ElementFilter filter,
      final boolean checkAccess,
      boolean checkInitialized,
      @Nullable Condition<String> nameCondition) {
    myCheckAccess = checkAccess;
    mySettings = CodeInsightSettings.getInstance();
    myResults = new ArrayList<CompletionElement>();
    myElement = element;
    myMatcher = nameCondition;
    myFilter = filter;
    PsiElement scope = element;
    if (JavaResolveUtil.isInJavaDoc(myElement)) myMembersFlag = true;
    while (scope != null && !(scope instanceof PsiFile) && !(scope instanceof PsiClass)) {
      scope = scope.getContext();
    }
    myScope = scope;
    if (!(element.getContainingFile() instanceof PsiJavaFile)) {
      myMembersFlag = true;
    }

    PsiElement elementParent = element.getContext();
    if (elementParent instanceof PsiReferenceExpression) {
      PsiExpression qualifier = ((PsiReferenceExpression) elementParent).getQualifierExpression();
      if (qualifier instanceof PsiSuperExpression) {
        final PsiJavaCodeReferenceElement qSuper = ((PsiSuperExpression) qualifier).getQualifier();
        if (qSuper == null) {
          myQualifierClass = JavaResolveUtil.getContextClass(myElement);
        } else {
          final PsiElement target = qSuper.resolve();
          myQualifierClass = target instanceof PsiClass ? (PsiClass) target : null;
        }
        if (myQualifierClass != null) {
          myQualifierType =
              JavaPsiFacade.getInstance(element.getProject())
                  .getElementFactory()
                  .createType(myQualifierClass);
        }
      } else if (qualifier != null) {
        myQualifierType = qualifier.getType();
        myQualifierClass = PsiUtil.resolveClassInType(myQualifierType);
        if (myQualifierType == null && qualifier instanceof PsiJavaCodeReferenceElement) {
          final PsiElement target = ((PsiJavaCodeReferenceElement) qualifier).resolve();
          if (target instanceof PsiClass) {
            myQualifierClass = (PsiClass) target;
          }
        }
      }
    }

    if (checkInitialized) {
      myNonInitializedFields.addAll(getNonInitializedFields(element));
    }
  }
Ejemplo n.º 22
0
 @Override
 public void visitThisExpression(PsiThisExpression expression) {
   super.visitThisExpression(expression);
   final PsiJavaCodeReferenceElement qualifier = expression.getQualifier();
   if (qualifier != null && qualifier.isReferenceTo(mySourceClass)) {
     try {
       qualifier.bindToElement(myTargetSuperClass);
     } catch (IncorrectOperationException e) {
       LOG.error(e);
     }
   }
 }
Ejemplo n.º 23
0
 public int findEntryIndex(@NotNull PsiImportStatementBase statement) {
   PsiJavaCodeReferenceElement ref = statement.getImportReference();
   if (ref == null) return -1;
   String packageName;
   if (statement.isOnDemand()) {
     packageName = ref.getCanonicalText();
   } else {
     String className = ref.getCanonicalText();
     packageName = getPackageOrClassName(className);
   }
   return findEntryIndex(packageName);
 }
  @Override
  public void beforeCompletion(@NotNull final CompletionInitializationContext context) {
    final PsiFile file = context.getFile();

    if (file instanceof PsiJavaFile) {
      JavaCompletionUtil.initOffsets(file, context.getOffsetMap());

      autoImport(file, context.getStartOffset() - 1, context.getEditor());

      if (context.getCompletionType() == CompletionType.BASIC) {
        if (semicolonNeeded(context.getEditor(), file, context.getStartOffset())) {
          context.setDummyIdentifier(CompletionInitializationContext.DUMMY_IDENTIFIER.trim() + ";");
          return;
        }

        final PsiJavaCodeReferenceElement ref =
            PsiTreeUtil.findElementOfClassAtOffset(
                file, context.getStartOffset(), PsiJavaCodeReferenceElement.class, false);
        if (ref != null && !(ref instanceof PsiReferenceExpression)) {
          if (ref.getParent() instanceof PsiTypeElement) {
            context.setDummyIdentifier(
                CompletionInitializationContext.DUMMY_IDENTIFIER.trim() + ";");
          }

          if (JavaSmartCompletionContributor.AFTER_NEW.accepts(ref)) {
            final PsiReferenceParameterList paramList = ref.getParameterList();
            if (paramList != null && paramList.getTextLength() > 0) {
              context
                  .getOffsetMap()
                  .addOffset(
                      ConstructorInsertHandler.PARAM_LIST_START,
                      paramList.getTextRange().getStartOffset());
              context
                  .getOffsetMap()
                  .addOffset(
                      ConstructorInsertHandler.PARAM_LIST_END,
                      paramList.getTextRange().getEndOffset());
            }
          }

          return;
        }

        final PsiElement element = file.findElementAt(context.getStartOffset());

        if (psiElement().inside(PsiAnnotation.class).accepts(element)) {
          return;
        }

        context.setDummyIdentifier(CompletionInitializationContext.DUMMY_IDENTIFIER_TRIMMED);
      }
    }
  }
Ejemplo n.º 25
0
 @Nullable
 private static PsiReferenceParameterList extractReferenceParameterList(
     final PsiClass superClass, final PsiReferenceList extendsList) {
   for (PsiJavaCodeReferenceElement referenceElement : extendsList.getReferenceElements()) {
     final PsiElement element = referenceElement.resolve();
     if (element instanceof PsiClass
         && InheritanceUtil.isInheritorOrSelf((PsiClass) element, superClass, true)) {
       return referenceElement.getParameterList();
     }
   }
   return null;
 }
 @Override
 public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
   super.visitReferenceElement(reference);
   if (reference.getQualifier() != null) {
     return;
   }
   final PsiElement target = reference.resolve();
   if (!(target instanceof PsiClass) || !PsiUtil.isLocalClass((PsiClass) target)) {
     return;
   }
   referenceToLocalClass = true;
 }
Ejemplo n.º 27
0
  private static PsiElement getElement(PsiElement targetElement) {
    if (targetElement instanceof PsiNewExpression) {
      PsiJavaCodeReferenceElement referenceElement =
          getReferenceElement((PsiNewExpression) targetElement);
      if (referenceElement == null) return null;
      return referenceElement.getReferenceNameElement();
    } else if (targetElement instanceof PsiEnumConstant) {
      return targetElement;
    }

    return null;
  }
 private static void decodeRef(
     final PsiJavaCodeReferenceElement expression,
     final Map<PsiClass, PsiElement> oldToNewMap,
     Set<PsiElement> rebindExpressions) {
   final PsiElement resolved = expression.resolve();
   if (resolved instanceof PsiClass) {
     final PsiClass psiClass = (PsiClass) resolved;
     if (oldToNewMap.containsKey(psiClass)) {
       rebindExpressions.add(expression.bindToElement(oldToNewMap.get(psiClass)));
     }
   }
 }
    private static boolean containsError(PsiAnnotation annotation) {
      final PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
      if (nameRef == null) {
        return true;
      }
      final PsiClass aClass = (PsiClass) nameRef.resolve();
      if (aClass == null || !aClass.isAnnotationType()) {
        return true;
      }
      final Set<String> names = new HashSet<String>();
      final PsiAnnotationParameterList annotationParameterList = annotation.getParameterList();
      if (PsiUtilCore.hasErrorElementChild(annotationParameterList)) {
        return true;
      }
      final PsiNameValuePair[] attributes = annotationParameterList.getAttributes();
      for (PsiNameValuePair attribute : attributes) {
        final PsiReference reference = attribute.getReference();
        if (reference == null) {
          return true;
        }
        final PsiMethod method = (PsiMethod) reference.resolve();
        if (method == null) {
          return true;
        }
        final PsiAnnotationMemberValue value = attribute.getValue();
        if (value == null || PsiUtilCore.hasErrorElementChild(value)) {
          return true;
        }
        if (value instanceof PsiAnnotation && containsError((PsiAnnotation) value)) {
          return true;
        }
        if (!hasCorrectType(value, method.getReturnType())) {
          return true;
        }
        final String name = attribute.getName();
        if (!names.add(name != null ? name : PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)) {
          return true;
        }
      }

      for (PsiMethod method : aClass.getMethods()) {
        if (!(method instanceof PsiAnnotationMethod)) {
          continue;
        }
        final PsiAnnotationMethod annotationMethod = (PsiAnnotationMethod) method;
        if (annotationMethod.getDefaultValue() == null
            && !names.contains(annotationMethod.getName())) {
          return true; // missing a required argument
        }
      }
      return false;
    }
Ejemplo n.º 30
0
  public static PsiAnnotation findAnnotation(
      @NotNull PsiAnnotationOwner modifierList, @NotNull String qualifiedName) {
    final String shortName = StringUtil.getShortName(qualifiedName);
    PsiAnnotation[] annotations = modifierList.getAnnotations();
    for (PsiAnnotation annotation : annotations) {
      final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement();
      if (referenceElement != null && shortName.equals(referenceElement.getReferenceName())) {
        if (qualifiedName.equals(annotation.getQualifiedName())) return annotation;
      }
    }

    return null;
  }