18.1 Check, format and fix
Page 2 of 11
18.1.1 What a tool is
Every chapter so far has used una the same way: you type a line such as una check . in a terminal, and una answers. A command is one such line, as chapter 1 showed: the name of a program, una, then words that tell it what to do. Those words are the command's arguments:
- The first word after
una, such ascheck,runortest, picks one of una's jobs. Each job is a subcommand; this chapter calls them commands too, as in "the commanduna check". - A word that starts with
--, such as--jsonor--dry-run, is a flag: a switch that changes how the command works. Some flags take a value, as--tier 0does. - The last word,
., is the path of the package to work on..means "the directory I am in". A few commands take a name instead of a path, such asuna explain U2004, which takes a diagnostic's code.
Together, the commands of una are its tools. Like the saw, the plane and the square on a carpenter's bench, each does one job around your code.
When a command finishes, it leaves two things besides the text you read:
- Two output streams. A program prints to two places that the terminal shows together. stdout, the standard output, carries the result you asked for: what the program prints, a report, a listing. stderr, the standard error, carries messages about problems, such as diagnostics. A script can keep the two apart, and save the result to a file while the problems show on the screen.
- An exit code. A number that the terminal does not print and that says how the command went: 0 when it succeeded, another number when it did not (section 18.5 lists them).
18.1.2 The commands of una
This chapter covers every command this book uses, in the order you use them:
| Command | What it does | Section |
|---|---|---|
una --version |
Prints the version, the editions and the Z3 version | chapter 1 |
una check . |
Looks for mistakes, without running anything | 18.1 |
una fmt . |
Rewrites the code in canonical form | 18.1 |
una fix . |
Applies the exact repairs, then formats | 18.1 |
una explain U1001 |
Explains a diagnostic's code | 18.2 |
una obligations . |
Lists every fact the verifier had to prove | 18.3 |
una contract NAME |
Prints a function's full header | 18.3 |
una trace NAME |
Follows a requirement to the code | 18.3 |
una report . |
Prints the build report | 18.4 |
una run . |
Checks, then runs main |
18.5 |
una test . |
Checks, then runs every example | 18.5 |
una build . |
Checks, then builds an executable | 18.5 |
una lsp |
Serves an editor | 18.1 |
Each example of this chapter is a package, made as chapter 2 explains, and the chapter's download, 18-tools.tar.gz, holds them all. Run every command in the package's directory.
18.1.3 Why you check before you run
A mistake in a program is normal: everyone makes them while writing code. What matters is when you find out.
Here is a receipt line written by someone used to another language. It has two habits from there: an = at the end of the header, which is how some languages open a body, and a second argument without its label. An argument's label is the name: before it in a call (chapter 6), not the security label of chapter 17.
module receipt
--- One line of a receipt: the units, the SKU and the line's total in cents.
line_text(units: Int, sku: Text, cents: Int) -> Text =
"{units} x {sku} {cents}"
pub main() -> Unit
uses @console: Console[print]
=
@console.print(line_text(2, "LAMP-01", cents: 3980))In many languages you would learn about such mistakes only when the program runs, or never, if no test reaches the line. una reads the whole package without running anything, and reports what is wrong first:
una check .[U0101] Error: unexpected end of line, expected an expression
╭─[ src/receipt.una:4:55 ]
│
4 │ line_text(units: Int, sku: Text, cents: Int) -> Text =
│ ┬
│ ╰── unexpected end of line, expected an expression
│
│ Help: repair 1: put `=` on a line of its own: a function whose body is a block has the long form, the header, `=`, then the indented body; edit src/receipt.una:4:1..5:1 to "line_text(units: Int, sku: Text, cents: Int) -> Text\n=\n"
│
│ Note: run `una explain U0101` for an explanation
───╯
1 of 1 diagnostics have an edit that `una fix` applies (`una fix --dry-run` lists them)The checker reports one problem, a syntax error: text that breaks the grammar of the language, the rules for how words and symbols may follow each other. Here it is U0101, a line that ends where an expression was expected. Before anything else, una parses each file: it works out which part of the text is a header, a body or a call. A file that does not parse cannot be checked further, so the missing label is not reported yet. The Help line holds a repair with an exact edit, and the last line counts the diagnostics that una fix can repair for you. The rest of this section shows the three commands of this loop: una check finds the problems, una fmt lays the code out, and una fix applies the exact repairs.
18.1.4 How to write the check loop
Commands that work on a package take its path, ., last; una trace, una contract and una explain take a name instead. Flags go between the command's name and the path. Two flags, --json and --color, are global: they work with every command but una lsp, which speaks an editor's protocol instead, and may go anywhere on the line, and this book writes them right after una.
18.1.4.1 una check .
una check . checks the package and changes nothing. It checks in tiers, two passes of increasing cost:
- Tier 0 checks the syntax, the names, the types, the capabilities and the information-flow labels (chapter 17), and that every file is in canonical form. It needs no solver and answers quickly.
- Tier 1 adds the verifier (chapter 5), which proves the contracts, refinements and divisions with Z3, a solver: a program that searches for values that break a fact, and proves the fact when there are none. It runs only when tier 0 reports nothing.
When the package is right, una check . prints nothing and exits with code 0. Fix the label by hand, put the body on the header's line, and that is what happens: the package of the next step checks clean. The same answer for a program is one JSON document with an empty list:
una --json check .$ una --json check .
{"schema":"una.diagnostics/1","diagnostics":[],"fixable":0}JSON is a plain text format for data that programs exchange: { and } hold named values, each a key in quotes, a : and its value, and [ and ] hold a list. schema names the shape of the document, diagnostics is the list of problems, empty here, and fixable counts the problems una fix could repair. Section 18.2 reads a full diagnostic.
18.1.4.2 una check --tier 0 .
--tier 0 stops after tier 0 and skips the solver, so it answers in a moment, as you want while you type. It does not prove anything: a promise the code breaks, such as the one of section 18.2, passes una check --tier 0 . and fails una check .. Run the full check before you consider a change done.
18.1.4.3 una fmt . and una fmt --check .
Canonical form is the one layout Una accepts for any code: indentation, spaces, line breaks and the order of a few parts. Since all Una code has one layout, no review ever argues about it. una fmt . rewrites every file of the package into it. una fmt --check . writes nothing and reports each place that differs, as the diagnostic U7001. una check . reports U7001 too, so a file out of canonical form never passes the check.
This step has the right label, but the body of a one-line function sits on its own line. The change from the previous step is shown as a diff: a line that starts with - was removed, a line with + was added, and the rest is unchanged context:
--- a/src/receipt.una
+++ b/src/receipt.una
@@ -1,7 +1,9 @@
module receipt
--- One line of a receipt: the units, the SKU and the line's total in cents.
-line_text(units: Int, sku: Text, cents: Int) -> Text = "{units} x {sku} {cents}"
+line_text(units: Int, sku: Text, cents: Int) -> Text
+=
+ "{units} x {sku} {cents}"
pub main() -> Unit
uses @console: Console[print][U7001] Error: lines 4 to 6 are not in canonical form
╭─[ src/receipt.una:4:1 ]
│
4 │ ╭─▶ line_text(units: Int, sku: Text, cents: Int) -> Text
┆ ┆
6 │ ├─▶ "{units} x {sku} {cents}"
│ │
│ ╰────────────────────────────────── lines 4 to 6 are not in canonical form
│
│ Help: repair 1: rewrite in canonical form, as `una fmt` does; edit src/receipt.una:4:1..7:1 to "line_text(units: Int, sku: Text, cents: Int) -> Text = \"{units} x {sku} {cents}\"\n"
│
│ Note: run `una explain U7001` for an explanation
───╯
1 of 1 diagnostics have an edit that `una fix` applies (`una fix --dry-run` lists them)The arrows on the left mark lines 4 to 6, out of form. The Help line is the edit una fmt . makes: a function with no clauses (no uses, requires, ensures or fails) whose body is one plain line (no when, no if with blocks, no with or handling clause) ends on the header line, after =. main, which has a uses clause, keeps the long form. The ┆ in the margin stands for a line the excerpt leaves out.
Spaces matter too: spaces inside the parentheses of a call are out of canonical form:
--- a/src/hello.una
+++ b/src/hello.una
@@ -4,4 +4,4 @@
pub main() -> Unit
uses @console: Console[print]
=
- @console.print("The store is open")
+ @console.print( "The store is open" )[U7001] Error: line 7 is not in canonical form
│ Help: repair 1: rewrite in canonical form, as `una fmt` does; edit src/hello.una:7:1..8:1 to " @console.print(\"The store is open\")\n"The Help line holds the line as canonical form writes it, and una fmt . makes that edit.
18.1.4.4 una fix --dry-run . and una fix .
una fix . applies the exact repairs that the diagnostics carry, then formats every file, then checks the package once more. una fix --dry-run . shows what una fix . would change, and writes nothing. On the receipt line of the first step:
una fix --dry-run .$ una fix --dry-run .
fixed src/receipt.una:4:1 U0101 put `=` on a line of its own: a function whose body is a block has the long form, the header, `=`, then the indented body
fixed src/receipt.una:11:31 U2004 label it `sku`Each line is one repair: the word fixed, the place, the code and what the repair does. The second repair is the missing label, which una check . had not reported yet: after the first repair, the file parses, and the next round finds it. Running una fix . gives the package that the next step holds:
--- a/src/receipt.una
+++ b/src/receipt.una
@@ -1,10 +1,9 @@
module receipt
--- One line of a receipt: the units, the SKU and the line's total in cents.
-line_text(units: Int, sku: Text, cents: Int) -> Text =
- "{units} x {sku} {cents}"
+line_text(units: Int, sku: Text, cents: Int) -> Text = "{units} x {sku} {cents}"
pub main() -> Unit
uses @console: Console[print]
=
- @console.print(line_text(2, "LAMP-01", cents: 3980))
+ @console.print(line_text(2, sku: "LAMP-01", cents: 3980))2 x LAMP-01 398018.1.4.5 --json and --color
The two global flags of How to write the check loop:
una --json check .prints one JSON document on stdout instead of the text for people, and nothing on stderr, except a usage error (exit code 2) or an internal error (exit code 3).una --color never check .prints without colors, as the outputs of this book are.auto, the default, uses colors when the output goes to a terminal, andalwaysuses them everywhere.
18.1.5 Habits from other languages
People who come to Una from other languages bring their habits, and the checker knows the common ones. When a syntax error has the shape of another language's form, the first repair names Una's form, and carries an exact edit when the rewrite is certain. Two more habits, in one function each: an if with then whose else is on the next line, and a name that starts with _, which some languages use for "unused":
module receipt
--- The total of a line in cents.
line_cents(units: Int, unit_cents: Int) -> Int = units * unit_cents
--- A label for a line: "bulk" from 10 units on.
size_label(units: Int) -> Text
=
if units >= 10 then "bulk"
else "single"
pub main() -> Unit
uses @console: Console[print]
=
let _total = line_cents(2, unit_cents: 1990)
@console.print("{size_label(2)} {_total}")[U0101] Error: unexpected end of line, expected `else`
╭─[ src/receipt.una:9:29 ]
│
9 │ if units >= 10 then "bulk"
│ ┬
│ ╰── unexpected end of line, expected `else`
│
│ Help 1: repair 1: write the `if` with blocks: `if` and its condition, the indented branch, `else`, then the indented branch; edit src/receipt.una:9:1..11:1 to " if units >= 10\n \"bulk\"\n else\n \"single\"\n"
│
│ Help 2: repair 2: an `if` with `then` needs `else`; to fail early, make the rest of the body its `else` branch, as in `if x < 0 then fail Broke else x`, or use the block form, whose `else` block holds the rest
│
│ Note: run `una explain U0101` for an explanation
───╯
[U0001] Error: invalid character `_`; names start with a letter
╭─[ src/receipt.una:15:7 ]
│
15 │ let _total = line_cents(2, unit_cents: 1990)
│ ┬
│ ╰── invalid character `_`; names start with a letter
│
│ Help: repair 1: rename `_total` to `total2` in its declaration: a name starts with a letter; edit src/receipt.una:15:7..16:42 to "total2 = line_cents(2, unit_cents: 1990)\n @console.print(\"{size_label(2)} {total2"
│
│ Note: run `una explain U0001` for an explanation
────╯
[U0001] Error: invalid character `_`; names start with a letter
╭─[ src/receipt.una:16:36 ]
│
16 │ @console.print("{size_label(2)} {_total}")
│ ┬
│ ╰── invalid character `_`; names start with a letter
│
│ Help: repair 1: rename `_total` to `total2` in its declaration: a name starts with a letter; edit src/receipt.una:15:7..16:42 to "total2 = line_cents(2, unit_cents: 1990)\n @console.print(\"{size_label(2)} {total2"
│
│ Note: run `una explain U0001` for an explanation
────╯
3 of 3 diagnostics have an edit that `una fix` applies (`una fix --dry-run` lists them)Read each one by its first line:
- U0101 at 9:29. An
ifwiththenon one line must end with itselseon that line. The repair rewrites theifin the block form: the condition, the indented branch,else, the indented branch. - U0001 at 15:7 and 16:36. A name starts with a letter. Both diagnostics carry the same repair, which renames the binding and every use of it to
total2, a name used nowhere else in the function.
Neither is reported as a warning to ignore: Una has one syntax, and the other form is an error. una fix --dry-run . lists the two repairs it would apply, one per edit; the rename counts once, since both diagnostics carry the same edit:
$ una fix --dry-run .
fixed src/receipt.una:9:1 U0101 write the `if` with blocks: `if` and its condition, the indented branch, `else`, then the indented branch
fixed src/receipt.una:15:7 U0001 rename `_total` to `total2` in its declaration: a name starts with a lettertotal2 is correct, but not the name you would choose. una fix cannot know the meaning of a name, so read the result, and rename by hand when a better name exists.
18.1.6 How the check loop behaves
18.1.6.1 What one check reports
- Every problem in one pass.
una check .reports all the problems it finds, not only the first: the receipt of Habits from other languages gave three at once (section 18.2 shows more). - Except after a syntax error. A file that does not parse is not checked for names, types or proofs, so its other problems appear once it parses, as the missing label of the first step did.
- In a fixed order. Diagnostics are sorted by file, then position, then code. The same package gives the same output on every run and every machine.
18.1.6.2 How una fix works
una fix . works in rounds. Each round checks the package, takes the first repair of each diagnostic when that repair has an exact edit, and applies the edits that do not overlap. The next round checks again, which is how the first step's label was found after the syntax repair. Each fixed line gives its place in the file as that round left it, so the label's line moved from 10 to 11. The rounds stop when one finds nothing more to apply, when the text comes back to an earlier state, or after 16 rounds. Then una fix . formats every file that parses, writes each changed file once, and checks the package a last time. The format step prints no fixed line: only the repairs of the rounds get one. What it could not repair stays, and it reports those diagnostics on stderr, as una check . would.
18.1.7 What una fix applies, and what it leaves to you
What una fix applies is narrow on purpose:
una fix applies |
una fix leaves to you |
|---|---|
| The first repair of a diagnostic, when it carries an exact edit | A repair without an edit, such as a guard for a refuted proof |
| Edits to the package's modules | Any change to una.toml or verification.lock |
| Edits that keep what the code may do | An edit that adds a uses, makes a declaration pub or adds a grant |
| Formatting of every file that parses | A repair marked as an escape, such as checked, which gives up a proof (Repairs that cost a guarantee) |
The right column holds every change that needs a decision: what a function is meant to compute, what the program may do, what it trusts. una fix --dry-run . names each repair with an edit that it skips, and why: A capability that is not there, in Common mistakes, shows it for a repair that would widen what a function may do.
18.1.8 In an editor: una lsp
An editor is the program where you write code. Many editors can show the problems of a file as you type, through a language server: a program that runs beside the editor and answers its questions about the code, in a standard form called the Language Server Protocol.
una lsp is Una's language server. You do not run it yourself: you set your editor to start it, and the editor talks to it over stdout and stdin, the standard input, the stream a program reads from. As you type, it shows the tier 0 diagnostics of una check; when you open or save a file, it also runs the proofs. Above each function it shows how many of its obligations are proven (a code lens). It offers the repairs with exact edits as quick fixes, one click each, and formats a file. It also shows what a name is when you hold the pointer over it, and where it is declared. It checks and proves, and it never runs a program.
18.1.9 Check, format or fix
Which to use:
| You want to… | Use |
|---|---|
| A quick answer while you type, without proofs | una check --tier 0 ., or an editor with una lsp |
| The full answer, proofs included, before you call a change done | una check . |
| The layout fixed, and nothing else | una fmt . |
| To know whether the layout is right, without changing files | una fmt --check . |
| To see the exact repairs before anything changes | una fix --dry-run . |
| To apply them, then format | una fix . |
18.1.10 Check yourself: the check loop
Start from the clean receipt of the second step, and make two changes at once: the body of line_text goes back on its own line, and the call loses its label again.
--- a/src/receipt.una
+++ b/src/receipt.una
@@ -1,9 +1,11 @@
module receipt
--- One line of a receipt: the units, the SKU and the line's total in cents.
-line_text(units: Int, sku: Text, cents: Int) -> Text = "{units} x {sku} {cents}"
+line_text(units: Int, sku: Text, cents: Int) -> Text
+=
+ "{units} x {sku} {cents}"
pub main() -> Unit
uses @console: Console[print]
=
- @console.print(line_text(2, sku: "LAMP-01", cents: 3980))
+ @console.print(line_text(2, "LAMP-01", cents: 3980))How many diagnostics does una check . report? And what does una fix --dry-run . print?
Show the answer
una check . reports two: U7001 for the layout and U2004 for the label. Both carry an exact edit, so the JSON document counts both as fixable:
$ una --json check .
{"schema":"una.diagnostics/1","diagnostics":[{"schema":"una.diagnostic/1","code":"U7001","severity":"error","domain":"project","message":"lines 4 to 6 are not in canonical form","primary":{"file":"src/receipt.una","start":{"line":4,"col":1},"end":{"line":6,"col":29}},"related":[],"repairs":[{"rank":1,"escape_cost":0,"description":"rewrite in canonical form, as `una fmt` does","edit":{"file":"src/receipt.una","start":{"line":4,"col":1},"end":{"line":7,"col":1},"replacement":"line_text(units: Int, sku: Text, cents: Int) -> Text = \"{units} x {sku} {cents}\"\n"}}],"explain":"una explain U7001"},{"schema":"una.diagnostic/1","code":"U2004","severity":"error","domain":"types","message":"argument 2 of `line_text` needs a label; only the first argument may go without one","primary":{"file":"src/receipt.una","start":{"line":11,"col":31},"end":{"line":11,"col":40}},"related":[],"repairs":[{"rank":1,"escape_cost":0,"description":"label it `sku`","edit":{"file":"src/receipt.una","start":{"line":11,"col":31},"end":{"line":11,"col":40},"replacement":"sku: \"LAMP-01\""}}],"explain":"una explain U2004"}],"fixable":2}But una fix --dry-run . prints one line:
$ una fix --dry-run .
fixed src/receipt.una:11:31 U2004 label it `sku`The label is a repair, so it gets a fixed line. The layout is not a repair round's edit: una fix formats every file after its rounds, as una fmt . does, and that step has no line of its own. una fix . would still fix both.