public PsiReturnStatement addReturnForMethod(final PsiFile file, final PsiMethod method) { final PsiModifierList modifiers = method.getModifierList(); if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT) || method.getBody() == null) { return null; } try { final ConvertReturnStatementsVisitor visitor = new ConvertReturnStatementsVisitor(factory, method, myTargetType); ControlFlow controlFlow; try { controlFlow = HighlightControlFlowUtil.getControlFlowNoConstantEvaluate(method.getBody()); } catch (AnalysisCanceledException e) { return null; // must be an error } PsiReturnStatement returnStatement; if (controlFlow != null && ControlFlowUtil.processReturns(controlFlow, visitor)) { // extra return statement not needed // get latest modified return statement and select... returnStatement = visitor.getLatestReturn(); } else { returnStatement = visitor.createReturnInLastStatement(); } if (method.getContainingFile() != file) { UndoUtil.markPsiFileForUndo(file); } return returnStatement; } catch (IncorrectOperationException e) { LOG.error(e); } return null; }
@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 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; }
private static void makeVariableFinalIfNeeded( InsertionContext context, @Nullable PsiReferenceExpression ref) { if (!Registry.is("java.completion.make.outer.variables.final") || ref == null || PsiUtil.isLanguageLevel8OrHigher(ref) || JspPsiUtil.isInJspFile(ref)) { return; } PsiElement target = ref.resolve(); if (target instanceof PsiLocalVariable || target instanceof PsiParameter) { PsiClass placeClass = PsiTreeUtil.findElementOfClassAtOffset( context.getFile(), context.getTailOffset() - 1, PsiClass.class, false); if (placeClass != null && !PsiTreeUtil.isAncestor(placeClass, target, true) && !HighlightControlFlowUtil.isReassigned( (PsiVariable) target, new HashMap<PsiElement, Collection<ControlFlowUtil.VariableInfo>>())) { PsiModifierList modifierList = ((PsiVariable) target).getModifierList(); if (modifierList != null) { modifierList.setModifierProperty(PsiModifier.FINAL, true); } } } }
public static boolean fieldOrMethodIsAnnotated(PsiElement element, String annotationType) { final PsiElement e = findFieldOrMethod(element); if (e instanceof PsiField) { final PsiModifierList modifierList = ((PsiField) e).getModifierList(); if (modifierList != null) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { final String qualifiedName = psiAnnotation.getQualifiedName(); if (qualifiedName != null && qualifiedName.equals(annotationType)) { return true; } } } } else if (e instanceof PsiMethod) { for (PsiAnnotation psiAnnotation : ((PsiMethod) e).getModifierList().getAnnotations()) { final String qualifiedName = psiAnnotation.getQualifiedName(); if (qualifiedName != null && qualifiedName.equals(annotationType)) { return true; } } } return false; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiModifierListOwner psiElement = PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class); if (psiElement != null) { RefJavaElement refElement = (RefJavaElement) (myManager != null ? myManager.getReference(psiElement) : null); try { if (psiElement instanceof PsiVariable) { ((PsiVariable) psiElement).normalizeDeclaration(); } final PsiModifierList modifierList = psiElement.getModifierList(); LOG.assertTrue(modifierList != null); modifierList.setModifierProperty(PsiModifier.FINAL, true); modifierList.setModifierProperty(PsiModifier.VOLATILE, false); } catch (IncorrectOperationException e) { LOG.error(e); } if (refElement != null) { RefJavaUtil.getInstance().setIsFinal(refElement, true); } } }
@Override public void visitMethod(@NotNull PsiMethod method) { // don't call super, to keep this from drilling in if (!method.isConstructor()) { return; } if (!method.hasModifierProperty(PsiModifier.PRIVATE)) { return; } final PsiClass aClass = method.getContainingClass(); if (aClass == null) { return; } if (!aClass.isEnum()) { return; } final PsiModifierList modifiers = method.getModifierList(); final PsiElement[] children = modifiers.getChildren(); for (final PsiElement child : children) { final String text = child.getText(); if (PsiModifier.PRIVATE.equals(text)) { registerError(child, child, method); } } }
@Nullable public static PsiAnnotation getAnnotation( @NotNull PsiModifierListOwner field, @NotNull String annotationName) { final PsiModifierList modifierList = field.getModifierList(); if (modifierList == null) return null; return modifierList.findAnnotation(annotationName); }
private static boolean canBePrivate( PsiMethod method, Collection<PsiReference> references, Collection<? extends PsiElement> deleted, final PsiElement[] allElementsToDelete) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { return false; } PsiManager manager = method.getManager(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); final PsiElementFactory factory = facade.getElementFactory(); final PsiModifierList privateModifierList; try { final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID); privateModifierList = newMethod.getModifierList(); privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true); } catch (IncorrectOperationException e) { LOG.assertTrue(false); return false; } for (PsiReference reference : references) { final PsiElement element = reference.getElement(); if (!isInside(element, allElementsToDelete) && !isInside(element, deleted) && !facade .getResolveHelper() .isAccessible(method, privateModifierList, element, null, null)) { return false; } } return true; }
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) { if (ApplicationManager.getApplication().isUnitTestMode()) { return null; } if (!(element instanceof PsiMethod) && !(element instanceof PsiClass)) { return null; } if (!PsiUtil.isPluginProject(element.getProject())) { return null; } final VirtualFile file = PsiUtilCore.getVirtualFile(element); if (file == null || !ProjectFileIndex.SERVICE .getInstance(element.getProject()) .isInTestSourceContent(file)) { return null; } if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod) element; if (isTestMethod(method)) { return new LineMarkerInfo<PsiMethod>( method, method.getModifierList().getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, null, new TestDataNavigationHandler(), GutterIconRenderer.Alignment.LEFT); } } else { final PsiClass psiClass = (PsiClass) element; final String basePath = getTestDataBasePath(psiClass); if (basePath != null) { PsiModifierList modifierList = psiClass.getModifierList(); assert modifierList != null; return new LineMarkerInfo<PsiClass>( psiClass, modifierList.getTextRange(), PlatformIcons.TEST_SOURCE_FOLDER, Pass.UPDATE_ALL, new TooltipProvider(basePath), new GutterIconNavigationHandler<PsiClass>() { @Override public void navigate(MouseEvent e, PsiClass elt) { final VirtualFile baseDir = VfsUtil.findFileByIoFile(new File(basePath), true); if (baseDir != null) { new OpenFileDescriptor(psiClass.getProject(), baseDir).navigate(true); } } }, GutterIconRenderer.Alignment.LEFT); } } return null; }
private static void annotate( final PsiElementFactory factory, final PsiModifierListOwner listOwner, final String annotationQName) throws IncorrectOperationException { final PsiModifierList modifierList = listOwner.getModifierList(); LOG.assertTrue(modifierList != null); modifierList.addAfter(factory.createAnnotationFromText("@" + annotationQName, listOwner), null); }
static PsiAnnotation findAnnotationOnMethod(PsiMethod psiMethod, String annotationName) { PsiModifierList modifierList = psiMethod.getModifierList(); for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { if (annotationName.equals(psiAnnotation.getQualifiedName())) { return psiAnnotation; } } return null; }
private static boolean isNotOpenMethod(@NotNull PsiMethod method) { if (method.getParent() instanceof PsiClass) { PsiModifierList parentModifierList = ((PsiClass) method.getParent()).getModifierList(); if ((parentModifierList != null && parentModifierList.hasExplicitModifier(Modifier.FINAL)) || ((PsiClass) method.getParent()).isEnum()) { return true; } } return false; }
@Override public void visitReferenceExpression(final PsiReferenceExpression reference) { if (myLineRange.intersects(reference.getTextRange())) { final PsiElement psiElement = reference.resolve(); if (psiElement instanceof PsiVariable) { final PsiVariable var = (PsiVariable) psiElement; if (var instanceof PsiField) { if (myCollectExpressions && !DebuggerUtils.hasSideEffectsOrReferencesMissingVars( reference, myVisibleLocals)) { /* if (var instanceof PsiEnumConstant && reference.getQualifier() == null) { final PsiClass enumClass = ((PsiEnumConstant)var).getContainingClass(); if (enumClass != null) { final PsiExpression expression = JavaPsiFacade.getInstance(var.getProject()).getParserFacade().createExpressionFromText(enumClass.getName() + "." + var.getName(), var); final PsiReference ref = expression.getReference(); if (ref != null) { ref.bindToElement(var); myExpressions.add(new TextWithImportsImpl(expression)); } } } else { myExpressions.add(new TextWithImportsImpl(reference)); } */ final PsiModifierList modifierList = var.getModifierList(); boolean isConstant = (var instanceof PsiEnumConstant) || (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC) && modifierList.hasModifierProperty(PsiModifier.FINAL)); if (!isConstant) { myExpressions.add(new TextWithImportsImpl(reference)); } } } else { if (myVisibleLocals.contains(var.getName())) { myVars.add(var.getName()); } else { // fix for variables used in inner classes if (!Comparing.equal( PsiTreeUtil.getParentOfType(reference, PsiClass.class), PsiTreeUtil.getParentOfType(var, PsiClass.class))) { myExpressions.add(new TextWithImportsImpl(reference)); } } } } } super.visitReferenceExpression(reference); }
public static boolean isInsideParameterList(PsiElement position) { PsiElement prev = PsiTreeUtil.prevVisibleLeaf(position); PsiModifierList modifierList = PsiTreeUtil.getParentOfType(prev, PsiModifierList.class); if (modifierList != null) { if (PsiTreeUtil.isAncestor(modifierList, position, false)) { return false; } PsiElement parent = modifierList.getParent(); return parent instanceof PsiParameterList || parent instanceof PsiParameter && parent.getParent() instanceof PsiParameterList; } return INSIDE_PARAMETER_LIST.accepts(position); }
private void makeStatic(PsiMethod member) { final PsiAnnotation overrideAnnotation = AnnotationUtil.findAnnotation(member, CommonClassNames.JAVA_LANG_OVERRIDE); if (overrideAnnotation != null) { overrideAnnotation.delete(); } setupTypeParameterList(member); // Add static modifier final PsiModifierList modifierList = member.getModifierList(); modifierList.setModifierProperty(PsiModifier.STATIC, true); modifierList.setModifierProperty(PsiModifier.FINAL, false); modifierList.setModifierProperty(PsiModifier.DEFAULT, false); }
public static boolean typeIsAnnotated(PsiClass psiClass, String annotationType) { final PsiModifierList modifierList = psiClass.getModifierList(); if (modifierList != null) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { final String qualifiedName = psiAnnotation.getQualifiedName(); if (qualifiedName != null && qualifiedName.equals(annotationType)) { return true; } } } return false; }
public static PsiAnnotation getAnnotationFromElement(PsiElement element, String annotationType) { if (element instanceof PsiModifierListOwner) { final PsiModifierList modifierList = ((PsiModifierListOwner) element).getModifierList(); if (modifierList != null) { for (PsiAnnotation annotation : modifierList.getAnnotations()) { if (annotationType.equals(annotation.getQualifiedName())) { return annotation; } } } } return null; }
@Override public boolean isAvailable( @NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { final PsiModifierList myModifierList = (PsiModifierList) startElement; PsiVariable variable = myVariable == null ? null : myVariable.getElement(); return myModifierList.isValid() && myModifierList.getManager().isInProject(myModifierList) && myModifierList.hasExplicitModifier(myModifier) != myShouldHave && (variable == null || variable.isValid()); }
/** * Returns a set of targets where the given annotation may be applied, or {@code null} when the * type is not a valid annotation. */ @Nullable public static Set<TargetType> getAnnotationTargets(@NotNull PsiClass annotationType) { if (!annotationType.isAnnotationType()) return null; PsiModifierList modifierList = annotationType.getModifierList(); if (modifierList == null) return null; PsiAnnotation target = modifierList.findAnnotation(CommonClassNames.JAVA_LANG_ANNOTATION_TARGET); if (target == null) return DEFAULT_TARGETS; // if omitted it is applicable to all but Java 8 // TYPE_USE/TYPE_PARAMETERS targets return extractRequiredAnnotationTargets(target.findAttributeValue(null)); }
private static PsiAnnotation[] getHierarchyAnnotations( PsiModifierListOwner listOwner, PsiModifierList modifierList) { final Set<PsiAnnotation> all = new HashSet<PsiAnnotation>() { public boolean add(PsiAnnotation o) { // don't overwrite "higher level" annotations return !contains(o) && super.add(o); } }; if (listOwner instanceof PsiMethod) { ContainerUtil.addAll(all, modifierList.getAnnotations()); SuperMethodsSearch.search((PsiMethod) listOwner, null, true, true) .forEach( new Processor<MethodSignatureBackedByPsiMethod>() { public boolean process(final MethodSignatureBackedByPsiMethod superMethod) { ContainerUtil.addAll( all, superMethod.getMethod().getModifierList().getAnnotations()); return true; } }); return all.toArray(new PsiAnnotation[all.size()]); } if (listOwner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter) listOwner; PsiElement declarationScope = parameter.getDeclarationScope(); PsiParameterList parameterList; if (declarationScope instanceof PsiMethod && parameter.getParent() == (parameterList = ((PsiMethod) declarationScope).getParameterList())) { PsiMethod method = (PsiMethod) declarationScope; final int parameterIndex = parameterList.getParameterIndex(parameter); ContainerUtil.addAll(all, modifierList.getAnnotations()); SuperMethodsSearch.search(method, null, true, true) .forEach( new Processor<MethodSignatureBackedByPsiMethod>() { public boolean process(final MethodSignatureBackedByPsiMethod superMethod) { PsiParameter superParameter = superMethod.getMethod().getParameterList().getParameters()[parameterIndex]; PsiModifierList modifierList = superParameter.getModifierList(); if (modifierList != null) { ContainerUtil.addAll(all, modifierList.getAnnotations()); } return true; } }); return all.toArray(new PsiAnnotation[all.size()]); } } return modifierList.getAnnotations(); }
@Nullable private static PsiField getReferencedFinalField(final PsiExpression argument) { if (argument instanceof PsiReferenceExpression) { final PsiElement element = ((PsiReferenceExpression) argument).resolve(); if (element instanceof PsiField) { final PsiField field = (PsiField) element; final PsiModifierList modifierList = field.getModifierList(); if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.FINAL)) { return field; } } } return null; }
private static boolean hasAnnotation( PsiModifierListOwner modifierListOwner, String qualifiedName) { PsiModifierList modifierList = modifierListOwner.getModifierList(); if (modifierList != null) { for (PsiAnnotation annotation : modifierList.getAnnotations()) { if (annotation instanceof ClsAnnotationImpl) { if (qualifiedName.equals(annotation.getQualifiedName())) { return true; } } } } return false; }
protected final void registerModifierError( @NotNull String modifier, @NotNull PsiModifierListOwner parameter, Object... infos) { final PsiModifierList modifiers = parameter.getModifierList(); if (modifiers == null) { return; } final PsiElement[] children = modifiers.getChildren(); for (final PsiElement child : children) { final String text = child.getText(); if (modifier.equals(text)) { registerError(child, infos); } } }
private static Collection<PsiClass> getClassesByAnnotation( String annotationName, Project project, GlobalSearchScope scope) { Collection<PsiClass> classes = Sets.newHashSet(); Collection<PsiAnnotation> annotations = JavaAnnotationIndex.getInstance().get(annotationName, project, scope); for (PsiAnnotation annotation : annotations) { PsiModifierList modifierList = (PsiModifierList) annotation.getParent(); PsiElement owner = modifierList.getParent(); if (owner instanceof PsiClass) { classes.add((PsiClass) owner); } } return classes; }
public static boolean isAnnotatedCheckHierarchyWithCache( @NotNull PsiClass aClass, @NotNull String annotationFQN) { Map<String, PsiClass> classMap = getSuperClassesWithCache(aClass); for (PsiClass psiClass : classMap.values()) { PsiModifierList modifierList = psiClass.getModifierList(); if (modifierList != null) { if (modifierList.findAnnotation(annotationFQN) != null) { return true; } } } return false; }
private static void makeMemberPackageLocal(PsiElement element) { final PsiElement parent = element.getParent(); final PsiReferenceExpression reference = (PsiReferenceExpression) parent; final PsiModifierListOwner member = (PsiModifierListOwner) reference.resolve(); if (member == null) { return; } final PsiModifierList modifiers = member.getModifierList(); if (modifiers == null) { return; } modifiers.setModifierProperty(PsiModifier.PUBLIC, false); modifiers.setModifierProperty(PsiModifier.PROTECTED, false); modifiers.setModifierProperty(PsiModifier.PRIVATE, false); }
private void changeModifierList(PsiModifierList modifierList) { try { modifierList.setModifierProperty(myModifier, myShouldHave); } catch (IncorrectOperationException e) { LOG.error(e); } }
private String format(PsiVariable variable, PsiModifierList modifierList) { String name = null; PsiElement parent = variable == null ? modifierList == null ? null : modifierList.getParent() : variable; if (parent instanceof PsiClass) { name = ((PsiClass) parent).getName(); } else { int options = PsiFormatUtilBase.SHOW_NAME | (myShowContainingClass ? PsiFormatUtilBase.SHOW_CONTAINING_CLASS : 0); if (parent instanceof PsiMethod) { name = PsiFormatUtil.formatMethod((PsiMethod) parent, PsiSubstitutor.EMPTY, options, 0); } else if (parent instanceof PsiVariable) { name = PsiFormatUtil.formatVariable((PsiVariable) parent, options, PsiSubstitutor.EMPTY); } else if (parent instanceof PsiClassInitializer) { PsiClass containingClass = ((PsiClassInitializer) parent).getContainingClass(); String className = containingClass instanceof PsiAnonymousClass ? QuickFixBundle.message( "anonymous.class.presentation", ((PsiAnonymousClass) containingClass).getBaseClassType().getPresentableText()) : containingClass != null ? containingClass.getName() : "unknown"; name = QuickFixBundle.message("class.initializer.presentation", className); } } String modifierText = VisibilityUtil.toPresentableText(myModifier); return QuickFixBundle.message( myShouldHave ? "add.modifier.fix" : "remove.modifier.fix", name, modifierText); }
public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); final PsiModifierList modifierList; if (element instanceof PsiModifierList) { modifierList = (PsiModifierList) element; } else { modifierList = (PsiModifierList) element.getParent(); } assert modifierList != null; if (modifierList.getParent() instanceof PsiClass) { modifierList.setModifierProperty(PsiModifier.STATIC, false); } else { modifierList.setModifierProperty(PsiModifier.PRIVATE, false); } }