language icon indicating copy to clipboard operation
language copied to clipboard

Metadata on primary constructor parameters.

Open lrhn opened this issue 2 years ago • 0 comments

A primary constructor declares "parameters" that implicitly define both constructor parameters and fields (instance variables).

We allow metadata on both constructor parameters and fields. If someone wants to apply metadata to either the field or the constructor parameter, they'd have to put it on the primary constructor parameter.

Annotation/metadata processing tools will have to figure out what that means. If the tool sees the desugared AST with synthetic fields and constructors, the parsing/desugaring logic will have to decide whether to duplicate the metadata from the primary constructor on one or both. If the tool sees the original source AST, it will need to understand primary constructors, and then itself decide what to do with the metadata.

That's not necessarily a problem, but we need to ensure that our own tools do something meaningful. In particular, the analyzer, which I believe is used as the core of most annotation processing tools, should decide what to do if it presents a desugared AST. (I do not know if it will.)

We currently have annotations on annotations to signal where they can be meaningfully applied. An annotation which uses that to say that it applies to parameters only, or to fields only, can be correctly copied only to the constructor parameter, or field, that it applies to, and not to the other one.

That also suggests that primary constructor parameters should accept annotations with both @Target(TargetKind.field) and @Target(TargetKind.parameter).

We could consider moving the Target annotation into dart:core (maybe tweak it a little, I'd like a @Target<SomeType>(target) to restrict the annotation to certain types too, now that we allow generic annotations). If the annotation is going to interact visibly with the meaning of a language feature, it might just belongs in the platform libraries. (On the other hand, if we drop dart:mirrors, there won't be any run-time way to access metadata, and then the platform runtime system doesn't need to understand Target.)

See also: https://github.com/dart-lang/sdk/issues/46844 for a similar issue. That's basically someone implementing a primary constructor-like functionality using code-gen, and having a problem with field-related metadata not working on the constructor parameters.

lrhn avatar Aug 10 '22 09:08 lrhn