Skip to content

Commit

Permalink
Properly generate code for parameter default value Strings.
Browse files Browse the repository at this point in the history
Fixes #756

In order to properly allow single quotes and dollar signs in parameter default values, we must not print as raw, and we must escape dollar signs ourselves, before passing to code_builder.

PiperOrigin-RevId: 646140324
  • Loading branch information
srawlins authored and copybara-github committed Jun 24, 2024
1 parent 2302814 commit e99ba54
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
6 changes: 5 additions & 1 deletion lib/src/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1822,7 +1822,11 @@ class _MockClassInfo {
} else if (constant.isInt) {
return literalNum(constant.intValue);
} else if (constant.isString) {
return literalString(constant.stringValue, raw: true);
// code_builder writes all strings with single quotes.
// Raw single quoted strings may not contain single quotes,
// so escape dollar signs and use a non-raw string instead.
final stringValue = constant.stringValue.replaceAll('\$', '\\\$');
return literalString(stringValue);
} else if (constant.isList) {
return literalConstList([
for (final element in constant.listValue)
Expand Down
47 changes: 40 additions & 7 deletions test/builder/auto_mocks_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -281,13 +281,46 @@ void main() {
await expectSingleNonNullableOutput(
dedent(r'''
class Foo {
void m([String a = 'Hello', String b = 'Hello ' r"World"]) {}
void m([String a = 'Hello', String b = "World"]) {}
}
'''),
_containsAllOf(dedent2('''
void m([
String? a = r'Hello',
String? b = r'Hello World',
String? a = 'Hello',
String? b = 'World',
]) =>
''')),
);
});

test('matches string literal parameter default values with quote characters',
() async {
await expectSingleNonNullableOutput(
dedent(r'''
class Foo {
void m([String a = 'Hel"lo', String b = "Wor'ld"]) {}
}
'''),
_containsAllOf(dedent2('''
void m([
String? a = 'Hel"lo',
String? b = 'Wor\\'ld',
]) =>
''')),
);
});

test('matches raw string literal parameter default values', () async {
await expectSingleNonNullableOutput(
dedent(r'''
class Foo {
void m([String a = r'$Hello', String b = r"$World"]) {}
}
'''),
_containsAllOf(dedent2('''
void m([
String? a = '\\\$Hello',
String? b = '\\\$World',
]) =>
''')),
);
Expand Down Expand Up @@ -337,8 +370,8 @@ void main() {
_containsAllOf(dedent2('''
void m(
[Map<int, String>? a = const {
1: r'a',
2: r'b',
1: 'a',
2: 'b',
}]) =>
''')),
);
Expand All @@ -354,8 +387,8 @@ void main() {
_containsAllOf(dedent2('''
void m(
[Map<int, String>? a = const {
1: r'a',
2: r'b',
1: 'a',
2: 'b',
}]) =>
''')),
);
Expand Down

0 comments on commit e99ba54

Please sign in to comment.