dart-lang / code_builder

A fluent API for generating valid Dart source code
https://pub.dev/packages/code_builder
BSD 3-Clause "New" or "Revised" License
423 stars 66 forks source link

Allow passing an `Expression` through `literal` #433

Closed natebosch closed 9 months ago

natebosch commented 9 months ago

The LiteralListExpression allows a mix of Dart values which could be passed to literal and values which are already a Spec (typically an Expression). Both types are handled by _acceptLiteral in the visitor implementation.

https://github.com/dart-lang/code_builder/blob/eb70874cf05427879ec47d8726eb3173e11880e3/lib/src/specs/expression.dart#L622-L628

The toString() for LiteralListExpression calls literal on each value in the list, which previously would throw if it was passed an Expression. Some tests for builders and their implementation details use .toString() in their user facing failure messages. When there is an exception creating the message for a failure, it can mask the cause of the failure.

Allow more flexibility for this toString by allowing Expression instances to flow through literal unchanged. This still does not handle non-expression Spec instances, but those are not likely to come up in practice.

Collapse the conditional returns in literal to a single line each. The pattern is easier to read with less vertical space.

Add tests for literal passing each type it accepts, and a test for the error behavior.

Add a regression test for the toString of a list literal not throwing when one of the values of the list is an Expression.