From 57967f7526e6935ce5e960b9817ce2012f337416 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 14 Oct 2026 02:05:30 -0700 Subject: [PATCH] Migrate from traditional Javadoc `/** ... */` to Markdown Javadoc `/// ...` PiperOrigin-RevId: 999216394 --- .../com/google/googlejavaformat/CloseOp.java | 16 +- .../googlejavaformat/CommentsHelper.java | 20 +- .../java/com/google/googlejavaformat/Doc.java | 288 +++++++--------- .../google/googlejavaformat/DocBuilder.java | 77 ++--- .../googlejavaformat/FormatterDiagnostic.java | 16 +- .../googlejavaformat/FormattingError.java | 2 +- .../com/google/googlejavaformat/Indent.java | 11 +- .../com/google/googlejavaformat/Input.java | 112 +++---- .../google/googlejavaformat/InputOutput.java | 46 ++- .../com/google/googlejavaformat/Newlines.java | 28 +- .../java/com/google/googlejavaformat/Op.java | 17 +- .../com/google/googlejavaformat/OpenOp.java | 19 +- .../google/googlejavaformat/OpsBuilder.java | 195 +++++------ .../com/google/googlejavaformat/Output.java | 42 +-- .../java/CommandLineOptions.java | 42 ++- .../java/CommandLineOptionsParser.java | 26 +- .../java/DimensionHelpers.java | 51 ++- .../java/FormatFileCallable.java | 6 +- .../googlejavaformat/java/Formatter.java | 159 ++++----- .../java/FormatterException.java | 2 +- .../java/GoogleJavaFormatTool.java | 2 +- .../java/GoogleJavaFormatToolProvider.java | 2 +- .../googlejavaformat/java/ImportOrderer.java | 170 +++++----- .../java/JavaCommentsHelper.java | 2 +- .../java/JavaFormatterOptions.java | 69 ++-- .../googlejavaformat/java/JavaInput.java | 173 ++++------ .../java/JavaInputAstVisitor.java | 309 ++++++++---------- .../googlejavaformat/java/JavaOutput.java | 54 ++- .../googlejavaformat/java/JavacTokens.java | 34 +- .../google/googlejavaformat/java/Main.java | 40 +-- .../java/ModifierOrderer.java | 25 +- .../java/RemoveUnusedImports.java | 12 +- .../googlejavaformat/java/Replacement.java | 10 +- .../java/SnippetFormatter.java | 12 +- .../googlejavaformat/java/StringWrapper.java | 50 ++- .../google/googlejavaformat/java/Trees.java | 22 +- .../java/TypeNameClassifier.java | 40 +-- .../googlejavaformat/java/UsageException.java | 2 +- .../java/filer/FormattingFiler.java | 37 +-- .../java/filer/FormattingJavaFileObject.java | 14 +- .../java/javadoc/CharStream.java | 18 +- .../java/javadoc/JavadocFormatter.java | 42 +-- .../java/javadoc/JavadocLexer.java | 111 +++---- .../java/javadoc/JavadocWriter.java | 53 ++- .../java/javadoc/MarkdownPositions.java | 40 +-- .../java/javadoc/NestingStack.java | 27 +- .../googlejavaformat/java/javadoc/Token.java | 194 +++++------ .../google/googlejavaformat/NewlinesTest.java | 2 +- .../java/ArrayDimensionTest.java | 6 +- .../java/CommandLineFlagsTest.java | 2 +- .../java/CommandLineOptionsParserTest.java | 2 +- .../googlejavaformat/java/DiagnosticTest.java | 2 +- .../java/FormatterIntegrationTest.java | 2 +- .../googlejavaformat/java/FormatterTest.java | 2 +- .../GoogleJavaFormatToolProviderTest.java | 2 +- .../java/GoogleJavaFormatToolTest.java | 2 +- .../java/ImportOrdererTest.java | 6 +- .../java/JavadocFormattingTest.java | 8 +- .../java/LineRangesToCharRangesTest.java | 2 +- .../googlejavaformat/java/MainTest.java | 2 +- .../java/ModifierOrdererTest.java | 2 +- .../java/PartialFormattingTest.java | 2 +- .../RemoveUnusedImportsCaseLabelsTest.java | 2 +- .../java/RemoveUnusedImportsTest.java | 2 +- .../java/ReplacementTest.java | 2 +- .../java/SnippetFormatterTest.java | 2 +- .../java/StringWrapperIntegrationTest.java | 2 +- .../java/StringWrapperTest.java | 2 +- .../java/TypeNameClassifierTest.java | 2 +- .../java/filer/FormattingFilerTest.java | 2 +- 70 files changed, 1171 insertions(+), 1628 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/CloseOp.java b/core/src/main/java/com/google/googlejavaformat/CloseOp.java index 59e7e5a28..05f0909ff 100644 --- a/core/src/main/java/com/google/googlejavaformat/CloseOp.java +++ b/core/src/main/java/com/google/googlejavaformat/CloseOp.java @@ -16,19 +16,15 @@ import com.google.common.base.MoreObjects; -/** - * A {@code CloseOp} closes a level. It is an {@link Op} in the sequence of {@link Op}s generated by - * {@link OpsBuilder}. When the sequence is turned into a {@link Doc} by {@link DocBuilder}, ranges - * delimited by {@link OpenOp}-{@code CloseOp} pairs turn into nested {@link Doc.Level}s. - */ +/// A `CloseOp` closes a level. It is an [Op] in the sequence of [Op]s generated by [OpsBuilder]. +/// When the sequence is turned into a [Doc] by [DocBuilder], ranges delimited by [OpenOp]-`CloseOp` +/// pairs turn into nested [Doc.Level]s. public enum CloseOp implements Op { CLOSE; - /** - * Make a {@code CloseOp}, returning a singleton since they are all the same. - * - * @return the singleton {@code CloseOp} - */ + /// Make a `CloseOp`, returning a singleton since they are all the same. + /// + /// @return the singleton `CloseOp` public static Op make() { return CLOSE; } diff --git a/core/src/main/java/com/google/googlejavaformat/CommentsHelper.java b/core/src/main/java/com/google/googlejavaformat/CommentsHelper.java index 1e33003b0..6910e6fc6 100644 --- a/core/src/main/java/com/google/googlejavaformat/CommentsHelper.java +++ b/core/src/main/java/com/google/googlejavaformat/CommentsHelper.java @@ -18,19 +18,15 @@ import java.util.Optional; import java.util.regex.Pattern; -/** - * Rewrite comments. This interface is implemented by {@link - * com.google.googlejavaformat.java.JavaCommentsHelper JavaCommentsHelper}. - */ +/// Rewrite comments. This interface is implemented by +/// [`JavaCommentsHelper`][com.google.googlejavaformat.java.JavaCommentsHelper]. public interface CommentsHelper { - /** - * Try to rewrite comments, returning rewritten text. - * - * @param tok the comment's tok - * @param maxWidth the line length for the output - * @param column0 the current column - * @return the rewritten comment - */ + /// Try to rewrite comments, returning rewritten text. + /// + /// @param tok the comment's tok + /// @param maxWidth the line length for the output + /// @param column0 the current column + /// @return the rewritten comment String rewrite(Input.Tok tok, int maxWidth, int column0); static Optional reformatParameterComment(Tok tok) { diff --git a/core/src/main/java/com/google/googlejavaformat/Doc.java b/core/src/main/java/com/google/googlejavaformat/Doc.java index 6c632666a..dc33eb373 100644 --- a/core/src/main/java/com/google/googlejavaformat/Doc.java +++ b/core/src/main/java/com/google/googlejavaformat/Doc.java @@ -29,51 +29,36 @@ import java.util.List; import java.util.Optional; -/** - * {@link com.google.googlejavaformat.java.JavaInputAstVisitor JavaInputAstVisitor} outputs a - * sequence of {@link Op}s using {@link OpsBuilder}. This linear sequence is then transformed by - * {@link DocBuilder} into a tree-structured {@code Doc}. The top-level {@code Doc} is a {@link - * Level}, which contains a sequence of {@code Doc}s, including other {@link Level}s. Leaf {@code - * Doc}s are {@link Token}s, representing language-level tokens; {@link Tok}s, which may also - * represent non-token {@link Input.Tok}s, including comments and other white-space; {@link Space}s, - * representing single spaces; and {@link Break}s, which represent optional line-breaks. - */ +/// [`JavaInputAstVisitor`][com.google.googlejavaformat.java.JavaInputAstVisitor] outputs a sequence +/// of [Op]s using [OpsBuilder]. This linear sequence is then transformed by [DocBuilder] into a +/// tree-structured `Doc`. The top-level `Doc` is a [Level], which contains a sequence of `Doc`s, +/// including other [Level]s. Leaf `Doc`s are [Token]s, representing language-level tokens; [Tok]s, +/// which may also represent non-token [Input.Tok]s, including comments and other white-space; +/// [Space]s, representing single spaces; and [Break]s, which represent optional line-breaks. public abstract class Doc { - /** - * Each {@link Break} in a {@link Level} is either {@link FillMode#UNIFIED} or {@link - * FillMode#INDEPENDENT}. - */ + /// Each [Break] in a [Level] is either [FillMode#UNIFIED] or [FillMode#INDEPENDENT]. public enum FillMode { - /** - * If a {@link Level} will not fit on one line, all of its {@code UNIFIED} {@link Break}s will - * be broken. - */ + /// If a [Level] will not fit on one line, all of its `UNIFIED` [Break]s will be broken. UNIFIED, - /** - * If a {@link Level} will not fit on one line, its {@code INDEPENDENT} {@link Break}s will be - * broken independently of each other, to fill in the {@link Level}. - */ + /// If a [Level] will not fit on one line, its `INDEPENDENT` [Break]s will be broken + /// independently of each other, to fill in the [Level]. INDEPENDENT, - /** - * A {@code FORCED} {@link Break} will always be broken, and a {@link Level} it appears in will - * not fit on one line. - */ + /// A `FORCED` [Break] will always be broken, and a [Level] it appears in will not fit on one + /// line. FORCED } - /** - * The maximum supported line width. - * - *

This can be used as a sentinel/threshold for {@code Doc}s that break unconditionally. - * - *

The value was selected to be obviously too large for any practical line, but small enough to - * prevent accidental overflow. - */ + /// The maximum supported line width. + /// + /// This can be used as a sentinel/threshold for `Doc`s that break unconditionally. + /// + /// The value was selected to be obviously too large for any practical line, but small enough to + /// prevent accidental overflow. public static final int MAX_LINE_WIDTH = 1000; - /** State for writing. */ + /// State for writing. public record State(int lastIndent, int indent, int column, boolean mustBreak) { public State(int indent0, int column0) { this(indent0, indent0, column0, false); @@ -99,68 +84,54 @@ State withMustBreak(boolean mustBreak) { // Memoized Range. private final Supplier> range = Suppliers.memoize(this::computeRange); - /** - * Return the width of a {@code Doc}. - * - * @return the width - */ + /// Return the width of a `Doc`. + /// + /// @return the width final int getWidth() { return width.get(); } - /** - * Return a {@code Doc}'s flat-string value; not defined (and never called) if the {@code Doc} - * contains forced breaks. - * - * @return the flat-string value - */ + /// Return a `Doc`'s flat-string value; not defined (and never called) if the `Doc` contains + /// forced breaks. + /// + /// @return the flat-string value final String getFlat() { return flat.get(); } - /** - * Return the {@link Range} of a {@code Doc}. - * - * @return the {@code Doc}'s {@link Range} - */ + /// Return the [Range] of a `Doc`. + /// + /// @return the `Doc`'s [Range] final Range range() { return range.get(); } - /** - * Compute the {@code Doc}'s width. - * - * @return the width - */ + /// Compute the `Doc`'s width. + /// + /// @return the width abstract int computeWidth(); - /** - * Compute the {@code Doc}'s flat value. Not defined (and never called) if contains forced breaks. - * - * @return the flat value - */ + /// Compute the `Doc`'s flat value. Not defined (and never called) if contains forced breaks. + /// + /// @return the flat value abstract String computeFlat(); - /** - * Compute the {@code Doc}'s {@link Range} of {@link Input.Token}s. - * - * @return the {@link Range} - */ + /// Compute the `Doc`'s [Range] of [Input.Token]s. + /// + /// @return the [Range] abstract Range computeRange(); - /** - * Make breaking decisions for a {@code Doc}. - * - * @param maxWidth the maximum line width - * @param state the current output state - * @return the new output state - */ + /// Make breaking decisions for a `Doc`. + /// + /// @param maxWidth the maximum line width + /// @param state the current output state + /// @return the new output state public abstract State computeBreaks(CommentsHelper commentsHelper, int maxWidth, State state); - /** Write a {@code Doc} to an {@link Output}, after breaking decisions have been made. */ + /// Write a `Doc` to an [Output], after breaking decisions have been made. public abstract void write(Output output); - /** A {@code Level} inside a {@link Doc}. */ + /// A `Level` inside a [Doc]. static final class Level extends Doc { private final Indent plusIndent; // The extra indent following breaks. private final List docs = new ArrayList<>(); // The elements of the level. @@ -169,21 +140,17 @@ private Level(Indent plusIndent) { this.plusIndent = plusIndent; } - /** - * Factory method for {@code Level}s. - * - * @param plusIndent the extra indent inside the {@code Level} - * @return the new {@code Level} - */ + /// Factory method for `Level`s. + /// + /// @param plusIndent the extra indent inside the `Level` + /// @return the new `Level` static Level make(Indent plusIndent) { return new Level(plusIndent); } - /** - * Add a {@link Doc} to the {@code Level}. - * - * @param doc the {@link Doc} to add - */ + /// Add a [Doc] to the `Level`. + /// + /// @param doc the [Doc] to add void add(Doc doc) { docs.add(doc); } @@ -215,16 +182,13 @@ Range computeRange() { // writing output. // TODO(cushon): represent phases as separate immutable data. - /** True if the entire {@link Level} fits on one line. */ + /// True if the entire [Level] fits on one line. boolean oneLine = false; - /** - * Groups of {@link Doc}s that are children of the current {@link Level}, separated by {@link - * Break}s. - */ + /// Groups of [Doc]s that are children of the current [Level], separated by [Break]s. List> splits = new ArrayList<>(); - /** {@link Break}s between {@link Doc}s in the current {@link Level}. */ + /// [Break]s between [Doc]s in the current [Level]. List breaks = new ArrayList<>(); @Override @@ -254,7 +218,7 @@ private static void splitByBreaks(List docs, List> splits, List docs) { int width = 0; for (Doc doc : docs) { @@ -358,9 +320,9 @@ public String toString() { } } - /** A leaf {@link Doc} for a token. */ + /// A leaf [Doc] for a token. public static final class Token extends Doc implements Op { - /** Is a Token a real token, or imaginary (e.g., a token generated incorrectly, or an EOF)? */ + /// Is a Token a real token, or imaginary (e.g., a token generated incorrectly, or an EOF)? public enum RealOrImaginary { REAL, IMAGINARY; @@ -390,29 +352,25 @@ private Token( this.breakAndIndentTrailingComment = breakAndIndentTrailingComment; } - /** - * How much extra to indent comments before the {@code Token}. - * - * @return the extra indent - */ + /// How much extra to indent comments before the `Token`. + /// + /// @return the extra indent public Indent getPlusIndentCommentsBefore() { return plusIndentCommentsBefore; } - /** Force a line break and indent trailing javadoc or block comments. */ + /// Force a line break and indent trailing javadoc or block comments. public Optional breakAndIndentTrailingComment() { return breakAndIndentTrailingComment; } - /** - * Make a {@code Token}. - * - * @param token the {@link Input.Token} to wrap - * @param realOrImaginary did this {@link Input.Token} appear in the input, or was it generated - * incorrectly? - * @param plusIndentCommentsBefore extra {@code plusIndent} for comments just before this token - * @return the new {@code Token} - */ + /// Make a `Token`. + /// + /// @param token the [Input.Token] to wrap + /// @param realOrImaginary did this [Input.Token] appear in the input, or was it generated + /// incorrectly? + /// @param plusIndentCommentsBefore extra `plusIndent` for comments just before this token + /// @return the new `Token` static Op make( Input.Token token, Doc.Token.RealOrImaginary realOrImaginary, @@ -422,20 +380,16 @@ static Op make( token, realOrImaginary, plusIndentCommentsBefore, breakAndIndentTrailingComment); } - /** - * Return the wrapped {@link Input.Token}. - * - * @return the {@link Input.Token} - */ + /// Return the wrapped [Input.Token]. + /// + /// @return the [Input.Token] public Input.Token getToken() { return token; } - /** - * Is the token good? That is, does it match an {@link Input.Token}? - * - * @return whether the @code Token} is good - */ + /// Is the token good? That is, does it match an [Input.Token]? + /// + /// @return whether the `Token` is good public RealOrImaginary realOrImaginary() { return realOrImaginary; } @@ -482,17 +436,15 @@ public String toString() { } } - /** A Leaf node in a {@link Doc} for a non-breaking space. */ + /// A Leaf node in a [Doc] for a non-breaking space. public static final class Space extends Doc implements Op { private static final Space SPACE = new Space(); private Space() {} - /** - * Factor method for {@code Space}. - * - * @return the new {@code Space} - */ + /// Factor method for `Space`. + /// + /// @return the new `Space` static Space make() { return SPACE; } @@ -533,7 +485,7 @@ public String toString() { } } - /** A leaf node in a {@link Doc} for an optional break. */ + /// A leaf node in a [Doc] for an optional break. public static final class Break extends Doc implements Op { private final FillMode fillMode; private final String flat; @@ -547,55 +499,45 @@ private Break(FillMode fillMode, String flat, Indent plusIndent, Optional optTag) { return new Break(fillMode, flat, plusIndent, optTag); } - /** - * Make a forced {@code Break}. - * - * @return the new forced {@code Break} - */ + /// Make a forced `Break`. + /// + /// @return the new forced `Break` public static Break makeForced() { return make(FillMode.FORCED, "", Indent.Const.ZERO); } - /** - * Return the {@code Break}'s extra indent. - * - * @return the extra indent - */ + /// Return the `Break`'s extra indent. + /// + /// @return the extra indent int getPlusIndent() { return plusIndent.eval(); } - /** - * Is the {@code Break} forced? - * - * @return whether the {@code Break} is forced - */ + /// Is the `Break` forced? + /// + /// @return whether the `Break` is forced boolean isForced() { return fillMode == FillMode.FORCED; } @@ -636,10 +578,10 @@ Range computeRange() { return EMPTY_RANGE; } - /** Was this break taken? */ + /// Was this break taken? boolean broken; - /** New indent after this break. */ + /// New indent after this break. int newIndent; public State computeBreaks(State state, int lastIndent, boolean broken) { @@ -688,7 +630,7 @@ public String toString() { } } - /** A leaf node in a {@link Doc} for a non-token. */ + /// A leaf node in a [Doc] for a non-token. static final class Tok extends Doc implements Op { private final Input.Tok tok; @@ -696,12 +638,10 @@ private Tok(Input.Tok tok) { this.tok = tok; } - /** - * Factory method for a {@code Tok}. - * - * @param tok the {@link Input.Tok} to wrap - * @return the new {@code Tok} - */ + /// Factory method for a `Tok`. + /// + /// @param tok the [Input.Tok] to wrap + /// @return the new `Tok` static Tok make(Input.Tok tok) { return new Tok(tok); } diff --git a/core/src/main/java/com/google/googlejavaformat/DocBuilder.java b/core/src/main/java/com/google/googlejavaformat/DocBuilder.java index 31cc798a9..50d582900 100644 --- a/core/src/main/java/com/google/googlejavaformat/DocBuilder.java +++ b/core/src/main/java/com/google/googlejavaformat/DocBuilder.java @@ -18,40 +18,35 @@ import java.util.ArrayDeque; import java.util.List; -/** A {@code DocBuilder} converts a sequence of {@link Op}s into a {@link Doc}. */ +/// A `DocBuilder` converts a sequence of [Op]s into a [Doc]. public final class DocBuilder { private final Doc.Level base = Doc.Level.make(Indent.Const.ZERO); private final ArrayDeque stack = new ArrayDeque<>(); - /** - * A possibly earlier {@link Doc.Level} for appending text, à la Philip Wadler. - * - *

Processing {@link Doc}s presents a subtle problem. Suppose we have a {@link Doc} for to an - * assignment node, {@code a = b}, with an optional {@link Doc.Break} following the {@code =}. - * Suppose we have 5 characters to write it, so that we think we don't need the break. - * Unfortunately, this {@link Doc} lies in an expression statement {@link Doc} for the statement - * {@code a = b;} and this statement does not fit in 3 characters. This is why many formatters - * sometimes emit lines that are too long, or cheat by using a narrower line length to avoid such - * problems. - * - *

One solution to this problem is not to decide whether a {@link Doc.Level} should be broken - * until later (in this case, after the semicolon has been seen). A simpler approach is to rewrite - * the {@link Doc} as here, so that the semicolon moves inside the inner {@link Doc}, and we can - * decide whether to break that {@link Doc} without seeing later text. - */ + /// A possibly earlier [Doc.Level] for appending text, à la Philip Wadler. + /// + /// Processing [Doc]s presents a subtle problem. Suppose we have a [Doc] for to an assignment + /// node, `a = b`, with an optional [Doc.Break] following the `=`. Suppose we have 5 characters to + /// write it, so that we think we don't need the break. Unfortunately, this [Doc] lies in an + /// expression statement [Doc] for the statement `a = b;` and this statement does not fit in 3 + /// characters. This is why many formatters sometimes emit lines that are too long, or cheat by + /// using a narrower line length to avoid such problems. + /// + /// One solution to this problem is not to decide whether a [Doc.Level] should be broken until + /// later (in this case, after the semicolon has been seen). A simpler approach is to rewrite the + /// [Doc] as here, so that the semicolon moves inside the inner [Doc], and we can decide whether + /// to break that [Doc] without seeing later text. private Doc.Level appendLevel = base; - /** Start to build a {@code DocBuilder}. */ + /// Start to build a `DocBuilder`. public DocBuilder() { stack.addLast(base); } - /** - * Add a list of {@link Op}s to the {@link OpsBuilder}. - * - * @param ops the {@link Op}s - * @return the {@link OpsBuilder} - */ + /// Add a list of [Op]s to the [OpsBuilder]. + /// + /// @param ops the [Op]s + /// @return the [OpsBuilder] public DocBuilder withOps(List ops) { for (Op op : ops) { op.add(this); // These operations call the operations below to build the doc. @@ -59,46 +54,38 @@ public DocBuilder withOps(List ops) { return this; } - /** - * Open a new {@link Doc.Level}. - * - * @param plusIndent the extra indent for the {@link Doc.Level} - */ + /// Open a new [Doc.Level]. + /// + /// @param plusIndent the extra indent for the [Doc.Level] void open(Indent plusIndent) { Doc.Level level = Doc.Level.make(plusIndent); stack.addLast(level); } - /** Close the current {@link Doc.Level}. */ + /// Close the current [Doc.Level]. void close() { Doc.Level top = stack.removeLast(); stack.peekLast().add(top); } - /** - * Add a {@link Doc} to the current {@link Doc.Level}. - * - * @param doc the {@link Doc} - */ + /// Add a [Doc] to the current [Doc.Level]. + /// + /// @param doc the [Doc] void add(Doc doc) { appendLevel.add(doc); } - /** - * Add a {@link Doc.Break} to the current {@link Doc.Level}. - * - * @param breakDoc the {@link Doc.Break} - */ + /// Add a [Doc.Break] to the current [Doc.Level]. + /// + /// @param breakDoc the [Doc.Break] void breakDoc(Doc.Break breakDoc) { appendLevel = stack.peekLast(); appendLevel.add(breakDoc); } - /** - * Return the {@link Doc}. - * - * @return the {@link Doc} - */ + /// Return the [Doc]. + /// + /// @return the [Doc] public Doc build() { return base; } diff --git a/core/src/main/java/com/google/googlejavaformat/FormatterDiagnostic.java b/core/src/main/java/com/google/googlejavaformat/FormatterDiagnostic.java index f0218d1de..af395da70 100644 --- a/core/src/main/java/com/google/googlejavaformat/FormatterDiagnostic.java +++ b/core/src/main/java/com/google/googlejavaformat/FormatterDiagnostic.java @@ -17,15 +17,13 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -/** - * An error that prevented formatting from succeeding. - * - * @param line the line number on which the error occurred, or {@code -1} if the error does not have - * a line number. - * @param column the 1-indexed column number on which the error occurred, or {@code -1} if the error - * does not have a column. - * @param message a description of the problem that prevented formatting from succeeding. - */ +/// An error that prevented formatting from succeeding. +/// +/// @param line the line number on which the error occurred, or `-1` if the error does not have a +/// line number. +/// @param column the 1-indexed column number on which the error occurred, or `-1` if the error does +/// not have a column. +/// @param message a description of the problem that prevented formatting from succeeding. public record FormatterDiagnostic(int line, int column, String message) { public FormatterDiagnostic { checkArgument(line >= -1); diff --git a/core/src/main/java/com/google/googlejavaformat/FormattingError.java b/core/src/main/java/com/google/googlejavaformat/FormattingError.java index 50381d0cd..8ff8a3902 100644 --- a/core/src/main/java/com/google/googlejavaformat/FormattingError.java +++ b/core/src/main/java/com/google/googlejavaformat/FormattingError.java @@ -17,7 +17,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; -/** An unchecked formatting error. */ +/// An unchecked formatting error. public class FormattingError extends Error { private final ImmutableList diagnostics; diff --git a/core/src/main/java/com/google/googlejavaformat/Indent.java b/core/src/main/java/com/google/googlejavaformat/Indent.java index 3c12398f6..a88b6f382 100644 --- a/core/src/main/java/com/google/googlejavaformat/Indent.java +++ b/core/src/main/java/com/google/googlejavaformat/Indent.java @@ -17,16 +17,13 @@ import com.google.common.base.MoreObjects; import com.google.googlejavaformat.Output.BreakTag; -/** - * An indent for a {@link Doc.Level} or {@link Doc.Break}. The indent is either a constant {@code - * int}, or a conditional expression whose value depends on whether or not a {@link Doc.Break} has - * been broken. - */ +/// An indent for a [Doc.Level] or [Doc.Break]. The indent is either a constant `int`, or a +/// conditional expression whose value depends on whether or not a [Doc.Break] has been broken. public abstract class Indent { public abstract int eval(); - /** A constant function, returning a constant indent. */ + /// A constant function, returning a constant indent. public static final class Const extends Indent { private final int n; @@ -51,7 +48,7 @@ public String toString() { } } - /** A conditional function, whose value depends on whether a break was taken. */ + /// A conditional function, whose value depends on whether a break was taken. public static final class If extends Indent { private final BreakTag condition; private final Indent thenIndent; diff --git a/core/src/main/java/com/google/googlejavaformat/Input.java b/core/src/main/java/com/google/googlejavaformat/Input.java index ad15e71f8..84f6a2c75 100644 --- a/core/src/main/java/com/google/googlejavaformat/Input.java +++ b/core/src/main/java/com/google/googlejavaformat/Input.java @@ -19,110 +19,90 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableRangeMap; -/** An input to the formatter. */ +/// An input to the formatter. public abstract class Input extends InputOutput { - /** - * A {@code Tok} ("tock") is a token, or a comment, or a newline, or a maximal string of blanks. A - * token {@code Tok} underlies a {@link Token}, and each other {@code Tok} is attached to a single - * {@code Token}. Tokens and comments have indices; white space {@code Tok}s do not. - */ + /// A `Tok` ("tock") is a token, or a comment, or a newline, or a maximal string of blanks. A + /// token `Tok` underlies a [Token], and each other `Tok` is attached to a single `Token`. Tokens + /// and comments have indices; white space `Tok`s do not. public interface Tok { - /** - * Return the {@code Tok}'s index. - * - * @return its index - */ + /// Return the `Tok`'s index. + /// + /// @return its index int getIndex(); - /** - * Return the {@code Tok}'s {@code 0}-based position. - * - * @return its position - */ + /// Return the `Tok`'s `0`-based position. + /// + /// @return its position int getPosition(); - /** - * Return the {@code Tok}'s {@code 0}-based column number. - * - * @return its column number - */ + /// Return the `Tok`'s `0`-based column number. + /// + /// @return its column number int getColumn(); - /** The {@code Tok}'s text. */ + /// The `Tok`'s text. String getText(); - /** The {@code Tok}'s original text (before processing escapes). */ + /// The `Tok`'s original text (before processing escapes). String getOriginalText(); - /** The length of the {@code Tok}'s original text. */ + /// The length of the `Tok`'s original text. int length(); - /** Is the {@code Tok} a newline? */ + /// Is the `Tok` a newline? boolean isNewline(); - /** Is the {@code Tok} a "//" comment? */ + /// Is the `Tok` a "//" comment? boolean isSlashSlashComment(); - /** Is the {@code Tok} a "/*" comment? */ + /// Is the `Tok` a "/*" comment? boolean isSlashStarComment(); - /** Is the {@code Tok} a javadoc comment? */ + /// Is the `Tok` a javadoc comment? boolean isJavadocComment(); - /** Is the {@code Tok} a comment? */ + /// Is the `Tok` a comment? boolean isComment(); } - /** A {@code Token} is a language-level token. */ + /// A `Token` is a language-level token. public interface Token { - /** - * Get the token's {@link Tok}. - * - * @return the token's {@link Tok} - */ + /// Get the token's [Tok]. + /// + /// @return the token's [Tok] Tok getTok(); - /** - * Get the earlier {@link Tok}s assigned to this {@code Token}. - * - * @return the earlier {@link Tok}s assigned to this {@code Token} - */ + /// Get the earlier [Tok]s assigned to this `Token`. + /// + /// @return the earlier [Tok]s assigned to this `Token` ImmutableList getToksBefore(); - /** - * Get the later {@link Tok}s assigned to this {@code Token}. - * - * @return the later {@link Tok}s assigned to this {@code Token} - */ + /// Get the later [Tok]s assigned to this `Token`. + /// + /// @return the later [Tok]s assigned to this `Token` ImmutableList getToksAfter(); } - /** - * Get the input tokens. - * - * @return the input tokens - */ + /// Get the input tokens. + /// + /// @return the input tokens public abstract ImmutableList getTokens(); - /** A map from [start, end] position ranges to {@link Token}s. */ + /// A map from [start, end] position ranges to [Token]s. public abstract ImmutableRangeMap getPositionTokenMap(); public abstract ImmutableMap getPositionToColumnMap(); public abstract String getText(); - /** - * Get the number of toks. - * - * @return the number of toks, excluding the EOF tok - */ + /// Get the number of toks. + /// + /// @return the number of toks, excluding the EOF tok public abstract int getkN(); - /** - * Get the Token by index. - * - * @param k the Tok index - */ + /// Get the Token by index. + /// + /// @param k the Tok index public abstract Token getToken(int k); @Override @@ -130,16 +110,14 @@ public String toString() { return MoreObjects.toStringHelper(this).add("super", super.toString()).toString(); } - /** Converts a character offset in the input to a line number. */ + /// Converts a character offset in the input to a line number. public abstract int getLineNumber(int inputPosition); - /** Converts a character offset in the input to a 0-based column number. */ + /// Converts a character offset in the input to a 0-based column number. public abstract int getColumnNumber(int inputPosition); - /** - * Construct a diagnostic. Populates the input filename, and converts character offsets to - * numbers. - */ + /// Construct a diagnostic. Populates the input filename, and converts character offsets to + /// numbers. public FormatterDiagnostic createDiagnostic(int inputPosition, String message) { return new FormatterDiagnostic( getLineNumber(inputPosition), getColumnNumber(inputPosition), message); diff --git a/core/src/main/java/com/google/googlejavaformat/InputOutput.java b/core/src/main/java/com/google/googlejavaformat/InputOutput.java index f7aa892b4..734b68bc9 100644 --- a/core/src/main/java/com/google/googlejavaformat/InputOutput.java +++ b/core/src/main/java/com/google/googlejavaformat/InputOutput.java @@ -22,38 +22,34 @@ import java.util.List; import java.util.Map; -/** This class defines methods common to an {@link Input} or an {@link Output}. */ +/// This class defines methods common to an [Input] or an [Output]. public abstract class InputOutput { private ImmutableList lines = ImmutableList.of(); protected static final Range EMPTY_RANGE = Range.closedOpen(-1, -1); private static final DiscreteDomain INTEGERS = DiscreteDomain.integers(); - /** Set the lines. */ + /// Set the lines. protected final void setLines(ImmutableList lines) { this.lines = lines; } - /** - * Get the line count. - * - * @return the line count - */ + /// Get the line count. + /// + /// @return the line count public final int getLineCount() { return lines.size(); } - /** - * Get a line. - * - * @param lineI the line number - * @return the line - */ + /// Get a line. + /// + /// @param lineI the line number + /// @return the line public final String getLine(int lineI) { return lines.get(lineI); } - /** The {@link Range}s of the tokens or comments lying on each line, in any part. */ + /// The [Range]s of the tokens or comments lying on each line, in any part. protected final List> ranges = new ArrayList<>(); private static void addToRanges(List> ranges, int i, int k) { @@ -79,13 +75,11 @@ protected final void computeRanges(List toks) { } } - /** - * Given an {@code InputOutput}, compute the map from tok indices to line ranges. - * - * @param put the {@code InputOutput} - * @return the map from {@code com.google.googlejavaformat.java.JavaInput.Tok} indices to line - * ranges in this {@code put} - */ + /// Given an `InputOutput`, compute the map from tok indices to line ranges. + /// + /// @param put the `InputOutput` + /// @return the map from `com.google.googlejavaformat.java.JavaInput.Tok` indices to line ranges + /// in this `put` public static Map> makeKToIJ(InputOutput put) { Map> map = new HashMap<>(); int ijN = put.getLineCount(); @@ -102,12 +96,10 @@ public static Map> makeKToIJ(InputOutput put) { return map; } - /** - * Get the {@link Range} of {@link Input.Tok}s lying in any part on a line. - * - * @param lineI the line number - * @return the {@link Range} of {@link Input.Tok}s on the specified line - */ + /// Get the [Range] of [Input.Tok]s lying in any part on a line. + /// + /// @param lineI the line number + /// @return the [Range] of [Input.Tok]s on the specified line public final Range getRanges(int lineI) { return 0 <= lineI && lineI < ranges.size() ? ranges.get(lineI) : EMPTY_RANGE; } diff --git a/core/src/main/java/com/google/googlejavaformat/Newlines.java b/core/src/main/java/com/google/googlejavaformat/Newlines.java index 20c51b558..5bb28cf6a 100644 --- a/core/src/main/java/com/google/googlejavaformat/Newlines.java +++ b/core/src/main/java/com/google/googlejavaformat/Newlines.java @@ -20,15 +20,15 @@ import java.util.Iterator; import java.util.NoSuchElementException; -/** Platform-independent newline handling. */ +/// Platform-independent newline handling. public class Newlines { - /** Returns the number of line breaks in the input. */ + /// Returns the number of line breaks in the input. public static int count(String input) { return Iterators.size(lineOffsetIterator(input)) - 1; } - /** Returns the index of the first break in the input, or {@code -1}. */ + /// Returns the index of the first break in the input, or `-1`. public static int firstBreak(String input) { Iterator it = lineOffsetIterator(input); it.next(); @@ -52,12 +52,12 @@ public static int lastLineStart(String input) { private static final ImmutableSet BREAKS = ImmutableSet.of("\r\n", "\n", "\r"); - /** Returns true if the entire input string is a recognized line break. */ + /// Returns true if the entire input string is a recognized line break. public static boolean isNewline(String input) { return BREAKS.contains(input); } - /** Returns the length of the newline sequence at the current offset, or {@code -1}. */ + /// Returns the length of the newline sequence at the current offset, or `-1`. public static int hasNewlineAt(String input, int idx) { for (String b : BREAKS) { if (input.startsWith(b, idx)) { @@ -67,10 +67,8 @@ public static int hasNewlineAt(String input, int idx) { return -1; } - /** - * Returns the terminating line break in the input, or {@code null} if the input does not end in a - * break. - */ + /// Returns the terminating line break in the input, or `null` if the input does not end in a + /// break. public static String getLineEnding(String input) { for (String b : BREAKS) { if (input.endsWith(b)) { @@ -80,10 +78,8 @@ public static String getLineEnding(String input) { return null; } - /** - * Returns the first line separator in the text, or {@code "\n"} if the text does not contain a - * single line separator. - */ + /// Returns the first line separator in the text, or `"\n"` if the text does not contain a single + /// line separator. public static String guessLineSeparator(String text) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); @@ -103,17 +99,17 @@ public static String guessLineSeparator(String text) { return "\n"; } - /** Returns true if the input contains any line breaks. */ + /// Returns true if the input contains any line breaks. public static boolean containsBreaks(String text) { return CharMatcher.anyOf("\n\r").matchesAnyOf(text); } - /** Returns an iterator over the start offsets of lines in the input. */ + /// Returns an iterator over the start offsets of lines in the input. public static Iterator lineOffsetIterator(String input) { return new LineOffsetIterator(input); } - /** Returns an iterator over lines in the input, including trailing whitespace. */ + /// Returns an iterator over lines in the input, including trailing whitespace. public static Iterator lineIterator(String input) { return new LineIterator(input); } diff --git a/core/src/main/java/com/google/googlejavaformat/Op.java b/core/src/main/java/com/google/googlejavaformat/Op.java index a48454179..c7783cf69 100644 --- a/core/src/main/java/com/google/googlejavaformat/Op.java +++ b/core/src/main/java/com/google/googlejavaformat/Op.java @@ -14,17 +14,12 @@ package com.google.googlejavaformat; -/** - * An {@code Op} is a member of the sequence of formatting operations emitted by {@link OpsBuilder} - * and transformed by {@link DocBuilder} into a {@link Doc}. Leaf subclasses of {@link Doc} - * implement {@code Op}; {@link Doc.Level} is the only non-leaf, and is represented by paired {@link - * OpenOp}-{@link CloseOp} {@code Op}s. - */ +/// An `Op` is a member of the sequence of formatting operations emitted by [OpsBuilder] and +/// transformed by [DocBuilder] into a [Doc]. Leaf subclasses of [Doc] implement `Op`; [Doc.Level] +/// is the only non-leaf, and is represented by paired [OpenOp]-[CloseOp] `Op`s. public interface Op { - /** - * Add an {@code Op} to a {@link DocBuilder}. - * - * @param builder the {@link DocBuilder} - */ + /// Add an `Op` to a [DocBuilder]. + /// + /// @param builder the [DocBuilder] void add(DocBuilder builder); } diff --git a/core/src/main/java/com/google/googlejavaformat/OpenOp.java b/core/src/main/java/com/google/googlejavaformat/OpenOp.java index e4f86f1a5..61224b133 100644 --- a/core/src/main/java/com/google/googlejavaformat/OpenOp.java +++ b/core/src/main/java/com/google/googlejavaformat/OpenOp.java @@ -16,12 +16,9 @@ import com.google.common.base.MoreObjects; -/** - * An {@code OpenOp} opens a level. It is an {@link Op} in the sequence of {@link Op}s generated by - * {@link OpsBuilder}. When the sequence is turned into a {@link Doc} by {@link DocBuilder}, {@link - * Input.Tok}s delimited by {@code OpenOp}-{@link CloseOp} pairs turn into nested {@link - * Doc.Level}s. - */ +/// An `OpenOp` opens a level. It is an [Op] in the sequence of [Op]s generated by [OpsBuilder]. +/// When the sequence is turned into a [Doc] by [DocBuilder], [Input.Tok]s delimited by +/// `OpenOp`-[CloseOp] pairs turn into nested [Doc.Level]s. public final class OpenOp implements Op { private final Indent plusIndent; @@ -29,12 +26,10 @@ private OpenOp(Indent plusIndent) { this.plusIndent = plusIndent; } - /** - * Make an ordinary {@code OpenOp}. - * - * @param plusIndent the indent for breaks at this level - * @return the {@code OpenOp} - */ + /// Make an ordinary `OpenOp`. + /// + /// @param plusIndent the indent for breaks at this level + /// @return the `OpenOp` public static Op make(Indent plusIndent) { return new OpenOp(plusIndent); } diff --git a/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java b/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java index dbd2eb3ce..ee0a1acd0 100644 --- a/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java +++ b/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java @@ -32,13 +32,10 @@ import java.util.List; import java.util.Optional; -/** - * An {@code OpsBuilder} creates a list of {@link Op}s, which is turned into a {@link Doc} by {@link - * DocBuilder}. - */ +/// An `OpsBuilder` creates a list of [Op]s, which is turned into a [Doc] by [DocBuilder]. public final class OpsBuilder { - /** Returns the actual size of the AST node at position, including comments. */ + /// Returns the actual size of the AST node at position, including comments. public int actualSize(int position, int length) { Token startToken = input.getPositionTokenMap().get(position); int start = startToken.getTok().getPosition(); @@ -57,7 +54,7 @@ public int actualSize(int position, int length) { return end - start; } - /** Returns the start column of the token at {@code position}, including leading comments. */ + /// Returns the start column of the token at `position`, including leading comments. public Integer actualStartColumn(int position) { Token startToken = input.getPositionTokenMap().get(position); int start = startToken.getTok().getPosition(); @@ -73,29 +70,27 @@ public Integer actualStartColumn(int position) { return start; } - /** A request to add or remove a blank line in the output. */ + /// A request to add or remove a blank line in the output. public abstract static class BlankLineWanted { - /** Always emit a blank line. */ + /// Always emit a blank line. public static final BlankLineWanted YES = new SimpleBlankLine(Optional.of(true)); - /** Never emit a blank line. */ + /// Never emit a blank line. public static final BlankLineWanted NO = new SimpleBlankLine(Optional.of(false)); - /** - * Explicitly preserve blank lines from the input (e.g. before the first member in a class - * declaration). Overrides conditional blank lines. - */ + /// Explicitly preserve blank lines from the input (e.g. before the first member in a class + /// declaration). Overrides conditional blank lines. public static final BlankLineWanted PRESERVE = new SimpleBlankLine(/* wanted= */ Optional.empty()); - /** Is the blank line wanted? */ + /// Is the blank line wanted? public abstract Optional wanted(); - /** Merge this blank line request with another. */ + /// Merge this blank line request with another. public abstract BlankLineWanted merge(BlankLineWanted wanted); - /** Emit a blank line if the given break is taken. */ + /// Emit a blank line if the given break is taken. public static BlankLineWanted conditional(BreakTag breakTag) { return new ConditionalBlankLine(ImmutableList.of(breakTag)); } @@ -154,10 +149,10 @@ public BlankLineWanted merge(BlankLineWanted other) { private int tokenI = 0; private int inputPosition = Integer.MIN_VALUE; - /** The number of unclosed open ops in the input stream. */ + /// The number of unclosed open ops in the input stream. int depth = 0; - /** Add an {@link Op}, and record open/close ops for later validation of unclosed levels. */ + /// Add an [Op], and record open/close ops for later validation of unclosed levels. public final void add(Op op) { if (op instanceof OpenOp) { depth++; @@ -170,56 +165,50 @@ public final void add(Op op) { ops.add(op); } - /** Add a list of {@link Op}s. */ + /// Add a list of [Op]s. public final void addAll(List ops) { for (Op op : ops) { add(op); } } - /** - * The {@code OpsBuilder} constructor. - * - * @param input the {@link Input}, used for retrieve information from the AST - * @param output the {@link Output}, used here only to record blank-line information - */ + /// The `OpsBuilder` constructor. + /// + /// @param input the [Input], used for retrieve information from the AST + /// @param output the [Output], used here only to record blank-line information public OpsBuilder(Input input, Output output) { this.input = input; this.output = output; } - /** Get the {@code OpsBuilder}'s {@link Input}. */ + /// Get the `OpsBuilder`'s [Input]. public final Input getInput() { return input; } - /** Returns the number of unclosed open ops in the input stream. */ + /// Returns the number of unclosed open ops in the input stream. public int depth() { return depth; } - /** - * Checks that all open ops in the op stream have matching close ops. - * - * @throws FormattingError if any ops were unclosed - */ + /// Checks that all open ops in the op stream have matching close ops. + /// + /// @throws FormattingError if any ops were unclosed public void checkClosed(int previous) { if (depth != previous) { throw new FormattingError(diagnostic(String.format("saw %d unclosed ops", depth))); } } - /** Create a {@link FormatterDiagnostic} at the current position. */ + /// Create a [FormatterDiagnostic] at the current position. public FormatterDiagnostic diagnostic(String message) { return input.createDiagnostic(inputPosition, message); } - /** - * Sync to position in the input. If we've skipped outputting any tokens that were present in the - * input tokens, output them here and optionally complain. - * - * @param inputPosition the {@code 0}-based input position - */ + /// Sync to position in the input. If we've skipped outputting any tokens that were present in the + /// input tokens, output them here and optionally complain. + /// + /// @param inputPosition the `0`-based input position public final void sync(int inputPosition) { if (inputPosition > this.inputPosition) { ImmutableList tokens = input.getTokens(); @@ -234,7 +223,7 @@ public final void sync(int inputPosition) { } } - /** Output any remaining tokens from the input stream (e.g. terminal whitespace). */ + /// Output any remaining tokens from the input stream (e.g. terminal whitespace). public final void drain() { int inputPosition = input.getText().length() + 1; if (inputPosition > this.inputPosition) { @@ -254,26 +243,24 @@ public final void drain() { checkClosed(0); } - /** - * Open a new level by emitting an {@link OpenOp}. - * - * @param plusIndent the extra indent for the new level - */ + /// Open a new level by emitting an [OpenOp]. + /// + /// @param plusIndent the extra indent for the new level public final void open(Indent plusIndent) { add(OpenOp.make(plusIndent)); } - /** Close the current level, by emitting a {@link CloseOp}. */ + /// Close the current level, by emitting a [CloseOp]. public final void close() { add(CloseOp.make()); } - /** Return the text of the next {@link Input.Token}, or absent if there is none. */ + /// Return the text of the next [Input.Token], or absent if there is none. public final Optional peekToken() { return peekToken(0); } - /** Return the text of an upcoming {@link Input.Token}, or absent if there is none. */ + /// Return the text of an upcoming [Input.Token], or absent if there is none. public final Optional peekToken(int skip) { ImmutableList tokens = input.getTokens(); int idx = tokenI + skip; @@ -282,10 +269,8 @@ public final Optional peekToken(int skip) { : Optional.empty(); } - /** - * Returns the {@link Input.Tok}s starting at the current source position, which are satisfied by - * the given predicate. - */ + /// Returns the [Input.Tok]s starting at the current source position, which are satisfied by the + /// given predicate. public ImmutableList peekTokens(int startPosition, Predicate predicate) { ImmutableList tokens = input.getTokens(); Preconditions.checkState( @@ -304,12 +289,10 @@ public ImmutableList peekTokens(int startPosition, Predicate pre return result.build(); } - /** - * Emit an optional token iff it exists on the input. This is used to emit tokens whose existence - * has been lost in the AST. - * - * @param token the optional token - */ + /// Emit an optional token iff it exists on the input. This is used to emit tokens whose existence + /// has been lost in the AST. + /// + /// @param token the optional token public final void guessToken(String token) { token( token, @@ -346,11 +329,9 @@ public final void token( } } - /** - * Emit a single- or multi-character op by breaking it into single-character {@link Doc.Token}s. - * - * @param op the operator to emit - */ + /// Emit a single- or multi-character op by breaking it into single-character [Doc.Token]s. + /// + /// @param op the operator to emit public final void op(String op) { int opN = op.length(); for (int i = 0; i < opN; i++) { @@ -362,81 +343,69 @@ public final void op(String op) { } } - /** Emit a {@link Doc.Space}. */ + /// Emit a [Doc.Space]. public final void space() { add(Doc.Space.make()); } - /** Emit a {@link Doc.Break}. */ + /// Emit a [Doc.Break]. public final void breakOp() { breakOp(Doc.FillMode.UNIFIED, "", ZERO); } - /** - * Emit a {@link Doc.Break}. - * - * @param plusIndent extra indent if taken - */ + /// Emit a [Doc.Break]. + /// + /// @param plusIndent extra indent if taken public final void breakOp(Indent plusIndent) { breakOp(Doc.FillMode.UNIFIED, "", plusIndent); } - /** Emit a filled {@link Doc.Break}. */ + /// Emit a filled [Doc.Break]. public final void breakToFill() { breakOp(Doc.FillMode.INDEPENDENT, "", ZERO); } - /** Emit a forced {@link Doc.Break}. */ + /// Emit a forced [Doc.Break]. public final void forcedBreak() { breakOp(Doc.FillMode.FORCED, "", ZERO); } - /** - * Emit a forced {@link Doc.Break}. - * - * @param plusIndent extra indent if taken - */ + /// Emit a forced [Doc.Break]. + /// + /// @param plusIndent extra indent if taken public final void forcedBreak(Indent plusIndent) { breakOp(Doc.FillMode.FORCED, "", plusIndent); } - /** - * Emit a {@link Doc.Break}, with a specified {@code flat} value (e.g., {@code " "}). - * - * @param flat the {@link Doc.Break} when not broken - */ + /// Emit a [Doc.Break], with a specified `flat` value (e.g., `" "`). + /// + /// @param flat the [Doc.Break] when not broken public final void breakOp(String flat) { breakOp(Doc.FillMode.UNIFIED, flat, ZERO); } - /** - * Emit a {@link Doc.Break}, with a specified {@code flat} value (e.g., {@code " "}). - * - * @param flat the {@link Doc.Break} when not broken - */ + /// Emit a [Doc.Break], with a specified `flat` value (e.g., `" "`). + /// + /// @param flat the [Doc.Break] when not broken public final void breakToFill(String flat) { breakOp(Doc.FillMode.INDEPENDENT, flat, ZERO); } - /** - * Emit a generic {@link Doc.Break}. - * - * @param fillMode the {@link Doc.FillMode} - * @param flat the {@link Doc.Break} when not broken - * @param plusIndent extra indent if taken - */ + /// Emit a generic [Doc.Break]. + /// + /// @param fillMode the [Doc.FillMode] + /// @param flat the [Doc.Break] when not broken + /// @param plusIndent extra indent if taken public final void breakOp(Doc.FillMode fillMode, String flat, Indent plusIndent) { breakOp(fillMode, flat, plusIndent, /* optionalTag= */ Optional.empty()); } - /** - * Emit a generic {@link Doc.Break}. - * - * @param fillMode the {@link Doc.FillMode} - * @param flat the {@link Doc.Break} when not broken - * @param plusIndent extra indent if taken - * @param optionalTag an optional tag for remembering whether the break was taken - */ + /// Emit a generic [Doc.Break]. + /// + /// @param fillMode the [Doc.FillMode] + /// @param flat the [Doc.Break] when not broken + /// @param plusIndent extra indent if taken + /// @param optionalTag an optional tag for remembering whether the break was taken public final void breakOp( Doc.FillMode fillMode, String flat, Indent plusIndent, Optional optionalTag) { add(Doc.Break.make(fillMode, flat, plusIndent, optionalTag)); @@ -444,10 +413,8 @@ public final void breakOp( private int lastPartialFormatBoundary = -1; - /** - * Make the boundary of a region that can be partially formatted. The boundary will be included in - * the following region, e.g.: [[boundary0, boundary1), [boundary1, boundary2), ...]. - */ + /// Make the boundary of a region that can be partially formatted. The boundary will be included + /// in the following region, e.g.: [[boundary0, boundary1), [boundary1, boundary2), ...]. public void markForPartialFormat() { if (lastPartialFormatBoundary == -1) { lastPartialFormatBoundary = tokenI; @@ -462,11 +429,9 @@ public void markForPartialFormat() { lastPartialFormatBoundary = tokenI; } - /** - * Force or suppress a blank line here in the output. - * - * @param wanted whether to force ({@code true}) or suppress {@code false}) the blank line - */ + /// Force or suppress a blank line here in the output. + /// + /// @param wanted whether to force (`true`) or suppress (`false`) the blank line public final void blankLineWanted(BlankLineWanted wanted) { output.blankLine(getI(input.getTokens().get(tokenI)), wanted); } @@ -482,11 +447,9 @@ private static int getI(Input.Token token) { private static final Doc.Space SPACE = Doc.Space.make(); - /** - * Build a list of {@link Op}s from the {@code OpsBuilder}. - * - * @return the list of {@link Op}s - */ + /// Build a list of [Op]s from the `OpsBuilder`. + /// + /// @return the list of [Op]s public final ImmutableList build() { markForPartialFormat(); // Rewrite the ops to insert comments. diff --git a/core/src/main/java/com/google/googlejavaformat/Output.java b/core/src/main/java/com/google/googlejavaformat/Output.java index ea039fa83..7d5c614c9 100644 --- a/core/src/main/java/com/google/googlejavaformat/Output.java +++ b/core/src/main/java/com/google/googlejavaformat/Output.java @@ -19,9 +19,9 @@ import com.google.googlejavaformat.OpsBuilder.BlankLineWanted; import java.util.Optional; -/** An output from the formatter. */ +/// An output from the formatter. public abstract class Output extends InputOutput { - /** Unique identifier for a break. */ + /// Unique identifier for a break. public static final class BreakTag { Optional taken = Optional.empty(); @@ -40,37 +40,29 @@ public boolean wasBreakTaken() { } } - /** - * Indent by outputting {@code indent} spaces. - * - * @param indent the current indent - */ + /// Indent by outputting `indent` spaces. + /// + /// @param indent the current indent public abstract void indent(int indent); - /** - * Output a string. - * - * @param text the string - * @param range the {@link Range} corresponding to the string - */ + /// Output a string. + /// + /// @param text the string + /// @param range the [Range] corresponding to the string public abstract void append(String text, Range range); - /** - * A blank line is or is not wanted here. - * - * @param k the {@link Input.Tok} index - * @param wanted whether a blank line is wanted here - */ + /// A blank line is or is not wanted here. + /// + /// @param k the [Input.Tok] index + /// @param wanted whether a blank line is wanted here public abstract void blankLine(int k, BlankLineWanted wanted); - /** Marks a region that can be partially formatted. */ + /// Marks a region that can be partially formatted. public abstract void markForPartialFormat(Input.Token start, Input.Token end); - /** - * Get the {@link CommentsHelper}. - * - * @return the {@link CommentsHelper} - */ + /// Get the [CommentsHelper]. + /// + /// @return the [CommentsHelper] public abstract CommentsHelper getCommentsHelper(); @Override diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java index 873e310c9..54330f65b 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java @@ -20,27 +20,25 @@ import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Optional; -/** - * Command line options for google-java-format. - * - * @param files The files to format. - * @param inPlace Format files in place. - * @param lines Line ranges to format. - * @param offsets Character offsets for partial formatting, paired with {@code lengths}. - * @param lengths Partial formatting region lengths, paired with {@code offsets}. - * @param style Code style configuration. - * @param version Print the version. - * @param help Print usage information. - * @param stdin Format input from stdin. - * @param fixImportsOnly Fix imports, but do no formatting. - * @param sortImports Sort imports. - * @param removeUnusedImports Remove unused imports. - * @param dryRun Print the paths of the files whose contents would change if the formatter were run - * normally. - * @param setExitIfChanged Return exit code 1 if there are any formatting changes. - * @param assumeFilename Return the name to use for diagnostics when formatting standard input. - * @param reorderModifiers Reorder modifiers into the JLS-recommended order. - */ +/// Command line options for google-java-format. +/// +/// @param files The files to format. +/// @param inPlace Format files in place. +/// @param lines Line ranges to format. +/// @param offsets Character offsets for partial formatting, paired with `lengths`. +/// @param lengths Partial formatting region lengths, paired with `offsets`. +/// @param style Code style configuration. +/// @param version Print the version. +/// @param help Print usage information. +/// @param stdin Format input from stdin. +/// @param fixImportsOnly Fix imports, but do no formatting. +/// @param sortImports Sort imports. +/// @param removeUnusedImports Remove unused imports. +/// @param dryRun Print the paths of the files whose contents would change if the formatter were run +/// normally. +/// @param setExitIfChanged Return exit code 1 if there are any formatting changes. +/// @param assumeFilename Return the name to use for diagnostics when formatting standard input. +/// @param reorderModifiers Reorder modifiers into the JLS-recommended order. record CommandLineOptions( ImmutableList files, boolean inPlace, @@ -69,7 +67,7 @@ int maxLineLength() { return style().maxLineLength(); } - /** Returns true if partial formatting was selected. */ + /// Returns true if partial formatting was selected. boolean isSelection() { return !lines().isEmpty() || !offsets().isEmpty() || !lengths().isEmpty(); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java index 35e5a8e00..73a6366ee 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java @@ -32,7 +32,7 @@ import java.util.Iterator; import java.util.List; -/** A parser for {@link CommandLineOptions}. */ +/// A parser for [CommandLineOptions]. final class CommandLineOptionsParser { private static final Splitter COMMA_SPLITTER = Splitter.on(','); @@ -40,7 +40,7 @@ final class CommandLineOptionsParser { private static final Splitter ARG_SPLITTER = Splitter.on(CharMatcher.breakingWhitespace()).omitEmptyStrings().trimResults(); - /** Parses {@link CommandLineOptions}. */ + /// Parses [CommandLineOptions]. static CommandLineOptions parse(Iterable options) { CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); JavaFormatterOptions.Style.Builder styleBuilder = JavaFormatterOptions.Style.GOOGLE.toBuilder(); @@ -133,22 +133,18 @@ private static String getValue(String flag, Iterator it, String value) { return it.next(); } - /** - * Parse multiple --lines flags, like {"1:12,14,20:36", "40:45,50"}. Multiple ranges can be given - * with multiple --lines flags or separated by commas. A single line can be set by a single - * number. Line numbers are {@code 1}-based, but are converted to the {@code 0}-based numbering - * used internally by google-java-format. - */ + /// Parse multiple --lines flags, like {"1:12,14,20:36", "40:45,50"}. Multiple ranges can be given + /// with multiple --lines flags or separated by commas. A single line can be set by a single + /// number. Line numbers are `1`-based, but are converted to the `0`-based numbering used + /// internally by google-java-format. private static void parseRangeSet(RangeSet result, String ranges) { for (String range : COMMA_SPLITTER.split(ranges)) { result.add(parseRange(range)); } } - /** - * Parse a range, as in "1:12" or "42". Line numbers provided are {@code 1}-based, but are - * converted here to {@code 0}-based. - */ + /// Parse a range, as in "1:12" or "42". Line numbers provided are `1`-based, but are converted + /// here to `0`-based. private static Range parseRange(String arg) { List args = COLON_SPLITTER.splitToList(arg); return switch (args.size()) { @@ -165,10 +161,8 @@ private static Range parseRange(String arg) { }; } - /** - * Pre-processes an argument list, expanding arguments of the form {@code @filename} by reading - * the content of the file and appending whitespace-delimited options to {@code arguments}. - */ + /// Pre-processes an argument list, expanding arguments of the form `@filename` by reading the + /// content of the file and appending whitespace-delimited options to `arguments`. private static void expandParamsFiles(Iterable args, List expanded) { for (String arg : args) { if (arg.isEmpty()) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java b/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java index 4d5b40966..d5ece33a6 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java +++ b/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java @@ -29,17 +29,15 @@ import java.util.List; import org.jspecify.annotations.Nullable; -/** - * Utilities for working with array dimensions. - * - *

javac's parser does not preserve concrete syntax for mixed-notation arrays, so we have to - * re-lex the input to extract it. - * - *

For example, {@code int [] a;} cannot be distinguished from {@code int [] a [];} in the AST. - */ +/// Utilities for working with array dimensions. +/// +/// javac's parser does not preserve concrete syntax for mixed-notation arrays, so we have to re-lex +/// the input to extract it. +/// +/// For example, `int [] a;` cannot be distinguished from `int [] a [];` in the AST. final class DimensionHelpers { - /** The array dimension specifiers (including any type annotations) associated with a type. */ + /// The array dimension specifiers (including any type annotations) associated with a type. record TypeWithDims(@Nullable Tree node, ImmutableList> dims) { TypeWithDims { requireNonNull(dims, "dims"); @@ -51,7 +49,7 @@ enum SortedDims { NO } - /** Returns a (possibly re-ordered) {@link TypeWithDims} for the given type. */ + /// Returns a (possibly re-ordered) [TypeWithDims] for the given type. static TypeWithDims extractDims(Tree node, SortedDims sorted) { Deque> builder = new ArrayDeque<>(); node = extractDims(builder, node); @@ -64,18 +62,16 @@ static TypeWithDims extractDims(Tree node, SortedDims sorted) { return new TypeWithDims(node, ImmutableList.copyOf(dims)); } - /** - * Rotate the list of dimension specifiers until all dimensions with type annotations appear in - * source order. - * - *

javac reorders dimension specifiers in method declarations with mixed-array notation, which - * means that any type annotations don't appear in source order. - * - *

For example, the type of {@code int @A [] f() @B [] {}} is parsed as {@code @B [] @A []}. - * - *

This doesn't handle cases with un-annotated dimension specifiers, so the formatting logic - * checks the token stream to figure out which side of the method name they appear on. - */ + /// Rotate the list of dimension specifiers until all dimensions with type annotations appear in + /// source order. + /// + /// javac reorders dimension specifiers in method declarations with mixed-array notation, which + /// means that any type annotations don't appear in source order. + /// + /// For example, the type of `int @A [] f() @B [] {}` is parsed as `@B [] @A []`. + /// + /// This doesn't handle cases with un-annotated dimension specifiers, so the formatting logic + /// checks the token stream to figure out which side of the method name they appear on. private static Iterable> reorderBySourcePosition( Deque> dims) { int lastAnnotation = -1; @@ -97,13 +93,10 @@ private static Iterable> reorderBySourcePosition( return dims; } - /** - * Accumulates a flattened list of array dimensions specifiers with type annotations, and returns - * the base type. - * - *

Given {@code int @A @B [][] @C []}, adds {@code [[@A, @B], [@C]]} to dims and returns {@code - * int}. - */ + /// Accumulates a flattened list of array dimensions specifiers with type annotations, and returns + /// the base type. + /// + /// Given `int @A @B [][] @C []`, adds `[[@A, @B], [@C]]` to dims and returns `int`. private static Tree extractDims(Deque> dims, Tree node) { return switch (node.getKind()) { case ARRAY_TYPE -> extractDims(dims, ((ArrayTypeTree) node).getType()); diff --git a/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java b/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java index d6e3cc793..d7f3ec118 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java @@ -23,10 +23,8 @@ import java.util.concurrent.Callable; import org.jspecify.annotations.Nullable; -/** - * Encapsulates information about a file to be formatted, including which parts of the file to - * format. - */ +/// Encapsulates information about a file to be formatted, including which parts of the file to +/// format. class FormatFileCallable implements Callable { record Result( diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index c55b2a7ff..bfb084294 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -39,38 +39,36 @@ import javax.tools.Diagnostic; import javax.tools.JavaFileObject; -/** - * This is google-java-format, a new Java formatter that follows the Google Java Style Guide quite - * precisely---to the letter and to the spirit. - * - *

This formatter uses the javac parser to generate an AST. Because the AST loses information - * about the non-tokens in the input (including newlines, comments, etc.), and even some tokens - * (e.g., optional commas or semicolons), this formatter lexes the input again and follows along in - * the resulting list of tokens. Its lexer splits all multi-character operators (like ">>") - * into multiple single-character operators. Each non-token is assigned to a token---non-tokens - * following a token on the same line go with that token; those following go with the next token--- - * and there is a final EOF token to hold final comments. - * - *

The formatter walks the AST to generate a Greg Nelson/Derek Oppen-style list of formatting - * {@link Op}s [1--2] that then generates a structured {@link Doc}. Each AST node type has a visitor - * to emit a sequence of {@link Op}s for the node. - * - *

Some data-structure operations are easier in the list of {@link Op}s, while others become - * easier in the {@link Doc}. The {@link Op}s are walked to attach the comments. As the {@link Op}s - * are generated, missing input tokens are inserted and incorrect output tokens are dropped, - * ensuring that the output matches the input even in the face of formatter errors. Finally, the - * formatter walks the {@link Doc} to format it in the given width. - * - *

This formatter also produces data structures of which tokens and comments appear where on the - * input, and on the output, to help output a partial reformatting of a slightly edited input. - * - *

Instances of the formatter are immutable and thread-safe. - * - *

[1] Nelson, Greg, and John DeTreville. Personal communication. - * - *

[2] Oppen, Derek C. "Prettyprinting". ACM Transactions on Programming Languages and Systems, - * Volume 2 Issue 4, Oct. 1980, pp. 465–483. - */ +/// This is google-java-format, a new Java formatter that follows the Google Java Style Guide quite +/// precisely---to the letter and to the spirit. +/// +/// This formatter uses the javac parser to generate an AST. Because the AST loses information about +/// the non-tokens in the input (including newlines, comments, etc.), and even some tokens (e.g., +/// optional commas or semicolons), this formatter lexes the input again and follows along in the +/// resulting list of tokens. Its lexer splits all multi-character operators (like ">>") into +/// multiple single-character operators. Each non-token is assigned to a token---non-tokens +/// following a token on the same line go with that token; those following go with the next token--- +/// and there is a final EOF token to hold final comments. +/// +/// The formatter walks the AST to generate a Greg Nelson/Derek Oppen-style list of formatting [Op]s +/// [1--2] that then generates a structured [Doc]. Each AST node type has a visitor to emit a +/// sequence of [Op]s for the node. +/// +/// Some data-structure operations are easier in the list of [Op]s, while others become easier in +/// the [Doc]. The [Op]s are walked to attach the comments. As the [Op]s are generated, missing +/// input tokens are inserted and incorrect output tokens are dropped, ensuring that the output +/// matches the input even in the face of formatter errors. Finally, the formatter walks the [Doc] +/// to format it in the given width. +/// +/// This formatter also produces data structures of which tokens and comments appear where on the +/// input, and on the output, to help output a partial reformatting of a slightly edited input. +/// +/// Instances of the formatter are immutable and thread-safe. +/// +/// [1] Nelson, Greg, and John DeTreville. Personal communication. +/// +/// [2] Oppen, Derek C. "Prettyprinting". ACM Transactions on Programming Languages and Systems, +/// Volume 2 Issue 4, Oct. 1980, pp. 465–483. @Immutable public final class Formatter { @@ -80,7 +78,7 @@ public final class Formatter { private final JavaFormatterOptions options; - /** A new Formatter instance with default options. */ + /// A new Formatter instance with default options. public Formatter() { this(JavaFormatterOptions.defaultOptions()); } @@ -93,14 +91,12 @@ JavaFormatterOptions options() { return options; } - /** - * Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link - * JavaInput} and the corresponding {@link JavaOutput}. - * - * @param javaInput the input, a Java compilation unit - * @param javaOutput the {@link JavaOutput} - * @param options the {@link JavaFormatterOptions} - */ + /// Construct a `Formatter` given a Java compilation unit. Parses the code; builds a [JavaInput] + /// and the corresponding [JavaOutput]. + /// + /// @param javaInput the input, a Java compilation unit + /// @param javaOutput the [JavaOutput] + /// @param options the [JavaFormatterOptions] static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options) throws FormatterException { Context context = new Context(); @@ -140,11 +136,9 @@ static boolean errorDiagnostic(Diagnostic input) { return !input.getCode().equals("compiler.err.invalid.meth.decl.ret.type.req"); } - /** - * Format the given input (a Java compilation unit) into the output stream. - * - * @throws FormatterException if the input cannot be parsed - */ + /// Format the given input (a Java compilation unit) into the output stream. + /// + /// @throws FormatterException if the input cannot be parsed public void formatSource(CharSource input, CharSink output) throws FormatterException, IOException { // TODO(cushon): proper support for streaming input/output. Input may @@ -152,31 +146,27 @@ public void formatSource(CharSource input, CharSink output) output.write(formatSource(input.read())); } - /** - * Format an input string (a Java compilation unit) into an output string. - * - *

Leaves import statements untouched. - * - * @param input the input string - * @return the output string - * @throws FormatterException if the input string cannot be parsed - */ + /// Format an input string (a Java compilation unit) into an output string. + /// + /// Leaves import statements untouched. + /// + /// @param input the input string + /// @return the output string + /// @throws FormatterException if the input string cannot be parsed public String formatSource(String input) throws FormatterException { return formatSource(input, ImmutableList.of(Range.closedOpen(0, input.length()))); } - /** - * Formats an input string (a Java compilation unit) and fixes imports. - * - *

Fixing imports includes ordering, spacing, and removal of unused import statements. - * - * @param input the input string - * @return the output string - * @throws FormatterException if the input string cannot be parsed - * @see - * Google Java Style Guide - 3.3.3 Import ordering and spacing - */ + /// Formats an input string (a Java compilation unit) and fixes imports. + /// + /// Fixing imports includes ordering, spacing, and removal of unused import statements. + /// + /// @param input the input string + /// @return the output string + /// @throws FormatterException if the input string cannot be parsed + /// @see + /// Google Java Style Guide - 3.3.3 Import ordering and spacing public String formatSourceAndFixImports(String input) throws FormatterException { input = ImportOrderer.reorderImports(input, options.style()); input = RemoveUnusedImports.removeUnusedImports(input); @@ -185,28 +175,24 @@ public String formatSourceAndFixImports(String input) throws FormatterException return formatted; } - /** - * Format an input string (a Java compilation unit), for only the specified character ranges. - * These ranges are extended as necessary (e.g., to encompass whole lines). - * - * @param input the input string - * @param characterRanges the character ranges to be reformatted - * @return the output string - * @throws FormatterException if the input string cannot be parsed - */ + /// Format an input string (a Java compilation unit), for only the specified character ranges. + /// These ranges are extended as necessary (e.g., to encompass whole lines). + /// + /// @param input the input string + /// @param characterRanges the character ranges to be reformatted + /// @return the output string + /// @throws FormatterException if the input string cannot be parsed public String formatSource(String input, Collection> characterRanges) throws FormatterException { return JavaOutput.applyReplacements(input, getFormatReplacements(input, characterRanges)); } - /** - * Emit a list of {@link Replacement}s to convert from input to output. - * - * @param input the input compilation unit - * @param characterRanges the character ranges to reformat - * @return a list of {@link Replacement}s, sorted from low index to high index, without overlaps - * @throws FormatterException if the input string cannot be parsed - */ + /// Emit a list of [Replacement]s to convert from input to output. + /// + /// @param input the input compilation unit + /// @param characterRanges the character ranges to reformat + /// @return a list of [Replacement]s, sorted from low index to high index, without overlaps + /// @throws FormatterException if the input string cannot be parsed public ImmutableList getFormatReplacements( String input, Collection> characterRanges) throws FormatterException { JavaInput javaInput = new JavaInput(input); @@ -234,9 +220,8 @@ public ImmutableList getFormatReplacements( return javaOutput.getFormatReplacements(tokenRangeSet); } - /** - * Converts zero-indexed, [closed, open) line ranges in the given source file to character ranges. - */ + /// Converts zero-indexed, [closed, open) line ranges in the given source file to character + /// ranges. public static RangeSet lineRangesToCharRanges( String input, RangeSet lineRanges) { List lines = new ArrayList<>(); diff --git a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java index 2c4e956f1..b83d51eb1 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java @@ -26,7 +26,7 @@ import javax.tools.Diagnostic; import javax.tools.JavaFileObject; -/** Checked exception class for formatter errors. */ +/// Checked exception class for formatter errors. public final class FormatterException extends Exception { private final ImmutableList diagnostics; diff --git a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java index 3c315aaf1..98fb05da1 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java +++ b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java @@ -25,7 +25,7 @@ import javax.lang.model.SourceVersion; import javax.tools.Tool; -/** Provide a way to be invoked without necessarily starting a new VM. */ +/// Provide a way to be invoked without necessarily starting a new VM. @AutoService(Tool.class) public class GoogleJavaFormatTool implements Tool { @Override diff --git a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java index 438eac596..249cdf4b2 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java +++ b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java @@ -18,7 +18,7 @@ import java.io.PrintWriter; import java.util.spi.ToolProvider; -/** Provide a way to be invoked without necessarily starting a new VM. */ +/// Provide a way to be invoked without necessarily starting a new VM. @AutoService(ToolProvider.class) public class GoogleJavaFormatToolProvider implements ToolProvider { @Override diff --git a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java index 7fef64f32..448ec80b9 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java @@ -33,30 +33,26 @@ import java.util.function.BiFunction; import java.util.stream.Stream; -/** Orders imports in Java source code. */ +/// Orders imports in Java source code. public class ImportOrderer { private static final Splitter DOT_SPLITTER = Splitter.on('.'); - /** - * Reorder the inputs in {@code text}, a complete Java program. On success, another complete Java - * program is returned, which is the same as the original except the imports are in order. - * - * @throws FormatterException if the input could not be parsed. - */ + /// Reorder the inputs in `text`, a complete Java program. On success, another complete Java + /// program is returned, which is the same as the original except the imports are in order. + /// + /// @throws FormatterException if the input could not be parsed. public static String reorderImports(String text, Style style) throws FormatterException { ImmutableList toks = JavaInput.buildToks(text, CLASS_START); return new ImportOrderer(text, toks, style).reorderImports(); } - /** - * Reorder the inputs in {@code text}, a complete Java program, in Google style. On success, - * another complete Java program is returned, which is the same as the original except the imports - * are in order. - * - * @deprecated Use {@link #reorderImports(String, Style)} instead - * @throws FormatterException if the input could not be parsed. - */ + /// Reorder the inputs in `text`, a complete Java program, in Google style. On success, another + /// complete Java program is returned, which is the same as the original except the imports are in + /// order. + /// + /// @deprecated Use [#reorderImports(String, Style)] instead + /// @throws FormatterException if the input could not be parsed. @Deprecated public static String reorderImports(String text) throws FormatterException { return reorderImports(text, Style.GOOGLE); @@ -103,40 +99,32 @@ private String reorderImports() throws FormatterException { return result.toString(); } - /** - * {@link TokenKind}s that indicate the start of a type definition. We use this to avoid scanning - * the whole file, since we know that imports must precede any type definition. - */ + /// [TokenKind]s that indicate the start of a type definition. We use this to avoid scanning the + /// whole file, since we know that imports must precede any type definition. private static final ImmutableSet CLASS_START = ImmutableSet.of(TokenKind.CLASS, TokenKind.INTERFACE, TokenKind.ENUM); - /** - * We use this set to find the first import, and again to check that there are no imports after - * the place we stopped gathering them. An annotation definition ({@code @interface}) is two - * tokens, the second which is {@code interface}, so we don't need a separate entry for that. - */ + /// We use this set to find the first import, and again to check that there are no imports after + /// the place we stopped gathering them. An annotation definition (`@interface`) is two tokens, + /// the second which is `interface`, so we don't need a separate entry for that. private static final ImmutableSet IMPORT_OR_CLASS_START = ImmutableSet.of("import", "class", "interface", "enum"); - /** - * A {@link Comparator} that orders {@link Import}s by Google Style, defined at - * https://google.github.io/styleguide/javaguide.html#s3.3.3-import-ordering-and-spacing. - * - *

Module imports are not allowed by Google Style, so we make an arbitrary choice about where - * to include them if they are present. - */ + /// A [Comparator] that orders [Import]s by Google Style, defined at + /// https://google.github.io/styleguide/javaguide.html#s3.3.3-import-ordering-and-spacing. + /// + /// Module imports are not allowed by Google Style, so we make an arbitrary choice about where to + /// include them if they are present. private static final Comparator GOOGLE_IMPORT_COMPARATOR = Comparator.comparing(Import::importType).thenComparing(Import::imported); - /** - * A {@link Comparator} that orders {@link Import}s by AOSP Style, defined at - * https://source.android.com/setup/contribute/code-style#order-import-statements and implemented - * in IntelliJ at - * https://android.googlesource.com/platform/development/+/master/ide/intellij/codestyles/AndroidStyle.xml. - * - *

Module imports are not mentioned by Android Style, so we make an arbitrary choice about - * where to include them if they are present. - */ + /// A [Comparator] that orders [Import]s by AOSP Style, defined at + /// https://source.android.com/setup/contribute/code-style#order-import-statements and implemented + /// in IntelliJ at + /// https://android.googlesource.com/platform/development/+/master/ide/intellij/codestyles/AndroidStyle.xml. + /// + /// Module imports are not mentioned by Android Style, so we make an arbitrary choice about where + /// to include them if they are present. private static final Comparator AOSP_IMPORT_COMPARATOR = Comparator.comparing(Import::importType) .thenComparing(Import::isAndroid, trueFirst()) @@ -144,18 +132,14 @@ private String reorderImports() throws FormatterException { .thenComparing(Import::isJava, trueFirst()) .thenComparing(Import::imported); - /** - * Determines whether to insert a blank line between the {@code prev} and {@code curr} {@link - * Import}s based on Google style. - */ + /// Determines whether to insert a blank line between the `prev` and `curr` [Import]s based on + /// Google style. private static boolean shouldInsertBlankLineGoogle(Import prev, Import curr) { return !prev.importType().equals(curr.importType()); } - /** - * Determines whether to insert a blank line between the {@code prev} and {@code curr} {@link - * Import}s based on AOSP style. - */ + /// Determines whether to insert a blank line between the `prev` and `curr` [Import]s based on + /// AOSP style. private static boolean shouldInsertBlankLineAosp(Import prev, Import curr) { if (!prev.importType().equals(curr.importType())) { return true; @@ -196,31 +180,29 @@ private enum ImportType { NORMAL } - /** - * An import statement. - * - * @param imported the name being imported, for example {@code java.util.List}. - * @param trailing the {@code //} comment lines after the final {@code ;}, up to and including the - * line terminator of the last one. Note: In case two imports were separated by a space (which - * is disallowed by the style guide), the trailing whitespace of the first import does not - * include a line terminator. - * @param importType the {@link ImportType} of the import. - * @param lineSeparator the line separator to use when formatting the import. - */ + /// An import statement. + /// + /// @param imported the name being imported, for example `java.util.List`. + /// @param trailing the `//` comment lines after the final `;`, up to and including the line + /// terminator of the last one. Note: In case two imports were separated by a space (which is + /// disallowed by the style guide), the trailing whitespace of the first import does not include + /// a line terminator. + /// @param importType the [ImportType] of the import. + /// @param lineSeparator the line separator to use when formatting the import. private record Import( String imported, String trailing, ImportType importType, String lineSeparator) { - /** The top-level package of the import. */ + /// The top-level package of the import. String topLevel() { return DOT_SPLITTER.split(imported).iterator().next(); } - /** True if this is an Android import per AOSP style. */ + /// True if this is an Android import per AOSP style. boolean isAndroid() { return Stream.of("android.", "androidx.", "dalvik.", "libcore.", "com.android.") .anyMatch(imported::startsWith); } - /** True if this is a Java import per AOSP style. */ + /// True if this is a Java import per AOSP style. boolean isJava() { return switch (topLevel()) { case "java", "javax" -> true; @@ -228,7 +210,7 @@ boolean isJava() { }; } - /** True if this is a third-party import per AOSP style. */ + /// True if this is a third-party import per AOSP style. boolean isThirdParty() { return !(isAndroid() || isJava()); } @@ -264,20 +246,18 @@ private String tokString(int start, int end) { private record ImportsAndIndex(ImmutableSortedSet imports, int index) {} - /** - * Scans a sequence of import lines. The parsing uses this approximate grammar: - * - *

{@code
-   *  -> ( | )*
-   *  -> "import"  ("static" )?
-   *     ("." )* ("." "*")? ? ";"
-   *    ? ? ( )*
-   * }
- * - * @param i the index to start parsing at. - * @return the result of parsing the imports. - * @throws FormatterException if imports could not parsed according to the grammar. - */ + /// Scans a sequence of import lines. The parsing uses this approximate grammar: + /// + /// ``` + /// -> ( | )* + /// -> "import" ("static" )? + /// ("." )* ("." "*")? ? ";" + /// ? ? ( )* + /// ``` + /// + /// @param i the index to start parsing at. + /// @return the result of parsing the imports. + /// @throws FormatterException if imports could not parsed according to the grammar. private ImportsAndIndex scanImports(int i) throws FormatterException { int afterLastImport = i; ImmutableSortedSet.Builder imports = ImmutableSortedSet.orderedBy(importComparator); @@ -382,18 +362,16 @@ private static class StringAndIndex { } } - /** - * Scans the imported thing, the dot-separated name that comes after import [static] and before - * the semicolon. We don't allow spaces inside the dot-separated name. Wildcard imports are - * supported: if the input is {@code import java.util.*;} then the returned string will be {@code - * java.util.*}. - * - * @param start the index of the start of the identifier. If the import is {@code import - * java.util.List;} then this index points to the token {@code java}. - * @return the parsed import ({@code java.util.List} in the example) and the index of the first - * token after the imported thing ({@code ;} in the example). - * @throws FormatterException if the imported name could not be parsed. - */ + /// Scans the imported thing, the dot-separated name that comes after import [static] and before + /// the semicolon. We don't allow spaces inside the dot-separated name. Wildcard imports are + /// supported: if the input is `import java.util.*;` then the returned string will be + /// `java.util.*`. + /// + /// @param start the index of the start of the identifier. If the import is `import + /// java.util.List;` then this index points to the token `java`. + /// @return the parsed import (`java.util.List` in the example) and the index of the first token + /// after the imported thing (`;` in the example). + /// @throws FormatterException if the imported name could not be parsed. private StringAndIndex scanImported(int start) throws FormatterException { int i = start; StringBuilder imported = new StringBuilder(); @@ -417,13 +395,11 @@ private StringAndIndex scanImported(int start) throws FormatterException { } } - /** - * Returns the index of the first place where one of the given identifiers occurs, or {@code - * Optional.empty()} if there is none. - * - * @param start the index to start looking at - * @param identifiers the identifiers to look for - */ + /// Returns the index of the first place where one of the given identifiers occurs, or + /// `Optional.empty()` if there is none. + /// + /// @param start the index to start looking at + /// @param identifiers the identifiers to look for private Optional findIdentifier(int start, ImmutableSet identifiers) { for (int i = start; i < toks.size(); i++) { if (isIdentifierToken(i)) { @@ -436,7 +412,7 @@ private Optional findIdentifier(int start, ImmutableSet identif return Optional.empty(); } - /** Returns the given token, or the preceding token if it is a whitespace token. */ + /// Returns the given token, or the preceding token if it is a whitespace token. private int unindent(int i) { if (i > 0 && isSpaceToken(i - 1)) { return i - 1; diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java index 846d12034..475c35d14 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java @@ -26,7 +26,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -/** {@code JavaCommentsHelper} extends {@link CommentsHelper} to rewrite Java comments. */ +/// `JavaCommentsHelper` extends [CommentsHelper] to rewrite Java comments. final class JavaCommentsHelper implements CommentsHelper { private final String lineSeparator; diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java b/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java index d58aac4ea..dcbfb28f6 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java @@ -22,25 +22,22 @@ import com.google.errorprone.annotations.Immutable; import com.google.googlejavaformat.Doc; -/** - * Options for a google-java-format invocation. - * - *

Like gofmt, the google-java-format CLI exposes no configuration options (aside from - * {@code --aosp}). - * - *

The goal of google-java-format is to provide consistent formatting, and to free developers - * from arguments over style choices. It is an explicit non-goal to support developers' individual - * preferences, and in fact it would work directly against our primary goals. - * - * @param style Returns the code style. - */ +/// Options for a google-java-format invocation. +/// +/// Like gofmt, the google-java-format CLI exposes *no* configuration options (aside from `--aosp`). +/// +/// The goal of google-java-format is to provide consistent formatting, and to free developers from +/// arguments over style choices. It is an explicit non-goal to support developers' individual +/// preferences, and in fact it would work directly against our primary goals. +/// +/// @param style Returns the code style. @Immutable public record JavaFormatterOptions(boolean formatJavadoc, boolean reorderModifiers, Style style) { public JavaFormatterOptions { requireNonNull(style, "style"); } - /** Code style configuration for layout and imports. */ + /// Code style configuration for layout and imports. @Immutable public record Style( int indentationMultiplier, int maxLineLength, boolean useTabs, ImportOrder importOrder) { @@ -53,17 +50,15 @@ public record Style( requireNonNull(importOrder, "importOrder"); } - /** - * The largest supported {@link #maxLineLength}. Layout widths saturate at {@link - * Doc#MAX_LINE_WIDTH}, which is also how forced breaks are represented, so the line length must - * be smaller than that. - */ + /// The largest supported [#maxLineLength]. Layout widths saturate at [Doc#MAX_LINE_WIDTH], + /// which is also how forced breaks are represented, so the line length must be smaller than + /// that. static final int MAX_LINE_LENGTH_LIMIT = Doc.MAX_LINE_WIDTH - 1; - /** The default Google Java Style configuration. */ + /// The default Google Java Style configuration. public static final Style GOOGLE = builder().google().build(); - /** The AOSP-compliant configuration. */ + /// The AOSP-compliant configuration. public static final Style AOSP = builder().aosp().build(); /** @@ -107,17 +102,15 @@ public String name() { return importOrder().name(); } - /** - * Returns the visual column width of a tab stop. - * - *

This matches the standard block indentation width for the style: 2 columns for Google - * Style and 4 columns for AOSP. - */ + /// Returns the visual column width of a tab stop. + /// + /// This matches the standard block indentation width for the style: 2 columns for Google Style + /// and 4 columns for AOSP. public int tabWidth() { return 2 * indentationMultiplier(); } - /** Returns the indentation string for the given visual column width. */ + /// Returns the indentation string for the given visual column width. public String indentString(int indent) { if (!useTabs()) { return JavaOutput.spaces(indent); @@ -126,12 +119,12 @@ public String indentString(int indent) { return "\t".repeat(indent / tabWidth) + " ".repeat(indent % tabWidth); } - /** Returns the visual column width of the given character sequence. */ + /// Returns the visual column width of the given character sequence. public int visualLength(CharSequence input) { return visualLength(input, 0, input.length()); } - /** Returns the visual column width of the given subsequence. */ + /// Returns the visual column width of the given subsequence. public int visualLength(CharSequence input, int start, int end) { if (!useTabs()) { return end - start; @@ -167,7 +160,7 @@ public Builder toBuilder() { .importOrder(importOrder()); } - /** A builder for {@link Style}. */ + /// A builder for [Style]. @AutoBuilder public abstract static class Builder { public abstract Builder indentationMultiplier(int indentationMultiplier); @@ -192,13 +185,13 @@ public Builder google() { } } - /** The import order to use. */ + /// The import order to use. public enum ImportOrder { GOOGLE, AOSP, } - /** Returns the multiplier for the unit of indent. */ + /// Returns the multiplier for the unit of indent. public int indentationMultiplier() { return style().indentationMultiplier(); } @@ -211,27 +204,27 @@ public boolean useTabs() { return style().useTabs(); } - /** Returns the indentation string for the given visual column width. */ + /// Returns the indentation string for the given visual column width. public String indentString(int indent) { return style().indentString(indent); } - /** Returns the visual column width of the given character sequence. */ + /// Returns the visual column width of the given character sequence. public int visualLength(CharSequence input) { return style().visualLength(input); } - /** Returns the visual column width of the given subsequence. */ + /// Returns the visual column width of the given subsequence. public int visualLength(CharSequence input, int start, int end) { return style().visualLength(input, start, end); } - /** Returns the default formatting options. */ + /// Returns the default formatting options. public static JavaFormatterOptions defaultOptions() { return builder().build(); } - /** Returns a builder for {@link JavaFormatterOptions}. */ + /// Returns a builder for [JavaFormatterOptions]. public static Builder builder() { return new AutoBuilder_JavaFormatterOptions_Builder() .style(Style.GOOGLE) @@ -239,7 +232,7 @@ public static Builder builder() { .reorderModifiers(true); } - /** A builder for {@link JavaFormatterOptions}. */ + /// A builder for [JavaFormatterOptions]. @AutoBuilder public abstract static class Builder { diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java index 879a83c50..4fe3a430f 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java @@ -58,20 +58,17 @@ import javax.tools.SimpleJavaFileObject; import org.jspecify.annotations.Nullable; -/** {@code JavaInput} extends {@link Input} to represent a Java input document. */ +/// `JavaInput` extends [Input] to represent a Java input document. final class JavaInput extends Input { - /** - * A {@code JavaInput} is a sequence of {@link Tok}s that cover the Java input. A {@link Tok} is - * either a token (if {@code isToken()}), or a non-token, which is a comment (if {@code - * isComment()}) or a newline (if {@code isNewline()}) or a maximal sequence of other whitespace - * characters (if {@code isSpaces()}). Each {@link Tok} contains a sequence of characters, an - * index (sequential starting at {@code 0} for tokens and comments, else {@code -1}), and a - * ({@code 0}-origin) position in the input. The concatenation of the texts of all the {@link - * Tok}s equals the input. Each Input ends with a token EOF {@link Tok}, with empty text. - * - *

A {@code /*} comment possibly contains newlines; a {@code //} comment does not contain the - * terminating newline character, but is followed by a newline {@link Tok}. - */ + /// A `JavaInput` is a sequence of [Tok]s that cover the Java input. A [Tok] is either a token (if + /// `isToken()`), or a non-token, which is a comment (if `isComment()`) or a newline (if + /// `isNewline()`) or a maximal sequence of other whitespace characters (if `isSpaces()`). Each + /// [Tok] contains a sequence of characters, an index (sequential starting at `0` for tokens and + /// comments, else `-1`), and a (`0`-origin) position in the input. The concatenation of the texts + /// of all the [Tok]s equals the input. Each Input ends with a token EOF [Tok], with empty text. + /// + /// A `/*` comment possibly contains newlines; a `//` comment does not contain the terminating + /// newline character, but is followed by a newline [Tok]. static final class Tok implements Input.Tok { private final int index; private final String originalText; @@ -81,17 +78,15 @@ static final class Tok implements Input.Tok { private final boolean isToken; private final TokenKind kind; - /** - * The {@code Tok} constructor. - * - * @param index its index - * @param originalText its original text, before removing Unicode escapes - * @param text its text after removing Unicode escapes - * @param position its {@code 0}-origin position in the input - * @param columnI its {@code 0}-origin column number in the input - * @param isToken whether the {@code Tok} is a token - * @param kind the token kind - */ + /// The `Tok` constructor. + /// + /// @param index its index + /// @param originalText its original text, before removing Unicode escapes + /// @param text its text after removing Unicode escapes + /// @param position its `0`-origin position in the input + /// @param columnI its `0`-origin column number in the input + /// @param isToken whether the `Tok` is a token + /// @param kind the token kind Tok( int index, String originalText, @@ -190,56 +185,46 @@ public TokenKind kind() { } } - /** - * A {@link Token} contains a token {@link Tok} and its associated non-tokens; each non-token - * {@link Tok} belongs to one {@link Token}. Each {@link Token} has an immutable list of its - * non-tokens that appear before it, and another list of its non-tokens that appear after it. The - * concatenation of the texts of all the {@link Token}s' {@link Tok}s, each preceded by the texts - * of its {@code toksBefore} and followed by the texts of its {@code toksAfter}, equals the input. - */ + /// A [Token] contains a token [Tok] and its associated non-tokens; each non-token [Tok] belongs + /// to one [Token]. Each [Token] has an immutable list of its non-tokens that appear before it, + /// and another list of its non-tokens that appear after it. The concatenation of the texts of all + /// the [Token]s' [Tok]s, each preceded by the texts of its `toksBefore` and followed by the texts + /// of its `toksAfter`, equals the input. static final class Token implements Input.Token { private final Tok tok; private final ImmutableList toksBefore; private final ImmutableList toksAfter; - /** - * Token constructor. - * - * @param toksBefore the earlier non-token {link Tok}s assigned to this {@code Token} - * @param tok this token {@link Tok} - * @param toksAfter the later non-token {link Tok}s assigned to this {@code Token} - */ + /// Token constructor. + /// + /// @param toksBefore the earlier non-token [Tok]s assigned to this `Token` + /// @param tok this token [Tok] + /// @param toksAfter the later non-token [Tok]s assigned to this `Token` Token(List toksBefore, Tok tok, List toksAfter) { this.toksBefore = ImmutableList.copyOf(toksBefore); this.tok = tok; this.toksAfter = ImmutableList.copyOf(toksAfter); } - /** - * Get the token's {@link Tok}. - * - * @return the token's {@link Tok} - */ + /// Get the token's [Tok]. + /// + /// @return the token's [Tok] @Override public Tok getTok() { return tok; } - /** - * Get the earlier {@link Tok}s assigned to this {@code Token}. - * - * @return the earlier {@link Tok}s assigned to this {@code Token} - */ + /// Get the earlier [Tok]s assigned to this `Token`. + /// + /// @return the earlier [Tok]s assigned to this `Token` @Override public ImmutableList getToksBefore() { return toksBefore; } - /** - * Get the later {@link Tok}s assigned to this {@code Token}. - * - * @return the later {@link Tok}s assigned to this {@code Token} - */ + /// Get the later [Tok]s assigned to this `Token`. + /// + /// @return the later [Tok]s assigned to this `Token` @Override public ImmutableList getToksAfter() { return toksAfter; @@ -270,15 +255,13 @@ public String toString() { private final ImmutableList tokens; // The Tokens for this input. private final ImmutableRangeMap positionTokenMap; // Map position to Token. - /** Map from Tok index to the associated Token. */ + /// Map from Tok index to the associated Token. private final Token[] kToToken; - /** - * Input constructor. - * - * @param text the input text - * @throws FormatterException if the input cannot be parsed - */ + /// Input constructor. + /// + /// @param text the input text + /// @throws FormatterException if the input cannot be parsed JavaInput(String text) throws FormatterException { this.text = checkNotNull(text); setLines(ImmutableList.copyOf(Newlines.lineIterator(text))); @@ -323,11 +306,9 @@ private static ImmutableMap makePositionToColumnMap(List return builder.buildOrThrow(); } - /** - * Get the input text. - * - * @return the input text - */ + /// Get the input text. + /// + /// @return the input text @Override public String getText() { return text; @@ -338,7 +319,7 @@ public ImmutableMap getPositionToColumnMap() { return positionToColumnMap; } - /** Lex the input and build the list of toks. */ + /// Lex the input and build the list of toks. private ImmutableList buildToks(String text) throws FormatterException { ImmutableList toks = buildToks(text, ImmutableSet.of()); kN = getLast(toks).getIndex(); @@ -346,13 +327,11 @@ private ImmutableList buildToks(String text) throws FormatterException { return toks; } - /** - * Lex the input and build the list of toks. - * - * @param text the text to be lexed. - * @param stopTokens a set of tokens which should cause lexing to stop. If one of these is found, - * the returned list will include tokens up to but not including that token. - */ + /// Lex the input and build the list of toks. + /// + /// @param text the text to be lexed. + /// @param stopTokens a set of tokens which should cause lexing to stop. If one of these is found, + /// the returned list will include tokens up to but not including that token. static ImmutableList buildToks(String text, ImmutableSet stopTokens) throws FormatterException { stopTokens = ImmutableSet.builder().addAll(stopTokens).add(TokenKind.EOF).build(); @@ -605,13 +584,11 @@ private static boolean isParamComment(Tok tok) { && tok.getText().matches("\\/\\*[A-Za-z0-9\\s_\\-]+=\\s*\\*\\/"); } - /** - * Convert from a character range to a token range. - * - * @param characterRange the {@code 0}-based {@link Range} of characters - * @return the {@code 0}-based {@link Range} of tokens - * @throws FormatterException if the upper endpoint of the range is outside the file - */ + /// Convert from a character range to a token range. + /// + /// @param characterRange the `0`-based [Range] of characters + /// @return the `0`-based [Range] of tokens + /// @throws FormatterException if the upper endpoint of the range is outside the file private Range characterRangeToTokenRange(Range characterRange) throws FormatterException { if (characterRange.upperEndpoint() > text.length()) { @@ -637,43 +614,35 @@ private Range characterRangeToTokenRange(Range characterRange) enclosed.iterator().next().getTok().getIndex(), getLast(enclosed).getTok().getIndex() + 1); } - /** - * Get the number of toks. - * - * @return the number of toks, excluding the EOF tok - */ + /// Get the number of toks. + /// + /// @return the number of toks, excluding the EOF tok @Override public int getkN() { return kN; } - /** - * Get the Token by index. - * - * @param k the Tok index - */ + /// Get the Token by index. + /// + /// @param k the Tok index @Override public Token getToken(int k) { return kToToken[k]; } - /** - * Get the input tokens. - * - * @return the input tokens - */ + /// Get the input tokens. + /// + /// @return the input tokens @Override public ImmutableList getTokens() { return tokens; } - /** - * Get the navigable map from position to {@link Token}. Used to look for tokens following a given - * one, and to implement the --offset and --length flags to reformat a character range in the - * input file. - * - * @return the navigable map from position to {@link Token} - */ + /// Get the navigable map from position to [Token]. Used to look for tokens following a given one, + /// and to implement the --offset and --length flags to reformat a character range in the input + /// file. + /// + /// @return the navigable map from position to [Token] @Override public ImmutableRangeMap getPositionTokenMap() { return positionTokenMap; diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index bae72bb1e..af29352ed 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -179,13 +179,10 @@ import javax.lang.model.element.Name; import org.jspecify.annotations.Nullable; -/** - * An AST visitor that builds a stream of {@link Op}s to format from the given {@link - * CompilationUnitTree}. - */ +/// An AST visitor that builds a stream of [Op]s to format from the given [CompilationUnitTree]. class JavaInputAstVisitor extends TreePathScanner { - /** Direction for Annotations (usually VERTICAL). */ + /// Direction for Annotations (usually VERTICAL). private enum Direction { VERTICAL, HORIZONTAL; @@ -195,7 +192,7 @@ boolean isVertical() { } } - /** Whether to break or not. */ + /// Whether to break or not. private enum BreakOrNot { YES, NO; @@ -205,7 +202,7 @@ boolean isYes() { } } - /** Whether to collapse empty blocks. */ + /// Whether to collapse empty blocks. private enum CollapseEmptyOrNot { YES, NO; @@ -219,13 +216,13 @@ boolean isYes() { } } - /** Whether to allow leading blank lines in blocks. */ + /// Whether to allow leading blank lines in blocks. private enum AllowLeadingBlankLine { YES, NO; } - /** Whether to allow trailing blank lines in blocks. */ + /// Whether to allow trailing blank lines in blocks. private enum AllowTrailingBlankLine { YES, NO; @@ -235,7 +232,7 @@ static AllowTrailingBlankLine valueOf(boolean b) { } } - /** Whether to include braces. */ + /// Whether to include braces. private enum BracesOrNot { YES, NO; @@ -245,7 +242,7 @@ boolean isYes() { } } - /** Whether these declarations are the first in the block. */ + /// Whether these declarations are the first in the block. private enum FirstDeclarationsOrNot { YES, NO; @@ -299,17 +296,13 @@ private static final ImmutableList forceBreakList(Optional breakTa return ImmutableList.of(Doc.Break.make(FillMode.FORCED, "", Indent.Const.ZERO, breakTag)); } - /** - * Allow multi-line filling (of array initializers, argument lists, and boolean expressions) for - * items with length less than or equal to this threshold. - */ + /// Allow multi-line filling (of array initializers, argument lists, and boolean expressions) for + /// items with length less than or equal to this threshold. private static final int MAX_ITEM_LENGTH_FOR_FILLING = 10; - /** - * The {@code Visitor} constructor. - * - * @param builder the {@link LayoutBuilder} - */ + /// The `Visitor` constructor. + /// + /// @param builder the [LayoutBuilder] JavaInputAstVisitor( LayoutBuilder builder, int indentMultiplier, @@ -323,7 +316,7 @@ private static final ImmutableList forceBreakList(Optional breakTa plusFour = Indent.Const.make(+4, indentMultiplier); } - /** A record of whether we have visited into an expression. */ + /// A record of whether we have visited into an expression. private final Deque inExpression = new ArrayDeque<>(ImmutableList.of(false)); private boolean inExpression() { @@ -405,7 +398,7 @@ private void handleModule(boolean afterFirstToken, CompilationUnitTree node) { } } - /** Skips over extra semicolons at the top-level, or in a class member declaration lists. */ + /// Skips over extra semicolons at the top-level, or in a class member declaration lists. private void dropEmptyDeclarations() { if (builder.peekToken().equals(Optional.of(";"))) { while (builder.peekToken().equals(Optional.of(";"))) { @@ -1675,23 +1668,21 @@ public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { return null; } - /** - * Special-cases log statements, to output: - * - *

{@code
-   * logger.atInfo().log(
-   *     "Number of foos: %d, foos.size());
-   * }
- * - *

Instead of: - * - *

{@code
-   * logger
-   *     .atInfo()
-   *     .log(
-   *         "Number of foos: %d, foos.size());
-   * }
- */ + /// Special-cases log statements, to output: + /// + /// ``` + /// logger.atInfo().log( + /// "Number of foos: %d, foos.size()); + /// ``` + /// + /// Instead of: + /// + /// ``` + /// logger + /// .atInfo() + /// .log( + /// "Number of foos: %d, foos.size()); + /// ``` private boolean handleLogStatement(MethodInvocationTree node) { Name methodName = getMethodName(node); if (!methodName.contentEquals("log") && !methodName.contentEquals("logVarargs")) { @@ -2267,7 +2258,7 @@ public Void visitWildcard(WildcardTree node, Void unused) { // Helper methods. - /** Helper method for annotations. */ + /// Helper method for annotations. private void visitAnnotations( List annotations, BreakOrNot breakBefore, BreakOrNot breakAfter) { if (!annotations.isEmpty()) { @@ -2296,7 +2287,7 @@ private void verticalAnnotations(List annotations) { } } - /** Helper method for blocks. */ + /// Helper method for blocks. private void visitBlock( BlockTree node, CollapseEmptyOrNot collapseEmptyOrNot, @@ -2339,7 +2330,7 @@ private void visitBlock( } } - /** Helper method for statements. */ + /// Helper method for statements. private void visitStatement( StatementTree node, CollapseEmptyOrNot collapseEmptyOrNot, @@ -2391,7 +2382,7 @@ private void typeDeclarationModifiers(ModifiersTree modifiers) { verticalAnnotations(typeAnnotations); } - /** Output combined modifiers and annotations and the trailing break. */ + /// Output combined modifiers and annotations and the trailing break. private void visitAndBreakModifiers( ModifiersTree modifiers, Direction annotationDirection, @@ -2406,7 +2397,7 @@ public Void visitModifiers(ModifiersTree node, Void unused) { throw new IllegalStateException("expected manual descent into modifiers"); } - /** Output combined modifiers and annotations and returns the trailing break. */ + /// Output combined modifiers and annotations and returns the trailing break. @CheckReturnValue private ImmutableList visitModifiers( ModifiersTree modifiersTree, @@ -2481,7 +2472,7 @@ private ImmutableList visitModifiers( return splitModifiers.typeAnnotations(); } - /** Represents an annotation or a modifier in a {@link ModifiersTree}. */ + /// Represents an annotation or a modifier in a [ModifiersTree]. @AutoOneOf(AnnotationOrModifier.Kind.class) abstract static class AnnotationOrModifier implements Comparable { enum Kind { @@ -2527,14 +2518,12 @@ public int compareTo(AnnotationOrModifier o) { } } - /** - * The modifiers annotations for a declaration, grouped in to a prefix that contains all of the - * declaration annotations and modifiers, and a suffix of type annotations. - * - *

For examples like {@code @Deprecated public @Nullable Foo foo();}, this allows us to format - * {@code @Deprecated public} as declaration modifiers, and {@code @Nullable} as a type annotation - * on the return type. - */ + /// The modifiers annotations for a declaration, grouped in to a prefix that contains all of the + /// declaration annotations and modifiers, and a suffix of type annotations. + /// + /// For examples like `@Deprecated public @Nullable Foo foo();`, this allows us to format + /// `@Deprecated public` as declaration modifiers, and `@Nullable` as a type annotation on the + /// return type. private record DeclarationModifiersAndTypeAnnotations( ImmutableList declarationModifiers, ImmutableList typeAnnotations) { @@ -2558,10 +2547,8 @@ boolean hasDeclarationAnnotation() { } } - /** - * Examines the token stream to convert the modifiers for a declaration into a {@link - * DeclarationModifiersAndTypeAnnotations}. - */ + /// Examines the token stream to convert the modifiers for a declaration into a + /// [DeclarationModifiersAndTypeAnnotations]. private DeclarationModifiersAndTypeAnnotations splitModifiers( ModifiersTree modifiersTree, List annotations) { Set flags = modifiersTree.getFlags(); @@ -2662,7 +2649,7 @@ public Void visitCatch(CatchTree node, Void unused) { throw new IllegalStateException("expected manual descent into catch trees"); } - /** Helper method for {@link CatchTree}s. */ + /// Helper method for [CatchTree]s. private void visitCatchClause(CatchTree node, AllowTrailingBlankLine allowTrailingBlankLine) { sync(node); builder.space(); @@ -2689,7 +2676,7 @@ private void visitCatchClause(CatchTree node, AllowTrailingBlankLine allowTraili node.getBlock(), CollapseEmptyOrNot.NO, AllowLeadingBlankLine.YES, allowTrailingBlankLine); } - /** Formats a union type declaration in a catch clause. */ + /// Formats a union type declaration in a catch clause. private void visitUnionType(VariableTree declaration) { UnionTypeTree type = (UnionTypeTree) declaration.getType(); builder.open(ZERO); @@ -2729,7 +2716,7 @@ private void visitUnionType(VariableTree declaration) { builder.close(); } - /** Accumulate the operands and operators. */ + /// Accumulate the operands and operators. private static void walkInfix( int precedence, ExpressionTree expression, @@ -2928,7 +2915,7 @@ public Void visitUses(UsesTree node, Void unused) { return null; } - /** Helper method for import declarations, names, and qualified names. */ + /// Helper method for import declarations, names, and qualified names. private void visitName(Tree node) { Deque stack = new ArrayDeque<>(); while (node instanceof MemberSelectTree memberSelectTree) { @@ -2978,7 +2965,7 @@ private void visitToDeclare( typeWithDims); } - /** Does not omit the leading {@code "<"}, which should be associated with the type name. */ + /// Does not omit the leading `"<"`, which should be associated with the type name. private void typeParametersRest( List typeParameters, Indent plusIndent) { builder.open(plusIndent); @@ -3000,11 +2987,9 @@ private void typeParametersRest( /** Collapse chains of {@code .} operators, across multiple {@link ASTNode} types. */ - /** - * Output a "." node. - * - * @param node0 the "." node - */ + /// Output a "." node. + /// + /// @param node0 the "." node private void visitDot(ExpressionTree node0) { ExpressionTree node = node0; @@ -3124,12 +3109,10 @@ private void visitDot(ExpressionTree node0) { } } - /** - * Output a "regular" chain of dereferences, possibly in builder-style. Break before every dot. - * - * @param items in the chain - * @param needDot whether a leading dot is needed - */ + /// Output a "regular" chain of dereferences, possibly in builder-style. Break before every dot. + /// + /// @param items in the chain + /// @param needDot whether a leading dot is needed private void visitRegularDot(List items, boolean needDot) { boolean trailingDereferences = items.size() > 1; boolean needDot0 = needDot; @@ -3199,16 +3182,14 @@ private boolean fillFirstArgument(ExpressionTree e, List items, return true; } - /** - * Output a chain of dereferences where some prefix should be treated as a single syntactic unit, - * either because it looks like a type name or because there is only a single method invocation in - * the chain. - * - * @param items in the chain - * @param needDot whether a leading dot is needed - * @param prefixes the terminal indices of 'prefixes' of the expression that should be treated as - * a syntactic unit - */ + /// Output a chain of dereferences where some prefix should be treated as a single syntactic unit, + /// either because it looks like a type name or because there is only a single method invocation + /// in the chain. + /// + /// @param items in the chain + /// @param needDot whether a leading dot is needed + /// @param prefixes the terminal indices of 'prefixes' of the expression that should be treated as + /// a syntactic unit private void visitDotWithPrefix( List items, boolean needDot, @@ -3254,7 +3235,7 @@ private void visitDotWithPrefix( builder.close(); } - /** Returns the simple names of expressions in a "." chain. */ + /// Returns the simple names of expressions in a "." chain. private static ImmutableList simpleNames(Deque stack) { ImmutableList.Builder simpleNames = ImmutableList.builder(); OUTER: @@ -3303,10 +3284,7 @@ private void dotExpressionUpToArgs(ExpressionTree expression, Optional } } - /** - * Returns the base expression of an array access, e.g. given {@code foo[0][0]} returns {@code - * foo}. - */ + /// Returns the base expression of an array access, e.g. given `foo[0][0]` returns `foo`. private static ExpressionTree getArrayBase(ExpressionTree node) { while (node instanceof ArrayAccessTree arrayAccessTree) { node = arrayAccessTree.getExpression(); @@ -3337,7 +3315,7 @@ private void dotExpressionArgsAndParen( formatArrayIndices(indices); } - /** Lays out one or more array indices. Does not output the expression for the array itself. */ + /// Lays out one or more array indices. Does not output the expression for the array itself. private void formatArrayIndices(Deque indices) { if (indices.isEmpty()) { return; @@ -3352,10 +3330,8 @@ private void formatArrayIndices(Deque indices) { builder.close(); } - /** - * Returns all array indices for the given expression, e.g. given {@code foo[0][0]} returns the - * expressions for {@code [0][0]}. - */ + /// Returns all array indices for the given expression, e.g. given `foo[0][0]` returns the + /// expressions for `[0][0]`. private static Deque getArrayIndices(ExpressionTree expression) { Deque indices = new ArrayDeque<>(); while (expression instanceof ArrayAccessTree array) { @@ -3365,7 +3341,7 @@ private static Deque getArrayIndices(ExpressionTree expression) return indices; } - /** Helper methods for method invocations. */ + /// Helper methods for method invocations. private void addTypeArguments(List typeArguments, Indent plusIndent) { if (typeArguments == null || typeArguments.isEmpty()) { return; @@ -3385,14 +3361,12 @@ private void addTypeArguments(List typeArguments, Indent plusInd token(">"); } - /** - * Add arguments to a method invocation, etc. The arguments indented {@code plusFour}, filled, - * from the current indent. The arguments may be output two at a time if they seem to be arguments - * to a map constructor, etc. - * - * @param arguments the arguments - * @param plusIndent the extra indent for the arguments - */ + /// Add arguments to a method invocation, etc. The arguments indented `plusFour`, filled, from the + /// current indent. The arguments may be output two at a time if they seem to be arguments to a + /// map constructor, etc. + /// + /// @param arguments the arguments + /// @param plusIndent the extra indent for the arguments private void addArguments(List arguments, Indent plusIndent) { builder.open(plusIndent); token("("); @@ -3451,25 +3425,23 @@ private void argList(List arguments) { builder.close(); } - /** - * Identifies String formatting methods like {@link String#format} which we prefer to format as: - * - *

{@code
-   * String.format(
-   *     "the format string: %s %s %s",
-   *     arg, arg, arg);
-   * }
- * - *

And not: - * - *

{@code
-   * String.format(
-   *     "the format string: %s %s %s",
-   *     arg,
-   *     arg,
-   *     arg);
-   * }
- */ + /// Identifies String formatting methods like [String#format] which we prefer to format as: + /// + /// ``` + /// String.format( + /// "the format string: %s %s %s", + /// arg, arg, arg); + /// ``` + /// + /// And not: + /// + /// ``` + /// String.format( + /// "the format string: %s %s %s", + /// arg, + /// arg, + /// arg); + /// ``` private boolean isFormatMethod(List arguments) { if (arguments.size() < 2) { return false; @@ -3504,7 +3476,7 @@ public void scan(JCTree tree) { return stringLiteral[0] && formatString[0]; } - /** Returns the number of columns if the arguments arg laid out in a grid, or else {@code -1}. */ + /// Returns the number of columns if the arguments arg laid out in a grid, or else `-1`. private int argumentsAreTabular(List arguments) { if (arguments.isEmpty()) { return -1; @@ -3588,7 +3560,7 @@ private Integer actualColumn(ExpressionTree expression) { return positionToColumnMap.get(builder.actualStartColumn(getStartPosition(expression))); } - /** Returns true if {@code atLeastM} of the expressions in the given column are the same kind. */ + /// Returns true if `atLeastM` of the expressions in the given column are the same kind. private static boolean expressionsAreParallel( List> rows, int column, int atLeastM) { Multiset nodeTypes = HashMultiset.create(); @@ -3613,14 +3585,14 @@ private static boolean expressionsAreParallel( // General helper functions. - /** Kind of declaration. */ + /// Kind of declaration. private enum DeclarationKind { NONE, FIELD, PARAMETER } - /** Declare one variable or variable-like thing. */ + /// Declare one variable or variable-like thing. private int declareOne( DeclarationKind kind, Direction annotationsDirection, @@ -3757,18 +3729,15 @@ private void maybeAddDims(Deque> annotations) { maybeAddDims(new ArrayDeque<>(), annotations); } - /** - * The compiler does not always preserve the concrete syntax of annotated array dimensions, and - * mixed-notation array dimensions. Use look-ahead to preserve the original syntax. - * - *

It is assumed that any number of regular dimension specifiers ({@code []} with no - * annotations) may be present in the input. - * - * @param dimExpressions an ordered list of dimension expressions (e.g. the {@code 0} in {@code - * new int[0]} - * @param annotations an ordered list of type annotations grouped by dimension (e.g. {@code - * [[@A, @B], [@C]]} for {@code int @A [] @B @C []} - */ + /// The compiler does not always preserve the concrete syntax of annotated array dimensions, and + /// mixed-notation array dimensions. Use look-ahead to preserve the original syntax. + /// + /// It is assumed that any number of regular dimension specifiers (`[]` with no annotations) may + /// be present in the input. + /// + /// @param dimExpressions an ordered list of dimension expressions (e.g. the `0` in `new int[0]`) + /// @param annotations an ordered list of type annotations grouped by dimension (e.g. `[[@A, @B], + /// [@C]]` for `int @A [] @B @C []`) private void maybeAddDims( Deque dimExpressions, Deque> annotations) { boolean lastWasAnnotation = false; @@ -3867,7 +3836,7 @@ private void declareMany(List fragments, Direction annotationDirec builder.close(); } - /** Add a list of declarations. */ + /// Add a list of declarations. private void addBodyDeclarations( List bodyDeclarations, BracesOrNot braces, FirstDeclarationsOrNot first0) { if (bodyDeclarations.isEmpty()) { @@ -3952,13 +3921,11 @@ private void classDeclarationTypeList(String token, List types) builder.close(); } - /** - * The parser expands multi-variable declarations into separate single-variable declarations. All - * of the fragments in the original declaration have the same start position, so we use that as a - * signal to collect them and preserve the multi-variable declaration in the output. - * - *

e.g. {@code int x, y;} is parsed as {@code int x; int y;}. - */ + /// The parser expands multi-variable declarations into separate single-variable declarations. All + /// of the fragments in the original declaration have the same start position, so we use that as a + /// signal to collect them and preserve the multi-variable declaration in the output. + /// + /// e.g. `int x, y;` is parsed as `int x; int y;`. private static List variableFragments( PeekingIterator it, Tree first) { List fragments = new ArrayList<>(); @@ -3999,7 +3966,7 @@ private OptionalInt javadocPosition(Tree bodyDeclaration) { return OptionalInt.empty(); } - /** Does this declaration have javadoc preceding it? */ + /// Does this declaration have javadoc preceding it? private boolean hasJavaDoc(Tree bodyDeclaration) { return javadocPosition(bodyDeclaration).isPresent(); } @@ -4008,7 +3975,7 @@ private static Optional getNextToken(Input input, int pos return Optional.ofNullable(input.getPositionTokenMap().get(position)); } - /** Does this list of trees end with the specified token? */ + /// Does this list of trees end with the specified token? private boolean hasTrailingToken(Input input, List nodes, String token) { if (nodes.isEmpty()) { return false; @@ -4019,13 +3986,11 @@ private boolean hasTrailingToken(Input input, List nodes, String return nextToken.isPresent() && nextToken.get().getTok().getText().equals(token); } - /** - * Can a local with a set of modifiers be declared with horizontal annotations? This is currently - * true if there is at most one parameterless annotation, and no others. - * - * @param modifiers the list of {@link ModifiersTree}s - * @return whether the local can be declared with horizontal annotations - */ + /// Can a local with a set of modifiers be declared with horizontal annotations? This is currently + /// true if there is at most one parameterless annotation, and no others. + /// + /// @param modifiers the list of [ModifiersTree]s + /// @return whether the local can be declared with horizontal annotations private static Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) { int parameterlessAnnotations = 0; for (AnnotationTree annotation : modifiers.getAnnotations()) { @@ -4039,10 +4004,8 @@ private static Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifie : Direction.VERTICAL; } - /** - * Should a field with a set of modifiers be declared with horizontal annotations? This is - * currently true if all annotations are parameterless annotations. - */ + /// Should a field with a set of modifiers be declared with horizontal annotations? This is + /// currently true if all annotations are parameterless annotations. private static Direction fieldAnnotationDirection(ModifiersTree modifiers) { for (AnnotationTree annotation : modifiers.getAnnotations()) { if (!annotation.getArguments().isEmpty()) { @@ -4052,11 +4015,9 @@ private static Direction fieldAnnotationDirection(ModifiersTree modifiers) { return Direction.HORIZONTAL; } - /** - * Emit a {@link Doc.Token}. - * - * @param token the {@link String} to wrap in a {@link Doc.Token} - */ + /// Emit a [Doc.Token]. + /// + /// @param token the [String] to wrap in a [Doc.Token] private void token(String token) { builder.token( token, @@ -4065,12 +4026,10 @@ private void token(String token) { /* breakAndIndentTrailingComment= */ Optional.empty()); } - /** - * Emit a {@link Doc.Token}. - * - * @param token the {@link String} to wrap in a {@link Doc.Token} - * @param plusIndentCommentsBefore extra indent for comments before this token - */ + /// Emit a [Doc.Token]. + /// + /// @param token the [String] to wrap in a [Doc.Token] + /// @param plusIndentCommentsBefore extra indent for comments before this token private void token(String token, Indent plusIndentCommentsBefore) { builder.token( token, @@ -4079,7 +4038,7 @@ private void token(String token, Indent plusIndentCommentsBefore) { /* breakAndIndentTrailingComment= */ Optional.empty()); } - /** Emit a {@link Doc.Token}, and breaks and indents trailing javadoc or block comments. */ + /// Emit a [Doc.Token], and breaks and indents trailing javadoc or block comments. final void tokenBreakTrailingComment(String token, Indent breakAndIndentTrailingComment) { builder.token( token, Doc.Token.RealOrImaginary.REAL, ZERO, Optional.of(breakAndIndentTrailingComment)); @@ -4091,12 +4050,10 @@ private void markForPartialFormat() { } } - /** - * Sync to position in the input. If we've skipped outputting any tokens that were present in the - * input tokens, output them here and complain. - * - * @param node the ASTNode holding the input position - */ + /// Sync to position in the input. If we've skipped outputting any tokens that were present in the + /// input tokens, output them here and complain. + /// + /// @param node the ASTNode holding the input position private void sync(Tree node) { builder.sync(((JCTree) node).getStartPosition()); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java index 5af399521..51f52b706 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java @@ -42,10 +42,8 @@ * toks. */ -/** - * {@code JavaOutput} extends {@link Output Output} to represent a Java output document. It includes - * methods to emit the output document. - */ +/// `JavaOutput` extends [Output] to represent a Java output document. It includes methods to emit +/// the output document. public final class JavaOutput extends Output { private final String lineSeparator; private final Input javaInput; // Used to follow along while emitting the output. @@ -65,7 +63,7 @@ public final class JavaOutput extends Output { private static final int MAX_CACHED_SPACES = 100; private static final String[] spaces = new String[MAX_CACHED_SPACES + 1]; - /** Returns an indentation string of the given number of spaces. */ + /// Returns an indentation string of the given number of spaces. static String spaces(int indent) { if (indent <= 0) { return ""; @@ -80,23 +78,19 @@ static String spaces(int indent) { return " ".repeat(indent); } - /** - * {@code JavaOutput} constructor. - * - * @param javaInput the {@link Input}, used to match up blank lines in the output - * @param commentsHelper the {@link CommentsHelper}, used to rewrite comments - */ + /// `JavaOutput` constructor. + /// + /// @param javaInput the [Input], used to match up blank lines in the output + /// @param commentsHelper the [CommentsHelper], used to rewrite comments public JavaOutput(String lineSeparator, Input javaInput, CommentsHelper commentsHelper) { this(lineSeparator, javaInput, commentsHelper, JavaOutput::spaces); } - /** - * {@code JavaOutput} constructor. - * - * @param javaInput the {@link Input}, used to match up blank lines in the output - * @param commentsHelper the {@link CommentsHelper}, used to rewrite comments - * @param indentFunction function mapping a visual column indent to an indentation string - */ + /// `JavaOutput` constructor. + /// + /// @param javaInput the [Input], used to match up blank lines in the output + /// @param commentsHelper the [CommentsHelper], used to rewrite comments + /// @param indentFunction function mapping a visual column indent to an indentation string public JavaOutput( String lineSeparator, Input javaInput, @@ -217,7 +211,7 @@ public void indent(int indent) { spacesPending.append(indentFunction.apply(indent)); } - /** Flush any incomplete last line, then add the EOF token into our data structures. */ + /// Flush any incomplete last line, then add the EOF token into our data structures. public void flush() { String lastLine = lineBuilder.toString(); if (!CharMatcher.whitespace().matchesAllOf(lastLine)) { @@ -239,11 +233,9 @@ public CommentsHelper getCommentsHelper() { return commentsHelper; } - /** - * Emit a list of {@link Replacement}s to convert from input to output. - * - * @return a list of {@link Replacement}s, sorted by start index, without overlaps - */ + /// Emit a list of [Replacement]s to convert from input to output. + /// + /// @return a list of [Replacement]s, sorted by start index, without overlaps public ImmutableList getFormatReplacements(RangeSet iRangeSet0) { ImmutableList.Builder result = ImmutableList.builder(); Map> kToJ = JavaOutput.makeKToIJ(this); @@ -350,12 +342,10 @@ public ImmutableList getFormatReplacements(RangeSet iRange return result.build(); } - /** - * Expand a token range to start and end on acceptable boundaries for re-formatting. - * - * @param iRange the {@link Range} of tokens - * @return the expanded token range - */ + /// Expand a token range to start and end on acceptable boundaries for re-formatting. + /// + /// @param iRange the [Range] of tokens + /// @return the expanded token range private Range expandToBreakableRegions(Range iRange) { // The original line range. int loTok = iRange.lowerEndpoint(); @@ -383,7 +373,7 @@ public static String applyReplacements(String input, List replaceme return writer.toString(); } - /** The earliest non-whitespace Tok in the Token. */ + /// The earliest non-whitespace Tok in the Token. public static Input.Tok startTok(Token token) { for (Input.Tok tok : token.getToksBefore()) { if (tok.getIndex() >= 0) { @@ -393,7 +383,7 @@ public static Input.Tok startTok(Token token) { return token.getTok(); } - /** The last non-whitespace Tok in the Token. */ + /// The last non-whitespace Tok in the Token. public static Input.Tok endTok(Token token) { for (int i = token.getToksAfter().size() - 1; i >= 0; i--) { Input.Tok tok = token.getToksAfter().get(i); diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java index 93382330e..b1dd1de3a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java @@ -30,24 +30,22 @@ import java.util.Map; import java.util.Set; -/** A wrapper around javac's lexer. */ +/// A wrapper around javac's lexer. final class JavacTokens { - /** The lexer eats terminal comments, so feed it one we don't care about. */ + /// The lexer eats terminal comments, so feed it one we don't care about. // TODO(b/33103797): fix javac and remove the work-around private static final CharSequence EOF_COMMENT = "\n//EOF"; - /** - * An unprocessed input token, including whitespace and comments. - * - * @param stringVal the escaped string value of a literal, or {@code null} for other tokens. - * @param kind the token kind, or {@code null} for whitespace and comments. - * @param pos the start position. - * @param endPos the end position. - */ + /// An unprocessed input token, including whitespace and comments. + /// + /// @param stringVal the escaped string value of a literal, or `null` for other tokens. + /// @param kind the token kind, or `null` for whitespace and comments. + /// @param pos the start position. + /// @param endPos the end position. record RawTok(String stringVal, TokenKind kind, int pos, int endPos) {} - /** Lex the input and return a list of {@link RawTok}s. */ + /// Lex the input and return a list of [RawTok]s. static ImmutableList getTokens( String source, Context context, Set stopTokens) { if (source == null) { @@ -105,7 +103,7 @@ private static ImmutableList getComments( return token.comments.stream().map(comments::get).collect(toImmutableList()).reverse(); } - /** A {@link JavaTokenizer} that saves comments. */ + /// A [JavaTokenizer] that saves comments. private static class CommentSavingTokenizer extends JavaTokenizer { private final Map comments = new HashMap<>(); @@ -147,14 +145,12 @@ private char[] getRawCharactersReflectively(int beginIndex, int endIndex) { } } - /** A {@link Comment} that saves its text and start position. */ + /// A [Comment] that saves its text and start position. private record CommentWithTextAndPosition(int pos, int endPos, String text) { - /** - * Returns the source position of the character at index {@code index} in the comment text. - * - *

The handling of javadoc comments in javac has more logic to skip over leading whitespace - * and '*' characters when indexing into doc comments, but we don't need any of that. - */ + /// Returns the source position of the character at index `index` in the comment text. + /// + /// The handling of javadoc comments in javac has more logic to skip over leading whitespace and + /// '*' characters when indexing into doc comments, but we don't need any of that. int getSourcePos(int index) { checkArgument( 0 <= index && index < (endPos - pos), diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index 19165b24a..dce08274f 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -39,7 +39,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -/** The main class for the Java formatter CLI. */ +/// The main class for the Java formatter CLI. public final class Main { private static final int MAX_THREADS = 20; private static final String STDIN_FILENAME = ""; @@ -58,32 +58,26 @@ public Main(PrintWriter outWriter, PrintWriter errWriter, InputStream inStream) this.inStream = inStream; } - /** - * The main method for the formatter, with some number of file names to format. We process them in - * parallel, but we must be careful; if multiple file names refer to the same file (which is hard - * to determine), we must serialize their updates. - * - * @param args the command-line arguments - */ + /// The main method for the formatter, with some number of file names to format. We process them + /// in parallel, but we must be careful; if multiple file names refer to the same file (which is + /// hard to determine), we must serialize their updates. + /// + /// @param args the command-line arguments public static void main(String... args) { int result = main(System.in, System.out, System.err, args); System.exit(result); } - /** - * Package-private main entry point used by the {@link javax.tools.Tool Tool} implementation in - * the same package as this Main class. - */ + /// Package-private main entry point used by the [`Tool`][javax.tools.Tool] implementation in the + /// same package as this Main class. static int main(InputStream in, PrintStream out, PrintStream err, String... args) { PrintWriter outWriter = new PrintWriter(new OutputStreamWriter(out, UTF_8)); PrintWriter errWriter = new PrintWriter(new OutputStreamWriter(err, UTF_8)); return main(in, outWriter, errWriter, args); } - /** - * Package-private main entry point used by the {@link java.util.spi.ToolProvider ToolProvider} - * implementation in the same package as this Main class. - */ + /// Package-private main entry point used by the [`ToolProvider`][java.util.spi.ToolProvider] + /// implementation in the same package as this Main class. static int main(InputStream in, PrintWriter out, PrintWriter err, String... args) { try { Main formatter = new Main(out, err, in); @@ -98,13 +92,11 @@ static int main(InputStream in, PrintWriter out, PrintWriter err, String... args } } - /** - * The main entry point for the formatter, with some number of file names to format. We process - * them in parallel, but we must be careful; if multiple file names refer to the same file (which - * is hard to determine), we must serialize their update. - * - * @param args the command-line arguments - */ + /// The main entry point for the formatter, with some number of file names to format. We process + /// them in parallel, but we must be careful; if multiple file names refer to the same file (which + /// is hard to determine), we must serialize their update. + /// + /// @param args the command-line arguments public int format(String... args) throws UsageException { CommandLineOptions parameters = processArgs(args); if (parameters.version()) { @@ -240,7 +232,7 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti return ok ? 0 : 1; } - /** Parses and validates command-line flags. */ + /// Parses and validates command-line flags. static CommandLineOptions processArgs(String... args) throws UsageException { CommandLineOptions parameters; try { diff --git a/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java index 5bb3e1503..251a3e84a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java @@ -37,20 +37,18 @@ import javax.lang.model.element.Modifier; import org.jspecify.annotations.Nullable; -/** Fixes sequences of modifiers to be in JLS order. */ +/// Fixes sequences of modifiers to be in JLS order. final class ModifierOrderer { - /** Reorders all modifiers in the given text to be in JLS order. */ + /// Reorders all modifiers in the given text to be in JLS order. static JavaInput reorderModifiers(String text) throws FormatterException { return reorderModifiers( new JavaInput(text), ImmutableList.of(Range.closedOpen(0, text.length()))); } - /** - * A class that contains the tokens corresponding to a modifier. This is usually a single token - * (e.g. for {@code public}), but may be multiple tokens for modifiers containing {@code -} (e.g. - * {@code non-sealed}). - */ + /// A class that contains the tokens corresponding to a modifier. This is usually a single token + /// (e.g. for `public`), but may be multiple tokens for modifiers containing `-` (e.g. + /// `non-sealed`). private record ModifierTokens(ImmutableList tokens, Modifier modifier) implements Comparable { @@ -97,10 +95,8 @@ public int compareTo(ModifierTokens o) { } } - /** - * Reorders all modifiers in the given text and within the given character ranges to be in JLS - * order. - */ + /// Reorders all modifiers in the given text and within the given character ranges to be in JLS + /// order. static JavaInput reorderModifiers(JavaInput javaInput, Collection> characterRanges) throws FormatterException { if (javaInput.getTokens().isEmpty()) { @@ -188,10 +184,7 @@ private static void addTrivia(StringBuilder replacement, ImmutableList replacementMap) throws FormatterException { // process in descending order so the replacement ranges aren't perturbed if any replacements diff --git a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java index 4b2211eae..732f37c67 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java +++ b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java @@ -57,10 +57,8 @@ import javax.tools.JavaFileObject; import org.jspecify.annotations.Nullable; -/** - * Removes unused imports from a source file. Imports that are only used in javadoc are nevertheless - * kept. - */ +/// Removes unused imports from a source file. Imports that are only used in javadoc are +/// nevertheless kept. public class RemoveUnusedImports { // Visits an AST, recording all simple names that could refer to imported @@ -91,7 +89,7 @@ private UnusedImportScanner(JavacTrees trees) { docTreeSymbolScanner = new DocTreeScanner(); } - /** Skip the imports themselves when checking for usage. */ + /// Skip the imports themselves when checking for usage. @Override public Void visitImport(ImportTree importTree, Void usedSymbols) { return null; @@ -227,7 +225,7 @@ private static JCCompilationUnit parse(Context context, String javaInput) return unit; } - /** Construct replacements to fix unused imports. */ + /// Construct replacements to fix unused imports. private static RangeMap buildReplacements( String contents, JCCompilationUnit unit, @@ -327,7 +325,7 @@ private static boolean isModuleImport(JCTree importTree) { } } - /** Applies the replacements to the given source, and re-format any edited javadoc. */ + /// Applies the replacements to the given source, and re-format any edited javadoc. private static String applyReplacements(String source, RangeMap replacements) { // save non-empty fixed ranges for reformatting after fixes are applied RangeSet fixedRanges = TreeRangeSet.create(); diff --git a/core/src/main/java/com/google/googlejavaformat/java/Replacement.java b/core/src/main/java/com/google/googlejavaformat/java/Replacement.java index 088f81597..62e91efb2 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Replacement.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Replacement.java @@ -20,12 +20,10 @@ import com.google.common.collect.Range; import com.google.errorprone.annotations.InlineMe; -/** - * Represents a range in the original source and replacement text for that range. - * - * @param replaceRange The range of characters in the original source to replace. - * @param replacementString The string to replace the range of characters with. - */ +/// Represents a range in the original source and replacement text for that range. +/// +/// @param replaceRange The range of characters in the original source to replace. +/// @param replacementString The string to replace the range of characters with. public record Replacement(Range replaceRange, String replacementString) { public static Replacement create(int startPosition, int endPosition, String replaceWith) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java b/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java index 2b75eb4a1..f7e07dfb8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java @@ -26,10 +26,10 @@ import java.util.ArrayList; import java.util.List; -/** Formats a subset of a compilation unit. */ +/// Formats a subset of a compilation unit. public class SnippetFormatter { - /** The kind of snippet to format. */ + /// The kind of snippet to format. public enum SnippetKind { COMPILATION_UNIT, CLASS_BODY_DECLARATIONS, @@ -92,7 +92,7 @@ private static List> offsetRanges(List> ranges, in return result; } - /** Runs the Google Java formatter on the given source, with only the given ranges specified. */ + /// Runs the Google Java formatter on the given source, with only the given ranges specified. public ImmutableList format( SnippetKind kind, String source, @@ -125,10 +125,8 @@ public ImmutableList format( .collect(toImmutableList()); } - /** - * Generates {@code Replacement}s rewriting {@code source} to {@code replacement}, under the - * assumption that they differ in whitespace alone. - */ + /// Generates `Replacement`s rewriting `source` to `replacement`, under the assumption that they + /// differ in whitespace alone. private static List toReplacements(String source, String replacement) { if (!NOT_WHITESPACE.retainFrom(source).equals(NOT_WHITESPACE.retainFrom(replacement))) { throw new IllegalArgumentException( diff --git a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java index 449644312..074dcea30 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -47,19 +47,17 @@ import javax.tools.Diagnostic; import javax.tools.JavaFileObject; -/** Wraps string literals that exceed the column limit. */ +/// Wraps string literals that exceed the column limit. public final class StringWrapper { private static final String TEXT_BLOCK_DELIMITER = "\"\"\""; - /** Reflows long string literals in the given Java source code. */ + /// Reflows long string literals in the given Java source code. public static String wrap(String input, Formatter formatter) throws FormatterException { return StringWrapper.wrap(formatter.options().maxLineLength(), input, formatter); } - /** - * Reflows string literals in the given Java source code that extend past the given column limit. - */ + /// Reflows string literals in the given Java source code that extend past the given column limit. static String wrap(final int columnLimit, String input, Formatter formatter) throws FormatterException { JavaFormatterOptions options = formatter.options(); @@ -268,10 +266,8 @@ private void wrapLongStrings( } } - /** - * Returns the source text of the given string literal trees, excluding the leading and trailing - * double-quotes and the `+` operator. - */ + /// Returns the source text of the given string literal trees, excluding the leading and trailing + /// double-quotes and the `+` operator. private static ImmutableList stringComponents( String input, JCTree.JCCompilationUnit unit, List flat) { ImmutableList.Builder result = ImmutableList.builder(); @@ -330,17 +326,15 @@ private static int hasEscapedNewlineAt(String input, int idx) { return offset > 0 ? offset : -1; } - /** - * Reflows the given source text, trying to split on word boundaries. - * - * @param separator the line separator - * @param columnLimit the number of columns to wrap at - * @param startColumn the column position of the beginning of the original text - * @param trailing extra space to leave after the last line, to accommodate a ; or ) - * @param components the text to reflow. This is a list of “words” of a single literal. Its first - * and last quotes have been stripped - * @param first0 true if the text includes the beginning of its enclosing concat chain - */ + /// Reflows the given source text, trying to split on word boundaries. + /// + /// @param separator the line separator + /// @param columnLimit the number of columns to wrap at + /// @param startColumn the column position of the beginning of the original text + /// @param trailing extra space to leave after the last line, to accommodate a ; or ) + /// @param components the text to reflow. This is a list of “words” of a single literal. Its first + /// and last quotes have been stripped + /// @param first0 true if the text includes the beginning of its enclosing concat chain private static String reflow( String separator, int columnLimit, @@ -402,10 +396,8 @@ private static boolean totalLengthLessThanOrEqual(Iterable input, int le return true; } - /** - * Flattens the given binary expression tree, and extracts the subset that contains the given path - * and any adjacent nodes that are also string literals. - */ + /// Flattens the given binary expression tree, and extracts the subset that contains the given + /// path and any adjacent nodes that are also string literals. private static List flatten( String input, JCTree.JCCompilationUnit unit, @@ -458,10 +450,8 @@ private static boolean noComments( private static final CharMatcher STRING_CONCAT_DELIMITER = CharMatcher.whitespace().or(CharMatcher.anyOf("\"+")); - /** - * Returns true if any lines in the given Java source exceed the column limit, or contain a {@code - * """} that could indicate a text block. - */ + /// Returns true if any lines in the given Java source exceed the column limit, or contain a `"""` + /// that could indicate a text block. private static boolean needWrapping(int columnLimit, String input, JavaFormatterOptions options) { // TODO(cushon): consider adding Newlines.lineIterable? Iterator it = Newlines.lineIterator(input); @@ -474,7 +464,7 @@ private static boolean needWrapping(int columnLimit, String input, JavaFormatter return false; } - /** Parses the given Java source. */ + /// Parses the given Java source. private static JCTree.JCCompilationUnit parse(String source, boolean allowStringFolding) throws FormatterException { List> errorDiagnostics = new ArrayList<>(); @@ -488,7 +478,7 @@ private static JCTree.JCCompilationUnit parse(String source, boolean allowString return unit; } - /** Applies replacements to the given string. */ + /// Applies replacements to the given string. private static String applyReplacements( String javaInput, TreeRangeMap replacementMap) throws FormatterException { // process in descending order so the replacement ranges aren't perturbed if any replacements diff --git a/core/src/main/java/com/google/googlejavaformat/java/Trees.java b/core/src/main/java/com/google/googlejavaformat/java/Trees.java index a2f349e71..ceb97d6dc 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Trees.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Trees.java @@ -53,24 +53,24 @@ import javax.tools.StandardLocation; import org.jspecify.annotations.Nullable; -/** Utilities for working with {@link Tree}s. */ +/// Utilities for working with [Tree]s. class Trees { - /** Returns the length of the source for the node. */ + /// Returns the length of the source for the node. static int getLength(Tree tree, TreePath path) { return getEndPosition(tree, path) - getStartPosition(tree); } - /** Returns the source start position of the node. */ + /// Returns the source start position of the node. static int getStartPosition(Tree expression) { return ((JCTree) expression).getStartPosition(); } - /** Returns the source end position of the node. */ + /// Returns the source end position of the node. static int getEndPosition(Tree expression, TreePath path) { return getEndPosition(expression, path.getCompilationUnit()); } - /** Returns the source end position of the node. */ + /// Returns the source end position of the node. static int getEndPosition(Tree tree, CompilationUnitTree unit) { try { return (int) GET_END_POS_HANDLE.invokeExact((JCTree) tree, (JCCompilationUnit) unit); @@ -80,7 +80,7 @@ static int getEndPosition(Tree tree, CompilationUnitTree unit) { } } - /** Returns the source text for the node. */ + /// Returns the source text for the node. static String getSourceForNode(Tree node, TreePath path) { CharSequence source; try { @@ -91,7 +91,7 @@ static String getSourceForNode(Tree node, TreePath path) { return source.subSequence(getStartPosition(node), getEndPosition(node, path)).toString(); } - /** Returns the simple name of a (possibly qualified) method invocation expression. */ + /// Returns the simple name of a (possibly qualified) method invocation expression. static Name getMethodName(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); return switch (select) { @@ -101,7 +101,7 @@ static Name getMethodName(MethodInvocationTree methodInvocation) { }; } - /** Returns the receiver of a qualified method invocation expression, or {@code null}. */ + /// Returns the receiver of a qualified method invocation expression, or `null`. static @Nullable ExpressionTree getMethodReceiver(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); return select instanceof MemberSelectTree memberSelectTree @@ -109,7 +109,7 @@ static Name getMethodName(MethodInvocationTree methodInvocation) { : null; } - /** Returns the string name of an operator, including assignment and compound assignment. */ + /// Returns the string name of an operator, including assignment and compound assignment. static String operatorName(ExpressionTree expression) { JCTree.Tag tag = ((JCTree) expression).getTag(); if (tag == JCTree.Tag.ASSIGN) { @@ -123,12 +123,12 @@ static String operatorName(ExpressionTree expression) { return assignOp ? name + "=" : name; } - /** Returns the precedence of an expression's operator. */ + /// Returns the precedence of an expression's operator. static int precedence(ExpressionTree expression) { return TreeInfo.opPrec(((JCTree) expression).getTag()); } - /** Skips a single parenthesized tree. */ + /// Skips a single parenthesized tree. static ExpressionTree skipParen(ExpressionTree node) { return ((ParenthesizedTree) node).getExpression(); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/TypeNameClassifier.java b/core/src/main/java/com/google/googlejavaformat/java/TypeNameClassifier.java index b1e07a76f..9a4d209b9 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/TypeNameClassifier.java +++ b/core/src/main/java/com/google/googlejavaformat/java/TypeNameClassifier.java @@ -18,15 +18,15 @@ import java.util.List; import java.util.Optional; -/** Heuristics for classifying qualified names as types. */ +/// Heuristics for classifying qualified names as types. final class TypeNameClassifier { private TypeNameClassifier() {} - /** A state machine for classifying qualified names. */ + /// A state machine for classifying qualified names. private enum TyParseState { - /** The start state. */ + /// The start state. START(false) { @Override public TyParseState next(JavaCaseFormat n) { @@ -44,7 +44,7 @@ public TyParseState next(JavaCaseFormat n) { } }, - /** The current prefix is a type. */ + /// The current prefix is a type. TYPE(true) { @Override public TyParseState next(JavaCaseFormat n) { @@ -55,7 +55,7 @@ public TyParseState next(JavaCaseFormat n) { } }, - /** The current prefix is a type, followed by a single static member access. */ + /// The current prefix is a type, followed by a single static member access. FIRST_STATIC_MEMBER(true) { @Override public TyParseState next(JavaCaseFormat n) { @@ -63,7 +63,7 @@ public TyParseState next(JavaCaseFormat n) { } }, - /** Anything not represented by one of the other states. */ + /// Anything not represented by one of the other states. REJECT(false) { @Override public TyParseState next(JavaCaseFormat n) { @@ -71,7 +71,7 @@ public TyParseState next(JavaCaseFormat n) { } }, - /** An ambiguous type prefix. */ + /// An ambiguous type prefix. AMBIGUOUS(false) { @Override public TyParseState next(JavaCaseFormat n) { @@ -93,22 +93,18 @@ boolean isSingleUnit() { return isSingleUnit; } - /** Transition function. */ + /// Transition function. abstract TyParseState next(JavaCaseFormat n); } - /** - * Returns the end index (inclusive) of the longest prefix that matches the naming conventions of - * a type or static field access, or -1 if no such prefix was found. - * - *

Examples: - * - *

    - *
  • ClassName - *
  • ClassName.staticMemberName - *
  • com.google.ClassName.InnerClass.staticMemberName - *
- */ + /// Returns the end index (inclusive) of the longest prefix that matches the naming conventions of + /// a type or static field access, or -1 if no such prefix was found. + /// + /// Examples: + /// + /// - ClassName + /// - ClassName.staticMemberName + /// - com.google.ClassName.InnerClass.staticMemberName static Optional typePrefixLength(List nameParts) { TyParseState state = TyParseState.START; Optional typeLength = Optional.empty(); @@ -124,14 +120,14 @@ static Optional typePrefixLength(List nameParts) { return typeLength; } - /** Case formats used in Java identifiers. */ + /// Case formats used in Java identifiers. enum JavaCaseFormat { UPPERCASE, LOWERCASE, UPPER_CAMEL, LOWER_CAMEL; - /** Classifies an identifier's case format. */ + /// Classifies an identifier's case format. static JavaCaseFormat from(String name) { Verify.verify(!name.isEmpty()); boolean firstUppercase = false; diff --git a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java index a51151ee6..354f1fcd3 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java @@ -16,7 +16,7 @@ import static com.google.common.base.Preconditions.checkNotNull; -/** Checked exception class for formatter command-line usage errors. */ +/// Checked exception class for formatter command-line usage errors. final class UsageException extends Exception { private static final String DOCS_LINK = diff --git a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java index e8da9fac9..d4d065839 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java +++ b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java @@ -27,10 +27,7 @@ import javax.tools.JavaFileObject; import org.jspecify.annotations.Nullable; -/** - * A decorating {@link Filer} implementation which formats Java source files with a {@link - * Formatter}. - */ +/// A decorating [Filer] implementation which formats Java source files with a [Formatter]. public final class FormattingFiler implements Filer { private final Filer delegate; @@ -38,11 +35,9 @@ public final class FormattingFiler implements Filer { private final Formatter formatter = new Formatter(); private final Messager messager; - /** - * Create a new {@link FormattingFiler}. - * - * @param processingEnv the processing environment - */ + /// Create a new [FormattingFiler]. + /// + /// @param processingEnv the processing environment public static Filer create(ProcessingEnvironment processingEnv) { Filer delegate = processingEnv.getFiler(); if (processingEnv.getOptions().containsKey("experimental_turbine_hjar")) { @@ -51,26 +46,22 @@ public static Filer create(ProcessingEnvironment processingEnv) { return new FormattingFiler(delegate, processingEnv.getMessager()); } - /** - * Create a new {@link FormattingFiler}. - * - * @param delegate filer to decorate - * @deprecated prefer {@link #create(ProcessingEnvironment)} - */ + /// Create a new [FormattingFiler]. + /// + /// @param delegate filer to decorate + /// @deprecated prefer [#create(ProcessingEnvironment)] @Deprecated public FormattingFiler(Filer delegate) { this(delegate, null); } - /** - * Create a new {@link FormattingFiler}. An optional {@link Messager} may be specified to make - * logs more visible. - * - * @param delegate filer to decorate - * @param messager to log warnings to - * @deprecated prefer {@link #create(ProcessingEnvironment)} - */ + /// Create a new [FormattingFiler]. An optional [Messager] may be specified to make logs more + /// visible. + /// + /// @param delegate filer to decorate + /// @param messager to log warnings to + /// @deprecated prefer [#create(ProcessingEnvironment)] @Deprecated public FormattingFiler(Filer delegate, @Nullable Messager messager) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java index b65258b1a..c170e43a8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java +++ b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java @@ -28,20 +28,18 @@ import javax.tools.JavaFileObject; import org.jspecify.annotations.Nullable; -/** A {@link JavaFileObject} decorator which {@linkplain Formatter formats} source code. */ +/// A [JavaFileObject] decorator which [formats][Formatter] source code. final class FormattingJavaFileObject extends ForwardingJavaFileObject { - /** A rough estimate of the average file size: 80 chars per line, 500 lines. */ + /// A rough estimate of the average file size: 80 chars per line, 500 lines. private static final int DEFAULT_FILE_SIZE = 80 * 500; private final Formatter formatter; private final Messager messager; - /** - * Create a new {@link FormattingJavaFileObject}. - * - * @param delegate {@link JavaFileObject} to decorate - * @param messager to log messages with. - */ + /// Create a new [FormattingJavaFileObject]. + /// + /// @param delegate [JavaFileObject] to decorate + /// @param messager to log messages with. FormattingJavaFileObject( JavaFileObject delegate, Formatter formatter, @Nullable Messager messager) { super(checkNotNull(delegate)); diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/CharStream.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/CharStream.java index 273bdcd33..153559955 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/CharStream.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/CharStream.java @@ -19,12 +19,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * String reader designed for use from the lexer. Callers invoke the {@link #tryConsume tryConsume*} - * methods to specify what characters they expect and then {@link #readAndResetRecorded} to retrieve - * and consume the matched characters. This is a slightly odd API -- why not just return the matched - * characters from tryConsume? -- but it is convenient for the lexer. - */ +/// String reader designed for use from the lexer. Callers invoke the [`tryConsume*`][#tryConsume] +/// methods to specify what characters they expect and then [#readAndResetRecorded] to retrieve and +/// consume the matched characters. This is a slightly odd API -- why not just return the matched +/// characters from tryConsume? -- but it is convenient for the lexer. final class CharStream { private final String input; private int position; @@ -42,11 +40,9 @@ boolean tryConsume(String expected) { return true; } - /** - * Tries to consume characters from the current position that match the given pattern. - * - * @param pattern the pattern to search for, which must be anchored to match only at position 0 - */ + /// Tries to consume characters from the current position that match the given pattern. + /// + /// @param pattern the pattern to search for, which must be anchored to match only at position 0 boolean tryConsumeRegex(Pattern pattern) { Matcher matcher = pattern.matcher(input).region(position, input.length()); if (!matcher.lookingAt()) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java index 83d997476..1e91eb8d8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java @@ -66,22 +66,18 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Entry point for formatting Javadoc. - * - *

This stateless class reads tokens from the stateful lexer and translates them to "requests" - * and "writes" to the stateful writer. It also munges tokens into "standardized" forms. Finally, it - * performs postprocessing to convert the written Javadoc to a one-liner if possible or to leave a - * single blank line if it's empty. - */ +/// Entry point for formatting Javadoc. +/// +/// This stateless class reads tokens from the stateful lexer and translates them to "requests" and +/// "writes" to the stateful writer. It also munges tokens into "standardized" forms. Finally, it +/// performs postprocessing to convert the written Javadoc to a one-liner if possible or to leave a +/// single blank line if it's empty. public final class JavadocFormatter { - /** - * Formats the given Javadoc comment. A classic Javadoc comment must start with ∕✱✱ and end with - * ✱∕, and the output will start and end with the same characters. A Markdown Javadoc comment - * consists of lines each of which starts with ///, and the output will also consist of such - * lines. - */ + /// Formats the given Javadoc comment. A classic Javadoc comment must start with ∕✱✱ and end with + /// ✱∕, and the output will start and end with the same characters. A Markdown Javadoc comment + /// consists of lines each of which starts with ///, and the output will also consist of such + /// lines. public static String formatJavadoc(String input, int blockIndent, int maxLineLength) { boolean classicJavadoc = switch (input) { @@ -177,10 +173,8 @@ private static T standardize(T token, T standardToken) { private static final Pattern ONE_CONTENT_LINE_PATTERN = compile(" */[*][*]\n *[*] (.*)\n *[*]/"); - /** - * Returns the given string or a one-line version of it (e.g., "∕✱✱ Tests for foos. ✱∕") if it - * fits on one line. - */ + /// Returns the given string or a one-line version of it (e.g., "∕✱✱ Tests for foos. ✱∕") if it + /// fits on one line. private static String makeSingleLineIfPossible(int blockIndent, String input, int maxLineLength) { Matcher matcher = ONE_CONTENT_LINE_PATTERN.matcher(input); if (matcher.matches()) { @@ -221,10 +215,8 @@ private static String stripJavadocBeginAndEnd(String input) { return input.substring("/**".length(), end); } - /** - * Returns the given classic Javadoc comment after removing the leading ∕✱✱, trailing ✱∕, and any - * leading asterisks and common leading whitespace on each line. - */ + /// Returns the given classic Javadoc comment after removing the leading ∕✱✱, trailing ✱∕, and any + /// leading asterisks and common leading whitespace on each line. private static String classicCommentText(String input) { String stripped = stripJavadocBeginAndEnd(input); List lines = stripped.lines().toList(); @@ -266,10 +258,8 @@ private static String classicCommentText(String input) { return stripCommonLeadingWhitespace(processedLines); } - /** - * Returns the given string with the leading /// and any common leading whitespace removed from - * each line. The resultant string can then be fed to a standard Markdown parser. - */ + /// Returns the given string with the leading /// and any common leading whitespace removed from + /// each line. The resultant string can then be fed to a standard Markdown parser. private static String markdownCommentText(String input) { List lines = input 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 c34b4f583..1762b6b21 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 @@ -68,9 +68,9 @@ import java.util.function.Function; import java.util.regex.Pattern; -/** Lexer for the Javadoc formatter. */ +/// Lexer for the Javadoc formatter. final class JavadocLexer { - /** Takes a Javadoc comment, including ∕✱✱ and ✱∕, and returns tokens, including ∕✱✱ and ✱∕. */ + /// Takes a Javadoc comment, including ∕✱✱ and ✱∕, and returns tokens, including ∕✱✱ and ✱∕. static ImmutableList lex(String input, boolean classicJavadoc) throws LexException { input = normalizeLineEndings(input); MarkdownPositions markdownPositions; @@ -87,7 +87,7 @@ static ImmutableList lex(String input, boolean classicJavadoc) throws Lex .generateTokens(); } - /** The lexer crashes on windows line endings, so for now just normalize to `\n`. */ + /// The lexer crashes on windows line endings, so for now just normalize to `\n`. // TODO(cushon): use the platform line separator for output private static String normalizeLineEndings(String input) { return NON_UNIX_LINE_ENDING.matcher(input).replaceAll("\n"); @@ -95,37 +95,31 @@ private static String normalizeLineEndings(String input) { private static final Pattern NON_UNIX_LINE_ENDING = Pattern.compile("\r\n?"); - /** - * An element of the nested contexts we might be in. For example, if we are inside {@code - *

{@code ...}
} then the stack of nested contexts would be {@code PRE} plus {@code - * CODE_CONTEXT}. - */ + /// An element of the nested contexts we might be in. For example, if we are inside `
{@code
+  /// ...}
` then the stack of nested contexts would be `PRE` plus `CODE_CONTEXT`. enum NestingContext { - /** {@code
...
}. */ + /// `
...
`. HTML_PRE_CONTEXT, - /** {@code ...}. */ + /// `...`. HTML_CODE_CONTEXT, - /** Markdown {@code `...`}. */ + /// Markdown `` `...` ``. MARKDOWN_CODE_CONTEXT, - /** {@code ...
}. */ + /// `...
`. TABLE, - /** {@code {@snippet ...}}. */ + /// `{@snippet ...}`. SNIPPET_CONTEXT, - /** Nested braces within one of the other contexts. */ + /// Nested braces within one of the other contexts. BRACE_CONTEXT, - /** - * An inline tag such as {@code {@link ...}} or {@code {@code ...}}, but not {@code {@snippet - * ...}}. - */ + /// An inline tag such as `{@link ...}` or `{@code ...}`, but not `{@snippet ...}`. INLINE_TAG_CONTEXT, - /** Markdown {@code >}. */ + /// Markdown `>`. BLOCKQUOTE } @@ -392,19 +386,16 @@ private void checkMatchingTags() throws LexException { } } - /** - * Join together adjacent literal tokens, and join together adjacent whitespace tokens. - * - *

For literal tokens, this means something like {@code ["", "foo", ""] => - * ["foo"]}. See {@link #literalPattern()} for discussion of why those tokens are separate - * to begin with. - * - *

Whitespace tokens are treated analogously. The joining of whitespace tokens allows our - * Markdown output to detect "loose lists" and our Traditional output to {@linkplain - * #inferParagraphTags infer where to place paragraph tags}. - * - *

Note that we do not merge a literal token and a whitespace token together. - */ + /// Join together adjacent literal tokens, and join together adjacent whitespace tokens. + /// + /// For literal tokens, this means something like `["", "foo", ""] => ["foo"]`. See + /// [#literalPattern()] for discussion of why those tokens are separate to begin with. + /// + /// Whitespace tokens are treated analogously. The joining of whitespace tokens allows our + /// Markdown output to detect "loose lists" and our Traditional output to [infer where to place + /// paragraph tags][#inferParagraphTags]. + /// + /// Note that we do *not* merge a literal token and a whitespace token together. private static ImmutableList joinAdjacentLiteralsAndAdjacentWhitespace(List input) { /* * Note: Our final token is always END_JAVADOC. This saves us some trouble: @@ -472,13 +463,11 @@ private static String consumeAdjacentWhitespace(PeekingIterator tokens) { return seenWhitespace.toString(); } - /** - * Where the input has two consecutive line breaks between literals, insert a {@code

} tag - * between the literals. - * - *

This method must be called after {@link #joinAdjacentLiteralsAndAdjacentWhitespace}, as it - * assumes that adjacent whitespace tokens have already been joined. - */ + /// Where the input has two consecutive line breaks between literals, insert a `

` tag between + /// the literals. + /// + /// This method must be called after [#joinAdjacentLiteralsAndAdjacentWhitespace], as it assumes + /// that adjacent whitespace tokens have already been joined. private static ImmutableList inferParagraphTags(List input) { ImmutableList.Builder output = ImmutableList.builder(); @@ -508,14 +497,12 @@ private static ImmutableList inferParagraphTags(List input) { */ } - /** - * Replaces whitespace after a {@code href=...>} token with an "optional link break." This allows - * us to output either {@code foo} or {@code \nfoo}, depending on - * how much space we have left on the line. - * - *

This method must be called after {@link #joinAdjacentLiteralsAndAdjacentWhitespace}, as it - * assumes that adjacent whitespace tokens have already been joined. - */ + /// Replaces whitespace after a `href=...>` token with an "optional link break." This allows us to + /// output either `foo` or `\nfoo`, depending on how much space we + /// have left on the line. + /// + /// This method must be called after [#joinAdjacentLiteralsAndAdjacentWhitespace], as it assumes + /// that adjacent whitespace tokens have already been joined. private static ImmutableList optionalizeSpacesAfterLinks(List input) { ImmutableList.Builder output = ImmutableList.builder(); @@ -540,11 +527,9 @@ private static ImmutableList optionalizeSpacesAfterLinks(List inpu */ } - /** - * Adjust indentation inside `

{@code` blocks.
-   *
-   * 

Also trim leading and trailing blank lines, and move the trailing `}` to its own line. - */ + /// Adjust indentation inside `

{@code` blocks.
+  ///
+  /// Also trim leading and trailing blank lines, and move the trailing `}` to its own line.
   private static ImmutableList deindentPreCodeBlocks(List input) {
     // TODO: b/323389829 - De-indent {@snippet ...} blocks, too.
     ImmutableList.Builder output = ImmutableList.builder();
@@ -628,24 +613,20 @@ private static void deindentPreCodeBlock(
     }
   }
 
-  /** Contexts that imply that we should not do HTML interpretation. */
+  /// Contexts that imply that we should not do HTML interpretation.
   private static final ImmutableSet TAG_CONTEXTS =
       ImmutableSet.of(NestingContext.SNIPPET_CONTEXT, NestingContext.INLINE_TAG_CONTEXT);
 
-  /**
-   * Contexts that are opened by a left brace and closed by a matching right brace. These are the
-   * ones where a nested left brace should open a nested context.
-   */
+  /// Contexts that are opened by a left brace and closed by a matching right brace. These are the
+  /// ones where a nested left brace should open a nested context.
   private static final ImmutableSet BRACE_CONTEXTS =
       ImmutableSet.of(
           NestingContext.SNIPPET_CONTEXT,
           NestingContext.INLINE_TAG_CONTEXT,
           NestingContext.BRACE_CONTEXT);
 
-  /**
-   * Contexts that preserve formatting, including line breaks and leading whitespace, within the
-   * context.
-   */
+  /// Contexts that preserve formatting, including line breaks and leading whitespace, within the
+  /// context.
   private static final ImmutableSet PRESERVE_FORMATTING_CONTEXTS =
       ImmutableSet.of(
           NestingContext.HTML_PRE_CONTEXT,
@@ -721,11 +702,9 @@ static boolean hasMultipleNewlines(String s) {
    */
   private static final Pattern MARKDOWN_LITERAL_PATTERN = compile(".\\p{IsAlphabetic}*", DOTALL);
 
-  /**
-   * The pattern used for "literals", things that do not have any special formatting meaning. This
-   * doesn't have to be a maximal sequence of literal characters, since adjacent literals will be
-   * joined together in a later step.
-   */
+  /// The pattern used for "literals", things that do not have any special formatting meaning. This
+  /// doesn't have to be a maximal sequence of literal characters, since adjacent literals will be
+  /// joined together in a later step.
   private Pattern literalPattern() {
     return classicJavadoc ? CLASSIC_LITERAL_PATTERN : MARKDOWN_LITERAL_PATTERN;
   }
diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java
index 38e1332e9..d57391859 100644
--- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java
+++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java
@@ -51,13 +51,11 @@
 import com.google.googlejavaformat.java.javadoc.Token.Whitespace;
 import java.util.List;
 
-/**
- * Stateful object that accepts "requests" and "writes," producing formatted Javadoc.
- *
- * 

Our Javadoc formatter doesn't ever generate a parse tree, only a stream of tokens, so the - * writer must compute and store the answer to questions like "How many levels of nested HTML list - * are we inside?" - */ +/// Stateful object that accepts "requests" and "writes," producing formatted Javadoc. +/// +/// Our Javadoc formatter doesn't ever generate a parse tree, only a stream of tokens, so the writer +/// must compute and store the answer to questions like "How many levels of nested HTML list are we +/// inside?" final class JavadocWriter { private static final Literal BACKSLASH_LITERAL = new Literal("\\"); @@ -67,11 +65,9 @@ final class JavadocWriter { private final int maxLineLength; private final StringBuilder output = new StringBuilder(); - /** - * Whether we are inside an {@code

  • } element, excluding the case in which the {@code
  • } - * contains a {@code
      } or {@code
        } that we are also inside -- unless of course we're - * inside an {@code
      1. } element in that inner list :) - */ + /// Whether we are inside an `
      2. ` element, excluding the case in which the `
      3. ` contains a + /// `
          ` or `
            ` that we are also inside -- unless of course we're inside an `
          1. ` element in + /// that inner list :) private boolean continuingListItemOfInnermostList; private boolean continuingFooterTag; @@ -90,11 +86,9 @@ final class JavadocWriter { this.maxLineLength = maxLineLength; } - /** - * Requests whitespace between the previously written token and the next written token. The - * request may be honored, or it may be overridden by a request for "more significant" whitespace, - * like a newline. - */ + /// Requests whitespace between the previously written token and the next written token. The + /// request may be honored, or it may be overridden by a request for "more significant" + /// whitespace, like a newline. void requestWhitespace() { requestWhitespace(WHITESPACE); } @@ -103,15 +97,12 @@ private void requestWhitespace(RequestedWhitespace requestedWhitespace) { this.requestedWhitespace = max(requestedWhitespace, this.requestedWhitespace); } - /** - * Requests whitespace or a blank line depending on the whitespace token. - * - *

            In Markdown Javadoc, if the whitespace token contains multiple newlines, it represents a - * blank line in the input (e.g., between a paragraph and a list, or between loose list items). We - * want to preserve these blank lines, so we request a blank line. Otherwise, or in classic - * Javadoc (where blank lines are handled via inferred {@code

            } tags), we just request standard - * whitespace. - */ + /// Requests whitespace or a blank line depending on the whitespace token. + /// + /// In Markdown Javadoc, if the whitespace token contains multiple newlines, it represents a blank + /// line in the input (e.g., between a paragraph and a list, or between loose list items). We want + /// to preserve these blank lines, so we request a blank line. Otherwise, or in classic Javadoc + /// (where blank lines are handled via inferred `

            ` tags), we just request standard whitespace. void requestWhitespaceOrBlankLine(Whitespace token) { if (!classicJavadoc && JavadocLexer.hasMultipleNewlines(token.value())) { requestBlankLine(); @@ -425,12 +416,10 @@ private void requestNewline() { requestWhitespace(NEWLINE); } - /** - * The kind of whitespace that has been requested between the previous and next tokens. The order - * of the values is significant: It goes from lowest priority to highest. For example, if the - * previous token requests {@link #BLANK_LINE} after it but the next token requests only {@link - * #NEWLINE} before it, we insert {@link #BLANK_LINE}. - */ + /// The kind of whitespace that has been requested between the previous and next tokens. The order + /// of the values is significant: It goes from lowest priority to highest. For example, if the + /// previous token requests [#BLANK_LINE] after it but the next token requests only [#NEWLINE] + /// before it, we insert [#BLANK_LINE]. enum RequestedWhitespace { NONE, WHITESPACE, diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java index 50d9b1f58..3e070ab9d 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java @@ -54,17 +54,14 @@ import org.commonmark.parser.IncludeSourceSpans; import org.commonmark.parser.Parser; -/** - * Determines the locations in a Markdown string where Markdown constructs occur. For example, if - * position 10 in the string looks like {@code # Heading\n}, the {@code positionToToken} map will - * contain an entry for 10 with a {@code HeaderOpenTag} token and an entry for (10 + - * "# Heading".length()) with a {@code HeaderCloseTag} token. These locations can then be - * inserted at the appropriate point in the stream of {@link Token} instances that the lexer - * produces. - * - *

            The text ({@Token#value()}) of these inserted tokens is mostly not added to the output, since - * the original Markdown characters are treated as literals. - */ +/// Determines the locations in a Markdown string where Markdown constructs occur. For example, if +/// position 10 in the string looks like `# Heading\n`, the `positionToToken` map will contain an +/// entry for 10 with a `HeaderOpenTag` token and an entry for (10 + "# Heading".length()) with +/// a `HeaderCloseTag` token. These locations can then be inserted at the appropriate point in the +/// stream of [Token] instances that the lexer produces. +/// +/// The text ([Token#value()]) of these inserted tokens is mostly not added to the output, since the +/// original Markdown characters are treated as literals. final class MarkdownPositions { final ImmutableListMultimap positionToToken; @@ -222,25 +219,20 @@ private void visitCodeSpan(Code code) { positionToToken.get(end - count).addFirst(new MarkdownCodeSpanEnd(backticks)); } - /** - * Visits the given node and the other nodes that are reachable from it via the {@link - * Node#getNext()} references. Does nothing if {@code node} is null. - */ + /// Visits the given node and the other nodes that are reachable from it via the + /// [Node#getNext()] references. Does nothing if `node` is null. private void visitNodeList(Node node) { for (; node != null; node = node.getNext()) { visit(node); } } - /** - * Adds tokens for the given node, {@code startToken} at the point where the node starts in the - * input, and {@code endToken} at the point where it ends. The {@code startToken} goes after any - * other tokens at that position and the {@code endToken} goes before any other tokens at that - * position. That reflects the structure. For example, at the start of a bullet list, the - * visitor we will translate this into {@link ListOpenTag} then {@link ListItemOpenTag} at the - * start position, and {@link ListItemCloseTag} then {@link ListCloseTag} (in that order) at the - * end position. - */ + /// Adds tokens for the given node, `startToken` at the point where the node starts in the + /// input, and `endToken` at the point where it ends. The `startToken` goes after any other + /// tokens at that position and the `endToken` goes before any other tokens at that position. + /// That reflects the structure. For example, at the start of a bullet list, the visitor we will + /// translate this into [ListOpenTag] then [ListItemOpenTag] at the start position, and + /// [ListItemCloseTag] then [ListCloseTag] (in that order) at the end position. private void addSpan(Node node, Token startToken, Token endToken) { addSpan(node, startToken, endToken, startPosition(node)); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/NestingStack.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/NestingStack.java index 7e0489b93..4d62b04f7 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/NestingStack.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/NestingStack.java @@ -19,18 +19,16 @@ import java.util.Deque; import org.jspecify.annotations.Nullable; -/** - * Stack for tracking the level of nesting. In the simplest case, we have a stack of {@link Integer} - * where each entry is just the integer 1, and the stack is effectively a counter. In more complex - * cases, the entries may depend on context. For example, if the stack is keeping track of Javadoc - * lists, the entries represent indentation levels, and those depend on whether the list is an HTML - * list or a Markdown list. - * - *

            Iterating over the stack goes from the bottom to the top. So for an indentation stack, for - * example, it produces the elements of indentation in the correct order. - * - * @param The type of the elements in the stack. - */ +/// Stack for tracking the level of nesting. In the simplest case, we have a stack of [Integer] +/// where each entry is just the integer 1, and the stack is effectively a counter. In more complex +/// cases, the entries may depend on context. For example, if the stack is keeping track of Javadoc +/// lists, the entries represent indentation levels, and those depend on whether the list is an HTML +/// list or a Markdown list. +/// +/// Iterating over the stack goes from the bottom to the top. So for an indentation stack, for +/// example, it produces the elements of indentation in the correct order. +/// +/// @param The type of the elements in the stack. final class NestingStack { private final Deque stack = new ArrayDeque<>(); @@ -49,9 +47,8 @@ void push(E value) { return stack.pop(); } - /** - * If the stack contains the given element, pop it and everything above it. Otherwise, do nothing. - */ + /// If the stack contains the given element, pop it and everything above it. Otherwise, do + /// nothing. void popUntil(E value) { if (stack.contains(value)) { E popped; diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/Token.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/Token.java index f4d2cb670..dda826221 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/Token.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/Token.java @@ -14,21 +14,19 @@ package com.google.googlejavaformat.java.javadoc; -/** - * Javadoc token. Our idea of what constitutes a token is often larger or smaller than what you'd - * naturally expect. The decision is usually pragmatic rather than theoretical. Most of the details - * are in {@link JavadocLexer}. - * - *

            The general idea is that every token that requires special handling (extra line breaks, - * indentation, forcing or forbidding whitespace) from {@link JavadocWriter} gets its own type. But - * I haven't been super careful about it, so I'd imagine that we could merge or remove some of these - * if we wanted. (For example, ParagraphCloseTag and ListItemCloseTag could be a common Ignorable - * token type. But their corresponding Open types exist, so I've kept the Close types.) - * - *

            Note, though, that tokens of the same type may still have been handled differently by {@link - * JavadocLexer} when it created them. For example, Literal is used for both plain text and inline - * tags, even though the two affect the lexer's state differently. - */ +/// Javadoc token. Our idea of what constitutes a token is often larger or smaller than what you'd +/// naturally expect. The decision is usually pragmatic rather than theoretical. Most of the details +/// are in [JavadocLexer]. +/// +/// The general idea is that every token that requires special handling (extra line breaks, +/// indentation, forcing or forbidding whitespace) from [JavadocWriter] gets its own type. But I +/// haven't been super careful about it, so I'd imagine that we could merge or remove some of these +/// if we wanted. (For example, ParagraphCloseTag and ListItemCloseTag could be a common Ignorable +/// token type. But their corresponding Open types exist, so I've kept the Close types.) +/// +/// Note, though, that tokens of the same type may still have been handled differently by +/// [JavadocLexer] when it created them. For example, Literal is used for both plain text and inline +/// tags, even though the two affect the lexer's state differently. sealed interface Token { String value(); @@ -36,30 +34,27 @@ default int length() { return value().length(); } - /** - * Tokens that are always pinned to the following token. For example, {@code

            } in {@code

            Foo - * bar} (never {@code

            Foo bar} or {@code

            \nFoo bar}); or {#code - *

          2. } or {@code -␣} in {@code
          3. Foo bar} or {@code -␣Foo bar}. - * - *

            This is not the only kind of "pinning" that we do: See also the joining of Literal - * tokens done by the lexer. The special pinning here is necessary because these tokens are - * not of type Literal (because they require other special handling). - */ + /// Tokens that are always pinned to the following token. For example, `

            ` in `

            Foo bar` + /// (never `

            Foo bar` or `

            \nFoo bar`); or `

          4. ` or `-␣` in `
          5. Foo bar` or `-␣Foo bar`. + /// + /// This is not the only kind of "pinning" that we do: See also the joining of Literal tokens done + /// by the lexer. The special pinning here is necessary because these tokens are not of type + /// Literal (because they require other special handling). interface StartOfLineToken {} - /** ∕✱✱ */ + /// ∕✱✱ record BeginJavadoc(String value) implements Token {} - /** ✱∕ */ + /// ✱∕ record EndJavadoc(String value) implements Token {} - /** The {@code @foo} that begins a block Javadoc tag like {@code @throws}. */ + /// The `@foo` that begins a block Javadoc tag like `@throws`. record FooterJavadocTagStart(String value) implements Token {} - /** The opening {@code {@snippet} of a code snippet. */ + /// The opening `{@snippet` of a code snippet. record SnippetBegin(String value) implements Token {} - /** The closing {@code }} of a code snippet. */ + /// The closing `}` of a code snippet. record SnippetEnd(String value) implements Token {} record ListOpenTag(String value) implements Token {} @@ -98,112 +93,93 @@ record TableOpenTag(String value) implements Token {} record TableCloseTag(String value) implements Token {} - /** {@code } */ + /// `` record MoeBeginStripComment(String value) implements Token {} - /** {@code } */ + /// `` record MoeEndStripComment(String value) implements Token {} record HtmlComment(String value) implements Token {} record BrTag(String value) implements Token {} - /** - * A Markdown code span start, like the start of {@code `foo`} or {@code ``bar``}. - * - * @param value the start backtick string, one or more backtick characters. - */ + /// A Markdown code span start, like the start of `` `foo` `` or ```` ``bar`` ````. + /// + /// @param value the start backtick string, one or more backtick characters. record MarkdownCodeSpanStart(String value) implements Token {} - /** - * A Markdown code span end, like the end of {@code `foo`} or {@code ``bar``}. - * - * @param value the end backtick string, one or more backtick characters (the same number as the - * corresponding start backtick string). - */ + /// A Markdown code span end, like the end of `` `foo` `` or ```` ``bar`` ````. + /// + /// @param value the end backtick string, one or more backtick characters (the same number as the + /// corresponding start backtick string). record MarkdownCodeSpanEnd(String value) implements Token {} - /** - * A fenced code block, like: - * - *
            -   * ```java
            -   * code block
            -   * with an info string ("java")
            -   * ```
            -   * 
            - * - * @param value the full text of the code block as it appeared in the input, including the start - * and end fences and the literal content. - * @param start the start fence, including the info string if any ({@code ```java} in the - * example). - * @param end the end fence. - * @param literal the text that the code block represents. This does not include the start and end - * fences, nor any indentation that precedes these fences and every intervening line. - */ + /// A fenced code block, like: + /// + /// ```` + /// ```java + /// code block + /// with an info string ("java") + /// ``` + /// ```` + /// + /// @param value the full text of the code block as it appeared in the input, including the start + /// and end fences and the literal content. + /// @param start the start fence, including the info string if any (```` ```java ```` in the + /// example). + /// @param end the end fence. + /// @param literal the text that the code block represents. This does not include the start and + /// end fences, nor any indentation that precedes these fences and every intervening line. record MarkdownFencedCodeBlock(String value, String start, String end, String literal) implements Token {} - /** - * A Markdown table, like: - * - * {@snippet : - * | foo | bar | - * | --- | --- | - * | baz | qux | - * } - * - * @param value the full text of the table as it appeared in the input, including the delimiters - * and the literal content. - */ + /// A Markdown table, like: + /// + /// ``` + /// | foo | bar | + /// | --- | --- | + /// | baz | qux | + /// ``` + /// + /// @param value the full text of the table as it appeared in the input, including the delimiters + /// and the literal content. record MarkdownTable(String value) implements Token {} - /** - * Whitespace that is not in a {@code
            } or {@code } section. Whitespace includes
            -   * leading newlines, asterisks, and tabs and spaces. In the output, it is translated to newlines
            -   * (with leading spaces and asterisks) or spaces.
            -   */
            +  /// Whitespace that is not in a `
            ` or `
            ` section. Whitespace includes leading + /// newlines, asterisks, and tabs and spaces. In the output, it is translated to newlines (with + /// leading spaces and asterisks) or spaces. record Whitespace(String value) implements Token {} - /** - * A newline in a {@code
            } or {@code 
            } section. We preserve user formatting in these - * sections, including newlines. - */ + /// A newline in a `
            ` or `
            ` section. We preserve user formatting in these sections, + /// including newlines. record ForcedNewline(String value) implements Token {} - /** A Markdown hard line break ({@code \} at the end of a line). */ + /// A Markdown hard line break (`\` at the end of a line). record MarkdownHardLineBreak(String value) implements Token {} - /** - * Token that permits but does not force a line break. The way that we accomplish this is somewhat - * indirect: As far as {@link JavadocWriter} is concerned, this token is meaningless. But its mere - * existence prevents {@link JavadocLexer} from joining two {@link Literal} tokens that would - * otherwise be adjacent. Since this token is not real whitespace, the writer may end up writing - * the literals together with no space between, just as if they'd been joined. However, if they - * don't fit together on the line, the writer will write the first one, start a new line, and - * write the second. Hence, the token acts as an optional line break. - */ + /// Token that permits but does not force a line break. The way that we accomplish this is + /// somewhat indirect: As far as [JavadocWriter] is concerned, this token is meaningless. But its + /// mere existence prevents [JavadocLexer] from joining two [Literal] tokens that would otherwise + /// be adjacent. Since this token is not real whitespace, the writer may end up writing the + /// literals together with no space between, just as if they'd been joined. However, if they don't + /// fit together on the line, the writer will write the first one, start a new line, and write the + /// second. Hence, the token acts as an optional line break. record OptionalLineBreak(String value) implements Token {} - /** - * Token representing a Markdown block quote marker ({@code >}). This token causes the - * corresponding text to be consumed, but does not itself lead to any output. - */ + /// Token representing a Markdown block quote marker (`>`). This token causes the corresponding + /// text to be consumed, but does not itself lead to any output. record BlockQuoteMarker(String value) implements Token {} - /** - * Anything else: {@code foo}, {@code }, {@code {@code foo}} etc. {@link JavadocLexer} - * sometimes creates adjacent literal tokens, which it then merges into a single, larger literal - * token before returning its output. - * - *

            This also includes whitespace in a {@code

            } or {@code 
            } section. We preserve - * user formatting in these sections, including arbitrary numbers of spaces. By treating such - * whitespace as a literal, we can merge it with adjacent literals, preventing us from - * autowrapping inside these sections -- and doing so naively, to boot. The wrapped line would - * have no indentation after "* " or, possibly worse, it might begin with an arbitrary amount of - * whitespace that didn't fit on the previous line. Of course, by doing this, we're potentially - * creating lines of more than 100 characters. But it seems fair to call in the humans to resolve - * such problems. - */ + /// Anything else: `foo`, ``, `{@code foo}` etc. [JavadocLexer] sometimes creates adjacent + /// literal tokens, which it then merges into a single, larger literal token before returning its + /// output. + /// + /// This also includes whitespace in a `
            ` or `
            ` section. We preserve user formatting + /// in these sections, including arbitrary numbers of spaces. By treating such whitespace as a + /// literal, we can merge it with adjacent literals, preventing us from autowrapping inside these + /// sections -- and doing so naively, to boot. The wrapped line would have no indentation after "* + /// " or, possibly worse, it might begin with an arbitrary amount of whitespace that didn't fit on + /// the previous line. Of course, by doing this, we're potentially creating lines of more than 100 + /// characters. But it seems fair to call in the humans to resolve such problems. record Literal(String value) implements Token {} } diff --git a/core/src/test/java/com/google/googlejavaformat/NewlinesTest.java b/core/src/test/java/com/google/googlejavaformat/NewlinesTest.java index e56191f37..113af445d 100644 --- a/core/src/test/java/com/google/googlejavaformat/NewlinesTest.java +++ b/core/src/test/java/com/google/googlejavaformat/NewlinesTest.java @@ -25,7 +25,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link Newlines}Test */ +/// [Newlines]Test @RunWith(JUnit4.class) public class NewlinesTest { @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/ArrayDimensionTest.java b/core/src/test/java/com/google/googlejavaformat/java/ArrayDimensionTest.java index 3da98347b..6552e3c9b 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ArrayDimensionTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ArrayDimensionTest.java @@ -25,10 +25,8 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -/** - * Tests for array dimension handling, especially mixed array notation and type annotations on - * dimensions. - */ +/// Tests for array dimension handling, especially mixed array notation and type annotations on +/// dimensions. @RunWith(Parameterized.class) public class ArrayDimensionTest { @Parameters diff --git a/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java b/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java index 928ce0078..115f356b2 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java @@ -21,7 +21,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for command-line flags. */ +/// Tests for command-line flags. @RunWith(JUnit4.class) public class CommandLineFlagsTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java index d28ee9f3c..51a4d7fac 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java @@ -30,7 +30,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link CommandLineOptionsParser}Test */ +/// [CommandLineOptionsParser]Test @RunWith(JUnit4.class) public class CommandLineOptionsParserTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java index 5f8c9cd26..d8009a87c 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -33,7 +33,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for error reporting. */ +/// Tests for error reporting. @RunWith(JUnit4.class) public class DiagnosticTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java index 7b3c3e889..bf09a17b1 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java @@ -42,7 +42,7 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -/** Integration test for google-java-format. */ +/// Integration test for google-java-format. @RunWith(Parameterized.class) public class FormatterIntegrationTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java index 29de05a37..9dbd59f3b 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java @@ -38,7 +38,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Integration test for google-java-format. */ +/// Integration test for google-java-format. @RunWith(JUnit4.class) public final class FormatterTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java index 461bd6793..ca589d161 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java @@ -24,7 +24,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for {@link GoogleJavaFormatToolProvider}. */ +/// Tests for [GoogleJavaFormatToolProvider]. @RunWith(JUnit4.class) public class GoogleJavaFormatToolProviderTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java index e3a7573a7..a6c4b3fdd 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java @@ -26,7 +26,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for {@link GoogleJavaFormatToolProvider}. */ +/// Tests for [GoogleJavaFormatToolProvider]. @RunWith(JUnit4.class) public class GoogleJavaFormatToolTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java index 6772b42be..d41677add 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java @@ -28,11 +28,11 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -/** Tests for {@link ImportOrderer}. */ +/// Tests for [ImportOrderer]. @RunWith(Enclosed.class) public class ImportOrdererTest { - /** Tests for import ordering in Google style. */ + /// Tests for import ordering in Google style. @RunWith(Parameterized.class) public static class GoogleStyle { @@ -573,7 +573,7 @@ public void reorder() throws FormatterException { } } - /** Tests for import ordering in AOSP style. */ + /// Tests for import ordering in AOSP style. @RunWith(Parameterized.class) public static class AospStyle { diff --git a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java index 1fc5d0b74..98185d283 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java @@ -24,17 +24,15 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests formatting javadoc. */ +/// Tests formatting javadoc. @RunWith(JUnit4.class) public final class JavadocFormattingTest { private static final boolean MARKDOWN_JAVADOC_SUPPORTED = Runtime.version().feature() >= 23; private final Formatter formatter = new Formatter(); - /** - * Tests that the formatter formats the given input string to the given expected string. Also - * tests that the formatter is idempotent when formatting an already formatted string. - */ + /// Tests that the formatter formats the given input string to the given expected string. Also + /// tests that the formatter is idempotent when formatting an already formatted string. private void doFormatTest(String input, String expected) { try { String actual = formatter.formatSource(input); diff --git a/core/src/test/java/com/google/googlejavaformat/java/LineRangesToCharRangesTest.java b/core/src/test/java/com/google/googlejavaformat/java/LineRangesToCharRangesTest.java index ca3ad7c7e..4daa4e3cd 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/LineRangesToCharRangesTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/LineRangesToCharRangesTest.java @@ -24,7 +24,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for {@link Formatter#lineRangesToCharRanges} */ +/// Tests for [Formatter#lineRangesToCharRanges] @RunWith(JUnit4.class) public class LineRangesToCharRangesTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java index 08c366f43..c87277175 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java @@ -42,7 +42,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for {@link Main}. */ +/// Tests for [Main]. @RunWith(JUnit4.class) public class MainTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/ModifierOrdererTest.java b/core/src/test/java/com/google/googlejavaformat/java/ModifierOrdererTest.java index df5c2ae62..94d96f21f 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ModifierOrdererTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ModifierOrdererTest.java @@ -27,7 +27,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link ModifierOrderer}Test */ +/// [ModifierOrderer]Test @RunWith(JUnit4.class) public class ModifierOrdererTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java index fb0baf690..ce69a947f 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java @@ -36,7 +36,7 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -/** Tests formatting parts of files. */ +/// Tests formatting parts of files. @RunWith(Parameterized.class) public final class PartialFormattingTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java index 9b2257a22..0d7587a97 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java @@ -21,7 +21,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests that unused import removal doesn't remove types used in case labels. */ +/// Tests that unused import removal doesn't remove types used in case labels. @RunWith(JUnit4.class) public class RemoveUnusedImportsCaseLabelsTest { @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java index f186b846e..affb0be6d 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java @@ -24,7 +24,7 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -/** {@link RemoveUnusedImports}Test */ +/// [RemoveUnusedImports]Test @RunWith(Parameterized.class) public class RemoveUnusedImportsTest { @Parameters(name = "{index}: {0}") diff --git a/core/src/test/java/com/google/googlejavaformat/java/ReplacementTest.java b/core/src/test/java/com/google/googlejavaformat/java/ReplacementTest.java index 6416f9c75..07192ae2d 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ReplacementTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ReplacementTest.java @@ -23,7 +23,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link Replacement}Test */ +/// [Replacement]Test @RunWith(JUnit4.class) public class ReplacementTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java index f763dd524..ef92c2fda 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java @@ -24,7 +24,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link SnippetFormatter}Test */ +/// [SnippetFormatter]Test @RunWith(JUnit4.class) public class SnippetFormatterTest { @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java index f13eec608..4ee700ac8 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java @@ -24,7 +24,7 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -/** {@link StringWrapper}IntegrationTest */ +/// [StringWrapper]IntegrationTest @RunWith(Parameterized.class) public class StringWrapperIntegrationTest { diff --git a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java index 302d4681b..abf719c04 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperTest.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link StringWrapper}Test */ +/// [StringWrapper]Test @RunWith(JUnit4.class) public class StringWrapperTest { @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java b/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java index 6d7e5666c..10a777bf5 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java @@ -23,7 +23,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** {@link TypeNameClassifier}Test */ +/// [TypeNameClassifier]Test @RunWith(JUnit4.class) public final class TypeNameClassifierTest { @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java index 5fa4f4217..0a9b4b99a 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java @@ -39,7 +39,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Tests for {@link com.google.googlejavaformat.java.filer.FormattingFiler}. */ +/// Tests for [FormattingFiler]. @RunWith(JUnit4.class) public class FormattingFilerTest {