dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.28k stars 1.58k forks source link

[Code] should be string interpolated to the code string #57064

Closed cedvdb closed 1 week ago

cedvdb commented 1 week ago

Currently using Code in an interpolated String will result in Instance of.. . In the context of macros, a more sensible option would be to override Code.toString() so string interpolatation returns a string that represents the actual code.

Use case:

Using strings is more readable than arrays in some cases. I wanted to do

RawCode.fromString('$valueReference.toIso8601String()')

but had to do:

RawCode.fromParts([valueReference, '.toIso8601String()']);

In place like here https://github.com/dart-lang/sdk/pull/57063/files#diff-e10def922b15028782e7fdcf395c5acab6f0cc2e86c1696a3e936eb775396d7aR638

dart-github-bot commented 1 week ago

Summary: The user wants to use a string instead of an array to represent code in the RawCode class, but the current API only accepts an array of parts. They suggest using a fromString constructor for better readability.

lrhn commented 1 week ago

The reason you cannot use a string interpolation is that it will eagerly create string at that point, and the macro processor doesn't know whether the reference will need an import prefix, or what it will be, until it has seen all the macro generated code. Passing the reference as an object allows the macro processor to recognize that a reference is made, and allows it to generate the best possible code for that reference at a later time, when more information is available.

cedvdb commented 1 week ago

I see. Maybe there is the possibility for a string lookalike, such as Code.fromCodeString(c'$code.doSomething') where c'...' would not be a string but it would look like one. Internally something like

factory Code.fromCodeString(CodeString stringLookalike) {
  return Code.fromParts(stringLookalike.toParts());
}

This may have been suggested elsewhere so I will close this as I just wanted to give my unimformed two cents.