Skip to content

Commit

Permalink
Add Expression.parenthesized (#425)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
natebosch committed Aug 7, 2023
1 parent 7707960 commit a51bd20
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions lib/code_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export 'src/specs/expression.dart'
InvokeExpressionType,
LiteralExpression,
LiteralListExpression,
ParenthesizedExpression,
ToCodeExpression,
declareConst,
declareFinal,
Expand Down
3 changes: 3 additions & 0 deletions lib/src/specs/expression.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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].
Expand Down
9 changes: 9 additions & 0 deletions test/specs/code/expression_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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\'))'));
});
}

0 comments on commit a51bd20

Please sign in to comment.