ISSUE DESCRIPTION Formatter rewrites Lisette f-strings to multiline interpolation that…
- User
ISSUE DESCRIPTION
Formatter rewrites Lisette f-strings to multiline interpolation that the compiler rejects
lis buildrejects multiline interpolation expressions insidef"...{...}"strings, but Zed’s Lisette formatter appears to rewrite single-line calls across lines automatically.Example:
f"You cannot use another ender pearl for {shared.format_duration( remaining, )}."The compiler reports:
[error] Multi-line f-string interpolation ... error: f-string interpolations must be single-lineImpact:
lis buildfails after formatting in touched spots.- This forces manual one-line edits to pass build.
Expected:
- Either Lisette formatter should preserve single-line interpolation in compatible cases, or
- Formatter rules should be configured to avoid splitting interpolation argument expressions across lines.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
Assistant
I'll start by exploring the repository structure to understand what we're working with.
Assistant
So
crates/format/has no references to f-strings. Let me look at the format code structure more carefully:Assistant
Now let me look at how
callis formatted to understand the issue better:Assistant
Now I need to look at where
format_stringis called from. The issue is that when we format a call inside an f-string interpolation{...}, the formatter breaks the call across multiple lines, which the lexer rejects.Let me search for the lexer error specifically:
Assistant
Now I understand the issue. The formatter formats the call as multiline, then when re-lexing the resulting source code, the lexer rejects the multiline f-string interpolation. We need to ensure the formatter doesn't break interpolation expressions across multiple lines.
Let me look at
format_stringmore carefully and understand the call structure:Assistant
Now let me look at the lindig module to understand how
Documentand breaking works:Assistant
Now let me reproduce the issue first. Let me set up a test:
Assistant
Now let me look at how the formatter handles call expressions to understand how to keep interpolation single-line:
Assistant
Let me first create a reproduction script:
Assistant
Now let me write a quick test to reproduce the issue. Let me look at the assertion macros:
Assistant
Now let me write a test to reproduce:
Assistant
Let me look at the existing build tooling to find an easy way to test:
Assistant
Let me write a quick Rust test in the format crate:
Assistant
Let me check if there are any tests in the format crate:
Assistant
No tests. Let me check the tests crate structure:
Assistant
Let me look at the format_string function more carefully and figure out how to fix this issue. The key insight is: when we format an interpolation expression
{expr}, the expr should be formatted in a way that doesn't introduce newlines (since the lexer rejects multiline interpolations).Let me look at how we could best solve this:
Assistant
Let me look at how lindig's Document handles breaks to understand the options:
Assistant
Now I understand the system. Let me think about the solution:
-
Option A: Disable breaking within format string interpolation expressions. This would prevent the formatter from inserting newlines within
{...}expressions. The simplest way is to use.group().next_break_fits(false)or some variant that prevents breaking within the expression. -
Option B: When the formatted output would exceed line width, allow breaking for the outer structure but not within the interpolation expression itself.
Let me think about it more carefully. The Lindig "Wadler-style" pretty printer uses
groupto determine fit, and any break within a group causes it to break. If a group's content doesn't fit, it gets broken.The issue here is that the
calland other expressions creategroup()boundaries that the formatter decides to break when they don't fit on one line.The cleanest fix is to force the interpolation expression to remain unbroken. We can do this by wrapping it with something that prevents breaking.
-
Assistant
Let me look at how
next_break_fitsworks:Assistant
Now let me trace through carefully:
In Lindig pretty-printing, when a
Groupdoc is rendered:- Try fitting it in unbroken mode (i.e. as if breaks become spaces)
- If it fits, render unbroken (breaks become "spaces")
- If not, render broken (breaks become newlines)
For our interpolation:
f"You cannot use another ender pearl for {shared.format_duration(remaining,)}."
The formatter first computes the entire module layout. When it tries to fit the f-string into unbroken mode, the long interpolation may not fit. Then it breaks.
The issue: the formatter decides to break at the
group()boundary inside the call expressionshared.format_duration(remaining,), splitting it across multiple lines.Solution approach: The interpolation expression inside the f-string must never be broken. We can wrap the expression document with something that prevents breaking.
Let me check
force_break:Assistant
Let me think... we need to prevent the formatter from breaking inside the interpolation.
Looking at the function:
Assistant
Now I understand. Let me design my fix.
The best approach: add a
Document::ForceUnbroken(or similar variant) that propagates the unbroken mode down to all breaks within. Then use it to wrap interpolation expressions.Actually, let me check if there's an existing pattern. Looking at how
force_break()is implemented - it'sSelf::ForceBroken(Box::new(self)). We need a similar mechanism but for "force unbroken."Let me check the whole Document enum:
Assistant
Now I have a clear understanding. Let me design the fix:
Approach: Add a new
Document::NoBreak(orForceUnbroken) variant. When this variant is encountered infitsandformat, all breaks within become unbroken.Actually, I think a simpler approach exists. Let me look at how
flex_breakworks:Assistant
Now let me write a quick reproducer using a simple inline test:
Assistant
Good, it builds. Now let me create a test file to reproduce the issue:
Assistant
OK so the formatter itself fails to parse it. Let me start with valid input that produces a multi-line interpolation:
Assistant
OK, so when the input fits on one line, it stays on one line. Let me push the limit to trigger the breaking. Let me look at what makes the formatter break a call:
Assistant
I've reproduced the issue! Now let me confirm
lis checkrejects this:Assistant
Excellent! I've reproduced the issue. Now let me design and implement the fix.
The best approach is to add a
Document::ForceUnbrokenvariant that propagates theUnbrokenmode to all breaks inside. Let me implement this.Assistant
Assistant
OK so
to_pretty_stringis the top-level entry. Let me think about the cleanest approach.I think the best approach is to introduce a new
Document::NoBreak(orForceUnbroken) variant that:- In
fits: when encountered, switches mode toUnbrokenand processes the inner content. If the inner content fits unbroken, it counts as fit; otherwise not (but at least the line might be very long but unbroken). - In
format: switches mode toUnbrokenand processes the inner content.
Wait, but if we switch to and a is inside, the group's fit check might still decide to break.
- In
Assistant
So
ForcedUnbrokenis used byNextBreakFits(_, false). Looking at how it's used in the formatter:Assistant
Assistant
Now let me look at the format function:
Assistant
Now I see the design clearly. Let me also look at FlexBreak carefully:
FlexBreak: if mode is Unbroken, render as unbroken. Otherwise, check if the unbroken version fits in remaining width. If yes, render as unbroken (with space). Else, render as broken (newline).OK so my approach:
Add
Document::NoBreak(Box<Self>)variant that switches mode toForcedUnbrokenfor bothfitsandformat.Assistant
Assistant
OK these
force_break()calls are for things like block expressions, where they want to ensure the block uses multiple lines. So these aren't typically inside f-string interpolations.OK let me implement my solution. First, let me think about whether
NextBreakFitsshould be modified too:NextBreakFits(doc, enabled):- If enabled: the next break encountered will be forced broken (unless mode is ForcedUnbroken).
- If disabled: the next break encountered will be forced unbroken.
If we're inside
NoBreak, we're forcing unbroken. So if we encounterNextBreakFits(_, true), it tries to force broken but our mode is ForcedUnbroken. Looking at the existing code:Document::NextBreakFits(doc, enabled) => { if *enabled { match mode { Mode::ForcedUnbroken => docs.push((indent, mode, doc)), _ => docs.push((indent, Mode::ForcedBroken, doc)), } } else { docs.push((indent, Mode::ForcedUnbroken, doc)); } }Assistant
Good. Now let me update the
format_stringfunction to useforce_unbreak():Assistant
Now let me build and test:
Assistant
Now let me test:
Assistant
The interpolation stays on one line. Let me also verify the result is valid:
Assistant
No more "Multi-line f-string interpolation" error. The remaining errors are unrelated (test function returning a value, format_duration not being a method on string, etc.). The key issue is fixed.
Let me also test with the original example:
Assistant
As expected, the original example fails to parse because it's invalid. Let me now think about idempotency - what if the user formats a string that has a long interpolation? The output should be the same when re-formatted:
Assistant
Idempotent. Now let me test other interesting cases - what about deeply nested calls inside interpolation?
Assistant
Let me also test what happens when a method chain is inside an interpolation:
Assistant
Good. Now let me make sure existing tests still pass:
Assistant
Hmm, looks like there are unrelated test failures in emit. Let me focus on format tests:
Assistant
All 292 format tests pass. Now let me check the emit tests - those failures might be unrelated to my change:
Assistant
OK these emit test failures are pre-existing (they're failing without my changes too). Let me restore my changes:
Assistant
Let me clean up the .new files (these are from the previous build but the diffs are from pre-existing failures, not from my changes):
Assistant
Let me verify these are pre-existing failures by looking at the snapshot files:
Assistant
The snapshot file hasn't been changed. The test failures are pre-existing - they're about emit (Go code generation), not format. Let me verify:
Assistant
These tests are about emitting Go code, not about formatting. Let me make sure these failures are indeed pre-existing (not caused by my changes):
Assistant
1437 emit tests are failing without my changes. These are all pre-existing failures, not related to my fix. Let me restore my changes:
Assistant
Good, clean state. Now let me also check that I haven't introduced regressions in other test categories:
Assistant
Many build tests fail. Let me check if these are pre-existing too:
Assistant
Yes, pre-existing failures. Let me restore my changes:
Assistant
Good. So the only changes are in the two files. Let me now also test desugar tests:
Assistant
All tests pass except for the pre-existing failures in emit and build. Now let me also add a specific test for the f-string interpolation issue. Let me look at what kinds of format tests exist:
Assistant
I should not add new tests as per the instructions. Let me verify the existing format tests still pass:
Assistant
All format tests pass. Now let me think about edge cases:
- Empty interpolation:
f"{}"- should work fine. - Simple identifier interpolation:
f"{x}"- should work fine. - Long identifier interpolation:
f"{very_long_variable_name}"- might exceed line width, but won't be broken into multiple lines. - Long call interpolation:
f"{foo(a, b, c, d, e, f, g, h)}"- won't be broken into multiple lines. - Nested call:
f"{foo(bar(x, y, z))}"- won't be broken into multiple lines. - Multiple interpolations:
f"{a} {b} {c}"- each interpolation is forced unbroken.
Let me test some of these:
- Empty interpolation:
Assistant
Let me verify the formatted output is valid:
Assistant
No more multi-line f-string errors. Let me also test multi-line text f-strings:
Assistant
Multi-line text with single-line interpolations works.
Let me also check what happens with comments inside an interpolation. Actually, let me think... if an interpolation has a comment, the formatter may need to break. Let's see:
Assistant
Good. Now let me test idempotency on this:
Assistant
Now let me think about a potential edge case. What if someone has a comment that would force a break? Let me think...
Actually, since comments are placed before or after expressions, they could force newlines. Let me check what happens if we have a comment inside an interpolation call:
Assistant
Good. Now let me consider another edge case - what if the formatter actually does need to break inside the interpolation to handle a comment? Let me try:
Assistant
The original parser doesn't accept this (it's a multi-line interpolation). But that's actually correct - the user shouldn't be writing that. The issue is about preventing the FORMATTER from generating such invalid code.
Let me think about what other approaches I could use. Actually let me look at the LSP implementation to see if it uses a different approach:
Assistant
The LSP uses the same
format_sourcefunction. So my fix applies there too.Let me check if there are LSP tests related to f-strings:
Assistant
Let me run the LSP tests related to f-strings:
Assistant
All LSP tests related to formatting pass.
Now let me also think about what happens with the original failing example from the issue. Let me create a similar test:
Assistant
Idempotent. Now let me think about a potential problem - what about method chain inside interpolation?
Assistant
Now let me also think about the
letbinding extraction suggestion from the error message:The compiler error suggests: "Extract the expression into a
letbinding and interpolate the variable". That's the workaround. My fix avoids creating that situation in the first place.Let me look at the test I should run:
Assistant
Let me check what
stress_test_all_positionsdoes to ensure my fix doesn't break it:Assistant
OK these tests don't seem to specifically test formatting. Let me run a broader LSP test:
Assistant
All LSP tests pass. Let me now think about what happens if the formatter is asked to format something with an extremely long single interpolation. The result might exceed the line width, but that's better than generating invalid code:
Assistant
Hmm, the binary operators are getting broken. Let me check why. Let me look at the binary operator formatter:
Assistant
I see - the binary operator uses a
group()at the end. Soa + b + c + ...is built as nested binary expressions, each with their own group. Let me check what happens:The expression
a + b + c + dis parsed as((a + b) + c) + d(left-associative). Each+is a binary expression with a group. Withforce_unbreak(), each group should be forced unbroken. But the result shows breaks...Let me re-check the code:
Assistant
Hmm! It's still breaking. Let me debug this.
Let me think... the binary expression
(a + b) + cwould be:- Binary { op: +, left: Binary { op: +, left: a, right: b }, right: c }
With my fix, when we call
format_stringand process the outer expressiona + b + c + ..., we wrap it inforce_unbreak(). This makes the mode ForcedUnbroken for the entire expression.Assistant
Assistant
Assistant
OK
a + bis fine. Let me try more operands:Assistant
Still breaking. Let me think... what if the outer group doesn't have my fix applied because the mode at the time isn't ForcedUnbroken?
Wait! Let me re-read my modification:
Document::Group(doc) => { if mode == Mode::ForcedUnbroken { docs.push((indent, Mode::ForcedUnbroken, doc)); } else { ... } }The mode here is the mode that was POPPED from the docs stack. If the Group is at the top level and the parent was ForcedUnbroken, then yes the popped mode is ForcedUnbroken.
But wait! In the format_string function:
docs.push(self.expression(e).force_unbreak());This pushes the result of
self.expression(e).force_unbreak(). So the doc pushed isNoWrap(expression_doc).Hmm let me look at where format_string is called from - it's called from
expression()when the expression isLiteral::FormatString(parts). The FormatString is inside a block expression or function body. Let me see what mode that block is in.Let me look at the block expression:
Assistant
OK so block uses
force_break(). That's aForceBrokendoc. Let me trace through how it interacts with my NoBreak.Actually wait - the
blockdoesn't wrap with anything. It just emits docs. Theforce_break()is on the entire block{...}. So when this block is rendered, it's in a ForcedBroken context.But within the block, the items are at the top level. They're not wrapped in any group. So they're rendered with mode ForcedBroken (because the block forces broken).
Let me trace this more carefully:
- The function
fn main() { f"...{expr}..." }is formatted. - The function body is a Block. The block's
force_break()makes it always broken. - Inside the block, items are rendered in
ForcedBrokenmode. - The
f"..."expression is an item in the block, formatted withself.expression(...). expression()for a Literal::FormatString returnsformat_string(parts).format_stringproduces a sequence including for the interpolation.
- The function
Assistant
OK so NoBreak does push with ForcedUnbroken. So my trace should be correct.
Let me add a debug print to see what's happening:
Assistant
Let me add some debug prints to lindig to trace:
Assistant
Let me look at the StrictBreak handler:
Assistant
OK StrictBreak handles ForcedUnbroken correctly. Let me add debug prints:
Assistant
OK now it doesn't break! Let me re-run my earlier failing test:
Assistant
Hmm wait, /tmp/format_output.txt has 0 lines? Let me check:
Assistant
OK, my test wrote to format_output.txt but the debug output went to stderr. Let me redo:
Assistant
OK now it works! Wait, did my earlier test work because of the eprintln! call? Let me clean up the debug and check again:
Assistant
It's working. Let me also verify the previous failing case:
Assistant
Wait, this case I already tested and it was working before. Let me try the case that was actually failing earlier:
Assistant
OK this also works. Let me re-verify my earlier finding by reverting my code and reproducing:
Assistant
Now let me look at the changes I made:
Assistant
Good. Let me run the format tests one more time to make sure everything still passes:
Assistant
All format and LSP format tests pass. Now let me check the original issue once more with the actual code from the issue:
Assistant
Let me also test with the format on the entire prelude/stdlib:
Assistant
That's the Go prelude, not Lisette source. Let me find Lisette source:
Assistant
These are typedefs, not actual code. Let me find some actual code:
Assistant
Let me also format this file to make sure my changes don't break things:
Assistant
There are some formatting changes but they're unrelated to my fix - they're just normal formatting improvements. Let me verify by reverting my changes and running the formatter again:
Assistant
Identical diff before and after my changes. So my fix doesn't affect other files. Let me restore the original file:
Assistant
Good. Now let me think about another edge case - what if the format string interpolation has a comment?
Assistant
Let me think about another edge case - what about the
letbinding extraction hint? That's a workaround suggested by the compiler. My fix avoids the need for this workaround, which is the desired behavior.Let me also think about what happens with
f-stringinside other expressions that might trigger breaking:Assistant
The
+ f"..."part is broken. This is OK because the binary operator's right side is the f-string. The f-string interpolation itself remains unbroken. The outer binary expression can still be broken.But wait, this might cause issues if the f-string itself is the one that gets broken. Let me see:
Assistant
No multi-line interpolation error. The formatter is doing its best - the outer expression is broken but the interpolation inside the f-string is not. This is the correct behavior.
Let me also check that the f-string itself doesn't get broken in the middle:
Assistant
Good, the f-string starts on one line.
Now let me think about another important consideration: what about the case where a call is inlinable? Looking at
format_call_with_head, there's anis_inlinable_argcheck that affects formatting:Assistant
OK so
Lambda,Block,Match,Tuple,Slice, and single-argCallare "inlinable". This doesn't directly affect my fix.Let me look at one more thing - the comment handling. Are there any places where comments might force a newline inside an interpolation?
Assistant
Comments are taken separately via
take_comments_before. Let me look at how they interact:Assistant
Hmm, comments are prepended via
prepend_comments, which adds a newline andforce_break. So if there's a comment before an interpolation expression, the expression itself is wrapped in aGroup(byprepend_comments).Wait wait, let me re-read
prepend_comments:pub fn prepend_comments<'a>(doc: Document<'a>, comments: Option<Document<'a>>) -> Document<'a> { match comments { Some(c) => c .append(Document::Newline) .force_break() .append(doc.group()), None => doc, } }If there's a comment, it appends a comment, a newline,
force_break(), and thendoc.group(). So the entire expression (including the comment and newline) is wrapped in a group.Now if this is wrapped in my
NoBreak:NoBreak(c.append(Newline).force_break().append(doc.group()))
Assistant
Good. Now what if the comment is INSIDE the interpolation? Like in the expression itself:
Assistant
Comments inside f-string interpolation are not supported (parsing fails). That's expected.
Let me also think about what happens with
ForceBrokeninsideNoBreak. With my fix,NoBreakswitches to ForcedUnbroken, but thenForceBrokeninside would do what?Let me check
fits:Document::ForceBroken(doc) => match mode { Mode::ForcedBroken => docs.push((indent, mode, doc)), _ => return false, },In
ForcedUnbrokenmode, this returns false. Sofitssays "doesn't fit". But that's only for the fits check, not for the actual rendering.In
format:Document::ForceBroken(document) | Document::NextBreakFits(document, _) => { docs.push((indent, mode, document)); }It just passes the mode through. So
ForceBrokeninsideNoBreakwould still try to be broken (via the recursive rendering).Hmm, this could be a problem. If we have
force_break()inside an interpolation expression, it would still break.But in practice,
force_break()is used for blocks and certain constructs. Let me check if it's used in places that could appear in an interpolation:Assistant
OK so
force_break()is used for trailing comments in method chains, etc. Let me check the ones at line 264, 293, 302:Assistant
So
force_break()is used by:- Block expressions - the block forces a break for
{...} - Comments after the block body
If someone writes
f"{let x = { y = 1; y } * 2 }", then the inner block would force a break. But wait, can you have a block in an interpolation expression? Let me check:- Block expressions - the block forces a break for
Assistant
Parsing fails. That's OK - blocks aren't allowed in interpolation expressions directly.
Let me think about other constructs. What about if/match?
Assistant
Hmm! The match is getting broken. Let me check why - this might be because the match is too long. Let me check the original:
Assistant
Oh, the match is still being broken! Let me investigate. The issue is that the match expression has a
force_break(or similar) inside it.Let me look at match:
Assistant
So
braced_bodyusesforce_break(). This means match, select, and various other constructs that usebraced_bodywill be force-broken.So when we have
f"{match x { ... } }", the match's braced_body forces a break. With my fix, the NoBreak wraps the entire match expression. The ForcedUnbroken mode propagates down. But theforce_break()inside still triggers.Looking at the flow:
NoWrap(match_doc)is processed, pushing match_doc with ForcedUnbroken.- match_doc =
header.append(" {").append(...).append("}").force_break(). - When we get to
force_break(), in format:
SoDocument::ForceBroken(document) | Document::NextBreakFits(document, _) => { docs.push((indent, mode, document)); }force_break()passes through with ForcedUnbroken mode. - The inner Sequence contains
Newline, which always renders as newline regardless of mode.
So even with my fix,
match x { ... }inside an interpolation will be broken across lines.But wait! The lexer rejects multi-line interpolations. So if the user writes
f"{match x { ... } }", the parser would reject it.Assistant
Assistant
Most uses are at the top level (between items) or inside blocks. Let me check what expressions can appear in interpolation expressions:
Looking at the expression types:
- Literal (including FormatString - but that would be nested f-strings)
- Identifier
- Unit
- Break, Continue
- Paren
- Block - has newlines
- Let - might have newlines if it has a block
- Return
- If - has newlines (braced_body)
- IfLet - has newlines
- Match - has newlines
- Binary
- Unary
- Call
- DotAccess
- IndexedAccess
- Tuple
- Slice
- Lambda
- Select - has newlines
So blocks, lets (with block values), ifs, iflets, matches, selects all have newlines.
Hmm. So if the user has
f"{if x { 1 } else { 2 }}", the if's braced_body would have newlines.Let me test:
Assistant
The
ifis inline. Let me try with a longer condition:Assistant
Still inline. Let me try a longer one:
Assistant
Still inline! Let me see what's going on - braced_body should force newlines. Let me check why these are inline.
Hmm wait, let me look at
if_:Assistant
OK so
as_inline_blockallows the block to be inline if it fits. Soif x { 1 } else { 2 }can be inline if it fits.Now if we wrap it in
NoBreak:- The if's
.group()is processed. - My Group handler sees ForcedUnbroken mode and pushes the inner with ForcedUnbroken.
- The inner contains the
as_inline_blockcalls which usestrict_break("", " ")etc. - In ForcedUnbroken mode, strict_break renders as unbroken (" ").
- So the if stays inline.
That's why
ifworks. Butmatchdoesn't becausematchusesbraced_bodywhich has explicitDocument::Newlines andforce_break().OK so I need to handle
matchand similar constructs that usebraced_body. Let me look at wherebraced_bodyis used:- The if's
Assistant
Assistant
Hmm, let me think about this differently. The issue is that certain expressions (match, select, block with multiple items) ALWAYS use multiple lines. The formatter forces this with
Document::Newline.For my NoBreak to work for these expressions too, I'd need to make
Document::NewlineandDocument::ForceBrokenbehave like "spaces" (or empty) inside NoBreak context.Let me try modifying NoBreak to handle these:
Actually, a different approach: instead of using
Mode::ForcedUnbroken, use a new mode that:- Renders
Document::Newlineas nothing (or a space). - Renders
Document::ForceBrokenas just passing through. - Renders breaks as unbroken.
This is getting complex. Let me take the simplest approach: use a "NoBreak" mode that completely ignores all break points - including newlines.
Wait, actually I have a better idea. Let me use a different approach. Instead of wrapping with
NoBreak, we can re-format with a much larger line width so that the Group fits.This way, the formatter would produce unbroken output (since the Group would fit within the larger width). Let me try this approach:
- Renders
Assistant
Let me try a different approach. Instead of NoBreak with ForcedUnbroken, let me think about how to render the document with a very large line width.
Actually, the cleanest approach would be to re-format the interpolation expression with a much larger line width so that all groups fit. Let me modify the
format_stringfunction to do this:Assistant
Hmm. The
to_pretty_stringtakes a limit. So if we format the interpolation with a huge limit, all Groups would fit unbroken.But how do we format part of the AST? We'd need to:
- Format the interpolation expression separately with a large limit.
- Insert the formatted expression into the f-string.
The current code calls
self.expression(e)which formats and returns a Document. The Document is later rendered with the outer limit.Hmm, but
Documentcarries the formatting decisions. Once we have a Document, we can't easily re-format part of it with a different limit.Let me think... what if
Documenthas a methodto_pretty_string_with_limit(self, limit)that uses a custom limit? Actually, it does -to_pretty_string(limit).But the issue is that when we render the document, the limit is applied globally. We can't apply different limits to different parts.
Unless... we render the document in parts! What if we:
- Identify interpolation expressions in the AST.
Assistant
Wait, but using
Document::verbatimwill preserve newlines, and might have issues with VerbatimText containing \n. Let me check VerbatimText:Assistant
So
VerbatimTextcan contain newlines - it splits on\nand emits each segment on a new line. So using VerbatimText with newlines is OK.But, the issue is
fits: if VerbatimText contains\n, fits returns false. This means if the f-string is inside a group, that group would break. Which is OK - the f-string's outer wrapping can break, just not the interpolation itself.But wait, there's another issue. If we format the interpolation with
isize::MAXline width, it will format to fit on one line. But if the result is multi-line (e.g., formatch), then we still get multi-line output.Hmm, let me actually test this:
Assistant
Hmm, the match is being formatted inside the interpolation, breaking it across multiple lines. So my approach of using
isize::MAXdoesn't help becauseDocument::Newlinealways renders as newline.Let me try another approach. What if I format the interpolation but render it specially?
Actually, the issue is that
matchalways uses multi-line formatting viabraced_body. To keep it inline, I'd need a different formatter for match.Let me try yet another approach: completely skip formatting of complex expressions inside interpolations. Use the original source text verbatim.
Actually wait - the simpler solution is to use my original
force_unbreakapproach combined with also suppressingDocument::NewlineandDocument::ForceBroken. Let me revert and try this:Assistant
Now let me think about this approach:
- For simple expressions (no forced breaks),
NoBreakworks. - For complex expressions (match, select, etc.),
NoBreakdoesn't help because ofDocument::Newlineandforce_break().
The best approach for these complex cases would be to:
- Detect the complex expression type.
- Use a different formatter that keeps things inline.
- OR use the original source verbatim.
Let me check what happens with the original source verbatim approach:
- For simple expressions (no forced breaks),
Assistant
OK so select also uses braced_body. Let me think about how to handle this.
Actually, here's an idea: what if I have
NoBreaksimply discard anyDocument::Newlineit encounters? This would mean that braced_body inside an interpolation would not produce newlines, but the content would still be formatted.Let me try this:
Assistant
Wait, I removed the Newline handling from the format function entirely! That's not right. Let me revert and try a different approach:
Assistant
OK reverted. Let me try a different approach: modify the Newline handler in format to check if we're inside NoBreak.
Actually, the cleanest approach is to use a new mode
Mode::NoBreakthat suppresses everything. Let me design it properly:Assistant
Wait, I lost the
Document::NoBreakvariant. Let me check what happened:Assistant
I see - the
Document::NoBreakvariant is missing from the enum but I'm still using it in the matches. Let me re-add it. Also the Group handler should check for NoBreak mode:Assistant
Now let me apply the formatter change:
Assistant
Now let me test:
Assistant
Excellent! The match is now on one line! Let me check that it's valid:
Assistant
No more multi-line interpolation error. Now let me test the other cases:
Assistant
Now let me also test other complex cases:
Assistant
Parse error - select syntax isn't right. Let me check:
Assistant
Select also stays inline. Let me check that this is valid:
Assistant
No multi-line interpolation errors. Let me run all format tests to make sure nothing's broken:
Assistant
All 292 format tests pass. Let me also run LSP tests:
Assistant
All LSP tests pass. Now let me think about edge cases. Let me test a few more:
Assistant
Let in interpolation isn't supported. Let me try other constructs:
Assistant
Let me also try a longer case:
Assistant
The call stays on one line. Let me check validity:
Assistant
No f-string errors. Let me also check idempotency:
Assistant
Now let me think about what happens with a lambda in interpolation:
Assistant
filterdoesn't exist. Let me try a simpler case:Assistant
OK that works. Let me also think about what could go wrong with my fix. The main concern is that I'm forcing interpolation expressions to be unbroken. This could produce extremely long lines, but that's better than producing invalid code.
Let me also test with a method chain:
Assistant
Method chain stays inline. Let me verify validity:
Assistant
No f-string errors.
Now let me think about one more potential issue. The
Document::VerbatimTextcontaining\n:Assistant
Multiline text in f-string still works correctly because the newlines are inside the text parts (not inside interpolation expressions).
Let me also check that my code handles
fitscorrectly. Specifically, when we're inside NoBreak, the fits check should also work (treating breaks as fits):Assistant
Good. Now let me also verify that the entire AST handling is OK. Let me look at the full file:
Assistant
Assistant
Let me also try with the match inside the interpolation:
Assistant
No multi-line f-string errors.
Now let me also run the comprehensive tests:
Assistant
All 502 LSP tests pass. Let me also check infer:
Assistant
All non-emit/build tests pass. Now let me also check the test we did before with the long expression that was getting broken in the
a + b + c + ...case:Assistant
Long binary expression stays inline.
Let me also think about what happens with comments in interpolation. Let me try to verify the case where there's a comment before the interpolation expression:
Assistant
Parse error - we can't have multi-line interpolations. That's expected and correct. The original input is invalid.
Let me now think about whether my fix could cause any issues with tests that have format_string tests:
Assistant
Let me also check format tests that might involve f-strings:
Assistant
Let me look at what's in mod.rs:
Assistant
That's just a comment. Let me also check that I haven't broken the multi-line f-string text test:
Assistant
These emit failures are pre-existing (we verified earlier).
Assistant
All format tests for f-strings pass.
Now let me think about the overall robustness of my solution. The key question is: in what situations could my fix produce invalid Lisette code?
- Forced newlines from
Document::Newline: Suppressed. ✓ - Forced breaks from
force_break(): Suppressed. ✓ - Group breaking: Suppressed (no fit check in NoBreak mode). ✓
- StrictBreak/FlexBreak: Treated as unbroken. ✓
- Document::VerbatimText with newlines: Not affected - it's rendered as-is.
What about comments? Comments inside interpolation expressions are extracted by
take_comments_beforeand prepended viaprepend_comments. Let me check what happens with comments inside an interpolation expression.Actually, comments are at the module level, not inside expressions. The lexer's comments are tracked separately. Let me check:
- Forced newlines from
Assistant
Comments are taken BEFORE the expression starts. So if a comment is inside
{...}interpolation, it would be considered "before" some inner expression. Hmm.Actually wait, the parser doesn't allow comments inside interpolation expressions (they cause parse errors). So this isn't an issue.
Let me also think about the
// commentsyntax inside interpolation:Actually, looking at the parser errors, comments inside interpolation cause parse errors. So this isn't possible.
Let me verify my fix doesn't have any subtle issues by running the tests once more:
Assistant
All format lib tests pass.
Let me also check what happens when I run the entire workspace tests:
Assistant
All lib tests pass. Now let me think about one more potential issue.
What if an interpolation expression is itself nested in a structure that could be broken? Like a tuple containing an f-string?
Assistant
Now let me think about a list of f-strings:
Assistant
Let me now think about what happens with the original issue example more carefully. The user reported:
f"You cannot use another ender pearl for {shared.format_duration( remaining, )}."This is INVALID Lisette code (multi-line interpolation). The user reported that the FORMATTER rewrites single-line calls into multi-line.
So the formatter is the one producing the bad code. Let me create a similar test that was VALID before formatting:
Assistant
Stays inline. Let me also verify it's valid:
Assistant
No errors.
Now let me think about potential issues with my NoBreak mode. One concern: what if the forced unbroken output exceeds the line width limit? Let me see:
Assistant
OK, even an extremely long expression stays inline. Let me check the line width:
Assistant
153 chars, well over 80. But that's the cost of keeping the interpolation valid. The user explicitly asked for this expression to be in an interpolation, so this is the best behavior.
Let me check the validity:
Assistant
No interpolation errors.
Now let me also think about whether there's any case where my fix could be problematic. The main case is when the user has an interpolation that doesn't NEED to be broken, but my fix prevents it from being broken for outer formatting purposes.
Wait, let me re-check that. The NoBreak only applies to the interpolation expression, not the surrounding code. The surrounding code can still break.
Let me test that:
Assistant
The outer binary expression can break (the
+), but the f-string itself stays on one line. The interpolation stays inline.Let me verify the f-string itself is valid:
Assistant
No errors.
Now let me also think about one more potential edge case: what about the
fitsfunction in NoBreak mode?Currently, in fits, NoBreak is treated like Unbroken. Let me verify:
Document::NoBreak(doc) => { docs.push((indent, Mode::NoBreak, doc)); },So NoBreak is pushed with NoBreak mode. Then the inner doc is processed with NoBreak mode. The breaks inside are treated as fitting (since NoBreak acts like Unbroken).
But what about Group in NoBreak mode?
Document::Group(doc) => match mode { Mode::Broken => docs.push((indent, Mode::Unbroken, doc)), _ => docs.push((indent, mode, doc)), },So Group in NoBreak mode keeps NoBreak. Good.
What about VerbatimText?
Document::VerbatimText(s) => { if s.contains('\n') { return false; } current_width += s.graphemes(true).count() as isize; },Assistant
All interpolation expressions are on single lines, including:
- Simple identifier:
{name},{age} - Method calls:
{items.length()},{items.to_string()} - If expressions:
{if age > 18 { "adult" } else { "minor" }} - Variables:
{result} - Multi-line text (with single-line interpolations):
hello\n{name}\nworld
Let me check validity:
- Simple identifier:
Assistant
No interpolation errors.
Let me also check idempotency:
Assistant
Idempotent.
Now let me look at my changes one more time to make sure they're clean:
Assistant
Assistant
All tests pass.
Let me also try to reproduce the EXACT scenario from the issue:
Assistant
No interpolation errors.
Let me also re-verify by reverting my fix and showing the original behavior:
Assistant
This confirms the original bug - the formatter breaks the call across multiple lines.
Assistant
The original bug is confirmed. Let me restore my fix:
Assistant
The fix works. The interpolation stays on one line and the code is valid.
Now let me also test the broader tests:
Assistant
All tests pass.
Now let me also think about one more thing - what about
to_pretty_stringbeing called with a non-80 width? Let me check:Assistant
The format is called with limit 80 in all places. My fix uses the same limit.
Let me think about one more thing. When the NoBreak doc is rendered, the limit is still 80. The
fitsfunction checks if the content fits within the limit. If the content is in NoBreak mode, the breaks are treated as fitting, so fits returns true. But if the content is very long, fits might return false (because the unbroken content exceeds the limit).But wait, this doesn't matter because in NoBreak mode, we don't actually use the fits result. We just push the content with NoBreak mode and render it.
Let me re-check my implementation:
For
formatfunction:Document::Group(doc) => { if mode == Mode::NoBreak { // In NoBreak context, groups don't try to fit - they remain // unbroken so interpolation expressions stay on one line. docs.push((indent, Mode::NoBreak, doc)); } else { let group_docs = vec![(indent, Mode::Unbroken, doc.as_ref())]; if fits(limit, width, group_docs) { docs.push((indent, Mode::Unbroken, doc)); } else { docs.push((indent, Mode::Broken, doc)); } } }Assistant
Only one place where f-strings are formatted - the
format_stringfunction. My fix targets this.Let me also check if there are any other places that could format f-string interpolation expressions:
Assistant
Just my comment. Good.
Let me also check the LSP code for any f-string handling:
Assistant
LSP uses
format::format_sourcewhich uses my fixed formatter.Now let me look at the final diff one more time:
Assistant
56 insertions, 14 deletions. Reasonable size for a fix.
Let me also do a final clean-up check. Let me make sure there are no leftover debug files:
Assistant
Clean.
Let me also verify the diff one more time:
Assistant
Now let me address the checklist:
Checklist
-
If an error was reported in the issue description, I have successfully reproduced it.
- YES. I reproduced the issue with the example f-string containing a call expression that would be wrapped to multiple lines. The original behavior produced invalid output. After my fix, the output is valid.
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- YES. I verified that no longer reports "Multi-line f-string interpolation" errors after my fix, even for cases where the formatter previously broke the call across multiple lines.
-
Assistant
Clean state. Let me also do one more round of testing to make sure everything works:
Assistant
All tests pass. The fix is complete.
Let me also run a final reproduction to confirm the fix works:
Assistant
No more "Multi-line f-string interpolation" error. The remaining errors are unrelated (test function returning a value, format_duration not being a method on string).
The fix is complete and working. Let me submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.