sdk
sdk copied to clipboard
Types Generated using the LibraryTypesMacro throws an error when instantiating
I've been experimenting with the new feature Macros and I'm trying to use it to introduce a new class/Type in a library. The editor successfully shows me the library augment but I cannot instantiate this new class.
This was tested using the following:
macros: ^0.1.0-main.5usingDart SDK version: 3.5.0-180.3.beta (beta) (Wed Jun 5 15:06:15 2024 +0000) on "linux_x64"macros: ^0.1.2-main.4usingDart SDK version: 3.5.0-307.0.dev (dev) (None) on "linux_x64"
Minimally reproducible example:
- Create a new package
dart create -t package macro_library_bug - Edit the
analysis_options.yamlfile to enable macros
... redacted contents of analysis_options.yaml
analyzer:
enable-experiment:
- macros
- Edit the
pubspec.yamlfile and add a dependency on macros
... redacted contents of pubspec.yaml
dependencies:
macros: ^0.1.2-main.4
- Run
dart pub get - Edit the
lib/src/macro_library_bug_base.dartfile and create a new LibraryTypeMacro
import 'dart:async';
import 'package:macros/macros.dart';
macro class LibraryAnnotator implements LibraryTypesMacro{
const LibraryAnnotator();
@override
FutureOr<void> buildTypesForLibrary(Library library, TypeBuilder builder) {
final randomType = "MyLibType";
builder.declareType(randomType, DeclarationCode.fromParts([
"class $randomType {",
"\n\tconst $randomType();",
"\n}"
]));
}
}
- Edit the
lib/macro_library_bug.dartfile and annotate the library with@LibraryAnnotator()
@LibraryAnnotator()
library macro_library_bug;
import 'package:macro_library_bug/src/macro_library_bug_base.dart';
export 'src/macro_library_bug_base.dart';
- Edit the
example/macro_library_bug_example.dartfile
import 'package:macro_library_bug/macro_library_bug.dart';
void main() {
final newLibType = MyLibType();
print(newLibType);
}
- Run the example file with the command
dart --enable-experiment=macros example/macro_library_bug_example.dart
Expected Result
The console should show Instance of MyLibType
** Actual Result **
example/macro_library_bug_example.dart:4:9: Error: 'MyLibType' isn't a type.
final MyLibType newLibType = MyLibType();
^^^^^^^^^
example/macro_library_bug_example.dart:4:32: Error: Method not found: 'MyLibType'.
final MyLibType newLibType = MyLibType();
Summary: The LibraryTypesMacro generated type MyLibType is not recognized as a type when attempting to instantiate it in a separate file. The editor correctly shows the library augmentation, but the type is not available for use at runtime.
Looks like this is just not implemented in the front end, but is implemented in the analyzer (which is why you can see the class, but it isn't actually there when you run the app).
It is expected that you will run into unimplemented stuff at this time, which is why I marked the priority as P2 for now, but this definitely should get implemented prior to launch.