From a51bd20f306586770fa40dc19af30133dfd0d57f Mon Sep 17 00:00:00 2001 From: Nate Bosch Date: Mon, 7 Aug 2023 09:05:54 -0700 Subject: [PATCH] Add Expression.parenthesized (#425) We use `ParenthesizedExpression` internally in a few places where it's know that they are required, but some corners of the syntax require extra parenthesis in ways that are not feasible to detect in this library. Allow for explicit manual parenthesis. --- CHANGELOG.md | 1 + lib/code_builder.dart | 1 + lib/src/specs/expression.dart | 3 +++ test/specs/code/expression_test.dart | 9 +++++++++ 4 files changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d14fcb..0c5f78d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ * Add support for named arguments in `enum` classes * Add support for external keyword on fields. +* Add `Expression.parenthesized` to manually wrap an expression in parenthesis. ## 4.5.0 diff --git a/lib/code_builder.dart b/lib/code_builder.dart index 6cfaf6a..c98e19e 100644 --- a/lib/code_builder.dart +++ b/lib/code_builder.dart @@ -25,6 +25,7 @@ export 'src/specs/expression.dart' InvokeExpressionType, LiteralExpression, LiteralListExpression, + ParenthesizedExpression, ToCodeExpression, declareConst, declareFinal, diff --git a/lib/src/specs/expression.dart b/lib/src/specs/expression.dart index 275404e..1b92557 100644 --- a/lib/src/specs/expression.dart +++ b/lib/src/specs/expression.dart @@ -331,6 +331,9 @@ abstract class Expression implements Spec { /// May be overridden to support other types implementing [Expression]. @visibleForOverriding Expression get expression => this; + + /// Returns this expression wrapped in parenthesis. + ParenthesizedExpression get parenthesized => ParenthesizedExpression._(this); } /// Declare a const variable named [variableName]. diff --git a/test/specs/code/expression_test.dart b/test/specs/code/expression_test.dart index 2f2576a..7e2ee01 100644 --- a/test/specs/code/expression_test.dart +++ b/test/specs/code/expression_test.dart @@ -731,4 +731,13 @@ void main() { .assign(refer('bar')), equalsDart('late String foo = bar')); }); + + test('should emit a perenthesized epression', () { + expect( + refer('foo').ifNullThen(refer('FormatException') + .newInstance([literalString('missing foo')]) + .thrown + .parenthesized), + equalsDart('foo ?? (throw FormatException(\'missing foo\'))')); + }); }