@Nullable Resolution getResolutionFrom(PsiField field) { PsiAnnotation annotation = scenarioStateProvider.getJGivenAnnotationOn(field); if (annotation == null) { return null; } PsiExpression annotationValue = annotationValueProvider.getAnnotationValue(annotation, FIELD_RESOLUTION); return Optional.ofNullable(annotationValue) .map(PsiElement::getText) .map(t -> { for (Resolution resolution : Resolution.values()) { if (resolution != Resolution.AUTO && t.contains(resolution.name())) { return resolution; } } return getResolutionForFieldType(field); }).orElse(getResolutionForFieldType(field)); }
private void addAnnotationToPackageInfo(Project project, PsiJavaFile packageInfoFile) { if (!FileModificationService.getInstance().preparePsiElementForWrite(packageInfoFile)) { return; } PsiPackageStatement packageStatement = packageInfoFile.getPackageStatement(); if (packageStatement == null) { return; } PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiAnnotation annotation = factory.createAnnotationFromText("@" + annotationForTypeQualifierFqn, packageInfoFile.getContext()); PsiElement addedAnnotation = packageInfoFile.addBefore(annotation, packageStatement); JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedAnnotation); removeRedundantAnnotationsInPackage(project, packageInfoFile.getContainingDirectory().getFiles(), annotation); }
@Nullable private static Set<PsiAnnotation.TargetType> targetTypesForDefault(PsiAnnotation annotation) { PsiJavaCodeReferenceElement element = annotation.getNameReferenceElement(); PsiElement declaration = element == null ? null : element.resolve(); if (!(declaration instanceof PsiClass)) { return Collections.emptySet(); } PsiClass classDeclaration = (PsiClass) declaration; PsiAnnotation tqDefault = AnnotationUtil.findAnnotation(classDeclaration, true, TYPE_QUALIFIER_DEFAULT); if (tqDefault == null) { return Collections.emptySet(); } return extractRequiredAnnotationTargets(tqDefault.findAttributeValue(null)); }
static List<String> findAnnotations(PsiModifierListOwner element, boolean nullable) { if (overridesSuper(element)) { return Collections.emptyList(); } List<String> annotations = new ArrayList<>(); Project project = element.getProject(); PsiModifierList modifierList = element.getModifierList(); List<String> nullabilityAnnotations = nullable ? NullableNotNullManager.getInstance(project).getNullables() : NullableNotNullManager.getInstance(project).getNotNulls(); for (String notNullAnnotationFqn : nullabilityAnnotations) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiAnnotation annotation = factory.createAnnotationFromText("@" + notNullAnnotationFqn, null); PsiAnnotation.TargetType[] targetTypes = getTargetsForLocation(modifierList); if (isNullabilityAnnotationForTypeQualifierDefault(annotation, nullable, targetTypes)) { annotations.add(annotation.getQualifiedName()); } } return annotations; }
private static boolean isNullabilityAnnotationForTypeQualifierDefault(PsiAnnotation annotation, boolean nullable, PsiAnnotation.TargetType[] targetTypes) { PsiJavaCodeReferenceElement element = annotation.getNameReferenceElement(); PsiElement declaration = element == null ? null : element.resolve(); if (!(declaration instanceof PsiClass)) { return false; } String fqn = nullable ? JAVAX_ANNOTATION_NULLABLE : JAVAX_ANNOTATION_NONNULL; PsiClass classDeclaration = (PsiClass) declaration; if (!AnnotationUtil.isAnnotated(classDeclaration, fqn, false, true)) { return false; } PsiAnnotation tqDefault = AnnotationUtil.findAnnotation(classDeclaration, true, TYPE_QUALIFIER_DEFAULT); if (tqDefault == null) { return false; } Set<PsiAnnotation.TargetType> required = extractRequiredAnnotationTargets(tqDefault.findAttributeValue(null)); return required != null && (required.isEmpty() || ContainerUtil.intersects(required, Arrays.asList(targetTypes))); }
@Override public void visitClass(UClass uClass) { //only check interface if(!uClass.isInterface()){ return; } Set<PropInfo> infos = getPropInfoWithSupers(uClass); if(infos.isEmpty()){ return; } //check method is relative of any field for(UMethod method: uClass.getMethods()){ PsiModifierList list = method.getModifierList(); PsiAnnotation pa_keep = list.findAnnotation(NAME_KEEP); PsiAnnotation pa_impl = list.findAnnotation(NAME_IMPL_METHOD); if (pa_keep == null && pa_impl == null) { if(!hasPropInfo(infos, method.getName())){ report(method); } } } }
public static PsiElement find( PsiModifierListOwner resolve, ManifoldPsiClass facade ) { PsiModifierList modifierList = resolve.getModifierList(); if( modifierList == null ) { return null; } PsiAnnotation[] annotations = modifierList.getAnnotations(); if( annotations.length > 0 && Objects.equals( annotations[0].getQualifiedName(), SourcePosition.class.getName() ) ) { return findTargetFeature( annotations[0], facade ); } if( !facade.getRawFiles().isEmpty() && DarkJavaTypeManifold.FILE_EXTENSIONS.stream() .anyMatch( ext -> ext.equalsIgnoreCase( facade.getRawFiles().get( 0 ).getVirtualFile().getExtension() ) ) ) { // DarkJava is Java return facade.getRawFiles().get( 0 ).findElementAt( resolve.getTextOffset() ); } return null; }
private void errrantThisOrExtension( PsiElement element, AnnotationHolder holder ) { if( element instanceof PsiModifierList ) { PsiModifierList mods = (PsiModifierList)element; PsiAnnotation annotation; if( (annotation = mods.findAnnotation( Extension.class.getName() )) != null || (annotation = mods.findAnnotation( This.class.getName() )) != null) { TextRange range = new TextRange( annotation.getTextRange().getStartOffset(), annotation.getTextRange().getEndOffset() ); //noinspection ConstantConditions holder.createErrorAnnotation( range, ExtIssueMsg.MSG_NOT_IN_EXTENSION_CLASS.get( ClassUtil.extractClassName( annotation.getQualifiedName() ) ) ); } } }
private boolean isStructuralType( PsiTypeElement typeElem ) { if( typeElem != null ) { PsiClass psiClass = PsiUtil.resolveClassInType( typeElem.getType() ); if( psiClass == null ) { return false; } PsiAnnotation structuralAnno = psiClass.getModifierList() == null ? null : psiClass.getModifierList().findAnnotation( "manifold.ext.api.Structural" ); if( structuralAnno != null ) { return true; } } return false; }
private static boolean isJavaElementForType( PsiModifierListOwner modifierListOwner, PsiClass psiClass ) { PsiAnnotation annotation = modifierListOwner.getModifierList().findAnnotation( TypeReference.class.getName() ); if( annotation != null ) { PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes(); for( PsiNameValuePair pair : attributes ) { String fqn = pair.getLiteralValue(); if( psiClass.getQualifiedName().contains( fqn ) ) { return true; } } } return false; }
static PsiAnnotation findAnnotation(PsiElement element, String annotationName) { if (element instanceof PsiModifierListOwner) { PsiModifierListOwner listOwner = (PsiModifierListOwner) element; PsiModifierList modifierList = listOwner.getModifierList(); if (modifierList != null) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { if (annotationName.equals(psiAnnotation.getQualifiedName())) { return psiAnnotation; } } } } return null; }
@Override public PsiAnnotation getPsiElement() { PsiAnnotation annotation = SoftReference.dereference(myParsedFromRepository); if (annotation != null) { return annotation; } final String text = getText(); try { PsiJavaParserFacade facade = JavaPsiFacade.getInstance(getProject()).getParserFacade(); annotation = facade.createAnnotationFromText(text, getPsi()); myParsedFromRepository = new SoftReference<PsiAnnotation>(annotation); return annotation; } catch (IncorrectOperationException e) { LOG.error("Bad annotation in repository!", e); return null; } }
@Override public boolean isAvailable(@NotNull final Project project, Editor editor, PsiFile file) { final PsiElement leaf = file.findElementAt(editor.getCaretModel().getOffset()); final PsiModifierListOwner owner = getAnnotationOwner(leaf); if (owner != null && isSourceCode(owner)) { boolean hasSrcInferredAnnotation = ContainerUtil.or(findSignatureNonCodeAnnotations(owner, true), new Condition<PsiAnnotation>() { @Override public boolean value(PsiAnnotation annotation) { return AnnotationUtil.isInferredAnnotation(annotation); } }); if (hasSrcInferredAnnotation) { setText((CodeInsightSettings.getInstance().SHOW_SOURCE_INFERRED_ANNOTATIONS ? "Hide" : "Show") + " annotations inferred from source code"); return true; } } return false; }
@NotNull public static Result render(@Nullable ResourceIdResolver resolver, @NotNull PsiAnnotation annotation, int value) { String qualifiedName = getQualifiedName(annotation); if (qualifiedName == null) { return renderUnknown(null, value); } if (SupportAnnotationDetector.COLOR_INT_ANNOTATION.equals(qualifiedName)) { return renderColorInt(value); } else if (qualifiedName.endsWith(SupportAnnotationDetector.RES_SUFFIX)) { return renderResourceRefAnnotation(resolver, value, qualifiedName); } else if (qualifiedName.equals(SdkConstants.INT_DEF_ANNOTATION)) { return renderIntDefAnnotation(annotation, value); } return renderUnknown(qualifiedName, value); }
@NotNull private static Result renderIntDefAnnotation(@NotNull final PsiAnnotation annotation, final int value) { final AtomicReference<AndroidResolveHelper.IntDefResolution> valuesRef = Atomics.newReference(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { valuesRef.set(AndroidResolveHelper.resolveIntDef(annotation)); } }); AndroidResolveHelper.IntDefResolution intDef = valuesRef.get(); if (intDef.valuesMap == null) { renderUnknown("IntDef", value); } return new Result(String.format(Locale.US, "0x%1$08x {%2$s}", value, renderIntDef(value, intDef)), null); }
public void testColorInt() { @Language("JAVA") String text = "package p1.p2;\n" + "\n" + "public class Foo {\n" + " @android.support.annotation.ColorInt int mColor;\n" + " \n" + " public void setColor(@android.support.annotation.ColorInt int c) {\n" + " mColor = <caret>c;\n" + " }\n" + "}\n"; PsiElement element = getPsiElement(text); assertNotNull(element); PsiAnnotation annotation = AndroidResolveHelper.getAnnotationForLocal(element, "c"); assertNotNull(annotation); assertEquals(SupportAnnotationDetector.COLOR_INT_ANNOTATION, annotation.getQualifiedName()); annotation = AndroidResolveHelper.getAnnotationForField(element, "p1.p2.Foo", "mColor"); assertNotNull(annotation); assertEquals(SupportAnnotationDetector.COLOR_INT_ANNOTATION, annotation.getQualifiedName()); }
@NotNull @Override protected InspectionGadgetsFix[] buildFixes(Object... infos) { final boolean suppressionIdPresent = ((Boolean)infos[1]).booleanValue(); if (infos[0] instanceof PsiAnnotation) { final PsiAnnotation annotation = (PsiAnnotation)infos[0]; return suppressionIdPresent ? new InspectionGadgetsFix[]{new DelegatingFix(new RemoveAnnotationQuickFix(annotation, null)), new AllowSuppressionsFix()} : new InspectionGadgetsFix[]{new DelegatingFix(new RemoveAnnotationQuickFix(annotation, null))}; } else if (infos[0] instanceof PsiComment) { return suppressionIdPresent ? new InspectionGadgetsFix[]{new RemoveSuppressCommentFix(), new AllowSuppressionsFix()} : new InspectionGadgetsFix[]{new RemoveSuppressCommentFix()}; } return InspectionGadgetsFix.EMPTY_ARRAY; }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement psiElement = descriptor.getPsiElement(); final Iterable<String> ids; if (psiElement instanceof PsiAnnotation) { ids = JavaSuppressionUtil.getInspectionIdsSuppressedInAnnotation((PsiModifierList)psiElement.getParent()); } else { final String suppressedIds = JavaSuppressionUtil.getSuppressedInspectionIdsIn(psiElement); if (suppressedIds == null) { return; } ids = StringUtil.tokenize(suppressedIds, ","); } for (String id : ids) { if (!myAllowedSuppressions.contains(id)) { myAllowedSuppressions.add(id); } } saveProfile(project); }
@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; }
@Override public void visitAnnotation(PsiAnnotation annotation) { super.visitAnnotation(annotation); final String qualifiedName = annotation.getQualifiedName(); if (StringUtils.isNotBlank(qualifiedName) && allProblemHandlers.containsKey(qualifiedName)) { final Collection<SqliteMagicProblem> problems = new HashSet<SqliteMagicProblem>(); for (Processor inspector : allProblemHandlers.get(qualifiedName)) { problems.addAll(inspector.verifyAnnotation(annotation)); } for (SqliteMagicProblem problem : problems) { holder.registerProblem(annotation, problem.getMessage(), problem.getHighlightType(), problem.getQuickFixes()); } } }
@Override public ProblemDescriptor[] checkClass( @NotNull PsiClass psiClass, @NotNull InspectionManager manager, boolean isOnTheFly ) { PsiAnnotation mixinsAnnotation = getMixinsAnnotation( psiClass ); if( mixinsAnnotation == null ) { return null; } if( psiClass.isInterface() ) { return null; } String message = message( "mixins.annotation.declared.on.mixin.type.error.declared.on.class" ); RemoveInvalidMixinClassReferenceFix fix = new RemoveInvalidMixinClassReferenceFix( mixinsAnnotation ); ProblemDescriptor problemDescriptor = manager.createProblemDescriptor( mixinsAnnotation, message, fix, GENERIC_ERROR_OR_WARNING ); return new ProblemDescriptor[]{ problemDescriptor }; }
@Nullable protected final ProblemDescriptor[] verifyAnnotationDeclaredCorrectly( @NotNull PsiVariable psiVariable, @NotNull PsiAnnotation structureAnnotation, @NotNull InspectionManager manager ) { StructureAnnotationDeclarationValidationResult annotationCheck = validateStructureAnnotationDeclaration( psiVariable ); switch( annotationCheck ) { case invalidInjectionType: String message = message( "injections.structure.annotation.declared.correctly.error.invalid.injection.type", psiVariable.getType().getCanonicalText() ); AbstractFix removeStructureAnnotationFix = createRemoveAnnotationFix( structureAnnotation ); ProblemDescriptor problemDescriptor = manager.createProblemDescriptor( structureAnnotation, message, removeStructureAnnotationFix, GENERIC_ERROR_OR_WARNING ); return new ProblemDescriptor[]{ problemDescriptor }; } return null; }
private void addOwnerDomainAttribute( @NotNull final Project project, final PsiAnnotation annotation) { new WriteCommandAction(project, annotation.getContainingFile()) { @Override protected void run(final Result result) throws Throwable { // @A(ownerDomain = "your-company.com") PsiAnnotationMemberValue newMemberValue = JavaPsiFacade.getInstance(project) .getElementFactory() .createAnnotationFromText( "@A(" + API_NAMESPACE_DOMAIN_ATTRIBUTE + " = \"" + SUGGESTED_DOMAIN_ATTRIBUTE + "\")", null) .findDeclaredAttributeValue(API_NAMESPACE_DOMAIN_ATTRIBUTE); annotation.setDeclaredAttributeValue(API_NAMESPACE_DOMAIN_ATTRIBUTE, newMemberValue); } }.execute(); }
private void addOwnerNameAttribute( @NotNull final Project project, final PsiAnnotation annotation) { new WriteCommandAction(project, annotation.getContainingFile()) { @Override protected void run(final Result result) throws Throwable { // @A(ownerName = "YourCo") PsiAnnotationMemberValue newMemberValue = JavaPsiFacade.getInstance(project) .getElementFactory() .createAnnotationFromText( "@A(" + API_NAMESPACE_NAME_ATTRIBUTE + " = \"" + SUGGESTED_OWNER_ATTRIBUTE + "\")", null) .findDeclaredAttributeValue(API_NAMESPACE_NAME_ATTRIBUTE); annotation.setDeclaredAttributeValue(API_NAMESPACE_NAME_ATTRIBUTE, newMemberValue); } }.execute(); }
private String getAttributeFromAnnotation( PsiAnnotation annotation, String annotationType, final String attribute) throws InvalidAnnotationException, MissingAttributeException { String annotationQualifiedName = annotation.getQualifiedName(); if (annotationQualifiedName == null) { throw new InvalidAnnotationException(annotation, annotationType); } if (annotationQualifiedName.equals(annotationType)) { PsiAnnotationMemberValue annotationMemberValue = annotation.findAttributeValue(attribute); if (annotationMemberValue == null) { throw new MissingAttributeException(annotation, attribute); } String httpMethodWithQuotes = annotationMemberValue.getText(); return httpMethodWithQuotes.substring(1, httpMethodWithQuotes.length() - 1); } else { throw new InvalidAnnotationException(annotation, annotationType); } }
private boolean hasParameterName(PsiParameter psiParameter) { PsiModifierList modifierList = psiParameter.getModifierList(); if (modifierList == null) { return false; } PsiAnnotation annotation = modifierList.findAnnotation("javax.inject.Named"); if (annotation != null) { return true; } annotation = modifierList.findAnnotation(GctConstants.APP_ENGINE_ANNOTATION_NAMED); if (annotation != null) { return true; } return false; }
/** * Tests that the FullMethodNameInspection's quick fix updates the name attribute of {@link * GctConstants.APP_ENGINE_ANNOTATION_API_METHOD} by adding "_1" as a suffix. */ public void testQuickFix_ApiMethodAnnotation() { Project myProject = myFixture.getProject(); String annotationString = "@" + GctConstants.APP_ENGINE_ANNOTATION_API_METHOD + "(name = \"someName\")"; PsiAnnotation annotation = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createAnnotationFromText(annotationString, null); FullMethodNameInspection.MyQuickFix myQuickFix = new FullMethodNameInspection().new MyQuickFix(); MockProblemDescriptor problemDescriptor = new MockProblemDescriptor(annotation, "", ProblemHighlightType.ERROR); myQuickFix.applyFix(myProject, problemDescriptor); Assert.assertEquals( "@" + GctConstants.APP_ENGINE_ANNOTATION_API_METHOD + "(name = \"someName_1\")", annotation.getText()); }
/** * Tests that the FullMethodNameInspection's quick fix does not update an annotation that is not * {@link GctConstants.APP_ENGINE_ANNOTATION_API_METHOD} */ public void testQuickFix_NonApiMethodAnnotation() { Project myProject = myFixture.getProject(); String annotationString = "@" + GctConstants.APP_ENGINE_ANNOTATION_NAMED + "(name = \"someName\")"; PsiAnnotation annotation = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createAnnotationFromText(annotationString, null); FullMethodNameInspection.MyQuickFix myQuickFix = new FullMethodNameInspection().new MyQuickFix(); MockProblemDescriptor problemDescriptor = new MockProblemDescriptor(annotation, "", ProblemHighlightType.ERROR); myQuickFix.applyFix(myProject, problemDescriptor); Assert.assertEquals(annotationString, annotation.getText()); }
private void initializePsiMethod(String methodName, String httpMethodValue, String pathValue) { PsiAnnotationMemberValue mockAnnotationMemberValue1 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue1.getText()).thenReturn(httpMethodValue); PsiAnnotationMemberValue mockAnnotationMemberValue2 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue2.getText()).thenReturn(pathValue); PsiAnnotation mockAnnotation = mock(PsiAnnotation.class); when(mockAnnotation.getQualifiedName()) .thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API_METHOD); when(mockAnnotation.findAttributeValue("httpMethod")).thenReturn(mockAnnotationMemberValue1); when(mockAnnotation.findAttributeValue("path")).thenReturn(mockAnnotationMemberValue2); PsiAnnotation[] mockAnnotationsArray = {mockAnnotation}; PsiModifierList mockModifierList = mock(PsiModifierList.class); when(mockModifierList.getAnnotations()).thenReturn(mockAnnotationsArray); mockPsiMethod = mock(PsiMethod.class); when(mockPsiMethod.getModifierList()).thenReturn(mockModifierList); when(mockPsiMethod.getName()).thenReturn(methodName); when(mockPsiMethod.getContainingClass()).thenReturn(mockPsiClass); PsiParameterList mockParameterList = mock(PsiParameterList.class); when(mockParameterList.getParameters()).thenReturn(new PsiParameter[0]); when(mockPsiMethod.getParameterList()).thenReturn(mockParameterList); }
private void initializePsiClass(String apiResource, String apiClassResource) { PsiAnnotationMemberValue mockAnnotationMemberValue1 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue1.getText()).thenReturn(apiResource); PsiAnnotationMemberValue mockAnnotationMemberValue2 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue2.getText()).thenReturn(apiClassResource); // Mock @Api(resource = "") PsiAnnotation mockAnnotation1 = mock(PsiAnnotation.class); when(mockAnnotation1.getQualifiedName()).thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API); when(mockAnnotation1.findAttributeValue("resource")).thenReturn(mockAnnotationMemberValue1); // Mock @ApiClass(resource = "") PsiAnnotation mockAnnotation2 = mock(PsiAnnotation.class); when(mockAnnotation2.getQualifiedName()) .thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API_CLASS); when(mockAnnotation2.findAttributeValue("resource")).thenReturn(mockAnnotationMemberValue2); PsiAnnotation[] mockAnnotationsArray = {mockAnnotation1, mockAnnotation2}; PsiModifierList mockModifierList = mock(PsiModifierList.class); when(mockModifierList.getAnnotations()).thenReturn(mockAnnotationsArray); mockPsiClass = mock(PsiClass.class); when(mockPsiClass.getModifierList()).thenReturn(mockModifierList); }
/** * Tests that the NamedResourceInspection's quick fix flagged with {@link * NamedResourceError#DUPLICATE_PARAMETER} for an @Named annotation updates the query name by * adding "_1" as a suffix. */ public void testQuickFix_duplicateParameter() { Project myProject = myFixture.getProject(); String annotationString = "@" + GctConstants.APP_ENGINE_ANNOTATION_NAMED + "(\"someName\")"; PsiAnnotation annotation = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createAnnotationFromText(annotationString, null); NamedResourceInspection.DuplicateNameQuickFix myQuickFix = new NamedResourceInspection().new DuplicateNameQuickFix(); MockProblemDescriptor problemDescriptor = new MockProblemDescriptor(annotation, "", ProblemHighlightType.ERROR); myQuickFix.applyFix(myProject, problemDescriptor); assertEquals( "@" + GctConstants.APP_ENGINE_ANNOTATION_NAMED + "(\"someName_1\")", annotation.getText()); }
/** * Tests that the NamedResourceInspection's quick fix flagged with {@link * NamedResourceError#MISSING_NAME} for an @Named annotation with no parent updates the query name * to "myName". */ public void testQuickFix_noQueryNameSpecifiedWithoutParameter() { Project myProject = myFixture.getProject(); String annotationString = "@" + GctConstants.APP_ENGINE_ANNOTATION_NAMED + "()"; PsiAnnotation annotation = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createAnnotationFromText(annotationString, null); NamedResourceInspection.MissingNameQuickFix myQuickFix = new NamedResourceInspection().new MissingNameQuickFix(); MockProblemDescriptor problemDescriptor = new MockProblemDescriptor(annotation, "", ProblemHighlightType.ERROR); myQuickFix.applyFix(myProject, problemDescriptor); assertEquals( "@" + GctConstants.APP_ENGINE_ANNOTATION_NAMED + "(\"myName\")", annotation.getText()); }
/** * Tests that the NamedResourceInspection's quick fix flagged with {@link * NamedResourceError#MISSING_NAME} for an @Named annotation with a {@link PsiParameter} parent * updates the query name to to the name of the {@link PsiParameter}. */ public void testQuickFix_noQueryNameSpecifiedWithParameter() { Project myProject = myFixture.getProject(); PsiParameter parameter = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createParameterFromText("@javax.inject.Named() String foobar", null); PsiAnnotation[] annotationsList = parameter.getModifierList().getAnnotations(); assert (annotationsList.length == 1); NamedResourceInspection.MissingNameQuickFix myQuickFix = new NamedResourceInspection().new MissingNameQuickFix(); MockProblemDescriptor problemDescriptor = new MockProblemDescriptor(annotationsList[0], "", ProblemHighlightType.ERROR); myQuickFix.applyFix(myProject, problemDescriptor); assertEquals("@javax.inject.Named(\"foobar\")", annotationsList[0].getText()); }
@Override public final void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { final PsiModifierList modifierList = element.getModifierList(); if(modifierList == null) { return; } for(final PsiAnnotation annotation : modifierList.getAnnotations()) { if(isAnnotation(annotation)) { annotation.delete(); } } }
@Override public boolean isMemberInplaceRenameAvailable(@NotNull final PsiElement elementToRename, final PsiElement context) { // disable in-place rename for @Inject and @Macro annotations // since it does weird stuff at the moment (qualified name is truncated) final PsiAnnotation annotation = PsiTreeUtil.getParentOfType(context, PsiAnnotation.class); //noinspection SimplifiableIfStatement if( annotation == null || !(isMacroAnnotation(annotation) || isInjectAnnotation(annotation))) { return super.isMemberInplaceRenameAvailable(elementToRename, context); } else { return false; } }
@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) || !GroovyRefactoringUtil.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 updateContract(PsiMethod method, String contract, boolean pure) { Project project = method.getProject(); ExternalAnnotationsManager manager = ExternalAnnotationsManager.getInstance(project); manager.deannotate(method, ControlFlowAnalyzer.ORG_JETBRAINS_ANNOTATIONS_CONTRACT); PsiAnnotation mockAnno = InferredAnnotationsManagerImpl.createContractAnnotation(project, pure, contract); if(mockAnno != null) { try { manager.annotateExternally(method, ControlFlowAnalyzer.ORG_JETBRAINS_ANNOTATIONS_CONTRACT, method.getContainingFile(), mockAnno.getParameterList().getAttributes()); } catch(ExternalAnnotationsManager.CanceledConfigurationException ignored) { } } DaemonCodeAnalyzer.getInstance(project).restart(); }
public boolean validate(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull PsiType psiType, @NotNull PsiAnnotation psiAnnotation, @NotNull ProblemBuilder builder) { boolean result = true; if (psiModifierListOwner.hasModifierProperty(PsiModifier.STATIC)) { builder.addError("@Delegate is legal only on instance fields or no-argument instance methods."); result = false; } final Collection<PsiType> types = collectDelegateTypes(psiAnnotation, psiType); result &= validateTypes(types, builder); final Collection<PsiType> excludes = collectExcludeTypes(psiAnnotation); result &= validateTypes(excludes, builder); return result; }
@NotNull @Override public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) { // TODO warning: "You're assigning an auto-cleanup variable to something else. This is a bad idea." final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(2); PsiLocalVariable psiVariable = PsiTreeUtil.getParentOfType(psiAnnotation, PsiLocalVariable.class); if (null != psiVariable) { final String cleanupName = PsiAnnotationUtil.getStringAnnotationValue(psiAnnotation, "value"); if (StringUtil.isEmptyOrSpaces(cleanupName)) { problemNewBuilder.addError("'@Cleanup': value cannot be the empty string"); } else { validateCleanUpMethodExists(psiVariable, cleanupName, problemNewBuilder); } validateInitializerExist(problemNewBuilder, psiVariable); } else { problemNewBuilder.addError("'@Cleanup' is legal only on local variable declarations"); } return problemNewBuilder.getProblems(); }