dart-lang / sdk

The Dart SDK, including the VM, dart2js, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
9.97k stars 1.53k forks source link

Auto-generate identifiers for `record_use` #56043

Open mosuem opened 3 weeks ago

mosuem commented 3 weeks ago

With the upcoming record_use feature, users can record usage of certain Dart objects by placing @RecordUse annotations on the objects. To retrieve the recordings, they need to provide the identifier of the object, a 3-tuple of URI, parent class, and name. This is a source of errors, as typos can be made, and the identifiers have to be updated whenever the annotations are placed elsewhere.

To alleviate this, we could auto-generate the IDs, for example using macros. Example:

//in lib/src/myfile.dart
class MyClass {
  @RecordUse
  static bool isPositive(int i) => i > 0; 
}

@RecordUse
class MyAnnotation {
  const MyAnnotation();
}

//in lib/src/ids.g.dart
const MyClass_isPositive_ID = Identifier(
  uri: 'package:mypackage/lib/src/myfile.dart',
  parent: 'MyClass',
  name: 'isPositive',
);

const MyAnnotation_ID = Identifier(
  uri: 'package:mypackage/lib/src/myfile.dart',
  name: 'MyAnnotation',
);

//in hook/link.dart
import '../lib/src/ids.g.dart';

void main(List<String> arguments){
  link(arguments, (config, output) async {
    final uses = config.recordedUses;

    final args = uses.constArgumentsTo(MyClass_isPositive_ID));

    final fields = uses.instanceReferencesTo(MyAnnotation_ID);

    ... // Do something with the information, such as tree-shaking native assets
  });
}

cc @dcharkes @mkustermann @jakemac53

jakemac53 commented 3 weeks ago

I don't know anything about the referenced record_use feature - but yes generating these identifiers should be trivial using a macro.