Comments and doc comments
A comment is a note for the person who reads the code. The program runs the same way without it.
A doc comment, written with ///, describes a declaration for the people who call it.
Comments
A comment is a note for whoever reads the file next, and the program takes no notice of it.
There are three ways to write one. // and # each start a note that runs to the end of the line, so either can sit on a line of its own or follow code you want to explain. /* … */ covers any span, from the middle of one line to a whole paragraph. A note meant for the people who call your code gets a third slash instead: /// written above a class or a method is a doc comment, and your editor shows it to whoever types that name.
Good to know: #[ is not a comment. It opens an attribute, so a note that starts with a square bracket has to use //. And a block comment ends at the first */, which means one cannot hold another.
The three ways to write a note
<?nvs// A note for a reader. The program runs exactly as it would without it.// `//` and `#` both run to the end of the line. `/* */` covers any span.
# Either spelling works on a line of its own.string $city = 'Vienna'; // ... or after code, to explain that line.
/* A block comment is the one to reach for when the note is longer than a line, and it can stop in the middle of one. */echo 'Weather for ', $city, "\n";
echo /* even here, between two values */ 'sunny', "\n";
// The markers only count outside text. Inside a string they are characters// like any other.echo 'the // and the /* stay put', "\n";Weather for Viennasunnythe // and the /* stay putDocument a class for whoever calls it
<?nvs// Three slashes write a doc comment. It belongs to the declaration on the// line under it, and your editor shows it to whoever types that name.
/// One greeting, written the same way everywhere in the program.class Greeting{ /// Greets `$name` by name. /// The name is used as it arrives, so capitalise it before you pass it in. public static function forName(string $name): string { //// Four or more slashes make an ordinary comment. //// Your editor does not show it as documentation. return 'Hello, ' . $name . '!'; }}
echo Greeting::forName('Ada'), "\n";Hello, Ada!Say why a line is the way it is
<?nvs// Shows two common uses of a comment. One says why a line is written this way.// The other turns off a line for a while without deleting it.
array<int> $basketCents = [1299, 450, 9900];
int $total = 0;foreach ($basketCents as int $price) { $total = $total + $price;}
// Baskets of 100 euro or more ship for free.// The shipping contract sets this limit.int $shippingCents = 495;if ($total >= 10000) { $shippingCents = 0;}
// This line is turned off until finance checks the new rate.// $shippingCents = $shippingCents * 2;
echo 'Items: ', $total, "\n";echo 'Shipping: ', $shippingCents, "\n";echo 'Total: ', $total + $shippingCents, "\n";Items: 11649Shipping: 0Total: 11649Doc comments
A doc comment is a note for whoever uses your code. The compiler and the editor read it.
Write it with three slashes, ///, directly above a class, a constant, a property, a method or an enum case. Your editor shows it to whoever types that name, and nvs doc puts it on the page it builds.
A doc comment can contain five tags, each at the start of a line. @see names a class, a method, a property or a constant. It can also name a file in your project, such as docs/billing.md#refunds. @example names a file that shows the code in use. @param $name, @return and @throws Name describe a parameter, the return value and an error the method throws. Each needs a sentence after it. The compiler checks every tag, so a tag that names something that does not exist stops the build. Any other @tag is an error.
Good to know: a tag never contains a type, because the declaration already has it. A blank line between a /// comment and its declaration is an error. Four or more slashes start an ordinary comment.
Document a class and its members
<?nvs// Shows how to document a class. Three slashes write a doc comment, and it// belongs to the declaration on the line under it.
/// A price in cents. A whole number of cents never needs rounding.final class Price{ /// The lowest price a shop may set. public const int MIN = 0;
/// Doubles a price. /// Several `///` lines in a row make one doc comment. public static function double(int $cents): int { return $cents * 2; }}
// This prints 0.echo Price::MIN, "\n";
// This prints 250.echo Price::double(125), "\n";0250Document the cases of an enum
<?nvs// Shows how to document the cases of an enum. Each case carries its own doc// comment, which is where the meaning of a status belongs.
/// How far an order has got.enum Status{ /// The customer has ordered and has not paid yet. Pending, /// The money has arrived. Paid, /// The goods have left the building. Shipped,}
Status $order = Status::Paid;
// A case is a whole number, counted from the first case. This prints 1.echo $order as int, "\n";1Point at related code with see
<?nvs// Shows how a doc comment points at related code. `@see` names a class, a method// or a property, and the compiler checks that the name exists.
/// One customer invoice. Every amount in it is in cents.////// @see Invoice::totalfinal class Invoice{ /// The amount of each line of the invoice, in cents. public array<int> $lines;
/// Builds an invoice from its lines. public function constructor(array<int> $lines) { $this->lines = $lines; }
/// Adds up the lines and returns the total in cents. /// /// @see Invoice::$lines public function total(): int { int $sum = 0; foreach ($this->lines as int $line) { $sum = $sum + $line; } return $sum; }}
array<int> $lines = [1250, 399, 80];var $invoice = new Invoice($lines);
// This prints 1729.echo $invoice->total(), "\n";1729Describe parameters return and errors
<?nvs// Shows how to describe each parameter, the return value and the errors of a method.// The compiler checks that each tag matches the method under it.
final class CardDeclined extends RuntimeError{}
final class Payments{ /// Charges a card and returns the id of the charge. /// /// @param $cents the amount to charge, in cents /// @param $card the card number, written without spaces /// @return the id of the charge, such as `ch-1250` /// @throws CardDeclined when the amount is zero or less public static function charge(int $cents, string $card): string { if ($cents <= 0) { throw new CardDeclined('the amount must be more than zero'); } return 'ch-' . $cents; }}
// This prints `ch-1250`.echo Payments::charge(1250, '4242424242424242'), "\n";
// This throws `CardDeclined`, and the `catch` prints its message.try { Payments::charge(0, '4242424242424242');} catch (CardDeclined $e) { echo $e->message, "\n";}ch-1250the amount must be more than zeroA tag never repeats a type
<?nvs// Shows that a tag cannot contain a type, so this program does not compile.// The signature already gives the type of `$cents`.// proof: compile-error
/// A price in cents.final class Price{ /// Doubles a price. /// /// @param int $cents the price to double public static function double(int $cents): int { return $cents * 2; }}
echo Price::double(250), "\n";error[E0138]: `@param` cannot contain a type --> 05-a-tag-never-repeats-a-type.nvs:11:16 |11 | /// @param int $cents the price to double | ^^^^ the type is already in the signature = suggestion: delete this text before the `$name` (delete)
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Point at a document with see
<?nvs// Shows how a doc comment points at a file, or at one heading of a Markdown file.
/// Pays money back to a customer.////// @see notes/refunds.mdfinal class Refund{ // `#how-a-refund-is-calculated` names a heading of `notes/refunds.md`. // The compiler checks that the file has this heading. /// Adds up the returned lines and returns the refund in cents. /// /// @see notes/refunds.md#how-a-refund-is-calculated public static function amount(array<int> $lines): int { int $sum = 0; foreach ($lines as int $line) { $sum = $sum + $line; } return $sum; }}
array<int> $returned = [1250, 399];
// This prints 1649.echo Refund::amount($returned), "\n";1649Details
The body of a doc comment is Markdown. nvs meta --json includes it, nvs doc shows it on a page, and the editor shows it when you hover over the name.
A tag counts only at the start of a line. @see must name a class, method, property or constant that exists, or the program does not compile (E0323). @example must name a file under examples/ or tests/ (E0325). Any other tag, such as @since, does not compile (E0128). @returns is an error too, and the editor's quick fix rewrites it to @return.
@see can also name a file. When the text after @see contains / or ., it is a file, such as @see notes/refunds.md. The path starts at the folder of the file that contains the comment. The file must exist, and it must be inside your project. The project is the folder of the file, or the nearest folder above it, that has an nvs.toml or a package.toml file. An absolute path, or a .. that leaves the project, does not compile (E0323).
After a Markdown file, # and a heading name one heading: @see notes/refunds.md#who-can-get-a-refund. The part after # is the heading text in lowercase. Each space is written as -, and other punctuation is removed. Only a .md or .markdown file takes a heading. If the heading is not in the file, the error suggests the most similar heading. The editor opens the file at that heading when you click the path. A package must list in [package] files every file that a @see or @example names. If one is missing, nvs pkg pack stops with an error.
@param, @return and @throws need a sentence after them (E0139). The sentence runs to the end of the line. The next /// line continues it, unless that line is blank or starts with a tag. A continuation line that starts with - is a list item. Use it to describe each key of a parameter whose type lists named keys. The editor and nvs doc show the list under that parameter. The compiler checks each tag against the method under it:
@param $name:$nameis a parameter of this method (E0335). Only one@paramdescribes it (E0331). Write$namewithout a type (E0138).@return: the method returns a value. Avoidornevermethod and a constructor take no@return(E0333).@throws Name:Nameis a class that extendsThrowable(E0334). The compiler findsNamethe same way it finds a type name, souselines apply.
A tag must not start its sentence with a type. @param $x int the count does not compile (E0332), because the method already declares the type. @param, @return and @throws go only on a function, a method or a constructor (E0333). The tags may be in any order. nvs doc and the editor show the parameters in the order of the signature.
You do not have to describe every parameter. If the comment has an @param for some parameters but not for all, the compiler prints the warning W1030. Its fix adds an empty @param line for the missing parameter.
A /// comment must be directly above a class, a constant, a property, a method or an enum case. If it is above a statement, above a blank line or at the end of the file, the program does not compile (E0127). Write // for a note to the reader.
/** … */ is an ordinary comment. Directly above a declaration it documents nothing, and the compiler prints the warning W1011. A line of four or more slashes is an ordinary comment too.
Do and don’t
Section titled “Do and don’t”- Do write
///above each public class and method. - Do write
@param $namewith a sentence when a parameter needs one. Don’t write its type there. - Do write
//for a short note inside a function. - Don’t write
/** ... */above a declaration. Write///instead. - Don’t leave an empty line between a
///comment and its declaration. That does not compile.
