Now let me understand the issue better. The problem is:
- The formatter currently takes an f-string with an interpolation expression like
f"...{shared.format_duration(remaining)}." and formats it.
- The formatter might decide that the expression inside the
{...} is too long to fit on one line, so it breaks the arguments across lines.
- This produces a multi-line f-string interpolation which the compiler rejects.
The fix should be in the format_string method. When formatting an FormatStringPart::Expression(e), we need to force the expression to be formatted on a single line, regardless of whether it fits.
Looking at the Document model, I need to find a way to force an expression to stay on one line. Looking at the format function, I see that:
ForceBroken forces content to break (multiline)
NextBreakFits(_, false) forces groups to NOT break
Group breaks when it doesn't fit
Wait, let me re-read the format function for Group:
Document::Group(doc) => {
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));
}
}
And fits for Group:
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
So in fits, a Group in Unbroken mode keeps Unbroken mode. A Group in Broken mode switches to Unbroken (because a group evaluates to see if its contents fit in one line).
Now, if we look at NextBreakFits(doc, false) in fits:
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));
}
}
When enabled is false, it forces ForcedUnbroken mode. In fits, ForcedUnbroken is treated like Unbroken for breaks. But the key is: in format function, Group doesn't check the mode - it always evaluates fits to decide if the group should break.
So NextBreakFits(_, false) doesn't actually prevent groups from breaking in the output. It just changes how fits evaluates.
Let me think about this differently. What I need is a way to force the expression inside the f-string interpolation to be rendered on a single line.
Looking at how the formatter handles calls that need to be on one line (like the next_break_fits(false) pattern):
head.append("(")
.append(last_doc)
.append(")")
.next_break_fits(false)
.group()
This wraps the whole call in a group with next_break_fits(false). The next_break_fits(false) tells the fits function: "treat all inner breaks as unbroken". So when fits is called on this group, it won't consider any inner breaks as line breaks, so the whole thing has to fit on one line. If it doesn't fit, fits returns false, and the group is set to Broken mode. But since next_break_fits(false) is wrapping the group, and in format it just passes through... hmm, this doesn't seem to prevent breaking either.
Wait, let me re-read more carefully. The Group in format decides whether to break based on fits. If fits returns false, the group is Broken. If true, it's Unbroken.
When we have:
next_break_fits(false).group()
The group() is the outermost. In format, when evaluating this group:
fits is called with the inner content (which includes next_break_fits(false))
- Inside
fits, next_break_fits(false) forces ForcedUnbroken mode
- In
ForcedUnbroken, breaks are treated as unbroken (they add width but don't break)
- If the total width exceeds the limit,
fits returns false
- Then the group is set to
Broken mode
So this doesn't actually prevent the expression from breaking! If the expression is too long, it still breaks.
But wait, let me think about the use case for next_break_fits(false). Looking at the call formatting code:
head.append("(")
.append(last_doc)
.append(")")
.next_break_fits(false)
.group()
The next_break_fits(false) is on the outer group. This means when the outer group is evaluating whether to break, the inner next_break_fits(false) makes fits treat all inner breaks as unbroken. So if the expression is long, fits returns false, and the outer group breaks. But the outer group has no breaks to break at... unless there's a strict_break or flex_break somewhere.
Actually, I think the point of next_break_fits(false) is to make the group prefer breaking. When used inside another group that has breaks, it forces the outer group to break instead of the inner one.
OK, I think I'm overthinking this. Let me just focus on the problem:
The format_string method needs to ensure that the interpolation expression stays on one line. The simplest approach is to use a mechanism that prevents the expression from being broken across lines.
Let me look at what happens when we have a document that's too long for one line. In a group:
fits is called to check if the content fits on one line
- If it doesn't fit, the group is set to
Broken mode
- In
Broken mode, breaks (strict_break, flex_break) produce newlines
The key insight: strict_break in the call formatting produces the indentation and newline when the group is broken. So if we can prevent the expression from being rendered in Broken mode, it won't produce newlines.
Looking at the format function for Group:
Document::Group(doc) => {
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));
}
}
The group checks fits and if it doesn't fit, it sets the mode to Broken. There's no way to override this behavior from the outside...
Unless we use NextBreakFits(_, false) to wrap the expression. Let me trace through this:
next_break_fits(false) = NextBreakFits(expr, false)
In format:
Document::ForceBroken(document) | Document::NextBreakFits(document, _) => {
docs.push((indent, mode, document));
}
NextBreakFits in format just passes through the mode and the inner document. So it doesn't change the behavior of Group inside.
Hmm, so NextBreakFits only affects fits, not format. It's used to influence how groups decide whether to break.
Let me look at this problem from a different angle. The issue says the formatter rewrites single-line calls across lines. So the original code is:
f"You cannot use another ender pearl for {shared.format_duration(remaining)}."
And the formatter produces:
f"You cannot use another ender pearl for {shared.format_duration(
remaining,
)}."
This means the formatter is breaking the call shared.format_duration(remaining) into multiple lines because it doesn't fit on one line (the whole line is too long).
The fix should be: when formatting an f-string interpolation expression, force it to stay on one line even if it means the line is too long.
To do this, I think we need to use NextBreakFits(_, false) to wrap the expression. In fits, this will force ForcedUnbroken mode. Then, when a Group is encountered inside, fits will treat it in ForcedUnbroken mode:
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
In ForcedUnbroken mode (which is not Broken), the group will keep ForcedUnbroken mode. Then breaks inside:
Document::StrictBreak { unbroken, .. } | Document::FlexBreak { unbroken, .. } => {
match mode {
Mode::Broken | Mode::ForcedBroken => return true,
Mode::Unbroken | Mode::ForcedUnbroken => {
current_width += unbroken.len() as isize;
}
}
}
In ForcedUnbroken mode, breaks add their unbroken width. So the fits function will compute the total width of the entire expression without any breaks. If this exceeds the limit, fits returns false.
But wait, if fits returns false, the outer group (if any) will be set to Broken mode. The outer group would be... the whole line? Let me think about what the outer context is.
Actually, the format_string method returns a Document that is part of a larger expression/statement. The format_string is called from literal, which is called from expression. The expression is part of some statement, which has its own group structure.
I think the key issue is that the format_string method doesn't wrap its content in a group. It just returns a sequence of documents. The call expression inside the interpolation (self.expression(e)) will have its own groups, and those groups will decide whether to break based on the available width.
So the solution is: inside the format_string method, when formatting an interpolation expression, wrap it in something that forces it to stay on one line.
Let me look at how next_break_fits(false) is used in the call formatting:
head.append("(")
.append(last_doc)
.append(")")
.next_break_fits(false)
.group()
This wraps the whole call (head + args + closing paren) in next_break_fits(false).group(). When this group is evaluated:
fits is called with the content
- Inside,
next_break_fits(false) forces ForcedUnbroken mode
- All breaks inside are treated as unbroken
- If the content is too long,
fits returns false
- The group is set to
Broken mode6. In Broken mode, breaks will produce newlines
Hmm, but this still allows breaking! The point of next_break_fits(false) must be something else...
Actually wait, I think I misread the code. Let me re-read the call formatting:
if init.is_empty() {
let last_doc = self.expression(last).group().next_break_fits(true);
head.append("(")
.append(last_doc)
.append(")")
.next_break_fits(false)
.group()
}
Here, last_doc is wrapped in .group().next_break_fits(true). The outer call is wrapped in .next_break_fits(false).group().
When the outer group is evaluated:
fits is called with the content
- Content includes
next_break_fits(false) (wait no, the outer next_break_fits(false) is outside the group)
Actually, let me re-read:
head.append("(")
.append(last_doc)
.append(")")
.next_break_fits(false)
.group()
This is: Group(NextBreakFits(Sequence(head, "(", last_doc, ")", false))
Wait no, next_break_fits(false) returns NextBreakFits(self, false) where self is the sequence. Then .group() wraps that in a Group.
So the structure is: Group(NextBreakFits(Sequence(head, "(", last_doc, ")"), false))
In format, when this Group is encountered:
fits is called with (indent, Mode::Unbroken, NextBreakFits(Sequence(...), false))
- In
fits, NextBreakFits(_, false) forces ForcedUnbroken mode
- The inner
last_doc is self.expression(last).group().next_break_fits(true), which is NextBreakFits(Group(Sequence(...)), true)
- In
fits, NextBreakFits(_, true) with mode ForcedUnbroken: since mode is ForcedUnbroken, it keeps ForcedUnbroken mode (not ForcedBroken)
- The inner
Group in fits: mode is ForcedUnbroken (not Broken), so it keeps ForcedUnbroken mode
- Breaks inside the inner group in
fits with ForcedUnbroken mode add their unbroken width
- If the total width exceeds the limit,
fits returns false
So when the content doesn't fit, fits returns false, and the outer Group is set to Broken mode.
Now in Broken mode, when the content is rendered:
NextBreakFits(_, false) passes through in format (just pushes inner document)
- The inner
Group (from last_doc) is now evaluated in Broken mode
- For
Group in format, fits is called to decide whether to break the inner group
- Inside the inner group, there's
NextBreakFits(_, true)
- In
fits, NextBreakFits(_, true) with mode Unbroken forces ForcedBroken mode
- In
ForcedBroken, breaks return true immediately (they always "fit" because they break the line)
- So
fits returns true for the inner group
- The inner group is set to
Unbroken mode
- In
Unbroken mode, breaks don't produce newlines
Wait, but if the inner group is Unbroken, then the breaks inside it won't produce newlines. So how does the call break across multiple lines?
Hmm, I think I'm missing something. Let me look at how the call with multiple args is formatted:
let mut entries = self.call_arg_entries(init);
let last_start = last.get_span().byte_offset;
let last_leading = self.split_for_rest(&mut entries, last_start);
let last_doc = self.expression(last).group().next_break_fits(true);
let (body, close_sep) =
Self::join_pattern_entries(entries, Some((last_leading, last_doc)), "");
head.append("(")
.append(strict_break("", ""))
.append(body)
.nest(INDENT_WIDTH)
.append(close_sep)
.append(")")
.next_break_fits(false)
.group()
Here there's a strict_break("", "") inside the group. This break will produce a newline when the outer group is in Broken mode.
OK so the flow is:
- Outer group evaluates
fits with ForcedUnbroken mode2. The strict_break in ForcedUnbroken adds0 to width (since unbroken is "")
- But the body content adds width
- If total width exceeds limit,
fits returns false
- Outer group is
Broken
- In
Broken mode, the strict_break("", "") produces a newline
- The inner content (args) is rendered on the next line
- The inner
last_doc with next_break_fits(true) is rendered in... wait, what mode?
Actually, the last_doc is nested inside the body, which is inside the outer group. When the outer group is Broken, all breaks inside produce newlines. But the last_doc has its own group...
I think I need to just try a simpler approach. Let me look at what would work for the f-string case.
The problem is: when the formatter renders the interpolation expression, it can break it into multiple lines. We need to prevent this.
One approach: wrap the expression in a way that forces all inner groups to be Unbroken. We can use NextBreakFits(_, false) for this purpose. In fits, this forces ForcedUnbroken, which means all groups inside will be treated as Unbroken in fits. But in format, it passes through...
Wait, let me re-read the format function for Group more carefully:
Document::Group(doc) => {
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));
}
}
The key: fits is called with mode Unbroken regardless of the current mode! So a group always evaluates its contents in Unbroken mode in fits. If it fits, the group is Unbroken; if not, the group is Broken.
But the current mode IS passed down to the content when it's rendered (the docs.push((indent, mode, doc)) where mode is from the outer context, not from the group's decision).
Wait no, the group's decision IS the mode:
- If fits:
docs.push((indent, Mode::Unbroken, doc))
- If not:
docs.push((indent, Mode::Broken, doc))
So the mode is set by the group's decision. The content inside the group will be rendered with the mode the group decided.
Now, for inner groups: when an inner group is encountered during rendering, it calls fits with Mode::Unbroken. So the inner group's decision is independent of the outer group's mode.
Hmm wait, that can't be right. If the outer group is Broken, and there's an inner group, the inner group should also break (otherwise why would we break the outer group?).
Let me re-read the format function for Group:
Document::Group(doc) => {
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));
}
}
When a group is encountered during rendering:
- It checks
fits with the current width and Mode::Unbroken
- If it fits, it pushes the group with
Mode::Unbroken
- If not, it pushes with
Mode::Broken
But wait, this is the group itself, not the inner content. The inner content of the group is the doc. When the group is pushed with Mode::Broken, the doc will be processed with Mode::Broken.
Now inside doc, when there's another group (inner group):
Document::Group(doc) => {
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));
}
}
The inner group also calls fits with Mode::Unbroken! So the inner group's decision is independent of the outer group's mode!
This means: even if the outer group is Broken, the inner group will still try to fit on one line. Only if the inner group doesn't fit will it be Broken.
So groups are always "optimistic" - they try to fit on one line first. Only if they don't fit do they break.
Now, this means if I want to force an expression to not break, I need to make all the inner groups always fit. Since fits returns true when content fits, and false when it doesn't, I can't prevent a group from breaking if it doesn't fit...
Unless I use NextBreakFits(_, false). Let me trace through this:
If I have: Group(Sequence(...)) that doesn't fit on one line.
In fits, the Group is processed:
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
If mode is ForcedUnbroken (from an outer NextBreakFits(_, false)), the group keeps ForcedUnbroken mode. Then breaks inside the group:
Document::StrictBreak { unbroken, .. } | Document::FlexBreak { unbroken, .. } => {
match mode {
Mode::Broken | Mode::ForcedBroken => return true,
Mode::Unbroken | Mode::ForcedUnbroken => {
current_width += unbroken.len() as isize;
}
}
}
In ForcedUnbroken mode, breaks add their unbroken width. So the group's content is evaluated as if no breaks. If the total width exceeds the limit, fits returns false.
But wait, NextBreakFits(_, false) is only evaluated in fits, not in format. So in format, the groups will still make their own decisions.
Hmm, let me re-think. Maybe the approach should be different.
Actually, I think the solution is to use NextBreakFits(_, false) at the right level. Let me look at what the format function does with Group:
Document::Group(doc) => {
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));
}
}
When fits is called for a group, it uses Mode::Unbroken. So the inner content's NextBreakFits(_, false) would force ForcedUnbroken mode for the rest of the content in the fits check. This means all inner breaks are treated as unbroken, so the total width is computed without line breaks. If the content is too wide, fits returns false, and the group breaks.
So NextBreakFits(_, false) doesn't prevent groups from breaking - it makes them more likely to break because it forces all inner content to be evaluated as unbroken.
OK I think I need to look at this problem differently. Let me think about what mechanism in this pretty-printer can prevent line breaks.
In Wadler-Lindig style printers, the main mechanism is:
Group: try to fit on one line, if not, break
ForceBroken: always break
- There's typically no "never break" mechanism
But we need a "never break" mechanism for f-string interpolations. Let me look at how NextBreakFits(_, false) is actually used.
Looking at the code:
head.append("(")
.append(last_doc)
.append(")")
.next_break_fits(false)
.group()
I think the purpose is: when this group is inside another group, and the outer group is evaluating whether to break, the next_break_fits(false) makes the outer group think this content can't be broken (it's forced unbroken in fits). So the outer group would see the full width of this content without any breaks.
But in format, when this group is actually rendered:
- The outer group decides whether to break based on
fits
- If the outer group breaks, the inner group is rendered in
Broken mode
- But
NextBreakFits(_, false) in format just passes through - it doesn't affect the mode
- So the inner group makes its own decision
I think the purpose of next_break_fits(false) is specifically for the "last arg" pattern:
last_doc is the last argument, wrapped in .group().next_break_fits(true)
- The whole call is wrapped in
.next_break_fits(false).group()
When the outer group is evaluated in fits:
next_break_fits(false) forces ForcedUnbroken
last_doc's group is evaluated in ForcedUnbroken mode (not Broken)
- So
last_doc's group keeps ForcedUnbroken mode
last_doc's next_break_fits(true) with ForcedUnbroken mode keeps ForcedUnbroken
- Breaks inside
last_doc add their unbroken width
When the outer group breaks:
next_break_fits(false) passes through
last_doc's group is evaluated normally (calls fits with Unbroken)
last_doc's next_break_fits(true) forces ForcedBroken
- In
ForcedBroken, breaks return true immediately
- So
last_doc's group always "fits" (always returns true from fits)
last_doc's group is rendered as Unbroken
- So the last argument stays on one line
This makes sense! The last argument should stay on one line even when the call is broken across lines. The next_break_fits(true) on the last arg ensures it doesn't break.
Now for the f-string case, I need to ensure the interpolation expression stays on one line. I can't use next_break_fits(true) because that only affects fits, not format.
Actually wait, let me re-read the format function for Group one more time:
Document::Group(doc) => {
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));
}
}
In fits:
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
If the mode is ForcedBroken, the group keeps ForcedBroken. Then breaks inside return true immediately, so fits returns true. So the group always "fits" in ForcedBroken mode. Then in format, the group is rendered as Unbroken (because fits returned true).
So NextBreakFits(_, true) wrapping a group makes the group always render as Unbroken! Because:
- In
fits, NextBreakFits(_, true) forces ForcedBroken
- The group inside is evaluated in
ForcedBroken mode
- In
ForcedBroken, breaks return true immediately
- So
fits returns true
- In
format, the group is rendered as Unbroken
- In
Unbroken mode, breaks don't produce newlines
So I can use NextBreakFits(_, true) to force a group to be Unbroken!
But wait, the expression inside the f-string interpolation has multiple nested groups (e.g., the call has a group, and each arg might have groups). I need to force ALL of them to be Unbroken.
Looking at how next_break_fits(true) works in fits:
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));
}
}
next_break_fits(true) forces ForcedBroken mode for the inner content (unless already ForcedUnbroken). In ForcedBroken mode, breaks return true, so fits always returns true.
But in format:
Document::ForceBroken(document) | Document::NextBreakFits(document, _) => {
docs.push((indent, mode, document));
}
NextBreakFits passes through the current mode. So the inner content is rendered with the current mode (which could be Unbroken or Broken).
Wait, but the outer group was set to Unbroken because fits returned true. So the mode for the inner content is Unbroken. In Unbroken mode, breaks don't produce newlines. And inner groups...
Inner groups in format:
Document::Group(doc) => {
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));
}
}
Inner groups still call fits with Unbroken mode. So they make their own decision! If the inner group doesn't fit, it will be Broken, and in Broken mode, breaks will produce newlines.
So next_break_fits(true) only affects the group that directly wraps it, not nested groups.
Hmm, so for the f-string case, I need a different approach. Let me think...
Actually, maybe I should look at how other formatters handle this. In prettier, for example, there's a concept of "irregular" groups that don't break. Maybe I can create a new document variant, or use an existing one.
Looking at ForceBroken:
- In
fits: returns false unless already in ForcedBroken mode
- In
format: passes through
So ForceBroken forces content to be "broken" (not fit). But I want the opposite.
What about VerbatimText? It outputs the text as-is without any formatting. But I can't use it for structured documents.
Let me look at the problem from a different angle. The issue says:
Formatter rules should be configured to avoid splitting interpolation argument expressions across lines.
Maybe the solution is simpler: in the format_string method, instead of using self.expression(e) which can break, I should format the expression in a way that prevents breaking.
One approach: after getting the expression document, recursively transform it to remove all groups and replace breaks with their unbroken form. This would force the entire expression to be rendered on one line.
But this is complex and might not be straightforward.
Another approach: use a flag in the formatter context to indicate "inside f-string interpolation". When this flag is set, all groups should be forced to Unbroken mode.
Actually, looking at the code more carefully, I notice that the format function for Group always calls fits with Mode::Unbroken. This means a group always tries to fit on one line. If it doesn't fit, it breaks.
But what if I change the behavior so that when inside an f-string interpolation, groups always report that they fit? This would make them always render as Unbroken.
I could add a field to the formatter that indicates whether we're inside an f-string interpolation, and pass it down to the document rendering.
But wait, the document rendering is in lindig.rs, which doesn't have access to the formatter state. The document is a pure data structure that's rendered independently.
Hmm, let me think of another approach. What if I modify the fits function to have a "force unbroken" mode that makes all groups report as fitting?
Actually, there's a simpler approach: I can modify the format function's Group handling to check a flag. But this would require changing the document model.
Let me look at what other options exist...
Actually, I just realized something. The NextBreakFits(_, false) variant exists. In fits:
Document::NextBreakFits(doc, enabled) => {
if *enabled {
...
} else {
docs.push((indent, Mode::ForcedUnbroken, doc));
}
}
When enabled is false, it forces ForcedUnbroken. And in fits, groups in ForcedUnbroken mode keep ForcedUnbroken:
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
Since ForcedUnbroken is not Broken, it keeps ForcedUnbroken. Then all breaks inside add their unbroken width. If the total width exceeds the limit, fits returns false.
But in format, NextBreakFits(_, false) passes through. So groups inside will still make their own decisions.
Wait wait wait. I just realized something crucial. In format, Group always calls fits with Mode::Unbroken:
Document::Group(doc) => {
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));
}
}
This means inner groups always try to fit on one line, regardless of the outer mode. So even if the outer group is Broken, inner groups still try to fit.
But in fits, Group preserves the mode:
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
In fits, a group in Broken mode switches to Unbroken (because the group itself is the boundary). In any other mode, it preserves the mode.
So in fits, if we have ForcedUnbroken mode, a group preserves ForcedUnbroken. Breaks inside add their unbroken width. This means the total width is computed without any line breaks, which makes fits more likely to return false (because the content is wider).
But in format, groups always make their own decision. So NextBreakFits(_, false) only affects the fits check, not the actual rendering.
OK I think the key insight I'm missing is: the format function for Group always calls fits with Mode::Unbroken. This is the "probe" - it checks if the group can fit on one line. If yes, render as Unbroken. If no, render as Broken.
So if I want to force a group to be Unbroken, I need to make fits return true for that group. The way to do that is to make all the content inside the group fit on one line.
One way: use NextBreakFits(_, true) inside the group. In fits, this forces ForcedBroken mode, which makes all breaks return true. So fits returns true, and the group is rendered as Unbroken.
But this only works for the outermost group. Inner groups will still make their own decisions.
Wait, but if the outermost group is Unbroken, then in format, when inner groups are encountered, they call fits with Mode::Unbroken. If the inner group doesn't fit, it will be Broken, and breaks inside will produce newlines. So the expression will still be broken!
Unless... the NextBreakFits(_, true) also propagates through inner groups in fits. Let me trace through:
NextBreakFits(Group(inner), true):
- In
fits, NextBreakFits(_, true) forces ForcedBroken mode
Group(inner) in fits with ForcedBroken mode: since mode is not Broken, it keeps ForcedBroken (wait, ForcedBroken IS Broken... let me re-read)
Document::Group(doc) => match mode {
Mode::Broken => docs.push((indent, Mode::Unbroken, doc)),
_ => docs.push((indent, mode, doc)),
},
The match is on Mode::Broken, not Mode::ForcedBroken. So ForcedBroken falls through to _, and the group keeps ForcedBroken mode. Then breaks inside return true immediately. So fits returns true.
But this is in the fits check for the outer group. The inner group is part of the content being checked. The fits function is checking if the outer group's content fits on one line. If it does (because NextBreakFits(_, true) makes everything "fit"), then the outer group is Unbroken.
Now in format, the outer group is Unbroken. When inner groups are encountered:
Document::Group(doc) => {
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));
}
}
The inner group calls fits with Mode::Unbroken. But the NextBreakFits(_, true) is outside the inner group, so it's already been processed. The inner group doesn't have NextBreakFits(_, true) wrapping it.
So the inner group's fits check uses Mode::Unbroken, and if the content doesn't fit, the inner group breaks.
Hmm, so NextBreakFits(_, true) wrapping the outermost expression only prevents the outermost group from breaking, not inner groups.
OK, I think the solution needs to be different. Let me think about what document transformation I can do.
Actually, I just had an idea. What if I modify the fits function to handle a new mode or a new document type that forces everything to be unbroken? Or, what if I modify the format function's Group handling to check if we're inside a "forced unbroken" context?
But modifying the document model seems risky and could have unintended consequences.
Let me look at this from a completely different angle. Maybe the solution is not in the document model, but in how the formatter generates the document for f-string interpolations.
Instead of self.expression(e), which generates a document with groups that can break, I could generate a flat document that doesn't have any groups or breaks. This would force the expression to be rendered on one line.
To do this, I could:
- Generate the expression document as usual
- Post-process it to remove all groups and replace breaks with their unbroken form
This is like "flattening" the document. Let me implement this.
Actually, I think there might be an even simpler approach. Looking at the Document enum, there's VerbatimText. What if I render the expression to a string and then use VerbatimText?
Let me check if the formatter has a way to render a document to a string...
Actually, the Document has to_pretty_string. But this requires a limit parameter. I could use a very large limit to prevent any breaks.
But this seems hacky. Let me look at other approaches.
Wait, I just realized something. Let me re-read the format function for Group:
Document::Group(doc) => {
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));
}
}
This checks if the group fits at the current position. If it does, it renders as Unbroken. If not, it renders as Broken.
But what if I make fits always return true for groups inside the f-string interpolation? I could do this by adding a "force unbroken" flag to the document rendering.
Actually, let me look at the ForceBroken variant again:
Document::ForceBroken(doc) => match mode {
Mode::ForcedBroken => docs.push((indent, mode, doc)),
_ => return false,
},
In fits, ForceBroken returns false unless in ForcedBroken mode. This means a group containing ForceBroken will never fit (unless in ForcedBroken mode), so it will always be Broken.
But I want the opposite: I want groups to always fit (always be Unbroken). There's no existing mechanism for this.
Let me consider adding a new document variant ForceUnbroken that:
- In
fits: forces ForcedUnbroken mode (like NextBreakFits(_, false) but also affects format)
- In
format: forces the inner content to be rendered in ForcedUnbroken mode
In fits:
Document::ForceUnbroken(doc) => {
docs.push((indent, Mode::ForcedUnbroken, doc));
}
In format:
Document::ForceUnbroken(doc) => {
docs.push((indent, Mode::ForcedUnbroken, doc));
}
But ForcedUnbroken mode doesn't change how groups are evaluated in format. Groups still call fits with Mode::Unbroken.
Hmm, what if I change the Group handling in format to use the current mode when it's ForcedUnbroken?
Wait, that would change the behavior for ALL groups, not just those inside f-string interpolations.
Let me think about this differently. The issue is that the formatter breaks expressions inside f-string interpolations. The simplest fix might be to detect when we're inside a f-string interpolation and avoid breaking.
I could add a context flag to the formatter: inside_fstring_interpolation: bool. When this flag is set, the expression method could avoid generating breaks. But this would require modifying many methods.
Actually, the cleanest approach might be to add a method to the Document that forces it to be rendered on one line. Let me call it flatten() or single_line(). This method would recursively transform the document to remove all groups and replace breaks with their unbroken form.
Let me implement this. I'll add a method to Document:
pub fn flatten(self) -> Self {
match self {
Document::Group(doc) => doc.flatten(),
Document::NextBreakFits(doc, _) => doc.flatten(),
Document::ForceBroken(doc) => doc.flatten(),
Document::Nest(_, doc) => doc.flatten(),
Document::NestIfBroken(_, doc) => doc.flatten(),
Document::Sequence(docs) => Document::Sequence(docs.into_iter().map(|d| d.flatten()).collect()),
Document::StrictBreak { unbroken, .. } => Document::str(unbroken),
Document::FlexBreak { unbroken, .. } => Document::str(unbroken),
Document::Newline => Document::Newline,
Document::Text(_) | Document::VerbatimText(_) => self,
}
}
Wait, but this would remove all groups and breaks, which means the document would always be rendered on one line. For f-string interpolations, this is exactly what we want!
But wait, what about Newline? In the f-string interpolation, we don't want newlines. Let me replace Newline with an empty string or just skip it.
Actually, Newline in the document model is used for line breaks. In the f-string interpolation, we don't want any line breaks. But removing Newline entirely might cause issues with the document structure.
Let me think about this more carefully. The flatten method should:
- Remove all
Group, NextBreakFits, ForceBroken, Nest, NestIfBroken wrappers
- Replace
StrictBreak and FlexBreak with their unbroken text
- Keep
Text and VerbatimText as-is
- Remove
Newline (or replace with nothing)
Actually, Newline is used for line breaks. If I remove it, the content before and after the newline would be concatenated without any separator. This might not be correct.
Hmm, let me think about what a Newline in the context of an f-string interpolation means. The Newline is generated by the formatter for things like:
- Between arguments in a function call
- Inside blocks
For f-string interpolations, we don't want any of these. So replacing Newline with nothing is correct.
But wait, Newline might also be used for indentation or other purposes. Let me check...
Looking at the format function, Newline outputs a newline and sets the pending indent. So it's a line break.
For the f-string interpolation, we want everything on one line. So we should:
- Remove all groups (so no breaks happen)
- Replace breaks with their unbroken form (so no newlines)
- Remove newlines (so no line breaks)
Let me implement this.
Actually, I realize there might be a simpler approach. Instead of flattening the document, I can just render the expression to a string and use that string directly in the f-string.
The expression document can be rendered to a string using to_pretty_string(limit). If I use a very large limit (like isize::MAX), no breaks will happen, and the expression will be rendered on one line.
But this requires knowing the limit, which is typically passed around in the formatter. Let me check...
Actually, looking at the to_pretty_string method:
pub fn to_pretty_string(&self, limit: isize) -> String {
let mut buffer = String::new();
self.pretty_print(limit, &mut buffer);
buffer
}
And pretty_print:
pub fn pretty_print(&self, limit: isize, writer: &mut String) {
format(writer, limit, 0, vec![(0, Mode::Unbroken, self)]);
}
If I use a very large limit, the fits function will always return true (because the content always fits within the limit). So all groups will be Unbroken, and no breaks will happen.
But this is a bit wasteful because it renders the expression twice (once for the string, once for the final output). Let me think of a better approach.
Actually, the simplest and cleanest approach is to add a flatten method to Document that transforms it to be single-line. Then in the format_string method, I can call flatten on the expression document.
Let me implement this.
Now I understand the issue. The format_string method in the formatter produces a Document for f-string interpolation expressions that can break across multiple lines. But the compiler requires f-string interpolations to be single-line. Let me write a script to reproduce the issue first: