Skip to content

Commit 4952334

Browse files
committed
Refactor expand_string_literal to use string_parts
Helper class that were used for raw string can replace expansion of string literal.
1 parent d18c6db commit 4952334

File tree

1 file changed

+6
-33
lines changed

1 file changed

+6
-33
lines changed

source/lex.h

Lines changed: 6 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,6 @@ auto expand_string_literal(
349349
}
350350

351351
auto pos = 0;
352-
auto ret = std::string{}; // the return string we're going to build
353352

354353
// Skip prefix to first non-" character
355354
while (
@@ -366,25 +365,8 @@ auto expand_string_literal(
366365
auto first_quote_pos = pos;
367366
++pos;
368367
auto current_start = pos; // the current offset before which the string has been added to ret
369-
auto first = true;
370368

371-
auto add_plus = [&](bool and_quote = false) {
372-
// Only add a "+" after the first term
373-
if (!first) {
374-
ret += " + ";
375-
}
376-
// If also adding a quote,
377-
if (and_quote) {
378-
// remember to pull in the prefix on the first term (e.g., u")
379-
if (first) {
380-
ret += text.substr(0, first_quote_pos+1);
381-
}
382-
else {
383-
ret += '"';
384-
}
385-
}
386-
first = false;
387-
};
369+
auto parts = string_parts{"\"", "\"", string_parts::on_both_ends};
388370

389371
// Now we're on the first character of the string itself
390372
for (
@@ -428,17 +410,13 @@ auto expand_string_literal(
428410

429411
// Put the next non-empty non-interpolated chunk straight into ret
430412
if (open != current_start) {
431-
add_plus(true);
432-
ret += text.substr(current_start, open - current_start);
433-
ret += '"';
413+
parts.add_string(text.substr(current_start, open - current_start));
434414
}
435415

436416
// Then put interpolated chunk into ret
437-
add_plus();
438-
ret += "cpp2::to_string";
439417
auto chunk = std::string{text.substr(open, pos - open)};
440418
replace_all(chunk, "\\\"", "\"");
441-
ret += chunk;
419+
parts.add_code("cpp2::to_string" + chunk);
442420

443421
current_start = pos+1;
444422
}
@@ -451,16 +429,11 @@ auto expand_string_literal(
451429
);
452430

453431
// Put the final non-interpolated chunk straight into ret
454-
if (
455-
first
456-
|| current_start < std::ssize(text)-1
457-
)
458-
{
459-
add_plus(true);
460-
ret += text.substr(current_start);
432+
if (current_start < std::ssize(text)-1) {
433+
parts.add_string(text.substr(current_start, std::ssize(text)-current_start-1));
461434
}
462435

463-
return ret;
436+
return parts.generate();
464437
}
465438

466439

0 commit comments

Comments
 (0)