Skip to content
This repository was archived by the owner on Apr 8, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/src/builders/expression.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Literal _literal(value) {
} else if (value is bool) {
return value ? _true : _false;
} else if (value is String) {
return astFactory.simpleStringLiteral(stringToken("'$value'"), value);
return astFactory.simpleStringLiteral(stringToken(_quote(value)), value);
} else if (value is int) {
return astFactory.integerLiteral(stringToken('$value'), value);
} else if (value is double) {
Expand All @@ -93,6 +93,16 @@ Literal _literal(value) {
throw new ArgumentError.value(value, 'Unsupported');
}

/// Quotes the string literal. It is assumed that the [value] is meant to be
/// the raw string, so all `\` are escaped.
String _quote(String value) {
value = value.replaceAll(r'\', r'\\').replaceAll(r"'", r"\'");
if (value.contains('\n')) {
return "'''$value'''";
}
return "'$value'";
}

/// Implements much of [ExpressionBuilder].
abstract class AbstractExpressionMixin implements ExpressionBuilder {
@override
Expand Down
26 changes: 24 additions & 2 deletions test/builders/expression_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,30 @@ void main() {
expect(literal(5.5), equalsSource(r'5.5'));
});

test('should emit a string', () {
expect(literal('Hello'), equalsSource(r"'Hello'"));
group('should emit a string', () {
test('simple', () {
expect(literal('Hello'), equalsSource(r"'Hello'"));
});

test("with a '", () {
expect(literal("Hello'"), equalsSource(r"'Hello\''"));
});

test(r"with a \'", () {
expect(literal(r"Hello\'"), equalsSource(r"'Hello\\\''"));
});

test(r"with a \\'", () {
expect(literal(r"Hello\\'"), equalsSource(r"'Hello\\\\\''"));
});

test(r"with a newline", () {
expect(literal("Hello\nworld"), equalsSource("'''Hello\nworld'''"));
});

test(r"with a newline and ending with a '", () {
expect(literal("Hello\nworld'"), equalsSource("'''Hello\nworld\\''''"));
});
});

test('should emit a list', () {
Expand Down