diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java index 3cb3bc201..32b6a7fe8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java @@ -19,6 +19,7 @@ import static com.google.common.collect.Iterators.peekingIterator; import static java.lang.String.format; import static java.util.regex.Pattern.CASE_INSENSITIVE; +import static java.util.regex.Pattern.COMMENTS; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.compile; @@ -186,6 +187,7 @@ private ImmutableList generateTokens() throws LexException { ImmutableList result = tokens.build(); result = joinAdjacentLiteralsAndAdjacentWhitespace(result); + result = joinLiteralsAcrossWhitespace(result, classicJavadoc); if (classicJavadoc) { result = inferParagraphTags(result); } @@ -202,10 +204,12 @@ private Token processMarkdownToken(Token markdownToken) { switch (markdownToken) { case MarkdownCodeSpanStart unused -> { contextStack.push(NestingContext.MARKDOWN_CODE_CONTEXT); + somethingSinceNewline = true; return new Literal(markdownToken.value()); } case MarkdownCodeSpanEnd unused -> { contextStack.popUntil(NestingContext.MARKDOWN_CODE_CONTEXT); + somethingSinceNewline = true; return new Literal(markdownToken.value()); } case Literal literal -> { @@ -264,6 +268,7 @@ private Function consumeToken() throws LexException { // // Backslash has no special meaning inside `...` so this code precedes the backslash code. verify(input.tryConsumeRegex(WORD_IN_CODE_SPAN_PATTERN)); + somethingSinceNewline = true; return Literal::new; } if (!classicJavadoc) { @@ -334,12 +339,17 @@ private Function consumeToken() throws LexException { return preserveExistingFormatting() ? Literal::new : PreCloseTag::new; } + // In Markdown Javadoc, emit ``/`` as literals (while still tracking + // HTML_CODE_CONTEXT) so they coalesce with adjacent literals and `joinLiteralsAcrossWhitespace` + // can pin following block markers (e.g., `end -`) onto them. Classic Javadoc keeps + // `CodeOpenTag`/`CodeCloseTag` because `inferParagraphTags` only inserts `

` between + // `Literal` tokens. if (input.tryConsumeRegex(CODE_OPEN_PATTERN)) { contextStack.push(NestingContext.HTML_CODE_CONTEXT); - return preserveExistingFormatting ? Literal::new : CodeOpenTag::new; + return (!classicJavadoc || preserveExistingFormatting) ? Literal::new : CodeOpenTag::new; } else if (input.tryConsumeRegex(CODE_CLOSE_PATTERN)) { contextStack.popUntil(NestingContext.HTML_CODE_CONTEXT); - return preserveExistingFormatting() ? Literal::new : CodeCloseTag::new; + return (!classicJavadoc || preserveExistingFormatting()) ? Literal::new : CodeCloseTag::new; } if (input.tryConsumeRegex(TABLE_OPEN_PATTERN)) { @@ -426,54 +436,127 @@ private static ImmutableList joinAdjacentLiteralsAndAdjacentWhitespace(Li continue; } - /* - * IF we have accumulated some literals to join together (say, "foobar"), and IF we'll - * next see whitespace followed by a "@" literal, we need to join that together with the - * previous literals. That ensures that we won't insert a line break before the "@," turning - * it into a tag. - */ + if (!accumulated.isEmpty()) { + output.add(new Literal(accumulated.toString())); + accumulated.setLength(0); + } - if (accumulated.isEmpty()) { - if (tokens.peek() instanceof Whitespace) { - output.add(new Whitespace(consumeAdjacentWhitespace(tokens))); - } else { - output.add(tokens.next()); - } - continue; + if (tokens.peek() instanceof Whitespace) { + output.add(new Whitespace(consumeAdjacentWhitespace(tokens))); + } else { + output.add(tokens.next()); } + } - String seenWhitespace = consumeAdjacentWhitespace(tokens); + return output.build(); + } - if (tokens.peek() instanceof Literal literal && literal.value().startsWith("@")) { - // OK, we're in the case described above. - accumulated.append(" "); - accumulated.append(tokens.next().value()); + /// Join literal tokens separated by whitespace when breaking between them would change the + /// meaning of the comment (for example, placing `@` or a Markdown block marker at the start of a + /// wrapped line) or when joining a hyphenated word broken across a line. + /// + /// This method must be called after [#joinAdjacentLiteralsAndAdjacentWhitespace], as it assumes + /// that adjacent literal tokens and adjacent whitespace tokens (including ignored + /// [BlockQuoteMarker] tokens) have already been merged. + private static ImmutableList joinLiteralsAcrossWhitespace( + List input, boolean classicJavadoc) { + ImmutableList.Builder output = ImmutableList.builder(); + StringBuilder accumulated = new StringBuilder(); + + for (int i = 0; i < input.size(); ) { + Token token = input.get(i); + if (token instanceof Literal) { + accumulated.append(token.value()); + i++; continue; } - if (seenWhitespace.contains("\n") - && !hasMultipleNewlines(seenWhitespace) - && isHyphenatedWordEnd(accumulated) - && tokens.peek() instanceof Literal literal - && isWordStart(literal.value()) - && !isSuspendedHyphenConjunction(literal.value())) { - accumulated.append(tokens.next().value()); + if (accumulated.isEmpty()) { + if (!classicJavadoc && token instanceof FooterJavadocTagStart) { + StringBuilder tagText = new StringBuilder(token.value()); + i++; + while (isSameParagraphWhitespace(input.get(i)) + && input.get(i + 1) instanceof Literal next + && couldStartMarkdownBlock(input, i + 1)) { + tagText.append(" ").append(next.value()); + i += 2; + } + output.add(new FooterJavadocTagStart(tagText.toString())); + continue; + } + output.add(token); + i++; continue; } - output.add(new Literal(accumulated.toString())); - accumulated.setLength(0); - - if (!seenWhitespace.isEmpty()) { - output.add(new Whitespace(seenWhitespace)); + if (isSameParagraphWhitespace(token) && input.get(i + 1) instanceof Literal next) { + String nextValue = next.value(); + if (nextValue.startsWith("@")) { + /* + * If we see whitespace followed by a "@" literal, join it onto the previous literal so + * we won't insert a line break before "@", turning it into a tag. + */ + accumulated.append(" ").append(nextValue); + i += 2; + continue; + } + if (token.value().contains("\n") + && isHyphenatedWordEnd(accumulated) + && isWordStart(nextValue) + && !isSuspendedHyphenConjunction(nextValue)) { + accumulated.append(nextValue); + i += 2; + continue; + } + if (!classicJavadoc && couldStartMarkdownBlock(input, i + 1)) { + /* + * In Markdown Javadoc, joining a block-marker literal onto the preceding literal + * prevents line wrapping from placing the marker at the start of a continuation line, + * where CommonMark would parse it as a list, block quote, heading, code fence, + * thematic break, table separator, or HTML block. + */ + accumulated.append(" ").append(nextValue); + i += 2; + continue; + } } - // We have another token coming. Leave it for the next iteration. + output.add(new Literal(accumulated.toString())); + accumulated.setLength(0); + output.add(token); + i++; } return output.build(); } + private static boolean isSameParagraphWhitespace(Token token) { + return token instanceof Whitespace whitespace && !hasMultipleNewlines(whitespace.value()); + } + + private static boolean couldStartMarkdownBlock(List input, int index) { + String s = input.get(index).value(); + return switch (s.charAt(0)) { + case '>' -> true; + case '+' -> s.equals("+"); + case '~' -> s.startsWith("~~~"); + case '<' -> MARKDOWN_HTML_BLOCK_START_PATTERN.matcher(s).lookingAt(); + case '-', ':' -> MARKDOWN_TABLE_SEPARATOR_PATTERN.matcher(s).matches(); + case '|' -> + s.equals("|") + ? isFollowedByTableSeparator(input, index) + : MARKDOWN_TABLE_SEPARATOR_PATTERN.matcher(s).matches(); + case '*', '_', '=', '#', '0', '1', '`' -> MARKDOWN_BLOCK_MARKER_PATTERN.matcher(s).matches(); + default -> false; + }; + } + + private static boolean isFollowedByTableSeparator(List input, int pipeIndex) { + return isSameParagraphWhitespace(input.get(pipeIndex + 1)) + && input.get(pipeIndex + 2) instanceof Literal next + && MARKDOWN_TABLE_SEPARATOR_PATTERN.matcher(next.value()).matches(); + } + private static boolean isHyphenatedWordEnd(CharSequence cs) { int length = cs.length(); return length >= 2 && cs.charAt(length - 1) == '-' && isWordChar(cs.charAt(length - 2)); @@ -729,6 +812,46 @@ static boolean hasMultipleNewlines(String s) { private static final Pattern MARKDOWN_HARD_LINE_BREAK_PATTERN = compile("\\\\[ \t]*\n"); private static final Pattern BACKSLASH_PLUS_CHARACTER_PATTERN = compile("\\\\."); + // Bullet list `-`, setext heading underlines (`-`, `--`), thematic breaks (`---`), and GFM table + // separator tokens (`|-|`, `|---`, `:--`, `--:`, etc.). + private static final Pattern MARKDOWN_TABLE_SEPARATOR_PATTERN = compile("[:|-]*-[:|-]*"); + + // Whole whitespace-delimited tokens that CommonMark may parse as a block start if placed at the + // start of a wrapped line: + // - `*+`, `_+`, `=+`: bullet list `*`, thematic breaks, setext heading underlines + // - `#{1,6}`: ATX headings + // - `0{0,8}1[.)]`: ordered list items (only start number 1 can interrupt a paragraph) + // - `` `{3,}[^`]* ``: backtick code fence openers (no subsequent backtick on the same token) + private static final Pattern MARKDOWN_BLOCK_MARKER_PATTERN = + compile("\\*+|_+|=+|#{1,6}|0{0,8}1[.)]|`{3,}[^`]*"); + + // CommonMark HTML block types 1-6, which can interrupt a paragraph (type 7 cannot). + private static final Pattern MARKDOWN_HTML_BLOCK_START_PATTERN = + compile( + """ + <(?:script|pre|style|textarea)(?:>|$) + |`. + /// Returns an HTML fragment representing the rendered widget content, such as `foo bar baz + /// value `. void f() {} - /// Use this helper method when rendering an inline element rather than a full standalone block - ///

element. + /// Use this helper method when rendering an inline element rather than a full standalone + /// block
element. void g() {} + + /// Returns an HTML fragment representing the rendered widget content, such as `foo bar baz + /// value
`. + void h() {} + + /// Returns an HTML fragment representing the rendered widget content, such as `foo bar baz + /// value
`. + void i() {} + + /// Returns an HTML fragment representing the rendered widget content, such as `foo bar baz + /// value `. + void j() {} + + /// Returns an HTML fragment representing the rendered widget content, such as `foo bar baz + /// value `. + void k() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); } @Test @@ -3422,12 +3455,11 @@ class T { void a() {} } """; - // TODO(b/587865985): Wrapping before - after turns the continuation line into a list. String expected = """ class T { - /// Returns the number of elements in the full range of an array, always equal to end - /// - start. + /// Returns the number of elements in the full range of an array, always equal to + /// end - start. void a() {} } """; @@ -3435,7 +3467,7 @@ void a() {} } @Test - public void markdownWrapMultipleConsecutiveBlockMarkers() throws FormatterException { + public void markdownWrapMultipleConsecutiveBlockMarkers() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3444,17 +3476,15 @@ class T { void a() {} } """; - // TODO(b/587865985): None of the consecutive block markers should start a wrapped line (and - // formatting a second time splits - and + into nested lists). String expected = """ class T { - /// Returns the combined result of evaluating the sequence of operators in the given expression `a - /// - + > b`. + /// Returns the combined result of evaluating the sequence of operators in the given expression + /// `a - + > b`. void a() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); } @Test @@ -3486,6 +3516,12 @@ void g() {} /// Returns the formatted output containing an escaped hyphen marker written explicitly with char \\- in the prose. void h() {} + + /// Returns the bitwise union produced by combining the first flag mask with the second flag id `a | b`. + void i() {} + + /// Returns the mapping between the input key and its corresponding computed output value labeled : value. + void j() {} } """; String expected = @@ -3522,6 +3558,151 @@ void g() {} /// Returns the formatted output containing an escaped hyphen marker written explicitly with char /// \\- in the prose. void h() {} + + /// Returns the bitwise union produced by combining the first flag mask with the second flag id `a + /// | b`. + void i() {} + + /// Returns the mapping between the input key and its corresponding computed output value labeled + /// : value. + void j() {} + } + """; + doFormatTest(input, expected); + } + + @Test + public void markdownCodeSpanInsideBlockQuoteAndBeforeBlockTag() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// > `> foo` + void a() {} + + /// > `foo + /// > ` > bar + void b() {} + + /// `foo + /// ` @param bar + void c() {} + + /// > `first + /// > start > end` + void d() {} + } + """; + String expected = + """ + class T { + /// > `> foo` + void a() {} + + /// > `foo ` > bar + void b() {} + + /// `foo ` @param bar + void c() {} + + /// > `first start > end` + void d() {} + } + """; + doFormatTest(input, expected); + } + + @Test + public void markdownWrapBeforeBlockMarkerAfterFooterTag() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// Summary. + /// + /// @return >veryLongIdentifierNameThatExceedsTheRemainingLineLengthAndWrapsOntoItsOwnLineForTestingCase12345 + void a() {} + + /// Summary. + /// + /// @return ~~~veryLongIdentifierNameThatExceedsTheRemainingLineLengthAndWrapsOntoItsOwnLineForTestingCase12345 + void b() {} + + /// Summary. + /// + /// @param - description + void c() {} + } + """; + String expected = + """ + class T { + /// Summary. + /// + /// @return >veryLongIdentifierNameThatExceedsTheRemainingLineLengthAndWrapsOntoItsOwnLineForTestingCase12345 + void a() {} + + /// Summary. + /// + /// @return ~~~veryLongIdentifierNameThatExceedsTheRemainingLineLengthAndWrapsOntoItsOwnLineForTestingCase12345 + void b() {} + + /// Summary. + /// + /// @param - + /// description + void c() {} + } + """; + doFormatTest(input, expected); + } + + @Test + public void markdownWrapBlockMarkerAcrossBlockQuoteLines() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// > Throws an exception if the requested indices are out of bounds for an array, i.e., if `start + /// > + + /// > end`. + void a() {} + + /// > Separates a header | column from a body section using a standard marker token sequence word | + /// > :-: + void b() {} + + /// > First paragraph in a block quote + /// > + /// > = + void c() {} + + /// >
foo
+ /// > + /// >
bar
+ void d() {} + } + """; + String expected = + """ + class T { + /// > Throws an exception if the requested indices are out of bounds for an array, i.e., if + /// > `start + end`. + void a() {} + + /// > Separates a header | column from a body section using a standard marker token sequence + /// > word | :-: + void b() {} + + /// > First paragraph in a block quote + /// > + /// > = + void c() {} + + /// >
foo
+ /// > + /// >
bar
+ void d() {} } """; doFormatTest(input, expected);