Sdk: invalid_annotation_target hints are not shown when top-level variable is used as annotation

Created on 16 Oct 2020  路  2Comments  路  Source: dart-lang/sdk

It's common practice for an annotation without parameters to be defined as a private class which is exposed as a public top-level variable:

const myAnnotation = _MyAnnotation();

class _MyAnnotation() {
  const _MyAnnotation();
}
import 'my_annotation.dart';

@myAnnotation
class MyClass {}

The new @Target annotation is a fantastic idea for enforcing correct usage of annotations. Unfortunately, the hints produced by this annotation (invalid_annotation_target) only occur when the annotation is used as a constructor and not as a top-level variable:

import 'package:meta/meta_meta.dart';

const myAnnotation = MyAnnotation();

@Target({TargetKind.classType})
class MyAnnotation() {
  const MyAnnotation();
}
import 'my_annotation.dart';

@myAnnotation // Hint is *NOT* produced for this incorrect target.
void f() {}

@MyAnnotation()
// ^^^^^^^^^^
// The annotation 'MyAnnotation' can only be used on classes [invalid_annotation_target]
void g() {}

I'd expect the invalid_annotation_target hint to be produced, regardless of how the annotation is consumed.

Version info

  • Dart SDK version: 2.11.337292321-edge+google3-v2 (google3) (google3) on "linux_x64"
analyzer-hint customer-google3 type-bug

Most helpful comment

Sorry for the bug, but thanks for letting us know! This should be fixed by https://dart-review.googlesource.com/c/sdk/+/168126

All 2 comments

Sorry for the bug, but thanks for letting us know! This should be fixed by https://dart-review.googlesource.com/c/sdk/+/168126

Thank you for the quick fix!

Was this page helpful?
0 / 5 - 0 ratings