public static <T> T getOrCreateCache(
      Key<T> cacheKey, PsiElement element, CacheProvider<T> provider) {
    final PsiFile containingFile;
    if (element instanceof PsiFile) {
      containingFile = (PsiFile) element;
    } else {
      final PsiClass topLevelClass = PsiUtil.getTopLevelClass(element);

      if (topLevelClass == null) {
        return provider.provide();
      }
      containingFile = topLevelClass.getContainingFile();
    }

    if (containingFile == null) {
      return provider.provide();
    }

    final PsiFile originalFile = containingFile.getOriginalFile();
    T copyableUserData = originalFile.getCopyableUserData(cacheKey);

    if (copyableUserData != null) {
      if (!provider.isCacheValid(copyableUserData)) {
        copyableUserData = null;
      }
    }

    if (copyableUserData == null) {
      originalFile.putCopyableUserData(cacheKey, copyableUserData = provider.provide());
    }

    return copyableUserData;
  }
  public static Collection<AnnotationSearchResult> findAllAnnotatedElements(
      PsiElement element, String annotation) {
    final PsiClass bean = PsiUtil.getTopLevelClass(element);
    if (bean == null) {
      return Collections.emptyList();
    }

    final List<AnnotationSearchResult> elementList = new ArrayList<AnnotationSearchResult>();
    PsiAnnotation a;
    for (PsiField e : bean.getAllFields()) {
      a = getAnnotationFromElement(e, annotation);
      if (a != null) {
        elementList.add(new AnnotationSearchResult(a, e));
      }
    }

    for (PsiMethod e : bean.getAllMethods()) {
      a = getAnnotationFromElement(e, annotation);

      if (a != null) {
        elementList.add(new AnnotationSearchResult(a, e));
      }

      for (PsiParameter p : e.getParameterList().getParameters()) {
        a = getAnnotationFromElement(p, annotation);

        if (a != null) {
          elementList.add(new AnnotationSearchResult(a, p));
        }
      }
    }

    return elementList;
  }
 public static long getLastUpdate(PsiElement element) {
   try {
     final PsiClass topLevelClass = PsiUtil.getTopLevelClass(element);
     if (topLevelClass == null) {
       return -1;
     }
     final PsiFile containingFile = topLevelClass.getContainingFile();
     return containingFile.getOriginalFile().getModificationStamp();
   } catch (PsiInvalidElementAccessException e) {
     return -1;
   }
 }
  @NotNull
  public static SearchScope getMemberUseScope(@NotNull PsiMember member) {
    PsiFile file = member.getContainingFile();
    PsiElement topElement = file == null ? member : file;
    Project project = topElement.getProject();
    final GlobalSearchScope maximalUseScope =
        ResolveScopeManager.getInstance(project).getUseScope(topElement);
    if (isInServerPage(file)) return maximalUseScope;

    PsiClass aClass = member.getContainingClass();
    if (aClass instanceof PsiAnonymousClass
        && !(aClass instanceof PsiEnumConstantInitializer
            && member instanceof PsiMethod
            && member.hasModifierProperty(PsiModifier.PUBLIC)
            && ((PsiMethod) member).findSuperMethods().length > 0)) {
      // member from anonymous class can be called from outside the class
      PsiElement methodCallExpr =
          PsiUtil.isLanguageLevel8OrHigher(aClass)
              ? PsiTreeUtil.getTopmostParentOfType(aClass, PsiStatement.class)
              : PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class);
      return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass);
    }

    PsiModifierList modifierList = member.getModifierList();
    int accessLevel =
        modifierList == null ? PsiUtil.ACCESS_LEVEL_PUBLIC : PsiUtil.getAccessLevel(modifierList);
    if (accessLevel == PsiUtil.ACCESS_LEVEL_PUBLIC
        || accessLevel == PsiUtil.ACCESS_LEVEL_PROTECTED) {
      return maximalUseScope; // class use scope doesn't matter, since another very visible class
      // can inherit from aClass
    }
    if (accessLevel == PsiUtil.ACCESS_LEVEL_PRIVATE) {
      PsiClass topClass = PsiUtil.getTopLevelClass(member);
      return topClass != null
          ? new LocalSearchScope(topClass)
          : file == null ? maximalUseScope : new LocalSearchScope(file);
    }
    if (file instanceof PsiJavaFile) {
      PsiPackage aPackage =
          JavaPsiFacade.getInstance(project).findPackage(((PsiJavaFile) file).getPackageName());
      if (aPackage != null) {
        SearchScope scope = PackageScope.packageScope(aPackage, false);
        return scope.intersectWith(maximalUseScope);
      }
    }
    return maximalUseScope;
  }
Example #5
0
  @Nullable
  public static String getSourcePositionPackageDisplayName(
      DebugProcessImpl debugProcess, @Nullable SourcePosition position) {
    if (position == null) {
      return null;
    }
    final PsiFile positionFile = position.getFile();
    if (positionFile instanceof JspFile) {
      final PsiDirectory dir = positionFile.getContainingDirectory();
      return dir != null ? dir.getVirtualFile().getPresentableUrl() : null;
    }

    final PsiClass psiClass = getClassAt(position);

    if (psiClass != null) {
      PsiClass toplevel = PsiUtil.getTopLevelClass(psiClass);
      if (toplevel != null) {
        String qName = toplevel.getQualifiedName();
        if (qName != null) {
          int i = qName.lastIndexOf('.');
          return i > 0 ? qName.substring(0, i) : "";
        }
      }
    }

    if (positionFile instanceof PsiClassOwner) {
      String name = ((PsiClassOwner) positionFile).getPackageName();
      if (!StringUtil.isEmpty(name)) {
        return name;
      }
    }

    if (debugProcess != null && debugProcess.isAttached()) {
      List<ReferenceType> allClasses = debugProcess.getPositionManager().getAllClasses(position);
      if (!allClasses.isEmpty()) {
        final String className = allClasses.get(0).name();
        int dotIndex = className.lastIndexOf('.');
        if (dotIndex >= 0) {
          return className.substring(0, dotIndex);
        }
      }
    }
    return "";
  }
  public static boolean isSourceLevelAccessible(
      PsiElement context, PsiClass psiClass, final boolean pkgContext) {
    if (!JavaPsiFacade.getInstance(psiClass.getProject())
        .getResolveHelper()
        .isAccessible(psiClass, context, null)) {
      return false;
    }

    if (pkgContext) {
      PsiClass topLevel = PsiUtil.getTopLevelClass(psiClass);
      if (topLevel != null) {
        String fqName = topLevel.getQualifiedName();
        if (fqName != null && StringUtil.isEmpty(StringUtil.getPackageName(fqName))) {
          return false;
        }
      }
    }

    return true;
  }
Example #7
0
  /**
   * Computes indentation of PsiClass, PsiMethod and PsiField elements after formatting
   *
   * @param element PsiClass or PsiMethod or PsiField
   * @return indentation size
   */
  private int getIndentSpecial(@NotNull PsiElement element) {
    assert (element instanceof PsiClass
        || element instanceof PsiField
        || element instanceof PsiMethod);

    int indentSize = mySettings.getIndentSize(JavaFileType.INSTANCE);
    boolean doNotIndentTopLevelClassMembers =
        mySettings.getCommonSettings(JavaLanguage.INSTANCE).DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS;

    int indent = 0;
    PsiClass top = PsiUtil.getTopLevelClass(element);
    while (top != null && !element.isEquivalentTo(top)) {
      if (doNotIndentTopLevelClassMembers && element.getParent().isEquivalentTo(top)) {
        break;
      }
      element = element.getParent();
      indent += indentSize;
    }

    return indent;
  }
  @NotNull
  public static SearchScope getClassUseScope(@NotNull PsiClass aClass) {
    if (aClass instanceof PsiAnonymousClass) {
      return new LocalSearchScope(aClass);
    }
    final GlobalSearchScope maximalUseScope = ResolveScopeManager.getElementUseScope(aClass);
    PsiFile file = aClass.getContainingFile();
    if (PsiImplUtil.isInServerPage(file)) return maximalUseScope;
    final PsiClass containingClass = aClass.getContainingClass();
    if (aClass.hasModifierProperty(PsiModifier.PUBLIC)
        || aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
      return containingClass == null ? maximalUseScope : containingClass.getUseScope();
    } else if (aClass.hasModifierProperty(PsiModifier.PRIVATE)
        || aClass instanceof PsiTypeParameter) {
      PsiClass topClass = PsiUtil.getTopLevelClass(aClass);
      return new LocalSearchScope(topClass == null ? aClass.getContainingFile() : topClass);
    } else {
      PsiPackage aPackage = null;
      if (file instanceof PsiJavaFile) {
        aPackage =
            JavaPsiFacade.getInstance(aClass.getProject())
                .findPackage(((PsiJavaFile) file).getPackageName());
      }

      if (aPackage == null) {
        PsiDirectory dir = file.getContainingDirectory();
        if (dir != null) {
          aPackage = JavaDirectoryService.getInstance().getPackage(dir);
        }
      }

      if (aPackage != null) {
        SearchScope scope = PackageScope.packageScope(aPackage, false);
        scope = scope.intersectWith(maximalUseScope);
        return scope;
      }

      return new LocalSearchScope(file);
    }
  }
 @Override
 public void visitField(@NotNull PsiField field) {
   super.visitField(field);
   if (!field.hasModifierProperty(PsiModifier.PRIVATE)) {
     return;
   }
   if (HighlightUtil.isSerializationImplicitlyUsedField(field)) {
     return;
   }
   final PsiClass containingClass = PsiUtil.getTopLevelClass(field);
   if (!shouldCheckVariable(field, containingClass)) {
     return;
   }
   final ArrayReadWriteVisitor visitor =
       new ArrayReadWriteVisitor(field, !isSimpleArrayExpression(field.getInitializer()));
   containingClass.accept(visitor);
   final boolean written = visitor.isWritten();
   if (!visitor.isReferenced() || written == visitor.isRead()) {
     return;
   }
   registerFieldError(field, Boolean.valueOf(written));
 }
  @NotNull
  public static SearchScope getMemberUseScope(@NotNull PsiMember member) {
    final GlobalSearchScope maximalUseScope = ResolveScopeManager.getElementUseScope(member);
    PsiFile file = member.getContainingFile();
    if (isInServerPage(file)) return maximalUseScope;

    PsiClass aClass = member.getContainingClass();
    if (aClass instanceof PsiAnonymousClass) {
      // member from anonymous class can be called from outside the class
      PsiElement methodCallExpr =
          PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class);
      return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass);
    }

    if (member.hasModifierProperty(PsiModifier.PUBLIC)) {
      return maximalUseScope; // class use scope doesn't matter, since another very visible class
      // can inherit from aClass
    } else if (member.hasModifierProperty(PsiModifier.PROTECTED)) {
      return maximalUseScope; // class use scope doesn't matter, since another very visible class
      // can inherit from aClass
    } else if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
      PsiClass topClass = PsiUtil.getTopLevelClass(member);
      return topClass != null ? new LocalSearchScope(topClass) : new LocalSearchScope(file);
    } else {
      if (file instanceof PsiJavaFile) {
        PsiPackage aPackage =
            JavaPsiFacade.getInstance(member.getProject())
                .findPackage(((PsiJavaFile) file).getPackageName());
        if (aPackage != null) {
          SearchScope scope = PackageScope.packageScope(aPackage, false);
          scope = scope.intersectWith(maximalUseScope);
          return scope;
        }
      }

      return maximalUseScope;
    }
  }
  private static void findLocalHidesFieldCollisions(
      final PsiElement element,
      final String newName,
      final Map<? extends PsiElement, String> allRenames,
      final List<UsageInfo> result) {
    if (!(element instanceof PsiLocalVariable) && !(element instanceof PsiParameter)) return;

    PsiClass toplevel = PsiUtil.getTopLevelClass(element);
    if (toplevel == null) return;

    PsiElement scopeElement;
    if (element instanceof PsiLocalVariable) {
      scopeElement = RefactoringUtil.getVariableScope((PsiLocalVariable) element);
    } else { // Parameter
      scopeElement = ((PsiParameter) element).getDeclarationScope();
    }

    LOG.assertTrue(scopeElement != null);
    scopeElement.accept(
        new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitReferenceExpression(PsiReferenceExpression expression) {
            super.visitReferenceExpression(expression);
            if (!expression.isQualified()) {
              PsiElement resolved = expression.resolve();
              if (resolved instanceof PsiField) {
                final PsiField field = (PsiField) resolved;
                String fieldNewName =
                    allRenames.containsKey(field) ? allRenames.get(field) : field.getName();
                if (newName.equals(fieldNewName)) {
                  result.add(new LocalHidesFieldUsageInfo(expression, element));
                }
              }
            }
          }
        });
  }
  public static void invoke(
      final Project project, PsiFile file, final Editor editor, PsiElement element) {
    if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

    final PsiJavaCodeReferenceElement refExpr = (PsiJavaCodeReferenceElement) element.getParent();
    final PsiClass aClass = (PsiClass) refExpr.resolve();
    if (aClass == null) {
      return;
    }
    final PsiClass containingClass = PsiUtil.getTopLevelClass(refExpr);
    if (aClass != containingClass) {
      PsiImportList importList = ((PsiJavaFile) file).getImportList();
      if (importList == null) {
        return;
      }
      boolean alreadyImported = false;
      for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
        if (!statement.isOnDemand()) continue;
        PsiClass staticResolve = statement.resolveTargetClass();
        if (aClass == staticResolve) {
          alreadyImported = true;
          break;
        }
      }
      if (!alreadyImported) {
        PsiImportStaticStatement importStaticStatement =
            JavaPsiFacade.getInstance(file.getProject())
                .getElementFactory()
                .createImportStaticStatement(aClass, "*");
        importList.add(importStaticStatement);
      }
    }

    List<PsiFile> roots = file.getViewProvider().getAllFiles();
    for (final PsiFile root : roots) {
      PsiElement copy = root.copy();
      final PsiManager manager = root.getManager();

      final TIntArrayList expressionToDequalifyOffsets = new TIntArrayList();
      copy.accept(
          new JavaRecursiveElementWalkingVisitor() {
            int delta;

            @Override
            public void visitReferenceElement(PsiJavaCodeReferenceElement expression) {
              if (isParameterizedReference(expression)) return;
              PsiElement qualifierExpression = expression.getQualifier();
              if (qualifierExpression instanceof PsiJavaCodeReferenceElement
                  && ((PsiJavaCodeReferenceElement) qualifierExpression).isReferenceTo(aClass)) {
                try {
                  PsiElement resolved = expression.resolve();
                  int end = expression.getTextRange().getEndOffset();
                  qualifierExpression.delete();
                  delta += end - expression.getTextRange().getEndOffset();
                  PsiElement after = expression.resolve();
                  if (manager.areElementsEquivalent(after, resolved)) {
                    expressionToDequalifyOffsets.add(
                        expression.getTextRange().getStartOffset() + delta);
                  }
                } catch (IncorrectOperationException e) {
                  LOG.error(e);
                }
              }
              super.visitElement(expression);
            }
          });

      expressionToDequalifyOffsets.forEachDescending(
          new TIntProcedure() {
            @Override
            public boolean execute(int offset) {
              PsiJavaCodeReferenceElement expression =
                  PsiTreeUtil.findElementOfClassAtOffset(
                      root, offset, PsiJavaCodeReferenceElement.class, false);
              if (expression == null) {
                return false;
              }
              PsiElement qualifierExpression = expression.getQualifier();
              if (qualifierExpression instanceof PsiJavaCodeReferenceElement
                  && ((PsiJavaCodeReferenceElement) qualifierExpression).isReferenceTo(aClass)) {
                qualifierExpression.delete();
                if (editor != null) {
                  HighlightManager.getInstance(project)
                      .addRangeHighlight(
                          editor,
                          expression.getTextRange().getStartOffset(),
                          expression.getTextRange().getEndOffset(),
                          EditorColorsManager.getInstance()
                              .getGlobalScheme()
                              .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES),
                          false,
                          null);
                }
              }

              return true;
            }
          });
    }
  }