@@ -339,9 +339,19 @@ private Optional<State> tryInlinePrefixOntoCurrentLine(
339339
340340 // Add the width of tokens, breaks before the lastLevel. We must always have space for
341341 // these.
342- List <Doc > leadingDocs = docs .subList (0 , docs .indexOf (lastLevel ));
342+ int lastLevelIndex = docs .indexOf (lastLevel );
343+ List <Doc > leadingDocs = docs .subList (0 , lastLevelIndex );
343344 float leadingWidth = getWidth (leadingDocs );
344345
346+ // A forced break after the lastLevel, such as the ones around a // comment that sits before this level's
347+ // closing token, cannot be laid out flat by tryToLayOutLevelOnOneLine: the comment would swallow every token
348+ // after it on the line. Such a level breaks normally instead, as tryBreakInnerLevel refuses it for the same
349+ // reason. (A forced break before the lastLevel makes leadingWidth infinite and fails the check below.)
350+ List <Doc > trailingDocs = docs .subList (lastLevelIndex + 1 , docs .size ());
351+ if (Float .isInfinite (getWidth (trailingDocs ))) {
352+ return Optional .empty ();
353+ }
354+
345355 // Potentially add the width of prefixes we want to consider as part of the width that
346356 // must fit on the same line, so that we don't accidentally break prefixes when we could
347357 // have avoided doing so.
@@ -592,6 +602,9 @@ private static Optional<State> tryBreakInnerLevel_checkInner(
592602 * Mark breaks in this level as not broken, but lay out the inner levels normally, according to their own
593603 * {@link BreakBehaviour}. The resulting {@link State#mustBreak} will be true if this level did not fit on exactly
594604 * one line.
605+ *
606+ * <p>The callers make sure that none of this level's own breaks is forced: a forced break laid out flat would put
607+ * the tokens after a {@code //} comment inside the comment.
595608 */
596609 private State tryToLayOutLevelOnOneLine (
597610 CommentsHelper commentsHelper ,
0 commit comments