diff --git a/CHANGELOG.md b/CHANGELOG.md index c16cccd..d82ab65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,34 @@ -## 2.1.1-dev +## 2.2.0-dev * Imports are prefixed with `_i1` rather than `_1` which satisfies the lint - `lowercase_with_underscores`. + `lowercase_with_underscores`. While not a strictly breaking change you may + have to fix/regenerate golden file-like tests. We added documentation that + the specific prefix is not considered stable. + +* Added `Expression.index` for accessing the `[]` operator: + +```dart +void main() { + test('should emit an index operator', () { + expect( + refer('bar').index(literalTrue).assignVar('foo').statement, + equalsDart('var foo = bar[true];'), + ); +} ); + + test('should emit an index operator set', () { + expect( + refer('bar') + .index(literalTrue) + .assign(literalFalse) + .assignVar('foo') + .statement, + equalsDart('var foo = bar[true] = false;'), + ); + }); +} +``` + * `literalList` accepts an `Iterable` argument. ## 2.1.0 diff --git a/lib/src/specs/expression.dart b/lib/src/specs/expression.dart index c1ae450..50d3ec6 100644 --- a/lib/src/specs/expression.dart +++ b/lib/src/specs/expression.dart @@ -45,6 +45,19 @@ abstract class Expression implements Spec { return new BinaryExpression._(expression, other, '&&'); } + /// Returns accessing the index operator (`[]`) on `this`. + Expression index(Expression index) { + return new BinaryExpression._( + expression, + new CodeExpression(new Block.of([ + const Code('['), + index.code, + const Code(']'), + ])), + '', + ); + } + /// This expression preceded by `await`. Expression get awaited { return new BinaryExpression._( diff --git a/pubspec.yaml b/pubspec.yaml index 2407864..0e58701 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: code_builder -version: 2.1.1-dev +version: 2.2.0-dev description: A fluent API for generating Dart code author: Dart Team homepage: https://github.com/dart-lang/code_builder diff --git a/test/specs/code/expression_test.dart b/test/specs/code/expression_test.dart index 3aa724c..7cf5845 100644 --- a/test/specs/code/expression_test.dart +++ b/test/specs/code/expression_test.dart @@ -266,6 +266,35 @@ void main() { ); }); + test('should emit an index operator', () { + expect( + refer('bar').index(literalString('key')).assignVar('foo').statement, + equalsDart("var foo = bar['key'];"), + ); + }); + + test('should emit an index operator set', () { + expect( + refer('bar') + .index(literalString('key')) + .assign(literalFalse) + .assignVar('foo') + .statement, + equalsDart("var foo = bar['key'] = false;"), + ); + }); + + test('should emit a null-aware index operator set', () { + expect( + refer('bar') + .index(literalTrue) + .assignNullAware(literalFalse) + .assignVar('foo') + .statement, + equalsDart('var foo = bar[true] ??= false;'), + ); + }); + test('should emit assigning to a var', () { expect( literalTrue.assignVar('foo'),