Comment syntax
The limits of my language mean the limits of my world.
— Ludwig Wittgenstein, Tractatus Logico-Philosophicus
A doc comment looks like prose, but it’s a small language with a grammar of its own. Scaladoc defined most of it: the * border, the @ tags, a wiki markup with ''italic'' and [[links]]. Over the years, comments picked up some HTML and a few habits from javadoc along the way, and real codebases contain all of it, often in the same comment.
The parser reads all of it, and this page walks through what it understands, from the outside in: first the comment as a whole, then its tags, then the markup inside them. Every example on this page is compiled and run when the site is built, so what you see after each snippet is what the parser really returns.
The comment
A doc comment starts with /** and ends with */. In between, each line usually starts with a * border: aligned under the second * of the opening marker in scaladoc’s style, under the first in javadoc’s. The border and one space after it belong to the comment’s frame, not to its text:
parse(
"""/** A comment in scaladoc's style,
| * the border under the second star.
| */""".stripMargin)
// res0: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(
// value = """A comment in scaladoc's style,
// the border under the second star."""
// )
// )
// )
// )
// )
parse(
"""/**
| * And one in javadoc's style.
| */""".stripMargin)
// res1: Markup = Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "And one in javadoc's style.")))
// )
// )
The border is optional, as it is for scaladoc. A line without one is text from its first character on:
parse(
"""/** No borders here,
| just text.
| */""".stripMargin)
// res2: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(
// value = """No borders here,
// just text."""
// )
// )
// )
// )
// )
Trailing whitespace and blank lines at the start and the end of a comment are dropped. What remains is text, and the text is always made of blocks: here, a single paragraph.
Tags
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
— Andy Hunt and Dave Thomas, The Pragmatic Programmer
A tag starts a line with @ and its name. Everything up to the next tag is its text, and the text before the first tag is the description. An @ in the middle of a line, as in an e-mail address or @tailrec, is just a character:
Scaladoc.fromString(
"""/** Sends mail to support@example.com, see `@tailrec`.
| *
| * @param to who gets it
| * @param body what it says,
| * over two lines
| * @throws java.io.IOException if the server is down
| * @return the message id
| */""".stripMargin).map(_.tags.map(_.productPrefix))
// res3: Either[ScaladocException, List[String]] = Right(
// value = List("Description", "Param", "Param", "Throws", "Returns")
// )
These are the tags the model knows by name. Any other one, like @contentDiagram, comes back as an OtherTag with its name and text.
| Tag | Model | Text |
|---|---|---|
| the text before the first tag | Description |
markup |
@constructor |
Constructor |
markup |
@param name |
Param(name, ...) |
markup |
@tparam name |
TypeParam(name, ...) |
markup |
@return (or @returns) |
Returns |
markup |
@throws type |
Throws(type, ...) |
markup |
@see, @note, @example |
See, Note, Example |
markup |
@usecase |
UseCase |
markup |
@todo, @deprecated, @migration |
Todo, Deprecated, Migration |
markup |
@author, @version, @since |
Author, Version, Since |
plain text |
@group id |
Group(id) |
none |
@groupname id |
GroupName(id, ...) |
plain text |
@groupdesc id |
GroupDescription(id, ...) |
markup |
@groupprio id n |
GroupPriority(id, n) |
a number |
@documentable, @inheritdoc |
Documentable, InheritDoc |
none |
| anything else | OtherTag(name, ...) |
markup |
A tag without text is dropped, since it says nothing, with two exceptions that scaladoc makes as well: @deprecated deprecates even without a reason, and @throws IOException names an exception even without saying when.
Inline markup
Inside a paragraph, a few markers change how text looks. They are scaladoc’s wiki markup:
| Markup | Model |
|---|---|
`code` |
Monospace |
''italic'' |
Italic |
'''bold''' |
Bold |
__underline__ |
Underline |
^super^ |
Superscript |
,,sub,, |
Subscript |
[[link]] |
Link |
Markup nests, so bold text can contain italic and links, and so on all the way down. The text of a monospace span is taken literally, which is what you want from code:
parse("/** '''Bold, with ''italic'' and [[scala.Option]] inside''', and `code with ''quotes''`. */")
// res4: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// Bold(
// spans = List(
// PlainText(value = "Bold, with "),
// Italic(spans = List(PlainText(value = "italic"))),
// PlainText(value = " and "),
// Link(target = "scala.Option", title = List()),
// PlainText(value = " inside")
// )
// ),
// PlainText(value = ", and "),
// Monospace(value = "code with ''quotes''"),
// PlainText(value = ".")
// )
// )
// )
// )
Be conservative in what you do, be liberal in what you accept from others.
— Jon Postel, RFC 761
Comments are written by people, and people write x^2 and forget a backtick. A marker that isn’t closed within its paragraph is therefore plain text, not an error that loses the whole comment:
parse("/** The cost grows like n^2, and `this backtick never closes. */")
// res5: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(
// value = "The cost grows like n^2, and `this backtick never closes."
// )
// )
// )
// )
// )
Links
A link holds a target and, optionally, a title. The target runs to the first whitespace and the rest is the title, which can have markup of its own. The target is either an entity, like a class or a member, or a URL:
parse("/** See [[scala.Option]] and [[https://docs.scala-lang.org the ''Scala'' docs]]. */")
// res6: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(value = "See "),
// Link(target = "scala.Option", title = List()),
// PlainText(value = " and "),
// Link(
// target = "https://docs.scala-lang.org",
// title = List(
// PlainText(value = "the "),
// Italic(spans = List(PlainText(value = "Scala"))),
// PlainText(value = " docs")
// )
// ),
// PlainText(value = ".")
// )
// )
// )
// )
Member signatures can contain ]] themselves. A link opened with more brackets closes with as many, which keeps such a target in one piece:
parse("/** Overloads are told apart like [[[baz(x:List[List[A]])*]]]. */")
// res7: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(value = "Overloads are told apart like "),
// Link(target = "baz(x:List[List[A]])*", title = List()),
// PlainText(value = ".")
// )
// )
// )
// )
Link.isUrl tells the two kinds of target apart.
Paragraphs and headings
A blank line ends a paragraph. A heading is a line of its own, wrapped in as many = on each side as its level, from one to six:
parse(
"""/** = The `App` trait =
| *
| * First paragraph,
| * still the first.
| *
| * == Caveats ==
| * Second paragraph.
| */""".stripMargin)
// res8: Markup = Document(
// elements = List(
// Heading(
// level = One,
// spans = List(
// PlainText(value = "The "),
// Monospace(value = "App"),
// PlainText(value = " trait")
// )
// ),
// Paragraph(
// markup = List(
// PlainText(
// value = """First paragraph,
// still the first."""
// )
// )
// ),
// Heading(level = Two, spans = List(PlainText(value = "Caveats"))),
// Paragraph(markup = List(PlainText(value = "Second paragraph.")))
// )
// )
A heading doesn’t need a blank line before or after it, and its title can have markup too.
Code blocks
Code goes between {{{ and }}}. A code block can span blank lines, and loses the indentation that all of its lines share, so the code reads the same however deeply the comment is nested:
parse(
"""/** For example:
| * {{{
| * val x = 1
| *
| * if (x > 0)
| * println(x)
| * }}}
| */""".stripMargin)
// res9: Markup = Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "For example:"))),
// CodeBlock(
// value = """val x = 1
//
// if (x > 0)
// println(x)"""
// )
// )
// )
Nothing inside a code block is a tag, so an example can show @main or @tailrec without the parser mistaking them for the start of a @main tag.
Lists
The list is the origin of culture.
— Umberto Eco
A list item is an indented line that starts with - for a bullet, or with 1., i., I., a. or A. for the numbering styles. The indentation matters twice. Without it, a line that starts with - is just text. And more of it nests a list under the item before it:
parse(
"""/** Steps:
| *
| * 1. Clone the repository
| * 1. Build it
| * - on the JVM
| * - on Scala.js
| * 1. Run the tests
| */""".stripMargin)
// res10: Markup = Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "Steps:"))),
// OrderedList(
// items = List(
// Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "Clone the repository")))
// )
// ),
// Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "Build it"))),
// UnorderedList(
// items = List(
// Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "on the JVM")))
// )
// ),
// Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "on Scala.js")))
// )
// )
// )
// )
// )
// ),
// Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "Run the tests")))
// )
// )
// ),
// style = Decimal
// )
// )
// )
Each item is a document of its own, holding the item’s text and the lists nested under it. An item’s text continues on the lines that follow, until the next item, a blank line or the end of the list. A blank line between items doesn’t end the list. A different numbering style at the same indentation starts a new list.
Tables
Tables use pipes, a header row, and a delimiter row that sets each column’s alignment with ::
parse(
"""/** Sizes:
| *
| * | Size | Price | Notes |
| * |:-----|------:|:----------:|
| * | S | 10 | ''cheap'' |
| * | M | 15 |
| */""".stripMargin)
// res11: Markup = Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "Sizes:"))),
// Table(
// header = Row(
// cells = List(
// Paragraph(markup = List(PlainText(value = "Size"))),
// Paragraph(markup = List(PlainText(value = "Price"))),
// Paragraph(markup = List(PlainText(value = "Notes")))
// )
// ),
// alignments = List(Left, Right, Center),
// rows = List(
// Row(
// cells = List(
// Paragraph(markup = List(PlainText(value = "S"))),
// Paragraph(markup = List(PlainText(value = "10"))),
// Paragraph(
// markup = List(Italic(spans = List(PlainText(value = "cheap"))))
// )
// )
// ),
// Row(
// cells = List(
// Paragraph(markup = List(PlainText(value = "M"))),
// Paragraph(markup = List(PlainText(value = "15"))),
// Paragraph(markup = List())
// )
// )
// )
// )
// )
// )
Cells hold inline markup, and \| is a pipe inside a cell. Rows are padded or cut to the width of the header. Lines without a valid delimiter row aren’t a table at all, and stay text.
Horizontal rules
Four or more dashes on a line of their own make a rule:
parse("/** Above.\n *\n * ----\n *\n * Below.\n */")
// res12: Markup = Document(
// elements = List(
// Paragraph(markup = List(PlainText(value = "Above."))),
// HorizontalRule,
// Paragraph(markup = List(PlainText(value = "Below.")))
// )
// )
As in scaladoc, a rule starts a block, but doesn’t interrupt a paragraph: ---- right under a line of text is text.
HTML
Doc comments have always had HTML in them, often from the days when they were written for javadoc. The parser turns it into the same model as the wiki markup, wherever the model has an equivalent:
<p>and<div>break paragraphs,<h1>to<h6>are headings,<li>are list items,<pre>is a code block<b>and<strong>are bold,<i>and<em>italic,<u>underlined,<sup>and<sub>raised and lowered<code>and<tt>are monospace,<a href="...">is a link,<br>is a line break- entities like
<,<and are the characters they stand for
parse("/** <p>Returns a <code>List<A></code> of <b>all</b> the <a href=\"https://example.com\">items</a>.</p> */")
// res13: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(value = "Returns a "),
// Monospace(value = "List<A>"),
// PlainText(value = " of "),
// Bold(spans = List(PlainText(value = "all"))),
// PlainText(value = " the "),
// Link(
// target = "https://example.com",
// title = List(PlainText(value = "items"))
// ),
// PlainText(value = ".")
// )
// )
// )
// )
Other tags that scaladoc keeps, like <span> or <table>, come back as HtmlTag spans with the tag as written. A < that isn’t a tag at all, as in List<String>, is text. HTML inside {{{ code blocks stays as it is.
Javadoc’s inline tags
Javadoc’s inline tags are understood too:
| Tag | Model |
|---|---|
{@code x} |
Monospace |
{@value x} |
Monospace |
{@link X}, {@link X label} |
Link, with the label as its title |
{@linkplain X}, {@linkplain X label} |
Link, with the label as its title |
{@literal x} |
text |
{@docRoot} |
nothing |
parse("/** Wraps a {@link java.util.Map} of {@code Map<K, {V}>}, see {@linkplain Foo#bar the bar}. */")
// res14: Markup = Document(
// elements = List(
// Paragraph(
// markup = List(
// PlainText(value = "Wraps a "),
// Link(target = "java.util.Map", title = List()),
// PlainText(value = " of "),
// Monospace(value = "Map<K, {V}>"),
// PlainText(value = ", see "),
// Link(target = "Foo#bar", title = List(PlainText(value = "the bar"))),
// PlainText(value = ".")
// )
// )
// )
// )
Braces inside a tag must balance, which is what lets {@code Map<K, {V}>} hold braces of its own.
Macros
I have made this longer than usual because I have not had time to make it shorter.
— Blaise Pascal, Lettres provinciales
When a phrase repeats across a comment, @define gives it a name. $name or ${name} then stands for it anywhere in the comment, and \$ is a plain dollar sign:
Scaladoc.fromString(
"""/** Adds an element to the $coll.
| *
| * @define coll immutable list
| * @param x the element to add to the $coll
| */""".stripMargin).map(doc => (doc.textDescriptions, doc.textParams))
// res15: Either[ScaladocException, (Seq[String], Map[String, String])] = Right(
// value = (
// List("Adds an element to the immutable list."),
// Map("x" -> "the element to add to the immutable list")
// )
// )
A define runs up to the next tag, can use other defines, and doesn’t show up in the parsed comment. Scaladoc also lets a comment use the defines of its enclosing and parent classes. Only the compiler knows those classes, though, so here a comment can use its own defines only, and an unknown variable stays as written.
How this differs from scaladoc
Scaladoc renders comments to HTML, and this parser turns them into a model for other tools to use. A few choices follow from that difference, and a few from fixing what scaladoc leaves to warnings:
- Monospace is literal. Scaladoc parses markup inside backticks; here the text of code stays as written.
- Unclosed markers are text. Scaladoc runs an unclosed
''to the end of the paragraph. - Bold inside italic works. In
''a '''b''' c'', scaladoc ends the italic at the'''; here the bold nests. - Broken tables aren’t tables. Without a valid delimiter row, scaladoc repairs the table and warns; here the lines stay text, which is what GitHub does and what scaladoc’s own source says it should do.
- HTML becomes the model. Scaladoc passes
<b>on as HTML; here it’sBold, and HTML in code blocks is left alone. {@literal}is text, as in javadoc. Scaladoc shows it as code.@definesees only its own comment, as described above.