Skip to content

Commit e75a034

Browse files
committed
Fold adjacent string literals into one expression
1 parent a70b411 commit e75a034

12 files changed

Lines changed: 508 additions & 27 deletions

File tree

‎src/DotPython.Compiler/PythonCompiler.cs‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -897,11 +897,7 @@ private void CompileTemplateString(PythonTemplateStringExpression template)
897897
switch (part)
898898
{
899899
case PythonFormattedStringLiteralPart literal:
900-
current.Append(
901-
template.IsRaw
902-
? literal.RawText
903-
: DecodePartEscapes(literal.RawText, literal.Span)
904-
);
900+
current.Append(DecodeLiteralPart(literal, template.IsRaw));
905901
break;
906902
case PythonFormattedStringInterpolationPart interpolation:
907903
statics.Add(current.ToString());
@@ -980,6 +976,36 @@ private string DecodePartEscapes(string rawText, TextSpan span)
980976
}
981977
}
982978

979+
/// <summary>
980+
/// The text a literal part contributes, read the way that part says: as written, by
981+
/// the f-string escape rules, by the string reader when a fold brought a whole
982+
/// literal in, or as its own string's prefix decides.
983+
/// </summary>
984+
private string DecodeLiteralPart(PythonFormattedStringLiteralPart literal, bool isRaw) =>
985+
literal.Decoding switch
986+
{
987+
PythonFormattedStringPartDecoding.Literal => literal.RawText,
988+
PythonFormattedStringPartDecoding.Escaped => DecodePartEscapes(
989+
literal.RawText,
990+
literal.Span
991+
),
992+
PythonFormattedStringPartDecoding.EncodedLiteral => DecodeEncodedLiteral(literal),
993+
_ => isRaw ? literal.RawText : DecodePartEscapes(literal.RawText, literal.Span),
994+
};
995+
996+
private string DecodeEncodedLiteral(PythonFormattedStringLiteralPart literal)
997+
{
998+
try
999+
{
1000+
return PythonLiteralDecoder.DecodeStringLiteral(literal.RawText);
1001+
}
1002+
catch (PythonLiteralDecodeException exception)
1003+
{
1004+
Report("DPY3003", exception.Message, literal.Span);
1005+
return literal.RawText;
1006+
}
1007+
}
1008+
9831009
private void CompileFormattedString(PythonFormattedStringExpression formatted)
9841010
{
9851011
var partCount = 0;
@@ -988,9 +1014,7 @@ private void CompileFormattedString(PythonFormattedStringExpression formatted)
9881014
switch (part)
9891015
{
9901016
case PythonFormattedStringLiteralPart literal:
991-
var decoded = formatted.IsRaw
992-
? literal.RawText
993-
: DecodePartEscapes(literal.RawText, literal.Span);
1017+
var decoded = DecodeLiteralPart(literal, formatted.IsRaw);
9941018
Emit(
9951019
PythonOpCode.LoadConstant,
9961020
AddConstant(new PythonConstant(PythonConstantType.TextValue, decoded)),

‎src/DotPython.Compiler/PythonLiteralDecoder.cs‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@ ICollection<Diagnostic> diagnostics
6565
),
6666
PythonConstantKind.StringLiteral => new PythonConstant(
6767
PythonConstantType.TextValue,
68-
DecodeString(expression.TokenText)
68+
Concatenated(expression, DecodeString)
6969
),
7070
PythonConstantKind.BytesLiteral => new PythonConstant(
7171
PythonConstantType.ByteSequence,
72-
DecodeBytes(expression.TokenText)
72+
Concatenated(expression, DecodeBytes)
7373
),
7474
PythonConstantKind.FormattedStringLiteral
7575
or PythonConstantKind.TemplateStringLiteral => UnsupportedInterpolatedString(
@@ -171,6 +171,38 @@ private static Complex DecodeImaginary(string text)
171171
);
172172
}
173173

174+
/// <summary>
175+
/// The value a literal stands for: its own text, or — when adjacent literals were
176+
/// folded into it — the parts joined, each decoded by the same reader.
177+
/// </summary>
178+
private static T Concatenated<T>(PythonConstantExpression expression, Func<string, T> decode)
179+
{
180+
if (expression.ConcatenatedParts is not { } parts)
181+
return decode(expression.TokenText);
182+
return expression.ConstantKind switch
183+
{
184+
PythonConstantKind.BytesLiteral => JoinBytes(
185+
parts.Select(part => decode(part.TokenText))
186+
),
187+
_ => JoinText(parts.Select(part => decode(part.TokenText))),
188+
};
189+
}
190+
191+
private static T JoinText<T>(IEnumerable<T> values) =>
192+
typeof(T) == typeof(string)
193+
? (T)(object)string.Concat(values.Cast<string>())
194+
: throw new FormatException();
195+
196+
private static T JoinBytes<T>(IEnumerable<T> values)
197+
{
198+
var joined = values.Cast<byte[]>().SelectMany(value => value).ToArray();
199+
return (T)(object)joined;
200+
}
201+
202+
/// <summary>Decodes one complete string literal, which is what an f-string takes from
203+
/// an adjacent plain literal.</summary>
204+
internal static string DecodeStringLiteral(string tokenText) => DecodeString(tokenText);
205+
174206
private static string DecodeString(string tokenText)
175207
{
176208
var (prefix, content) = SplitStringToken(tokenText);

‎src/DotPython.Language/Ast/PythonAst.cs‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,13 @@ public sealed record PythonNameExpression(string Name, TextSpan Span) : PythonEx
293293
public sealed record PythonConstantExpression(
294294
PythonConstantKind ConstantKind,
295295
string TokenText,
296-
TextSpan Span
296+
TextSpan Span,
297+
/// <summary>
298+
/// The adjacent literals this one stands for, in source order, when a string or
299+
/// bytes literal is followed by others: `"a" "b"` is one constant of two parts.
300+
/// Null for a literal that stands alone, whose text is <see cref="TokenText"/>.
301+
/// </summary>
302+
IReadOnlyList<PythonConstantExpression>? ConcatenatedParts = null
297303
) : PythonExpression(Span);
298304

299305
public sealed record PythonUnaryExpression(
@@ -394,8 +400,32 @@ TextSpan Span
394400

395401
public abstract record PythonFormattedStringPart(TextSpan Span) : PythonNode(Span);
396402

397-
public sealed record PythonFormattedStringLiteralPart(string RawText, TextSpan Span)
398-
: PythonFormattedStringPart(Span);
403+
/// <summary>How a literal part of an f-string or template string is read.</summary>
404+
public enum PythonFormattedStringPartDecoding
405+
{
406+
/// <summary>The part follows the string it belongs to: literal when that string is
407+
/// raw, escape-decoded when it is not.</summary>
408+
Expression,
409+
410+
/// <summary>The text stands as written, which is what a raw string's parts do.</summary>
411+
Literal,
412+
413+
/// <summary>The text's escapes are decoded with the f-string rules.</summary>
414+
Escaped,
415+
416+
/// <summary>
417+
/// The text is a whole string literal — prefix, quotes and all — decoded by the
418+
/// string reader, which is what an adjacent plain literal contributes to a string it
419+
/// was folded into.
420+
/// </summary>
421+
EncodedLiteral,
422+
}
423+
424+
public sealed record PythonFormattedStringLiteralPart(
425+
string RawText,
426+
TextSpan Span,
427+
PythonFormattedStringPartDecoding Decoding = PythonFormattedStringPartDecoding.Expression
428+
) : PythonFormattedStringPart(Span);
399429

400430
public sealed record PythonFormattedStringInterpolationPart(
401431
PythonExpression Expression,

‎src/DotPython.ParserGenerator/Generated/PythonGrammar.g.cs‎

Lines changed: 4 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/DotPython.ParserGenerator/Grammar/README.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,4 @@ just parser-check
1818
```
1919

2020
Generation is offline and deterministic. Changing the grammar or its provenance comments changes
21-
the embedded SHA-256 fingerprint and must produce a reviewed generated-file diff. Subset version 39
22-
adds class-header keyword arguments and positional/mapping unpacking using the call argument grammar.
21+
the embedded SHA-256 fingerprint and must produce a reviewed generated-file diff. Subset version 42 adds adjacent string literals: `atom` accepts a `strings` rule of one or more STRING tokens, the way CPython's `strings: (fstring | string)+` does.

‎src/DotPython.ParserGenerator/Grammar/python314-subset.gram‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# DotPython executable PEG subset, version 41.
1+
# DotPython executable PEG subset, version 42.
22
# Upstream tag: CPython v3.14.7.
33
# Upstream commit: 823f0323ee6ec1402088b73bce1a38473cac36dc.
44
# Provenance: https://github.com/python/cpython/blob/823f0323ee6ec1402088b73bce1a38473cac36dc/Grammar/python.gram
@@ -93,7 +93,9 @@ arguments: ','.argument+ [',']
9393
argument: NAME '=' expression | '**' expression | '*' expression | expression [comp_clauses]
9494
expression_list: ','.star_expression+ [',']
9595
star_expression: '*' expression | expression
96-
atom: NAME | NUMBER | STRING | 'None' | 'True' | 'False' | '...' | list_display | tuple_display | dict_display | group
96+
atom: NAME | NUMBER | strings | 'None' | 'True' | 'False' | '...' | list_display | tuple_display | dict_display | group
97+
# Adjacent string literals are one expression, as CPython's `strings: (fstring | string)+` says.
98+
strings: STRING+
9799
list_display: '[' expression comp_clauses ']' | '[' [expression_list] ']'
98100
tuple_display: '(' ')' | '(' star_expression ',' [expression_list] ')'
99101
dict_display: '{' expression ':' expression comp_clauses '}' | '{' expression comp_clauses '}' | '{' [dict_items] '}' | '{' expression_list '}'

‎src/DotPython.ParserGenerator/ParserGeneratorCapabilities.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public static class ParserGeneratorCapabilities
99
public static bool SupportsParsingExpressionGrammars => true;
1010

1111
/// <summary>Gets the version of the executable Python grammar subset.</summary>
12-
public const int ExecutableSubsetVersion = 41;
12+
public const int ExecutableSubsetVersion = 42;
1313

1414
/// <summary>Gets the SHA-256 fingerprint of the pinned grammar input.</summary>
1515
public static string GeneratedGrammarFingerprint => GeneratedPythonGrammar.SourceSha256;

‎src/DotPython.ParserGenerator/PythonParser.cs‎

Lines changed: 152 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3613,19 +3613,166 @@ IReadOnlyList<Diagnostic> Diagnostics
36133613
return Constant(Advance(), PythonConstantKind.EllipsisLiteral);
36143614
}
36153615

3616-
if (Current.Kind == SyntaxTokenKind.FormattedStringLiteral)
3616+
if (
3617+
Current.Kind
3618+
is SyntaxTokenKind.StringLiteral
3619+
or SyntaxTokenKind.BytesLiteral
3620+
or SyntaxTokenKind.FormattedStringLiteral
3621+
or SyntaxTokenKind.TemplateStringLiteral
3622+
)
36173623
{
3618-
return ParseFormattedString(Advance());
3624+
return ParseAdjacentStrings();
36193625
}
36203626

3621-
if (Current.Kind == SyntaxTokenKind.TemplateStringLiteral)
3627+
return constantKind is null ? null : Constant(Advance(), constantKind.Value);
3628+
}
3629+
3630+
/// <summary>
3631+
/// A literal, with any adjacent literals folded into it: `"a" "b"` is one string,
3632+
/// `"a" f"{x}"` is one f-string, and bytes never mix with anything that is not
3633+
/// bytes, nor a template string with anything that is not a template string.
3634+
/// </summary>
3635+
private PythonExpression ParseAdjacentStrings()
3636+
{
3637+
var parts = new List<PythonExpression> { ParseStringAtom() };
3638+
while (
3639+
Current.Kind
3640+
is SyntaxTokenKind.StringLiteral
3641+
or SyntaxTokenKind.BytesLiteral
3642+
or SyntaxTokenKind.FormattedStringLiteral
3643+
or SyntaxTokenKind.TemplateStringLiteral
3644+
)
36223645
{
3623-
return ParseFormattedString(Advance(), isTemplate: true);
3646+
parts.Add(ParseStringAtom());
36243647
}
36253648

3626-
return constantKind is null ? null : Constant(Advance(), constantKind.Value);
3649+
return parts.Count == 1 ? parts[0] : FoldStrings(parts);
3650+
}
3651+
3652+
private PythonExpression ParseStringAtom() =>
3653+
Current.Kind switch
3654+
{
3655+
SyntaxTokenKind.StringLiteral => Constant(
3656+
Advance(),
3657+
PythonConstantKind.StringLiteral
3658+
),
3659+
SyntaxTokenKind.BytesLiteral => Constant(
3660+
Advance(),
3661+
PythonConstantKind.BytesLiteral
3662+
),
3663+
SyntaxTokenKind.FormattedStringLiteral => ParseFormattedString(Advance()),
3664+
_ => ParseFormattedString(Advance(), isTemplate: true),
3665+
};
3666+
3667+
private PythonExpression FoldStrings(List<PythonExpression> parts)
3668+
{
3669+
var span = TextSpan.FromBounds(parts[0].Span.Start, parts[^1].Span.End);
3670+
var hasBytes = parts.Exists(part =>
3671+
part is PythonConstantExpression { ConstantKind: PythonConstantKind.BytesLiteral }
3672+
);
3673+
var hasString = parts.Exists(part =>
3674+
part is PythonConstantExpression { ConstantKind: PythonConstantKind.StringLiteral }
3675+
);
3676+
var hasFormatted = parts.Exists(part => part is PythonFormattedStringExpression);
3677+
var hasTemplate = parts.Exists(part => part is PythonTemplateStringExpression);
3678+
// A template string joins only other template strings, and bytes join only
3679+
// bytes; anything else is the mix CPython refuses.
3680+
if (hasTemplate && (hasBytes || hasString || hasFormatted))
3681+
{
3682+
Report("DPY2001", TemplateMixMessage, span);
3683+
return parts[0];
3684+
}
3685+
if (hasBytes && (hasString || hasFormatted))
3686+
{
3687+
Report("DPY2001", BytesMixMessage, span);
3688+
return parts[0];
3689+
}
3690+
if (hasTemplate)
3691+
return FoldInterpolatedStrings(parts, span, isTemplate: true);
3692+
if (hasFormatted)
3693+
return FoldInterpolatedStrings(parts, span, isTemplate: false);
3694+
3695+
return new PythonConstantExpression(
3696+
hasBytes ? PythonConstantKind.BytesLiteral : PythonConstantKind.StringLiteral,
3697+
((PythonConstantExpression)parts[0]).TokenText,
3698+
span,
3699+
[.. parts.Cast<PythonConstantExpression>()]
3700+
);
36273701
}
36283702

3703+
/// <summary>
3704+
/// An f-string or template string joined with its neighbours: the interpolated
3705+
/// strings contribute their parts, and each plain literal contributes itself,
3706+
/// whole, for the string reader to decode.
3707+
/// </summary>
3708+
private static PythonExpression FoldInterpolatedStrings(
3709+
List<PythonExpression> parts,
3710+
TextSpan span,
3711+
bool isTemplate
3712+
)
3713+
{
3714+
var folded = new List<PythonFormattedStringPart>();
3715+
var isRaw = false;
3716+
foreach (var part in parts)
3717+
{
3718+
switch (part)
3719+
{
3720+
case PythonFormattedStringExpression formatted:
3721+
isRaw = formatted.IsRaw;
3722+
FoldedParts(folded, formatted.Parts, formatted.IsRaw);
3723+
break;
3724+
case PythonTemplateStringExpression template:
3725+
isRaw = template.IsRaw;
3726+
FoldedParts(folded, template.Parts, template.IsRaw);
3727+
break;
3728+
case PythonConstantExpression literal:
3729+
folded.Add(
3730+
new PythonFormattedStringLiteralPart(
3731+
literal.TokenText,
3732+
literal.Span,
3733+
PythonFormattedStringPartDecoding.EncodedLiteral
3734+
)
3735+
);
3736+
break;
3737+
}
3738+
}
3739+
3740+
return isTemplate
3741+
? new PythonTemplateStringExpression(folded.AsReadOnly(), isRaw, span)
3742+
: new PythonFormattedStringExpression(folded.AsReadOnly(), isRaw, span);
3743+
}
3744+
3745+
/// <summary>
3746+
/// The parts one folded string contributes, with the rawness of the string they
3747+
/// came from settled on each of them — a raw `rf"a\n"` beside a plain `f"b"` keeps
3748+
/// its backslash whatever the string they end up in says.
3749+
/// </summary>
3750+
private static void FoldedParts(
3751+
List<PythonFormattedStringPart> folded,
3752+
IReadOnlyList<PythonFormattedStringPart> parts,
3753+
bool isRaw
3754+
)
3755+
{
3756+
foreach (var part in parts)
3757+
{
3758+
folded.Add(
3759+
part is PythonFormattedStringLiteralPart literal
3760+
? literal with
3761+
{
3762+
Decoding = isRaw
3763+
? PythonFormattedStringPartDecoding.Literal
3764+
: PythonFormattedStringPartDecoding.Escaped,
3765+
}
3766+
: part
3767+
);
3768+
}
3769+
}
3770+
3771+
private const string BytesMixMessage = "cannot mix bytes and nonbytes literals";
3772+
3773+
private const string TemplateMixMessage =
3774+
"cannot mix t-string literals with string or bytes literals";
3775+
36293776
private PythonExpression? ParseParenthesizedOrTuple(SyntaxToken leftParenthesis)
36303777
{
36313778
if (Match(SyntaxTokenKind.RightParenthesis, out var emptyRightParenthesis))

0 commit comments

Comments
 (0)