diff --git a/Cargo.lock b/Cargo.lock
index a9415ee182..7a84114468 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3315,6 +3315,7 @@ name = "roc_build"
version = "0.0.1"
dependencies = [
"bumpalo",
+ "const_format",
"inkwell",
"libloading",
"roc_builtins",
@@ -4159,6 +4160,7 @@ version = "0.1.0"
dependencies = [
"bitvec 1.0.1",
"bumpalo",
+ "clap 3.2.20",
"roc_wasm_module",
]
diff --git a/README.md b/README.md
index 57a4c6f867..0ce48d4b8c 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
Roc is not ready for a 0.1 release yet, but we do have:
- [**installation** guide](https://github.com/roc-lang/roc/tree/main/getting_started)
-- [**tutorial**](https://github.com/roc-lang/roc/blob/main/TUTORIAL.md)
+- [**tutorial**](https://roc-lang.org/tutorial)
- [**docs** for the standard library](https://www.roc-lang.org/builtins/Str)
- [frequently asked questions](https://github.com/roc-lang/roc/blob/main/FAQ.md)
- [Zulip chat](https://roc.zulipchat.com) for help, questions and discussions
diff --git a/TUTORIAL.md b/TUTORIAL.md
deleted file mode 100644
index 4215a07e5e..0000000000
--- a/TUTORIAL.md
+++ /dev/null
@@ -1,2142 +0,0 @@
-# Tutorial
-
-This is a tutorial to learn how to build Roc applications.
-It covers the REPL, basic types like strings, lists, tags, and functions, syntax like `when` and `if then else`, and more!
-
-Enjoy!
-
-## Getting started
-
-Learn how to install roc on your machine [here](https://github.com/roc-lang/roc/tree/main/getting_started#installation).
-
-## REPL (Read - Eval - Print - Loop)
-
-Let’s start by getting acquainted with Roc’s Read Eval Print Loop, or REPL for
-short. Run this in a terminal:
-
-```sh
-$ roc repl
-```
-
-You should see this:
-
-```sh
-The rockin’ roc repl
-```
-
-Try typing this in and pressing enter:
-
-```coffee
->> "Hello, World!"
-"Hello, World!" : Str
-```
-
-Congratulations! You've just written your first Roc code!
-
-## Strings and Numbers
-
-Previously you entered the *expression* `"Hello, World!"` into the REPL,
-and the REPL printed it back out. It also printed `: Str`, which is the
-expression's type. We'll talk about types later; for now, we'll ignore the `:`
-and whatever comes after it whenever the REPL prints them.
-
-Let's try a more complicated expression:
-
-```coffee
->> 1 + 1
-2 : Num *
-```
-
-According to the Roc REPL, one plus one equals two. Checks out!
-
-Roc will respect [order of operations](https://en.wikipedia.org/wiki/Order_of_operations) when using multiple arithmetic operators
-like `+` and `-`, but you can use parentheses to specify exactly how they should
-be grouped.
-
-```coffee
->> 1 + 2 * (3 - 4)
--1 : Num *
-```
-
-Let's try calling a function:
-
-```coffee
->> Str.concat "Hi " "there!"
-"Hi there!" : Str
-```
-
-In this expression, we're calling the `Str.concat` function
-passing two arguments: the string `"Hi "` and the string `"there!"`. The
-`Str.concat` function *concatenates* two strings together (that is, it puts
-one after the other) and returns the resulting combined string of
-`"Hi there!"`.
-
-Note that in Roc, we don't need parentheses or commas to call functions.
-We don't write `Str.concat("Hi ", "there!")` but rather `Str.concat "Hi " "there!"`.
-
-Just like in the arithmetic example above, we can use parentheses to specify
-how nested function calls should work. For example, we could write this:
-
-```coffee
->> Str.concat "Birds: " (Num.toStr 42)
-"Birds: 42" : Str
-```
-
-This calls `Num.toStr` on the number `42`, which converts it into the string
-`"42"`, and then passes that string as the second argument to `Str.concat`.
-The parentheses are important here to specify how the function calls nest!
-Try removing them, and see what happens:
-
-```coffee
->> Str.concat "Birds: " Num.toStr 42
-
-```
-
-This error message says that we've given `Str.concat` too many arguments.
-Indeed we have! We've passed it three arguments: the string `"Birds"`, the
-function `Num.toStr`, and the number `42`. That's not what we wanted to do.
-Putting parentheses around the `Num.toStr 42` call clarifies that we want it
-to be evaluated as its own expression, rather than being two arguments to
-`Str.concat`.
-
-Both the `Str.concat` function and the `Num.toStr` function have a `.` in
-their names. In `Str.concat`, `Str` is the name of a *module*, and `concat`
-is the name of a function inside that module. Similarly, `Num` is a different
-module, and `toStr` is a function inside that module.
-
-We'll get into more depth about modules later, but for now you can think of
-a module as a named collection of functions. It'll be awhile before we want
-to use them for more than that anyway!
-
-## Building an Application
-
-Let's move out of the REPL and create our first Roc application.
-
-Create a new file called `Hello.roc` and put the following code inside it:
-
-```coffee
-app "hello"
- packages { pf: "examples/cli/cli-platform/main.roc" }
- imports [pf.Stdout, pf.Program]
- provides [main] to pf
-
-main = Stdout.line "I'm a Roc application!" |> Program.quick
-```
-
-> **NOTE:** This assumes you've put Hello.roc in the root directory of the Roc
-> source code. If you'd like to put it somewhere else, you'll need to replace
-> `"examples/cli/cli-platform/main.roc"` with the path to the
-> `examples/cli/cli-platform/main.roc` file in that source code. In the future,
-> Roc will have the tutorial built in, and this aside will no longer be
-> necessary!
-
-Try running this with:
-
-```sh
-$ roc Hello.roc
-```
-
-You should see this:
-
-```sh
-I'm a Roc application!
-```
-
-Congratulations - you've now written your first Roc application! We'll go over what the parts of
-this file above `main` do later, but first let's play around a bit.
-Try replacing the `main` line with this:
-
-```coffee
-main = Stdout.line "There are \(total) animals." |> Program.quick
-
-birds = 3
-
-iguanas = 2
-
-total = Num.toStr (birds + iguanas)
-```
-
-Now if you run `roc Hello.roc`, you should see this:
-
-```sh
-There are 5 animals.
-```
-
-`Hello.roc` now has four definitions - or *defs* for
-short - namely, `main`, `birds`, `iguanas`, and `total`.
-
-A definition names an expression.
-
-- The first def assigns the name `main` to the expression `Stdout.line "There are \(total) animals." |> Program.quick`. The `Stdout.line` function takes a string and prints it as a line to [`stdout`] (the terminal's standard output device). Then `Program.quick` wrap this expression into an executable Roc program.
-- The next two defs assign the names `birds` and `iguanas` to the expressions `3` and `2`.
-- The last def assigns the name `total` to the expression `Num.toStr (birds + iguanas)`.
-
-Once we have a def, we can use its name in other expressions.
-For example, the `total` expression refers to `birds` and `iguanas`.
-
-We can also refer to defs inside strings using *string interpolation*. The
-string `"There are \(total) animals."` evaluates to the same thing as calling
-`Str.concat "There are " (Str.concat total " animals.")` directly.
-
-You can name a def using any combination of letters and numbers, but they have
-to start with a letter. Note that definitions are constant; once we've assigned
-a name to an expression, we can't reassign it! We'd get an error if we wrote this:
-
-```coffee
-birds = 3
-
-birds = 2
-```
-
-Order of defs doesn't matter. We defined `birds` and `iguanas` before
-`total` (which uses both of them), but we defined `main` before `total` even though
-it uses `total`. If you like, you can change the order of these defs to anything
-you like, and everything will still work the same way!
-
-This works because Roc expressions don't have *side effects*. We'll talk more
-about side effects later.
-
-## Functions
-
-So far we've called functions like `Num.toStr`, `Str.concat`, and `Stdout.line`.
-Next let's try defining a function of our own.
-
-```coffee
-main = Stdout.line "There are \(total) animals." |> Program.quick
-
-birds = 3
-
-iguanas = 2
-
-total = addAndStringify birds iguanas
-
-addAndStringify = \num1, num2 ->
- Num.toStr (num1 + num2)
-```
-
-This new `addAndStringify` function we've defined takes two numbers, adds them,
-calls `Num.toStr` on the result, and returns that. The `\num1, num2 ->` syntax
-defines a function's arguments, and the expression after the `->` is the body
-of the function. The expression at the end of the body (`Num.toStr (num1 + num2)`
-in this case) is returned automatically.
-
-Note that there is no separate syntax for named and anonymous functions in Roc.
-
-## if then else
-
-Let's modify the function to return an empty string if the numbers add to zero.
-
-```coffee
-addAndStringify = \num1, num2 ->
- sum = num1 + num2
-
- if sum == 0 then
- ""
- else
- Num.toStr sum
-```
-
-We did two things here:
-
-- We introduced a local def named `sum`, and set it equal to `num1 + num2`. Because we defined `sum` inside `addAndStringify`, it will not be accessible outside that function.
-- We added an `if` / `then` / `else` conditional to return either `""` or `Num.toStr sum` depending on whether `sum == 0`.
-
-Of note, we couldn't have done `total = num1 + num2` because that would be
-redefining `total` in the global scope, and defs can't be redefined. (However, we could use the name
-`sum` for a def in a different function, because then they'd be in completely
-different scopes and wouldn't affect each other.)
-
-Also note that every `if` must be accompanied by both `then` and also `else`.
-Having an `if` without an `else` is an error, because in Roc, everything is
-an expression - which means it must evaluate to a value. If there were ever an
-`if` without an `else`, that would be an expression that might not evaluate to
-a value!
-
-We can combine `if` and `else` to get `else if`, like so:
-
-```coffee
-addAndStringify = \num1, num2 ->
- sum = num1 + num2
-
- if sum == 0 then
- ""
- else if sum < 0 then
- "negative"
- else
- Num.toStr sum
-```
-
-Note that `else if` is not a separate language keyword! It's just an `if`/`else` where
-the `else` branch contains another `if`/`else`. This is easier to see with different indentation:
-
-```coffee
-addAndStringify = \num1, num2 ->
- sum = num1 + num2
-
- if sum == 0 then
- ""
- else
- if sum < 0 then
- "negative"
- else
- Num.toStr sum
-```
-
-This code is equivalent to writing `else if sum < 0 then` on one line, although the stylistic
-convention is to write `else if` on the same line.
-
-> *Note*: In Roc, `if` conditions must always be booleans. (Roc doesn't have a concept of "truthiness,"
-> so the compiler will report an error for conditionals like `if 1 then` or `if "true" then`.)
-
-## Records
-
-Currently our `addAndStringify` function takes two arguments. We can instead make
-it take one argument like so:
-
-```coffee
-total = addAndStringify { birds: 5, iguanas: 7 }
-
-addAndStringify = \counts ->
- Num.toStr (counts.birds + counts.iguanas)
-```
-
-The function now takes a *record*, which is a group of values that travel together.
-Records are not objects; they don't have methods or inheritance, they just store values.
-
-We create the record when we write `{ birds: 5, iguanas: 7 }`. This defines
-a record with two *fields* - namely, the `birds` field and the `iguanas` field -
-and then assigns the number `5` to the `birds` field and the number `7` to the
-`iguanas` field. Order doesn't matter with record fields; we could have also specified
-`iguanas` first and `birds` second, and Roc would consider it the exact same record.
-
-When we write `counts.birds`, it accesses the `birds` field of the `counts` record,
-and when we write `counts.iguanas` it accesses the `iguanas` field. When we use `==`
-on records, it compares all the fields in both records with `==`, and only returns true
-if all fields on both records return true for their `==` comparisons. If one record has
-more fields than the other, or if the types associated with a given field are different
-between one field and the other, the Roc compiler will give an error at build time.
-
-> **Note:** Some other languages have a concept of "identity equality" that's separate from
-> the "structural equality" we just described. Roc does not have a concept of identity equality;
-> this is the only way equality works!
-
-The `addAndStringify` function will accept any record with at least the fields `birds` and
-`iguanas`, but it will also accept records with more fields. For example:
-
-```coffee
-total = addAndStringify { birds: 5, iguanas: 7 }
-
-totalWithNote = addAndStringify { birds: 4, iguanas: 3, note: "Whee!" }
-
-addAndStringify = \counts ->
- Num.toStr (counts.birds + counts.iguanas)
-```
-
-This works because `addAndStringify` only uses `counts.birds` and `counts.iguanas`.
-If we were to use `counts.note` inside `addAndStringify`, then we would get an error
-because `total` is calling `addAndStringify` passing a record that doesn't have a `note` field.
-
-Record fields can have any combination of types we want. `totalWithNote` uses a record that
-has a mixture of numbers and strings, but we can also have record fields with other types of
-values - including other records, or even functions!
-
-```coffee
-{ birds: 4, nestedRecord: { someFunction: (\arg -> arg + 1), name: "Sam" } }
-```
-
-### Record shorthands
-
-Roc has a couple of shorthands you can use to express some record-related operations more concisely.
-
-Instead of writing `\record -> record.x` we can write `.x` and it will evaluate to the same thing:
-a function that takes a record and returns its `x` field. You can do this with any field you want.
-For example:
-
-```elm
-# function returnFoo takes a Record and returns the 'foo' field of that record.
-returnFoo = .foo
-
-returnFoo { foo: "hi!", bar: "blah" }
-# returns "hi!"
-```
-
-Whenever we're setting a field to be a def that has the same name as the field -
-for example, `{ x: x }` - we can shorten it to just writing the name of the def alone -
-for example, `{ x }`. We can do this with as many fields as we like, e.g.
-`{ x: x, y: y }` can alternately be written `{ x, y }`, `{ x: x, y }`, or `{ x, y: y }`.
-
-### Record destructuring
-
-We can use *destructuring* to avoid naming a record in a function argument, instead
-giving names to its individual fields:
-
-```coffee
-addAndStringify = \{ birds, iguanas } ->
- Num.toStr (birds + iguanas)
-```
-
-Here, we've *destructured* the record to create a `birds` def that's assigned to its `birds`
-field, and an `iguanas` def that's assigned to its `iguanas` field. We can customize this if we
-like:
-
-```coffee
-addAndStringify = \{ birds, iguanas: lizards } ->
- Num.toStr (birds + lizards)
-```
-
-In this version, we created a `lizards` def that's assigned to the record's `iguanas` field.
-(We could also do something similar with the `birds` field if we like.)
-
-Finally, destructuring can be used in defs too:
-
-```coffee
-{ x, y } = { x: 5, y: 10 }
-```
-
-### Building records from other records
-
-So far we've only constructed records from scratch, by specifying all of their fields. We can
-also construct new records by using another record to use as a starting point, and then
-specifying only the fields we want to be different. For example, here are two ways to
-get the same record:
-
-```coffee
-original = { birds: 5, iguanas: 7, zebras: 2, goats: 1 }
-
-fromScratch = { birds: 4, iguanas: 3, zebras: 2, goats: 1 }
-fromOriginal = { original & birds: 4, iguanas: 3 }
-```
-
-The `fromScratch` and `fromOriginal` records are equal, although they're assembled in
-different ways.
-
-- `fromScratch` was built using the same record syntax we've been using up to this point.
-- `fromOriginal` created a new record using the contents of `original` as defaults for fields that it didn't specify after the `&`.
-
-Note that when we do this, the fields you're overriding must all be present on the original record,
-and their values must have the same type as the corresponding values in the original record.
-
-## Tags
-
-Sometimes we want to represent that something can have one of several values. For example:
-
-```coffee
-stoplightColor =
- if something > 0 then
- Red
- else if something == 0 then
- Yellow
- else
- Green
-```
-
-Here, `stoplightColor` can have one of three values: `Red`, `Yellow`, or `Green`.
-The capitalization is very important! If these were lowercase (`red`, `yellow`, `green`),
-then they would refer to defs. However, because they are capitalized, they instead
-refer to *tags*.
-
-A tag is a literal value just like a number or a string. Similarly to how I can write
-the number `42` or the string `"forty-two"` without defining them first, I can also write
-the tag `FortyTwo` without defining it first. Also, similarly to how `42 == 42` and
-`"forty-two" == "forty-two"`, it's also the case that `FortyTwo == FortyTwo`.
-
-Let's say we wanted to turn `stoplightColor` from a `Red`, `Green`, or `Yellow` into
-a string. Here's one way we could do that:
-
-```elm
-stoplightStr =
- if stoplightColor == Red then
- "red"
- else if stoplightColor == Green then
- "green"
- else
- "yellow"
-```
-
-### Pattern matching
-We can express the same logic more concisely using `when`/`is` instead of `if`/`then`:
-
-```elm
-stoplightStr =
- when stoplightColor is
- Red -> "red"
- Green -> "green"
- Yellow -> "yellow"
-```
-
-This results in the same value for `stoplightStr`. In both the `when` version and the `if` version, we
-have three conditional branches, and each of them evaluates to a string. The difference is how the
-conditions are specified; here, we specify between `when` and `is` that we're making comparisons against
-`stoplightColor`, and then we specify the different things we're comparing it to: `Red`, `Green`, and `Yellow`.
-
-Besides being more concise, there are other advantages to using `when` here.
-
-1. We don't have to specify an `else` branch, so the code can be more self-documenting about exactly what all the options are.
-2. We get more compiler help. If we try deleting any of these branches, we'll get a compile-time error saying that we forgot to cover a case that could come up. For example, if we delete the `Green ->` branch, the compiler will say that we didn't handle the possibility that `stoplightColor` could be `Green`. It knows this because `Green` is one of the possibilities in the `stoplightColor` definition we made earlier.
-
-We can still have the equivalent of an `else` branch in our `when` if we like. Instead of writing "else", we write
-"_ ->" like so:
-
-```coffee
-stoplightStr =
- when stoplightColor is
- Red -> "red"
- _ -> "not red"
-```
-
-This lets us more concisely handle multiple cases. However, it has the downside that if we add a new case -
-for example, if we introduce the possibility of `stoplightColor` being `Orange`, the compiler can no longer
-tell us we forgot to handle that possibility in our `when`. After all, we are handling it - just maybe not
-in the way we'd decide to if the compiler had drawn our attention to it!
-
-We can make this `when` *exhaustive* (that is, covering all possibilities) without using `_ ->` by using
-`|` to specify multiple matching conditions for the same branch:
-
-```coffee
-stoplightStr =
- when stoplightColor is
- Red -> "red"
- Green | Yellow -> "not red"
-```
-
-You can read `Green | Yellow` as "either `Green` or `Yellow`". By writing it this way, if we introduce the
-possibility that `stoplightColor` can be `Orange`, we'll get a compiler error telling us we forgot to cover
-that case in this `when`, and then we can handle it however we think is best.
-
-We can also combine `if` and `when` to make branches more specific:
-
-```coffee
-stoplightStr =
- when stoplightColor is
- Red -> "red"
- Green | Yellow if contrast > 75 -> "not red, but very high contrast"
- Green | Yellow if contrast > 50 -> "not red, but high contrast"
- Green | Yellow -> "not red"
-```
-
-This will give the same answer for `stoplightStr` as if we had written the following:
-
-```coffee
-stoplightStr =
- when stoplightColor is
- Red -> "red"
- Green | Yellow ->
- if contrast > 75 then
- "not red, but very high contrast"
- else if contrast > 50 then
- "not red, but high contrast"
- else
- "not red"
-```
-
-Either style can be a reasonable choice depending on the circumstances.
-
-### Tags with payloads
-
-Tags can have *payloads* - that is, values contained within them. For example:
-
-```coffee
-stoplightColor =
- if something > 100 then
- Red
- else if something > 0 then
- Yellow
- else if something == 0 then
- Green
- else
- Custom "some other color"
-
-stoplightStr =
- when stoplightColor is
- Red -> "red"
- Green | Yellow -> "not red"
- Custom description -> description
-```
-
-This makes two changes to our earlier `stoplightColor` / `stoplightStr` example.
-
-1. We sometimes set `stoplightColor` to be `Custom "some other color"`. When we did this, we gave the `Custom` tag a *payload* of the string `"some other color"`.
-2. We added a `Custom` tag in our `when`, with a payload which we named `description`. Because we did this, we were able to refer to `description` in the body of the branch (that is, the part after the `->`) just like any other def.
-
-Any tag can be given a payload like this. A payload doesn't have to be a string; we could also have said (for example) `Custom { r: 40, g: 60, b: 80 }` to specify an RGB color instead of a string. Then in our `when` we could have written `Custom record ->` and then after the `->` used `record.r`, `record.g`, and `record.b` to access the `40`, `60`, `80` values. We could also have written `Custom { r, g, b } ->` to *destructure* the record, and then
-accessed these `r`, `g`, and `b` defs after the `->` instead.
-
-A tag can also have a payload with more than one value. Instead of `Custom { r: 40, g: 60, b: 80 }` we could
-write `Custom 40 60 80`. If we did that, then instead of destructuring a record with `Custom { r, g, b } ->`
-inside a `when`, we would write `Custom r g b ->` to destructure the values directly out of the payload.
-
-We refer to whatever comes before a `->` in a `when` expression as a *pattern* - so for example, in the
-`Custom description -> description` branch, `Custom description` would be a pattern. In programming, using
-patterns in branching conditionals like `when` is known as [pattern matching](https://en.wikipedia.org/wiki/Pattern_matching). You may hear people say things like "let's pattern match on `Custom` here" as a way to
-suggest making a `when` branch that begins with something like `Custom description ->`.
-
-### Pattern Matching on Lists
-You can also pattern match on lists, like so:
-
- when myList is
- [] -> 0 # the list is empty
- [Foo, ..] -> 1 # it starts with a Foo tag
- [_, ..] -> 2 # it contains at least one element, which we ignore
- [Foo, Bar, ..] -> 3 # it starts with a Foo tag followed by a Bar tag
- [Foo, Bar, Baz] -> 4 # it contains exactly three elements: Foo, Bar, and Baz
- [Foo, a, ..] -> 5 # it starts with a Foo tag followed by something we name `a`
- [Ok a, ..] -> 6 # it starts with an Ok tag containing a payload named `a`
- [.., Foo] -> 7 # it ends with a Foo tag
- [A, B, .., C, D] -> 8 # it has certain elements at the beginning and and
-
-This can be both more concise and more efficient (at runtime) than calling [`List.get`](https://www.roc-lang.org/builtins/List#get)
-multiple times, since each call to `get` requires a separate conditional to handle the different
-`Result`s they return.
-
-> **Note:** Each list pattern can only have one `..`, which is known as the "rest pattern" because it's where the _rest_ of the list goes.
-
-## Booleans
-
-In many programming languages, `true` and `false` are special language keywords that refer to
-the two boolean values. In Roc, booleans do not get special keywords; instead, they are exposed
-as the ordinary values `Bool.true` and `Bool.false`.
-
-This design is partly to keep the number of special keywords in the language smaller, but mainly
-to suggest how booleans are intended be used in Roc: for
-[*boolean logic*](https://en.wikipedia.org/wiki/Boolean_algebra) (`&&`, `||`, and so on) as opposed
-to for data modeling. Tags are the preferred choice for data modeling, and having tag values be
-more concise than boolean values helps make this preference clear.
-
-As an example of why tags are encouraged for data modeling, in many languages it would be common
-to write a record like `{ name: "Richard", isAdmin: Bool.true }`, but in Roc it would be preferable
-to write something like `{ name: "Richard", role: Admin }`. At first, the `role` field might only
-ever be set to `Admin` or `Normal`, but because the data has been modeled using tags instead of
-booleans, it's much easier to add other alternatives in the future, like `Guest` or `Moderator` -
-some of which might also want payloads.
-
-## Lists
-
-Another thing we can do in Roc is to make a *list* of values. Here's an example:
-
-```coffee
-names = ["Sam", "Lee", "Ari"]
-```
-
-This is a list with three elements in it, all strings. We can add a fourth
-element using `List.append` like so:
-
-```coffee
-List.append names "Jess"
-```
-
-This returns a **new** list with `"Jess"` after `"Ari"`, and doesn't modify the original list at all.
-All values in Roc (including lists, but also records, strings, numbers, and so on) are immutable,
-meaning whenever we want to "change" them, we want to instead pass them to a function which returns some
-variation of what was passed in.
-
-### List.map
-
-A common way to transform one list into another is to use `List.map`. Here's an example of how to
-use it:
-
-```coffee
-List.map [1, 2, 3] \num -> num * 2
-```
-
-This returns `[2, 4, 6]`. `List.map` takes two arguments:
-
-1. An input list
-2. A function that will be called on each element of that list
-
-It then returns a list which it creates by calling the given function on each element in the input list.
-In this example, `List.map` calls the function `\num -> num * 2` on each element in
-`[1, 2, 3]` to get a new list of `[2, 4, 6]`.
-
-We can also give `List.map` a named function, instead of an anonymous one:
-
-For example, the `Num.isOdd` function returns `true` if it's given an odd number, and `false` otherwise.
-So `Num.isOdd 5` returns `true` and `Num.isOdd 2` returns `false`.
-
-As such, calling `List.map [1, 2, 3] Num.isOdd` returns a new list of `[Bool.true, Bool.false, Bool.true]`.
-
-### List element type compatibility
-
-If we tried to give `List.map` a function that didn't work on the elements in the list, then we'd get
-an error at compile time. Here's a valid, and then an invalid example:
-
-```coffee
-# working example
-List.map [-1, 2, 3, -4] Num.isNegative
-# returns [Bool.true, Bool.false, Bool.false, Bool.true]
-```
-
-```coffee
-# invalid example
-List.map ["A", "B", "C"] Num.isNegative
-# error: isNegative doesn't work on strings!
-```
-
-Because `Num.isNegative` works on numbers and not strings, calling `List.map` with `Num.isNegative` and a
-list of numbers works, but doing the same with a list of strings doesn't work.
-
-This wouldn't work either:
-
-```coffee
-List.map ["A", "B", "C", 1, 2, 3] Num.isNegative
-```
-
-In fact, this wouldn't work for a more fundamental reason: every element in a Roc list has to share the same type.
-For example, we can have a list of strings like `["Sam", "Lee", "Ari"]`, or a list of numbers like
-`[1, 2, 3, 4, 5]` but we can't have a list which mixes strings and numbers like `["Sam", 1, "Lee", 2, 3]` -
-that would be a compile-time error.
-
-Ensuring all elements in a list share a type eliminates entire categories of problems.
-For example, it means that whenever you use `List.append` to
-add elements to a list, as long as you don't have any compile-time errors, you won't get any runtime errors
-from calling `List.map` afterwards - no matter what you appended to the list! More generally, it's safe to assume
-that unless you run out of memory, `List.map` will run successfully unless you got a compile-time error about an
-incompatibility (like `Num.negate` on a list of strings).
-
-### Lists that hold elements of different types
-
-We can use tags with payloads to make a list that contains a mixture of different types. For example:
-
-```coffee
-List.map [StrElem "A", StrElem "b", NumElem 1, StrElem "c", NumElem -3] \elem ->
- when elem is
- NumElem num -> Num.isNegative num
- StrElem str -> Str.isCapitalized str
-
-# returns [Bool.true, Bool.false, Bool.false, Bool.false, Bool.true]
-```
-
-Compare this with the example from earlier, which caused a compile-time error:
-
-```coffee
-List.map ["A", "B", "C", 1, 2, 3] Num.isNegative
-```
-
-The version that uses tags works because we aren't trying to call `Num.isNegative` on each element.
-Instead, we're using a `when` to tell when we've got a string or a number, and then calling either
-`Num.isNegative` or `Str.isCapitalized` depending on which type we have.
-
-We could take this as far as we like, adding more different tags (e.g. `BoolElem Bool.true`) and then adding
-more branches to the `when` to handle them appropriately.
-
-### Using tags as functions
-
-Let's say I want to apply a tag to a bunch of elements in a list. For example:
-
-```elm
-List.map ["a", "b", "c"] \str -> Foo str
-```
-
-This is a perfectly reasonable way to write it, but I can also write it like this:
-
-```elm
-List.map ["a", "b", "c"] Foo
-```
-
-These two versions compile to the same thing. As a convenience, Roc lets you specify
-a tag name where a function is expected; when you do this, the compiler infers that you
-want a function which uses all of its arguments as the payload to the given tag.
-
-### `List.any` and `List.all`
-
-There are several functions that work like `List.map` - they walk through each element of a list and do
-something with it. Another is `List.any`, which returns `Bool.true` if calling the given function on any element
-in the list returns `true`:
-
-```coffee
-List.any [1, 2, 3] Num.isOdd
-# returns `Bool.true` because 1 and 3 are odd
-```
-
-```coffee
-List.any [1, 2, 3] Num.isNegative
-# returns `Bool.false` because none of these is negative
-```
-
-There's also `List.all` which only returns `true` if all the elements in the list pass the test:
-
-```coffee
-List.all [1, 2, 3] Num.isOdd
-# returns `Bool.false` because 2 is not odd
-```
-
-```coffee
-List.all [1, 2, 3] Num.isPositive
-# returns `Bool.true` because all of these are positive
-```
-
-### Removing elements from a list
-
-You can also drop elements from a list. One way is `List.dropAt` - for example:
-
-```coffee
-List.dropAt ["Sam", "Lee", "Ari"] 1
-# drops the element at offset 1 ("Lee") and returns ["Sam", "Ari"]
-```
-
-Another way is to use `List.keepIf`, which passes each of the list's elements to the given
-function, and then keeps them only if that function returns `true`.
-
-```coffee
-List.keepIf [1, 2, 3, 4, 5] Num.isEven
-# returns [2, 4]
-```
-
-There's also `List.dropIf`, which does the reverse:
-
-```coffee
-List.dropIf [1, 2, 3, 4, 5] Num.isEven
-# returns [1, 3, 5]
-```
-
-### Custom operations that walk over a list
-
-You can make your own custom operations that walk over all the elements in a list, using `List.walk`.
-Let's look at an example and then walk (ha!) through it.
-
-```coffee
-List.walk [1, 2, 3, 4, 5] { evens: [], odds: [] } \state, elem ->
- if Num.isEven elem then
- { state & evens: List.append state.evens elem }
- else
- { state & odds: List.append state.odds elem }
-
-# returns { evens: [2, 4], odds: [1, 3, 5] }
-```
-
-`List.walk` walks through each element of the list, building up a state as it goes. At the end,
-it returns the final state - whatever it ended up being after processing the last element. The `\state, elem ->`
-function that `List.walk` takes as its last argument accepts both the current state as well as the current list element
-it's looking at, and then returns the new state based on whatever it decides to do with that element.
-
-In this example, we walk over the list `[1, 2, 3, 4, 5]` and add each element to either the `evens` or `odds`
-field of a `state` record `{ evens, odds }`. By the end, that record has a list of all the even numbers in the
-list as well as a list of all the odd numbers.
-
-The state doesn't have to be a record; it can be anything you want. For example, if you made it a boolean, you
-could implement `List.any` using `List.walk`. You could also make the state be a list, and implement `List.map`,
-`List.keepIf`, or `List.dropIf`. There are a lot of things you can do with `List.walk` - it's very flexible!
-
-It can be tricky to remember the argument order for `List.walk` at first. A helpful trick is that the arguments
-follow the same pattern as what we've seen with `List.map`, `List.any`, `List.keepIf`, and `List.dropIf`: the
-first argument is a list, and the last argument is a function. The difference here is that `List.walk` has one
-more argument than those other functions; the only place it could go while preserving that pattern is the middle!
-
-That third argument specifies the initial `state` - what it's set to before the `\state, elem ->` function has
-been called on it even once. (If the list is empty, the `\state, elem ->` function will never get called and
-the initial state gets returned immediately.)
-
-> **Note:** Other languages give this operation different names, such as "fold," "reduce," "accumulate,"
-> "aggregate," "compress," and "inject."
-
-### Getting an element from a List
-
-Another thing we can do with a list is to get an individual element out of it. `List.get` is a common way to do this;
-it takes a list and an index, and then returns the element at that index...if there is one. But what if there isn't?
-
-For example, what do each of these return?
-
-```coffee
-List.get ["a", "b", "c"] 1
-```
-
-```coffee
-List.get ["a", "b", "c"] 100
-```
-
-The answer is that the first one returns `Ok "b"` and the second one returns `Err OutOfBounds`.
-They both return tags! This is done so that the caller becomes responsible for handling the possibility that
-the index is outside the bounds of that particular list.
-
-Here's how calling `List.get` can look in practice:
-
-```coffee
-when List.get ["a", "b", "c"] index is
- Ok str -> "I got this string: \(str)"
- Err OutOfBounds -> "That index was out of bounds, sorry!"
-```
-
-There's also `List.first`, which always gets the first element, and `List.last` which always gets the last.
-They return `Err ListWasEmpty` instead of `Err OutOfBounds`, because the only way they can fail is if you
-pass them an empty list!
-
-These functions demonstrate a common pattern in Roc: operations that can fail returning either an `Ok` tag
-with the answer (if successful), or an `Err` tag with another tag describing what went wrong (if unsuccessful).
-In fact, it's such a common pattern that there's a whole module called `Result` which deals with these two tags.
-Here are some examples of `Result` functions:
-
-```coffee
-Result.withDefault (List.get ["a", "b", "c"] 100) ""
-# returns "" because that's the default we said to use if List.get returned an Err
-```
-
-```coffee
-Result.isOk (List.get ["a", "b", "c"] 1)
-# returns `Bool.true` because `List.get` returned an `Ok` tag. (The payload gets ignored.)
-
-# Note: There's a Result.isErr function that works similarly.
-```
-
-### The pipe operator
-
-When you have nested function calls, sometimes it can be clearer to write them in a "pipelined"
-style using the `|>` operator. Here are three examples of writing the same expression; they all
-compile to exactly the same thing, but two of them use the `|>` operator to change how the calls look.
-
-```coffee
-Result.withDefault (List.get ["a", "b", "c"] 1) ""
-```
-
-```coffee
-List.get ["a", "b", "c"] 1
- |> Result.withDefault ""
-```
-
-The `|>` operator takes the value that comes before the `|>` and passes it as the first argument to whatever
-comes after the `|>` - so in the example above, the `|>` takes `List.get ["a", "b", "c"] 1` and passes that
-value as the first argument to `Result.withDefault` - making `""` the second argument to `Result.withDefault`.
-
-We can take this a step further like so:
-
-```coffee
-["a", "b", "c"]
- |> List.get 1
- |> Result.withDefault ""
-```
-
-This is still equivalent to the first expression. Since `|>` is known as the "pipe operator," we can read
-this as "start with `["a", "b", "c"]`, then pipe it to `List.get`, then pipe it to `Result.withDefault`."
-
-One reason the `|>` operator injects the value as the first argument is to make it work better with
-functions where argument order matters. For example, these two uses of `List.append` are equivalent:
-
-```coffee
-List.append ["a", "b", "c"] "d"
-```
-
-```coffee
-["a", "b", "c"]
- |> List.append "d"
-```
-
-Another example is `Num.div`. All three of the following do the same thing, because `a / b` in Roc is syntax
-sugar for `Num.div a b`:
-
-```coffee
-first / second
-```
-
-```coffee
-Num.div first second
-```
-
-```coffee
-first
- |> Num.div second
-```
-
-All operators in Roc are syntax sugar for normal function calls. See the "Operator Desugaring Table"
-at the end of this tutorial for a complete list of them.
-
-## Types
-
-Sometimes you may want to document the type of a definition. For example, you might write:
-
-```ruby
-# Takes a firstName string and a lastName string, and returns a string
-fullName = \firstName, lastName ->
- "\(firstName) \(lastName)"
-```
-
-Comments can be valuable documentation, but they can also get out of date and become misleading.
-If someone changes this function and forgets to update the comment, it will no longer be accurate.
-
-### Type annotations
-
-Here's another way to document this function's type, which doesn't have that problem:
-
-```coffee
-fullName : Str, Str -> Str
-fullName = \firstName, lastName ->
- "\(firstName) \(lastName)"
-```
-
-The `fullName :` line is a *type annotation*. It's a strictly optional piece of metadata we can add
-above a def to describe its type. Unlike a comment, the Roc compiler will check type annotations for
-accuracy. If the annotation ever doesn't fit with the implementation, we'll get a compile-time error.
-
-The annotation `fullName : Str, Str -> Str` says "`fullName` is a function that takes two strings as
-arguments and returns a string."
-
-#### Strings
-
-We can give type annotations to any value, not just functions. For example:
-
-```coffee
-firstName : Str
-firstName = "Amy"
-
-lastName : Str
-lastName = "Lee"
-```
-
-These annotations say that both `firstName` and `lastName` have the type `Str`.
-
-#### Records
-
-We can annotate records similarly. For example, we could move `firstName` and `lastName` into a record like so:
-
-```coffee
-amy : { firstName : Str, lastName : Str }
-amy = { firstName: "Amy", lastName: "Lee" }
-
-jen : { firstName : Str, lastName : Str }
-jen = { firstName: "Jen", lastName: "Majura" }
-```
-
-#### Type Aliasing
-
-When we have a recurring type annotation like before, it can be nice to give it its own name. We do this like
-so:
-
-```coffee
-Musician : { firstName : Str, lastName : Str }
-
-amy : Musician
-amy = { firstName: "Amy", lastName: "Lee" }
-
-simone : Musician
-simone = { firstName: "Simone", lastName: "Simons" }
-```
-
-Here, `Musician` is a *type alias*. A type alias is like a def, except it gives a name to a type
-instead of to a value. Just like how you can read `name : Str` as "`name` has the type `Str`,"
-you can also read `Musician : { firstName : Str, lastName : Str }` as "`Musician` has the type
-`{ firstName : Str, lastName : Str }`."
-
-#### Tag Unions
-
-We can also give type annotations to tag unions:
-
-```coffee
-colorFromStr : Str -> [Red, Green, Yellow]
-colorFromStr = \string ->
- when string is
- "red" -> Red
- "green" -> Green
- _ -> Yellow
-```
-
-You can read the type `[Red, Green, Yellow]` as "a tag union of the tags `Red`, `Green`, and `Yellow`."
-
-#### List
-
-When we annotate a list type, we have to specify the type of its elements:
-
-```coffee
-names : List Str
-names = ["Amy", "Simone", "Tarja"]
-```
-
-You can read `List Str` as "a list of strings." Here, `Str` is a *type parameter* that tells us what type of
-`List` we're dealing with. `List` is a *parameterized type*, which means it's a type that requires a type
-parameter; there's no way to give something a type of `List` without a type parameter - you have to specify
-what type of list it is, such as `List Str` or `List Bool` or `List { firstName : Str, lastName : Str }`.
-
-#### Wildcard type
-
-There are some functions that work on any list, regardless of its type parameter. For example, `List.isEmpty`
-has this type:
-
-```coffee
-isEmpty : List * -> Bool
-```
-
-The `*` is a *wildcard type* - that is, a type that's compatible with any other type. `List *` is compatible
-with any type of `List` - so, `List Str`, `List Bool`, and so on. So you can call
-`List.isEmpty ["I am a List Str"]` as well as `List.isEmpty [Bool.true]`, and they will both work fine.
-
-The wildcard type also comes up with empty lists. Suppose we have one function that takes a `List Str` and another
-function that takes a `List Bool`. We might reasonably expect to be able to pass an empty list (that is, `[]`) to
-either of these functions. And so we can! This is because a `[]` value has the type `List *` - that is,
-"a list with a wildcard type parameter," or "a list whose element type could be anything."
-
-`List.reverse` works similarly to `List.isEmpty`, but with an important distinction. As with `isEmpty`, we can
-call `List.reverse` on any list, regardless of its type parameter. However, consider these calls:
-
-```coffee
-strings : List Str
-strings = List.reverse ["a", "b"]
-
-bools : List Bool
-bools = List.reverse [Bool.true, Bool.false]
-```
-
-In the `strings` example, we have `List.reverse` returning a `List Str`. In the `bools` example, it's returning a
-`List Bool`. So what's the type of `List.reverse`?
-
-We saw that `List.isEmpty` has the type `List * -> Bool`, so we might think the type of `List.reverse` would be
-`reverse : List * -> List *`. However, remember that we also saw that the type of the empty list is `List *`?
-`List * -> List *` is actually the type of a function that always returns empty lists! That's not what we want.
-
-#### Type Variables
-
-What we want is something like one of these:
-
-```coffee
-reverse : List elem -> List elem
-```
-
-```coffee
-reverse : List value -> List value
-```
-
-```coffee
-reverse : List a -> List a
-```
-
-Any of these will work, because `elem`, `value`, and `a` are all *type variables*. A type variable connects
-two or more types in the same annotation. So you can read `List elem -> List elem` as "takes a list and returns
-a list that has the same element type." Just like `List.reverse` does!
-
-You can choose any name you like for a type variable, but it has to be lowercase. (You may have noticed all the
-types we've used until now are uppercase; that is no accident! Lowercase types are always type variables, so
-all other named types have to be uppercase.) All three of the above type annotations are equivalent;
-the only difference is that we chose different names (`elem`, `value`, and `a`) for their type variables.
-
-You can tell some interesting things about functions based on the type parameters involved. For example,
-any function that returns `List *` definitely always returns an empty list. You don't need to look at the rest
-of the type annotation, or even the function's implementation! The only way to have a function that returns
-`List *` is if it returns an empty list.
-
-Similarly, the only way to have a function whose type is `a -> a` is if the function's implementation returns
-its argument without modifying it in any way. This is known as [the identity function](https://en.wikipedia.org/wiki/Identity_function).
-
-## Tag Unions
-
-We can also annotate types that include tags:
-
-```coffee
-colorFromStr : Str -> [Red, Green, Yellow]
-colorFromStr = \string ->
- when string is
- "red" -> Red
- "green" -> Green
- _ -> Yellow
-```
-
-You can read the type `[Red, Green, Yellow]` as "a *tag union* of the tags `Red`, `Green`, and `Yellow`."
-
-Some tag unions have only one tag in them. For example:
-
-```coffee
-redTag : [Red]
-redTag = Red
-```
-
-Tag unions can accumulate additional tags based on how they're used in the program. Consider this `if` expression:
-
-```elm
-\str ->
- if Str.isEmpty str then
- Ok "it was empty"
- else
- Err ["it was not empty"]
-```
-
-Here, Roc sees that the first branch has the type `[Ok Str]` and that the `else` branch has
-the type `[Err (List Str)]`, so it concludes that the whole `if` expression evaluates to the
-combination of those two tag unions: `[Ok Str, Err (List Str)]`.
-
-This means the entire `\str -> …` funcion here has the type `Str -> [Ok Str, Err (List Str)]`.
-However, it would be most common to annotate it as `Result Str (List Str)` instead, because
-the `Result` type (for operations like `Result.withDefault`, which we saw earlier) is a type
-alias for a tag union with `Ok` and `Err` tags that each have one payload:
-
-```haskell
-Result ok err : [Ok ok, Err err]
-```
-
-We just saw how tag unions get combined when different branches of a conditional return different tags. Another way tag unions can get combined is through pattern matching. For example:
-
-```coffeescript
-when color is
- Red -> "red"
- Yellow -> "yellow"
- Green -> "green"
-```
-
-Here, Roc's compiler will infer that `color`'s type is `[Red, Yellow, Green]`, because
-those are the three possibilities this `when` handles.
-
-## Numeric types
-
-Roc has different numeric types that each have different tradeoffs.
-They can all be broken down into two categories: [fractions](https://en.wikipedia.org/wiki/Fraction),
-and [integers](https://en.wikipedia.org/wiki/Integer). In Roc we call these `Frac` and `Int` for short.
-
-### Integers
-
-Roc's integer types have two important characteristics: their *size* and their [*signedness*](https://en.wikipedia.org/wiki/Signedness).
-Together, these two characteristics determine the range of numbers the integer type can represent.
-
-For example, the Roc type `U8` can represent the numbers 0 through 255, whereas the `I16` type can represent
-the numbers -32768 through 32767. You can actually infer these ranges from their names (`U8` and `I16`) alone!
-
-The `U` in `U8` indicates that it's *unsigned*, meaning that it can't have a minus [sign](https://en.wikipedia.org/wiki/Sign_(mathematics)), and therefore can't be negative. The fact that it's unsigned tells us immediately that
-its lowest value is zero. The 8 in `U8` means it is 8 [bits](https://en.wikipedia.org/wiki/Bit) in size, which
-means it has room to represent 2⁸ (which is equal to 256) different numbers. Since one of those 256 different numbers
-is 0, we can look at `U8` and know that it goes from `0` (since it's unsigned) to `255` (2⁸ - 1, since it's 8 bits).
-
-If we change `U8` to `I8`, making it a *signed* 8-bit integer, the range changes. Because it's still 8 bits, it still
-has room to represent 2⁸ (that is, 256) different numbers. However, now in addition to one of those 256 numbers
-being zero, about half of the rest will be negative, and the others positive. So instead of ranging from, say -255
-to 255 (which, counting zero, would represent 511 different numbers; too many to fit in 8 bits!) an `I8` value
-ranges from -128 to 127.
-
-Notice that the negative extreme is `-128` versus `127` (not `128`) on the positive side. That's because of
-needing room for zero; the slot for zero is taken from the positive range because zero doesn't have a minus sign.
-So in general, you can find the lowest signed number by taking its total range (256 different numbers in the case
-of an 8-bit integer) and dividing it in half (half of 256 is 128, so -128 is `I8`'s lowest number). To find the
-highest number, take the positive version of the lowest number (so, convert `-128` to `128`) and then subtract 1
-to make room for zero (so, `128` becomes `127`; `I8` ranges from -128 to 127).
-
-Following this pattern, the 16 in `I16` means that it's a signed 16-bit integer.
-That tells us it has room to represent 2¹⁶ (which is equal to 65536) different numbers. Half of 65536 is 32768,
-so the lowest `I16` would be -32768, and the highest would be 32767. Knowing that, we can also quickly tell that
-the lowest `U16` would be zero (since it always is for unsigned integers), and the highest `U16` would be 65535.
-
-Choosing a size depends on your performance needs and the range of numbers you want to represent. Consider:
-
-- Larger integer sizes can represent a wider range of numbers. If you absolutely need to represent numbers in a certain range, make sure to pick an integer size that can hold them!
-- Smaller integer sizes take up less memory. These savings rarely matters in variables and function arguments, but the sizes of integers that you use in data structures can add up. This can also affect whether those data structures fit in [cache lines](https://en.wikipedia.org/wiki/CPU_cache#Cache_performance), which can easily be a performance bottleneck.
-- Certain processors work faster on some numeric sizes than others. There isn't even a general rule like "larger numeric sizes run slower" (or the reverse, for that matter) that applies to all processors. In fact, if the CPU is taking too long to run numeric calculations, you may find a performance improvement by experimenting with numeric sizes that are larger than otherwise necessary. However, in practice, doing this typically degrades overall performance, so be careful to measure properly!
-
-Here are the different fixed-size integer types that Roc supports:
-
-| Range | Type | Size |
-| -----------------------------------------------------------: | :---- | :------- |
-| `-128` `127` | `I8` | 1 Byte |
-| `0` `255` | `U8` | 1 Byte |
-| `-32_768` `32_767` | `I16` | 2 Bytes |
-| `0` `65_535` | `U16` | 2 Bytes |
-| `-2_147_483_648` `2_147_483_647` | `I32` | 4 Bytes |
-| `0` (over 4 billion) `4_294_967_295` | `U32` | 4 Bytes |
-| `-9_223_372_036_854_775_808` `9_223_372_036_854_775_807` | `I64` | 8 Bytes |
-| `0` (over 18 quintillion) `18_446_744_073_709_551_615` | `U64` | 8 Bytes |
-| `-170_141_183_460_469_231_731_687_303_715_884_105_728` `170_141_183_460_469_231_731_687_303_715_884_105_727` | `I128` | 16 Bytes |
-| `0` (over 340 undecillion) `340_282_366_920_938_463_463_374_607_431_768_211_455` | `U128` | 16 Bytes |
-
-#### Nat
-
-Roc also has one variable-size integer type: `Nat` (short for "natural number").
-The size of `Nat` is equal to the size of a memory address, which varies by system.
-For example, when compiling for a 64-bit system, `Nat` works the same way as `U64`.
-When compiling for a 32-bit system, it works the same way as `U32`. Most popular
-computing devices today are 64-bit, so `Nat` is usually the same as `U64`, but
-Web Assembly is typically 32-bit - so when running a Roc program built for Web Assembly,
-`Nat` will work like a `U32` in that program.
-
-A common use for `Nat` is to store the length of a collection like a `List`;
-there's a function `List.len : List * -> Nat` which returns the length of the given list.
-64-bit systems can represent longer lists in memory than 32-bit systems can,
-which is why the length of a list is represented as a `Nat`.
-
-If any operation would result in an integer that is either too big
-or too small to fit in that range (e.g. calling `Int.maxI32 + 1`, which adds 1 to
-the highest possible 32-bit integer), then the operation will *overflow*.
-When an overflow occurs, the program will crash.
-
-As such, it's very important to design your integer operations not to exceed these bounds!
-
-### Fractions
-
-Roc has three fractional types:
-
-- `F32`, a 32-bit [floating-point number](https://en.wikipedia.org/wiki/IEEE_754)
-- `F64`, a 64-bit [floating-point number](https://en.wikipedia.org/wiki/IEEE_754)
-- `Dec`, a 128-bit decimal [fixed-point number](https://en.wikipedia.org/wiki/Fixed-point_arithmetic)
-
-These are different from integers in that they can represent numbers with fractional components,
-such as 1.5 and -0.123.
-
-`Dec` is the best default choice for representing base-10 decimal numbers
-like currency, because it is base-10 under the hood. In contrast,
-`F64` and `F32` are base-2 under the hood, which can lead to decimal
-precision loss even when doing addition and subtraction. For example, when
-using `F64`, running 0.1 + 0.2 returns 0.3000000000000000444089209850062616169452667236328125,
-whereas when using `Dec`, 0.1 + 0.2 returns 0.3.
-
-`F32` and `F64` have direct hardware support on common processors today. There is no hardware support
-for fixed-point decimals, so under the hood, a `Dec` is an `I128`; operations on it perform
-[base-10 fixed-point arithmetic](https://en.wikipedia.org/wiki/Fixed-point_arithmetic)
-with 18 decimal places of precision.
-
-This means a `Dec` can represent whole numbers up to slightly over 170
-quintillion, along with 18 decimal places. (To be precise, it can store
-numbers between `-170_141_183_460_469_231_731.687303715884105728`
-and `170_141_183_460_469_231_731.687303715884105727`.) Why 18
-decimal places? It's the highest number of decimal places where you can still
-convert any `U64` to a `Dec` without losing information.
-
-While the fixed-point `Dec` has a fixed range, the floating-point `F32` and `F64` do not.
-Instead, outside of a certain range they start to lose precision instead of immediately overflowing
-the way integers and `Dec` do. `F64` can represent [between 15 and 17 significant digits](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) before losing precision, whereas `F32` can only represent [between 6 and 9](https://en.wikipedia.org/wiki/Single-precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32).
-
-There are some use cases where `F64` and `F32` can be better choices than `Dec`
-despite their precision drawbacks. For example, in graphical applications they
-can be a better choice for representing coordinates because they take up less memory,
-various relevant calculations run faster, and decimal precision loss isn't as big a concern
-when dealing with screen coordinates as it is when dealing with something like currency.
-
-### Num, Int, and Frac
-
-Some operations work on specific numeric types - such as `I64` or `Dec` - but operations support
-multiple numeric types. For example, the `Num.abs` function works on any number, since you can
-take the [absolute value](https://en.wikipedia.org/wiki/Absolute_value) of integers and fractions alike.
-Its type is:
-
-```elm
-abs : Num a -> Num a
-```
-
-This type says `abs` takes a number and then returns a number of the same type. That's because the
-`Num` type is compatible with both integers and fractions.
-
-There's also an `Int` type which is only compatible with integers, and a `Frac` type which is only
-compatible with fractions. For example:
-
-```elm
-Num.xor : Int a, Int a -> Int a
-```
-
-```elm
-Num.cos : Frac a -> Frac a
-```
-
-When you write a number literal in Roc, it has the type `Num *`. So you could call `Num.xor 1 1`
-and also `Num.cos 1` and have them all work as expected; the number literal `1` has the type
-`Num *`, which is compatible with the more constrained types `Int` and `Frac`. For the same reason,
-you can pass number literals to functions expecting even more constrained types, like `I32` or `F64`.
-
-### Typed Number Literals
-
-When writing a number literal in Roc you can specify the numeric type as a suffix of the literal.
-`1u8` specifies `1` as an unsigned 8-bit integer, `5i32` specifies `5` as a signed 32-bit integer, etc.
-The full list of possible suffixes includes:
-`i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`, `u64`, `i128`, `u128`, `nat`, `f32`, `f64`, `dec`
-
-### Hexadecimal Integer Literals
-
-Integer literals can be written in hexadecimal form by prefixing with `0x` followed by hexadecimal characters.
-`0xFE` evaluates to decimal `254`
-The integer type can be specified as a suffix to the hexadecimal literal,
-so `0xC8u8` evaluates to decimal `200` as an unsigned 8-bit integer.
-
-### Binary Integer Literals
-
-Integer literals can be written in binary form by prefixing with `0b` followed by the 1's and 0's representing
-each bit. `0b0000_1000` evaluates to decimal `8`
-The integer type can be specified as a suffix to the binary literal,
-so `0b0100u8` evaluates to decimal `4` as an unsigned 8-bit integer.
-
-## Tests and expectations
-
-You can write automated tests for your Roc code like so:
-
-```swift
-pluralize = \singular, plural, count ->
- countStr = Num.toStr count
-
- if count == 1 then
- "\(countStr) \(singular)"
- else
- "\(countStr) \(plural)"
-
-expect pluralize "cactus" "cacti" 1 == "1 cactus"
-
-expect pluralize "cactus" "cacti" 2 == "2 cacti"
-```
-
-If you put this in a file named `main.roc` and run `roc test`, Roc will execute the two `expect`
-expressions (that is, the two `pluralize` calls) and report any that returned `false`.
-
-### Inline `expect`s
-
-For example:
-
-```swift
- if count == 1 then
- "\(countStr) \(singular)"
- else
- expect count > 0
-
- "\(countStr) \(plural)"
-```
-
-This `expect` will fail if you call `pluralize` passing a count of 0, and it will fail
-regardless of whether the inline `expect` is reached when running your program via `roc dev`
-or in the course of running a test (with `roc test`).
-
-So for example, if we added this top-level `expect`...
-
-```swift
-expect pluralize "cactus" "cacti" 0 == "0 cacti"
-```
-
-...it would hit the inline `expect count > 0`, which would then fail the test.
-
-Note that inline `expect`s do not halt the program! They are designed to inform, not to affect
-control flow. In fact, if you do `roc build`, they are not even included in the final binary.
-
-If you try this code out, you may note that when an `expect` fails (either a top-level or inline
-one), the failure message includes the values of any named variables - such as `count` here.
-This leads to a useful technique, which we will see next.
-
-### Quick debugging with inline `expect`s
-
-An age-old debugging technique is printing out a variable to the terminal. In Roc you can use
-`expect` to do this. Here's an example:
-
-```elm
-\arg ->
- x = arg - 1
-
- # Reports the value of `x` without stopping the program
- expect x != x
-
- Num.abs x
-```
-
-The failure output will include both the value of `x` as well as the comment immediately above it,
-which lets you use that comment for extra context in your output.
-
-## Roc Modules
-
-Every `.roc` file is a *module*. There are three types of modules:
- - builtin
- - app
- - interface
-
-### App module
-
-Let's take a closer look at the part of `Hello.roc` above `main`:
-
-```coffee
-app "hello"
- packages { pf: "examples/cli/cli-platform/main.roc" }
- imports [pf.Stdout, pf.Program]
- provides main to pf
-```
-
-This is known as a *module header*. We know this particular one is an *application module*
-(or *app module* for short) because it begins with the `app` keyword.
-Every Roc program has one app module.
-
-The line `app "hello"` states that this module defines a Roc application, and
-that building this application should produce an executable named `hello`. This
-means when you run `roc Hello.roc`, the Roc compiler will build an executable
-named `hello` (or `hello.exe` on Windows) and run it. You can also build the executable
-without running it by running `roc build Hello.roc`.
-
-The remaining lines all involve the *platform* this application is built on:
-
-```coffee
-packages { pf: "examples/cli/cli-platform/main.roc" }
-imports [pf.Stdout, pf.Program]
-provides main to pf
-```
-
-The `packages { pf: "examples/cli/cli-platform/main.roc" }` part says two things:
-
-- We're going to be using a *package* (that is, a collection of modules) called `"examples/cli/cli-platform/main.roc"`
-- We're going to name that package `pf` so we can refer to it more concisely in the future.
-
-The `imports [pf.Stdout, pf.Program]` line says that we want to import the `Stdout` and `Program` modules
-from the `pf` package, and make them available in the current module.
-
-This import has a direct interaction with our definition of `main`. Let's look
-at that again:
-
-```coffee
-main = Stdout.line "I'm a Roc application!" |> Program.quick
-```
-
-Here, `main` is calling a function called `Stdout.line`. More specifically, it's
-calling a function named `line` which is exposed by a module named
-`Stdout`.
-Then the result of that function call is passed to the `quick` function of the `Program` module,
-which effectively makes it a simple Roc program.
-
-When we write `imports [pf.Stdout, pf.Program]`, it specifies that the `Stdout`
-and `Program` modules come from the `pf` package.
-
-Since `pf` was the name we chose for the `examples/cli/cli-platform/main.roc`
-package (when we wrote `packages { pf: "examples/cli/cli-platform/main.roc" }`),
-this `imports` line tells the Roc compiler that when we call `Stdout.line`, it
-should look for that `line` function in the `Stdout` module of the
-`examples/cli/cli-platform/main.roc` package.
-
-If we would like to include other modules in our application, say `AdditionalModule.roc`
-and `AnotherModule.roc`, then they can be imported directly in `imports` like this:
-
-```coffee
-packages { pf: "examples/cli/cli-platform/main.roc" }
-imports [pf.Stdout, pf.Program, AdditionalModule, AnotherModule]
-provides main to pf
-```
-
-### Interface module
-
-Let's take a look at the following module header:
-
-```coffee
-interface Parser.Core
- exposes [
- Parser,
- ParseResult,
- buildPrimitiveParser
- ]
- imports []
-```
-
-This says that the current .roc file is an *interface module* because it begins with the `interface` keyword.
-We are naming this module when we write `interface Parser.Core`. It means that this file is in
-a package `Parser` and the current module is named `core`.
-When we write `exposes [Parser, ParseResult, ...]`, it specifies the definitions we
-want to *expose*. Exposing makes them importable from other modules.
-
-Now lets import this interface from an *app module*:
-
-```coffee
-app 'interface-example'
- packages { pf: "examples/cli/cli-platform/main.roc" }
- imports [Parser.Core.{ Parser, buildPrimitiveParser }]
- provides main to pf
-```
-Here we are importing a type and a function from the 'Core' module from the package 'Parser'. Now we can use e.g.
-`buildPrimitiveParser` in this module without having to write `Parser.Core.buildPrimitiveParser`.
-
-### Builtin modules
-
-There are several modules that are built into the Roc compiler, which are imported automatically into every
-Roc module. They are:
-
-1. `Bool`
-2. `Str`
-3. `Num`
-4. `List`
-5. `Result`
-6. `Dict`
-7. `Set`
-
-You may have noticed that we already used the first five - for example, when we wrote `Str.concat` and `Num.isEven`,
-we were referencing functions stored in the `Str` and `Num` modules.
-
-These modules are not ordinary `.roc` files that live on your filesystem. Rather, they are built directly into the
-Roc compiler. That's why they're called "builtins!"
-
-Besides being built into the compiler, the builtin modules are different from other modules in that:
-
-- They are always imported. You never need to add them to `imports`.
-- All their types are imported unqualified automatically. So you never need to write `Num.Nat`, because it's as if the `Num` module was imported using `imports [Num.{ Nat }]` (and the same for all the other types in the `Num` module).
-
-## Platforms
-
-TODO
-
-## Comments
-
-Comments that begin with `##` will be included in generated documentation (```roc docs```). They require a single space after the `##`, and can include code blocks by adding five spaces after `##`.
-
-```coffee
-## This is a comment for documentation, and includes a code block.
-##
-## x = 2
-## expect x == 2
-```
-
-Roc also supports inline comments and line comments with `#`. They can be used to add information that won't be included in documentation.
-
-```coffee
-# This is a line comment that won't appear in documentation.
-myFunction : U8 -> U8
-myFunction = \bit -> bit % 2 # this is an inline comment
-```
-
-Roc does not have multiline comment syntax.
-
-## Tasks
-
-Tasks are technically not part of the Roc language, but they're very common in
-platforms. Let's use the CLI platform in `examples/cli/cli-platform/main.roc` as an example!
-
-In the CLI platform, we have four operations we can do:
-
-- Write a string to the console
-- Read a string from user input
-- Write a string to a file
-- Read a string from a file
-
-We'll use these four operations to learn about tasks.
-
-First, let's do a basic "Hello World" using the tutorial app.
-
-```coffee
-app "cli-tutorial"
- packages { pf: "examples/cli/cli-platform/main.roc" }
- imports [pf.Stdout, pf.Program]
- provides [main] to pf
-
-main =
- Stdout.line "Hello, World!"
- |> Program.quick
-```
-
-The `Stdout.line` function takes a `Str` and writes it to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)).
-It has this type:
-
-```coffee
-Stdout.line : Str -> Task {} *
-```
-
-A `Task` represents an *effect* - that is, an interaction with state outside your Roc program,
-such as the console's standard output, or a file.
-
-When we set `main` to be a `Task`, the task will get run when we run our program. Here, we've set
-`main` to be a task that writes `"Hello, World!"` to `stdout` when it gets run, so that's what
-our program does!
-
-`Task` has two type parameters: the type of value it produces when it finishes running, and any
-errors that might happen when running it. `Stdout.line` has the type `Task {} *` because it doesn't
-produce any values when it finishes (hence the `{}`) and there aren't any errors that can happen
-when it runs (hence the `*`).
-
-In contrast, `Stdin.line` produces a `Str` when it finishes reading from [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). That `Str` is reflected in its type:
-
-```coffee
-Stdin.line : Task Str *
-```
-
-Let's change `main` to read a line from `stdin`, and then print it back out again:
-
-```swift
-app "cli-tutorial"
- packages { pf: "examples/cli/cli-platform/main.roc" }
- imports [pf.Stdout, pf.Stdin, pf.Task, pf.Program]
- provides [main] to pf
-
-main = Program.quick task
-
-task =
- Task.await Stdin.line \text ->
- Stdout.line "You just entered: \(text)"
-```
-
-If you run this program, at first it won't do anything. It's waiting for you to type something
-in and press Enter! Once you do, it should print back out what you entered.
-
-The `Task.await` function combines two tasks into one bigger `Task` which first runs one of the
-given tasks and then the other. In this case, it's combining a `Stdin.line` task with a `Stdout.line`
-task into one bigger `Task`, and then setting `main` to be that bigger task.
-
-The type of `Task.await` is:
-
-```haskell
-Task.await : Task a err, (a -> Task b err) -> Task b err
-```
-
-The second argument to `Task.await` is a "callback function" which runs after the first task
-completes. This callback function receives the output of that first task, and then returns
-the second task. This means the second task can make use of output from the first task, like
-we did in our `\text -> …` callback function here:
-
-```swift
-\text ->
- Stdout.line "You just entered: \(text)"
-```
-
-Notice that, just like before, we're still building `main` from a single `Task`. This is how we'll
-always do it! We'll keep building up bigger and bigger `Task`s out of smaller tasks, and then setting
-`main` to be that one big `Task`.
-
-For example, we can print a prompt before we pause to read from `stdin`, so it no longer looks like
-the program isn't doing anything when we start it up:
-
-```swift
-task =
- Task.await (Stdout.line "Type something press Enter:") \_ ->
- Task.await Stdin.line \text ->
- Stdout.line "You just entered: \(text)"
-```
-
-This works, but we can make it a little nicer to read. Let's change it to the following:
-
-```haskell
-app "cli-tutorial"
- packages { pf: "examples/cli/cli-platform/main.roc" }
- imports [pf.Stdout, pf.Stdin, pf.Task.{ await }, pf.Program]
- provides [main] to pf
-
-main = Program.quick task
-
-task =
- await (Stdout.line "Type something press Enter:") \_ ->
- await Stdin.line \text ->
- Stdout.line "You just entered: \(text)"
-```
-
-Here we've changed how we're importing the `Task` module. Before it was
-`pf.Task` and now it's `pf.Task.{ await }`. The difference is that we're
-importing `await` in an *unqualified* way, meaning now whenever we write `await`
-in this module, it will refer to `Task.await` - so we no longer need to write
-`Task.` every time we want to `await`.
-
-It's most common in Roc to call functions from other modules in a *qualified* way
-(`Task.await`) rather than unqualified (`await`) like this, but it can be nice
-for a function with an uncommon name (like "await") which often gets called repeatedly
-across a small number of lines of code.
-
-### Backpassing
-
-Speaking of calling `await` repeatedly, if we keep calling it more and more on this
-code, we'll end up doing a lot of indenting. If we'd rather not indent so much, we
-can rewrite `task` into this style which looks different but does the same thing:
-
-```swift
-task =
- _ <- await (Stdout.line "Type something press Enter:")
- text <- await Stdin.line
-
- Stdout.line "You just entered: \(text)"
-```
-
-This `<-` syntax is called *backpassing*. The `<-` is a way to define an
-anonymous function, just like `\ … ->` is.
-
-Here, we're using backpassing to define two anonymous functions. Here's one of them:
-
-```swift
-text <-
-
-Stdout.line "You just entered: \(text)"
-```
-
-It may not look like it, but this code is defining an anonymous function! You might
-remember it as the anonymous function we previously defined like this:
-
-```swift
-\text ->
- Stdout.line "You just entered: \(text)"
-```
-
-These two anonymous functions are the same, just defined using different syntax.
-
-The reason the `<-` syntax is called *backpassing* is because it both defines a
-function and passes that function *back* as an argument to whatever comes after
-the `<-` (which in this case is `await Stdin.line`).
-
-Let's look at these two complete expressions side by side. They are both
-saying exactly the same thing, with different syntax!
-
-Here's the original:
-
-```swift
-await Stdin.line \text ->
- Stdout.line "You just entered: \(text)"
-```
-
-And here's the equivalent expression with backpassing syntax:
-
-```swift
-text <- await Stdin.line
-
-Stdout.line "You just entered: \(text)"
-```
-
-Here's the other function we're defining with backpassing:
-
-```swift
-_ <-
-text <- await Stdin.line
-
-Stdout.line "You just entered: \(text)"
-```
-
-We could also have written that function this way if we preferred:
-
-```swift
-_ <-
-
-await Stdin.line \text ->
- Stdout.line "You just entered: \(text)"
-```
-
-This is using a mix of a backpassing function `_ <-` and a normal function `\text ->`,
-which is totally allowed! Since backpassing is nothing more than syntax sugar for
-defining a function and passing back as an argument to another function, there's no
-reason we can't mix and match if we like.
-
-That said, the typical style in which this `task` would be written in Roc is using
-backpassing for all the `await` calls, like we had above:
-
-```swift
-task =
- _ <- await (Stdout.line "Type something press Enter:")
- text <- await Stdin.line
-
- Stdout.line "You just entered: \(text)"
-```
-
-This way, it reads like a series of instructions:
-
-1. First, run the `Stdout.line` task and await its completion. Ignore its output (hence the underscore in `_ <-`)
-2. Next, run the `Stdin.line` task and await its completion. Name its output `text`.
-3. Finally, run the `Stdout.line` task again, using the `text` value we got from the `Stdin.line` effect.
-
-Some important things to note about backpassing and `await`:
-
-- `await` is not a language keyword in Roc! It's referring to the `Task.await` function, which we imported unqualified by writing `Task.{ await }` in our module imports. (That said, it is playing a similar role here to the `await` keyword in languages that have `async`/`await` keywords, even though in this case it's a function instead of a special keyword.)
-- Backpassing syntax does not need to be used with `await` in particular. It can be used with any function.
-- Roc's compiler treats functions defined with backpassing exactly the same way as functions defined the other way. The only difference between `\text ->` and `text <-` is how they look, so feel free to use whichever looks nicer to you!
-
-### Empty Tag Unions
-
-If you look up the type of [`Program.exit`](https://www.roc-lang.org/examples/cli/Program#exit),
-you may notice that it takes a `Task` where the error type is `[]`. What does that mean?
-
-Just like how `{}` is the type of an empty record, `[]` is the type of an empty tag union.
-There is no way to create an empty tag union at runtime, since creating a tag union requires
-making an actual tag, and an empty tag union has no tags in it!
-
-This means if you have a function with the type `[] -> Str`, you can be sure that it will
-never execute. It requires an argument that can't be provided! Similarly, if you have a
-function with the type `Str -> []`, you can call it, but you can be sure it will not terminate
-normally. The only way to implement a function like that is using [infinite recursion](https://en.wikipedia.org/wiki/Infinite_loop#Infinite_recursion), which will either run indefinitely or else crash with a [stack overflow](https://en.wikipedia.org/wiki/Stack_overflow).
-
-Empty tag unions can be useful as type parameters. For example, a function with the type
-`List [] -> Str` can be successfully called, but only if you pass it an empty list. That's because
-an empty list has the type `List *`, which means it can be used wherever any type of `List` is
-needed - even a `List []`!
-
-Similarly, a function which accepts a `Result Str []` only accepts a "Result which is always `Ok`" - so you could call that function passing something like `Ok "hello"` with no problem,
-but if you tried to give it an `Err`, you'd get a type mismatch.
-
-Applying this to `Task`, a task with `[]` for its error type is a "task which can never fail." The only way to obtain one is by obtaining a task with an error type of `*`, since that works with any task. You can get one of these "tasks that can never fail" by using [`Task.succeed`](https://www.roc-lang.org/examples/cli/Task#succeed) or, more commonly, by handling all possible errors using [`Task.attempt`](https://www.roc-lang.org/examples/cli/Task#attempt).
-
-## What now?
-
-That's it, you can start writing Roc apps now!
-Modifying an example from the [examples folder](./examples) is probably a good place to start.
-[Advent of Code](https://adventofcode.com/2021) problems can also be fun to get to know Roc.
-
-If you are hungry for more, check out the Advanced Concepts below.
-
-## Appendix: Advanced Concepts
-
-Here are some concepts you likely won't need as a beginner, but may want to know about eventually.
-This is listed as an appendix rather than the main tutorial, to emphasize that it's totally fine
-to stop reading here and go build things!
-
-### Open Records and Closed Records
-
-Let's say I write a function which takes a record with a `firstName`
-and `lastName` field, and puts them together with a space in between:
-
-```swift
-fullName = \user ->
- "\(user.firstName) \(user.lastName)"
-```
-
-I can pass this function a record that has more fields than just
-`firstName` and `lastName`, as long as it has *at least* both of those fields
-(and both of them are strings). So any of these calls would work:
-
-- `fullName { firstName: "Sam", lastName: "Sample" }`
-- `fullName { firstName: "Sam", lastName: "Sample", email: "blah@example.com" }`
-- `fullName { age: 5, firstName: "Sam", things: 3, lastName: "Sample", role: Admin }`
-
-This `user` argument is an *open record* - that is, a description of a minimum set of fields
-on a record, and their types. When a function takes an open record as an argument,
-it's okay if you pass it a record with more fields than just the ones specified.
-
-In contrast, a *closed record* is one that requires an exact set of fields (and their types),
-with no additional fields accepted.
-
-If we add a type annotation to this `fullName` function, we can choose to have it accept either
-an open record or a closed record:
-
-```coffee
-# Closed record
-fullName : { firstName : Str, lastName : Str } -> Str
-fullName = \user ->
- "\(user.firstName) \(user.lastName)"
-```
-
-```coffee
-# Open record (because of the `*`)
-fullName : { firstName : Str, lastName : Str }* -> Str
-fullName = \user ->
- "\(user.firstName) \(user.lastName)"
-```
-
-The `*` in the type `{ firstName : Str, lastName : Str }*` is what makes it an open record type.
-This `*` is the *wildcard type* we saw earlier with empty lists. (An empty list has the type `List *`,
-in contrast to something like `List Str` which is a list of strings.)
-
-This is because record types can optionally end in a type variable. Just like how we can have `List *`
-or `List a -> List a`, we can also have `{ first : Str, last : Str }*` or
-`{ first : Str, last : Str }a -> { first: Str, last : Str }a`. The differences are that in `List a`,
-the type variable is required and appears with a space after `List`; in a record, the type variable
-is optional, and appears (with no space) immediately after `}`.
-
-If the type variable in a record type is a `*` (such as in `{ first : Str, last : Str }*`), then
-it's an open record. If the type variable is missing, then it's a closed record. You can also specify
-a closed record by putting a `{}` as the type variable (so for example, `{ email : Str }{}` is another way to write
-`{ email : Str }`). In practice, closed records are basically always written without the `{}` on the end,
-but later on we'll see a situation where putting types other than `*` in that spot can be useful.
-
-### Constrained Records
-
-The type variable can also be a named type variable, like so:
-
-```coffee
-addHttps : { url : Str }a -> { url : Str }a
-addHttps = \record ->
- { record & url: "https://\(record.url)" }
-```
-
-This function uses *constrained records* in its type. The annotation is saying:
-
-- This function takes a record which has at least a `url` field, and possibly others
-- That `url` field has the type `Str`
-- It returns a record of exactly the same type as the one it was given
-
-So if we give this function a record with five fields, it will return a record with those
-same five fields. The only requirement is that one of those fields must be `url : Str`.
-
-In practice, constrained records appear in type annotations much less often than open or closed records do.
-
-Here's when you can typically expect to encounter these three flavors of type variables in records:
-
-- *Open records* are what the compiler infers when you use a record as an argument, or when destructuring it (for example, `{ x, y } =`).
-- *Closed records* are what the compiler infers when you create a new record (for example, `{ x: 5, y: 6 }`)
-- *Constrained records* are what the compiler infers when you do a record update (for example, `{ user & email: newEmail }`)
-
-Of note, you can pass a closed record to a function that accepts a smaller open record, but not the reverse.
-So a function `{ a : Str, b : Bool }* -> Str` can accept an `{ a : Str, b : Bool, c : Bool }` record,
-but a function `{ a : Str, b : Bool, c : Bool } -> Str` would not accept an `{ a : Str, b : Bool }*` record.
-
-This is because if a function accepts `{ a : Str, b : Bool, c : Bool }`, that means it might access the `c`
-field of that record. So if you passed it a record that was not guaranteed to have all three of those fields
-present (such as an `{ a : Str, b : Bool }*` record, which only guarantees that the fields `a` and `b` are present),
-the function might try to access a `c` field at runtime that did not exist!
-
-### Type Variables in Record Annotations
-
-You can add type annotations to make record types less flexible than what the compiler infers, but not more
-flexible. For example, you can use an annotation to tell the compiler to treat a record as closed when it would
-be inferred as open (or constrained), but you can't use an annotation to make a record open when it would be
-inferred as closed.
-
-If you like, you can always annotate your functions as accepting open records. However, in practice this may not
-always be the nicest choice. For example, let's say you have a `User` type alias, like so:
-
-```coffee
-User : {
- email : Str,
- firstName : Str,
- lastName : Str,
-}
-```
-
-This defines `User` to be a closed record, which in practice is the most common way records named `User`
-tend to be defined.
-
-If you want to have a function take a `User`, you might write its type like so:
-
-```elm
-isValid : User -> Bool
-```
-
-If you want to have a function return a `User`, you might write its type like so:
-
-```elm
-userFromEmail : Str -> User
-```
-
-A function which takes a user and returns a user might look like this:
-
-```elm
-capitalizeNames : User -> User
-```
-
-This is a perfectly reasonable way to write all of these functions. However, I
-might decide that I really want the `isValid` function to take an open record -
-that is, a record with *at least* the fields of this `User` record, but possibly others as well.
-
-Since open records have a type variable (like `*` in `{ email : Str }*` or `a` in
-`{ email : Str }a -> { email : Str }a`), in order to do this I'd need to add a
-type variable to the `User` type alias:
-
-```coffee
-User a : {
- email : Str,
- firstName : Str,
- lastName : Str,
-}a
-```
-
-Notice that the `a` type variable appears not only in `User a` but also in `}a` at the end of the
-record type!
-
-Using `User a` type alias, I can still write the same three functions, but now their types need to look different.
-This is what the first one would look like:
-
-```elm
-isValid : User * -> Bool
-```
-
-Here, the `User *` type alias substitutes `*` for the type variable `a` in the type alias,
-which takes it from `{ email : Str, … }a` to `{ email : Str, … }*`. Now I can pass it any
-record that has at least the fields in `User`, and possibly others as well, which was my goal.
-
-```elm
-userFromEmail : Str -> User {}
-```
-
-Here, the `User {}` type alias substitutes `{}` for the type variable `a` in the type alias,
-which takes it from `{ email : Str, … }a` to `{ email : Str, … }{}`. As noted earlier,
-this is another way to specify a closed record: putting a `{}` after it, in the same place that
-you'd find a `*` in an open record.
-
-> **Aside:** This works because you can form new record types by replacing the type variable with
-> other record types. For example, `{ a : Str, b : Str }` can also be written `{ a : Str }{ b : Str }`.
-> You can chain these more than once, e.g. `{ a : Str }{ b : Str }{ c : Str, d : Str }`.
-> This is more useful when used with type annotations; for example, `{ a : Str, b : Str }User` describes
-> a closed record consisting of all the fields in the closed record `User`, plus `a : Str` and `b : Str`.
-
-This function still returns the same record as it always did, it just needs to be annotated as
-`User {}` now instead of just `User`, because the `User` type alias has a variable in it that must be
-specified.
-
-The third function might need to use a named type variable:
-
-```elm
-capitalizeNames : User a -> User a
-```
-
-If this function does a record update on the given user, and returns that - for example, if its
-definition were `capitalizeNames = \user -> { user & email: "blah" }` - then it needs to use the
-same named type variable for both the argument and return value.
-
-However, if returns a new `User` that it created from scratch, then its type could instead be:
-
-```elm
-capitalizeNames : User * -> User {}
-```
-
-This says that it takes a record with at least the fields specified in the `User` type alias,
-and possibly others...and then returns a record with exactly the fields specified in the `User`
-type alias, and no others.
-
-These three examples illustrate why it's relatively uncommon to use open records for type aliases:
-it makes a lot of types need to incorporate a type variable that otherwise they could omit,
-all so that `isValid` can be given something that has not only the fields `User` has, but
-some others as well. (In the case of a `User` record in particular, it may be that the extra
-fields were included due to a mistake rather than on purpose, and accepting an open record could
-prevent the compiler from raising an error that would have revealed the mistake.)
-
-That said, this is a useful technique to know about if you want to (for example) make a record
-type that accumulates more and more fields as it progresses through a series of operations.
-
-### Open and Closed Tag Unions
-
-Just like how Roc has open records and closed records, it also has open and closed tag unions. Similarly to how an open record can have other fields besides the ones explicitly listed, an open tag union can have other tags beyond the ones explicitly listed.
-
-For example, here `[Red, Green]` is a closed union like the ones we saw earlier:
-
-```coffee
-colorToStr : [Red, Green] -> String
-colorToStr = \color ->
- when color is
- Red -> "red"
- Green -> "green"
-
-Now let's compare to an *open union* version:
-
-```coffee
-colorOrOther : [Red, Green]* -> String
-colorOrOther = \color ->
- when color is
- Red -> "red"
- Green -> "green"
- _ -> "other"
-```
-
-Two things have changed compared to the first example.
-1. The `when color is` now has an extra branch: `_ -> "other"`
-2. Since this branch matches any tag, the type annotation for the `color` argument changed from the closed union `[Red, Green]` to the _open union_ `[Red, Green]*`.
-
-Also like with open records, you can name the type variable in an open tag union. For example:
-
-```coffee
-stopGoOther : [Red, Green]a -> [Stop, Go]a
-stopGoOther = \color ->
- when color is
- Red -> Stop
- Green -> Go
- other -> other
-```
-
-You can read this type annotation as "`stopGoOther` takes either a `Red` tag, a `Green` tag, or some other tag. It returns either a `Stop` tag, a `Go` tag, or any one of the tags it received in its argument."
-
-So let's say you called this `stopGoOther` function passing `Foo "hello"`. Then the `a` type variable would be the closed union `[Foo Str]`, and `stopGoOther` would return a union with the type `[Stop, Go][Foo Str]` - which is equivalent to `[Stop, Go, Foo Str]`.
-
-Just like with records, you can replace the type variable in tag union types with a concrete type.
-For example, `[Foo Str][Bar Bool][Baz (List Str)]` is equivalent to `[Foo Str, Bar Bool, Baz (List Str)]`.
-
-Also just like with records, you can use this to compose tag union type aliases. For example, you can write `NetworkError : [Timeout, Disconnected]` and then `Problem : [InvalidInput, UnknownFormat]NetworkError`.
-
-Note that that a function which accepts an open union does not accept "all possible tags."
-For example, if I have a function `[Ok Str]* -> Bool` and I pass it
-`Ok 5`, that will still be a type mismatch. A `when` on that function's argument might
-have the branch `Ok str ->` which assumes there's a string inside that `Ok`,
-and if `Ok 5` type-checked, then that assumption would be false and things would break!
-
-So `[Ok Str]*` is more restrictive than `[]*`. It's basically saying "this may or may not be an `Ok` tag, but if it _is_ an `Ok` tag, then it's guaranteed to have a payload of exactly `Str`."
-
-> **Note:** As with open and closed records, we can use type annotations to make tag union types less flexible
-> than what the compiler would infer. For example, if we changed the type of the second
-> `colorOrOther` function from the open `[Red, Green]*` to the closed `[Red, Green]`, Roc's compiler
-> would accept it as a valid annotation, but it would give a warning that the `_ -> "other"`
-> branch had become unreachable.
-
-### Phantom Types
-
-[This part of the tutorial has not been written yet. Coming soon!]
-
-### Operator Desugaring Table
-
-Here are various Roc expressions involving operators, and what they desugar to.
-
-| Expression | Desugars to |
-| --------------- | ---------------- |
-| `a + b` | `Num.add a b` |
-| `a - b` | `Num.sub a b` |
-| `a * b` | `Num.mul a b` |
-| `a / b` | `Num.div a b` |
-| `a // b` | `Num.divTrunc a b` |
-| `a ^ b` | `Num.pow a b` |
-| `a % b` | `Num.rem a b` |
-| `a >> b` | `Num.shr a b` |
-| `a << b` | `Num.shl a b` |
-| `-a` | `Num.neg a` |
-| `-f x y` | `Num.neg (f x y)` |
-| `a == b` | `Bool.isEq a b` |
-| `a != b` | `Bool.isNotEq a b` |
-| `a && b` | `Bool.and a b` |
-| `a \|\| b` | `Bool.or a b` |
-| `!a` | `Bool.not a` |
-| `!f x y` | `Bool.not (f x y)` |
-| `a \|> b` | `b a` |
-| `a b c \|> f x y` | `f (a b c) x y` |
diff --git a/ci/benchmarks/prep_folder.sh b/ci/benchmarks/prep_folder.sh
index 926c000cc5..486abe152c 100755
--- a/ci/benchmarks/prep_folder.sh
+++ b/ci/benchmarks/prep_folder.sh
@@ -14,12 +14,10 @@ cd crates/cli && cargo criterion --no-run && cd ../..
mkdir -p bench-folder/crates/cli_testing_examples/benchmarks
mkdir -p bench-folder/crates/compiler/builtins/bitcode/src
mkdir -p bench-folder/target/release/deps
-mkdir -p bench-folder/target/release/lib
cp "crates/cli_testing_examples/benchmarks/"*".roc" bench-folder/crates/cli_testing_examples/benchmarks/
cp -r crates/cli_testing_examples/benchmarks/platform bench-folder/crates/cli_testing_examples/benchmarks/
cp crates/compiler/builtins/bitcode/src/str.zig bench-folder/crates/compiler/builtins/bitcode/src
cp target/release/roc bench-folder/target/release
-cp -r target/release/lib bench-folder/target/release
# copy the most recent time bench to bench-folder
cp target/release/deps/`ls -t target/release/deps/ | grep time_bench | head -n 1` bench-folder/target/release/deps/time_bench
diff --git a/ci/package_release.sh b/ci/package_release.sh
index ff3755f64e..a7ed841e8f 100755
--- a/ci/package_release.sh
+++ b/ci/package_release.sh
@@ -4,5 +4,4 @@
set -euxo pipefail
cp target/release/roc ./roc # to be able to exclude "target" later in the tar command
-cp -r target/release/lib ./lib
-tar -czvf $1 --exclude="target" --exclude="zig-cache" roc lib LICENSE LEGAL_DETAILS examples/helloWorld.roc examples/platform-switching examples/cli crates/roc_std
+tar -czvf $1 --exclude="target" --exclude="zig-cache" roc LICENSE LEGAL_DETAILS examples/helloWorld.roc examples/platform-switching examples/cli crates/roc_std
diff --git a/crates/ast/src/lang/core/def/def.rs b/crates/ast/src/lang/core/def/def.rs
index 14b38b01c2..1510f6b704 100644
--- a/crates/ast/src/lang/core/def/def.rs
+++ b/crates/ast/src/lang/core/def/def.rs
@@ -278,6 +278,7 @@ fn to_pending_def<'a>(
Type(TypeDef::Opaque { .. }) => internal_error!("opaques not implemented"),
Type(TypeDef::Ability { .. }) => todo_abilities!(),
+ Value(AstValueDef::Dbg { .. }) => todo!(),
Value(AstValueDef::Expect { .. }) => todo!(),
Value(AstValueDef::ExpectFx { .. }) => todo!(),
diff --git a/crates/ast/src/lang/core/types.rs b/crates/ast/src/lang/core/types.rs
index 36f8f89490..7ef0b52e51 100644
--- a/crates/ast/src/lang/core/types.rs
+++ b/crates/ast/src/lang/core/types.rs
@@ -405,6 +405,9 @@ pub fn to_type2<'a>(
Type2::Variable(var)
}
+ Tuple { fields: _, ext: _ } => {
+ todo!("tuple type");
+ }
Record { fields, ext, .. } => {
let field_types_map =
can_assigned_fields(env, scope, references, &fields.items, region);
diff --git a/crates/cli/src/build.rs b/crates/cli/src/build.rs
index 36de753bb4..6b8a1c12bc 100644
--- a/crates/cli/src/build.rs
+++ b/crates/cli/src/build.rs
@@ -1,6 +1,9 @@
use bumpalo::Bump;
use roc_build::{
- link::{link, preprocess_host_wasm32, rebuild_host, LinkType, LinkingStrategy},
+ link::{
+ legacy_host_filename, link, preprocess_host_wasm32, preprocessed_host_filename,
+ rebuild_host, LinkType, LinkingStrategy,
+ },
program::{self, CodeGenOptions},
};
use roc_builtins::bitcode;
@@ -106,28 +109,27 @@ pub fn build_file<'a>(
}
};
- use target_lexicon::Architecture;
- let emit_wasm = matches!(target.architecture, Architecture::Wasm32);
-
- // TODO wasm host extension should be something else ideally
- // .bc does not seem to work because
- //
- // > Non-Emscripten WebAssembly hasn't implemented __builtin_return_address
- //
- // and zig does not currently emit `.a` webassembly static libraries
- let (host_extension, app_extension, extension) = {
+ let (app_extension, extension, host_filename) = {
use roc_target::OperatingSystem::*;
match roc_target::OperatingSystem::from(target.operating_system) {
Wasi => {
if matches!(code_gen_options.opt_level, OptLevel::Development) {
- ("wasm", "wasm", Some("wasm"))
+ ("wasm", Some("wasm"), "host.zig".to_string())
} else {
- ("zig", "bc", Some("wasm"))
+ ("bc", Some("wasm"), "host.zig".to_string())
}
}
- Unix => ("o", "o", None),
- Windows => ("obj", "obj", Some("exe")),
+ Unix => (
+ "o",
+ None,
+ legacy_host_filename(target, code_gen_options.opt_level).unwrap(),
+ ),
+ Windows => (
+ "obj",
+ Some("exe"),
+ legacy_host_filename(target, code_gen_options.opt_level).unwrap(),
+ ),
}
};
@@ -140,9 +142,7 @@ pub fn build_file<'a>(
let host_input_path = if let EntryPoint::Executable { platform_path, .. } = &loaded.entry_point
{
- cwd.join(platform_path)
- .with_file_name("host")
- .with_extension(host_extension)
+ cwd.join(platform_path).with_file_name(host_filename)
} else {
unreachable!();
};
@@ -172,23 +172,43 @@ pub fn build_file<'a>(
})
.collect();
- let preprocessed_host_path = if emit_wasm {
- host_input_path.with_file_name("preprocessedhost.o")
+ let preprocessed_host_path = if linking_strategy == LinkingStrategy::Legacy {
+ host_input_path
+ .with_file_name(legacy_host_filename(target, code_gen_options.opt_level).unwrap())
} else {
- host_input_path.with_file_name("preprocessedhost")
+ host_input_path.with_file_name(preprocessed_host_filename(target).unwrap())
};
- let rebuild_thread = spawn_rebuild_thread(
- code_gen_options.opt_level,
- linking_strategy,
- prebuilt,
- host_input_path.clone(),
- preprocessed_host_path.clone(),
- binary_path.clone(),
- target,
- exposed_values,
- exposed_closure_types,
- );
+ // We don't need to spawn a rebuild thread when using a prebuilt host.
+ let rebuild_thread = if prebuilt {
+ if !preprocessed_host_path.exists() {
+ eprintln!(
+ "\nBecause I was run with --prebuilt-platform=true, I was expecting this file to exist:\n\n {}\n\nHowever, it was not there!\n\nIf you have the platform's source code locally, you may be able to regenerate it by re-running this command with --prebuilt-platform=false\n",
+ preprocessed_host_path.to_string_lossy()
+ );
+
+ std::process::exit(1);
+ }
+
+ if linking_strategy == LinkingStrategy::Surgical {
+ // Copy preprocessed host to executable location.
+ // The surgical linker will modify that copy in-place.
+ std::fs::copy(&preprocessed_host_path, binary_path.as_path()).unwrap();
+ }
+
+ None
+ } else {
+ Some(spawn_rebuild_thread(
+ code_gen_options.opt_level,
+ linking_strategy,
+ host_input_path.clone(),
+ preprocessed_host_path.clone(),
+ binary_path.clone(),
+ target,
+ exposed_values,
+ exposed_closure_types,
+ ))
+ };
let buf = &mut String::with_capacity(1024);
@@ -247,19 +267,24 @@ pub fn build_file<'a>(
ConcurrentWithApp(JoinHandle),
}
- let rebuild_timing = if linking_strategy == LinkingStrategy::Additive {
- let rebuild_duration = rebuild_thread
- .join()
- .expect("Failed to (re)build platform.");
- if emit_timings && !prebuilt {
- println!(
- "Finished rebuilding the platform in {} ms\n",
- rebuild_duration
- );
+ let opt_rebuild_timing = if let Some(rebuild_thread) = rebuild_thread {
+ if linking_strategy == LinkingStrategy::Additive {
+ let rebuild_duration = rebuild_thread
+ .join()
+ .expect("Failed to (re)build platform.");
+ if emit_timings && !prebuilt {
+ println!(
+ "Finished rebuilding the platform in {} ms\n",
+ rebuild_duration
+ );
+ }
+
+ Some(HostRebuildTiming::BeforeApp(rebuild_duration))
+ } else {
+ Some(HostRebuildTiming::ConcurrentWithApp(rebuild_thread))
}
- HostRebuildTiming::BeforeApp(rebuild_duration)
} else {
- HostRebuildTiming::ConcurrentWithApp(rebuild_thread)
+ None
};
let (roc_app_bytes, code_gen_timing, expect_metadata) = program::gen_from_mono_module(
@@ -300,7 +325,7 @@ pub fn build_file<'a>(
);
}
- if let HostRebuildTiming::ConcurrentWithApp(thread) = rebuild_timing {
+ if let Some(HostRebuildTiming::ConcurrentWithApp(thread)) = opt_rebuild_timing {
let rebuild_duration = thread.join().expect("Failed to (re)build platform.");
if emit_timings && !prebuilt {
println!(
@@ -361,9 +386,8 @@ pub fn build_file<'a>(
inputs.push(builtins_host_tempfile.path().to_str().unwrap());
}
- let (mut child, _) = // TODO use lld
- link(target, binary_path.clone(), &inputs, link_type)
- .map_err(|_| todo!("gracefully handle `ld` failing to spawn."))?;
+ let (mut child, _) = link(target, binary_path.clone(), &inputs, link_type)
+ .map_err(|_| todo!("gracefully handle `ld` failing to spawn."))?;
let exit_status = child
.wait()
@@ -376,12 +400,10 @@ pub fn build_file<'a>(
if exit_status.success() {
problems
} else {
- let mut problems = problems;
-
- // Add an error for `ld` failing
- problems.errors += 1;
-
- problems
+ todo!(
+ "gracefully handle `ld` (or `zig` in the case of wasm with --optimize) returning exit code {:?}",
+ exit_status.code()
+ );
}
}
};
@@ -406,7 +428,6 @@ pub fn build_file<'a>(
fn spawn_rebuild_thread(
opt_level: OptLevel,
linking_strategy: LinkingStrategy,
- prebuilt: bool,
host_input_path: PathBuf,
preprocessed_host_path: PathBuf,
binary_path: PathBuf,
@@ -416,54 +437,49 @@ fn spawn_rebuild_thread(
) -> std::thread::JoinHandle {
let thread_local_target = target.clone();
std::thread::spawn(move || {
- if !prebuilt {
- // Printing to stderr because we want stdout to contain only the output of the roc program.
- // We are aware of the trade-offs.
- // `cargo run` follows the same approach
- eprintln!("🔨 Rebuilding platform...");
- }
+ // Printing to stderr because we want stdout to contain only the output of the roc program.
+ // We are aware of the trade-offs.
+ // `cargo run` follows the same approach
+ eprintln!("🔨 Rebuilding platform...");
let rebuild_host_start = Instant::now();
- if !prebuilt {
- match linking_strategy {
- LinkingStrategy::Additive => {
- let host_dest = rebuild_host(
- opt_level,
- &thread_local_target,
- host_input_path.as_path(),
- None,
- );
+ match linking_strategy {
+ LinkingStrategy::Additive => {
+ let host_dest = rebuild_host(
+ opt_level,
+ &thread_local_target,
+ host_input_path.as_path(),
+ None,
+ );
- preprocess_host_wasm32(host_dest.as_path(), &preprocessed_host_path);
- }
- LinkingStrategy::Surgical => {
- roc_linker::build_and_preprocess_host(
- opt_level,
- &thread_local_target,
- host_input_path.as_path(),
- preprocessed_host_path.as_path(),
- exported_symbols,
- exported_closure_types,
- );
- }
- LinkingStrategy::Legacy => {
- rebuild_host(
- opt_level,
- &thread_local_target,
- host_input_path.as_path(),
- None,
- );
- }
+ preprocess_host_wasm32(host_dest.as_path(), &preprocessed_host_path);
+ }
+ LinkingStrategy::Surgical => {
+ roc_linker::build_and_preprocess_host(
+ opt_level,
+ &thread_local_target,
+ host_input_path.as_path(),
+ preprocessed_host_path.as_path(),
+ exported_symbols,
+ exported_closure_types,
+ );
+
+ // Copy preprocessed host to executable location.
+ // The surgical linker will modify that copy in-place.
+ std::fs::copy(&preprocessed_host_path, binary_path.as_path()).unwrap();
+ }
+ LinkingStrategy::Legacy => {
+ rebuild_host(
+ opt_level,
+ &thread_local_target,
+ host_input_path.as_path(),
+ None,
+ );
}
}
- if linking_strategy == LinkingStrategy::Surgical {
- // Copy preprocessed host to executable location.
- std::fs::copy(preprocessed_host_path, binary_path.as_path()).unwrap();
- }
- let rebuild_host_end = rebuild_host_start.elapsed();
- rebuild_host_end.as_millis()
+ rebuild_host_start.elapsed().as_millis()
})
}
diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs
index 15eb1b57a5..f4d0fd3969 100644
--- a/crates/cli/src/lib.rs
+++ b/crates/cli/src/lib.rs
@@ -940,7 +940,11 @@ fn roc_dev_native(
expect_metadata: ExpectMetadata,
) -> ! {
use roc_repl_expect::run::ExpectMemory;
- use signal_hook::{consts::signal::SIGCHLD, consts::signal::SIGUSR1, iterator::Signals};
+ use signal_hook::{
+ consts::signal::SIGCHLD,
+ consts::signal::{SIGUSR1, SIGUSR2},
+ iterator::Signals,
+ };
let ExpectMetadata {
mut expectations,
@@ -948,7 +952,7 @@ fn roc_dev_native(
layout_interner,
} = expect_metadata;
- let mut signals = Signals::new(&[SIGCHLD, SIGUSR1]).unwrap();
+ let mut signals = Signals::new(&[SIGCHLD, SIGUSR1, SIGUSR2]).unwrap();
// let shm_name =
let shm_name = format!("/roc_expect_buffer_{}", std::process::id());
@@ -994,6 +998,19 @@ fn roc_dev_native(
)
.unwrap();
}
+ SIGUSR2 => {
+ // this is the signal we use for a dbg
+
+ roc_repl_expect::run::render_dbgs_in_memory(
+ &mut writer,
+ arena,
+ &mut expectations,
+ &interns,
+ &layout_interner,
+ &memory,
+ )
+ .unwrap();
+ }
_ => println!("received signal {}", sig),
}
}
diff --git a/crates/cli/tests/cli_run.rs b/crates/cli/tests/cli_run.rs
index 0b4330dca9..abb58f7a65 100644
--- a/crates/cli/tests/cli_run.rs
+++ b/crates/cli/tests/cli_run.rs
@@ -1056,50 +1056,29 @@ mod cli_run {
&[],
indoc!(
r#"
- ── TYPE MISMATCH ─ ...known_bad/../../../../examples/cli/cli-platform/main.roc ─
+ ── TYPE MISMATCH ─────────────────────────────── tests/known_bad/TypeError.roc ─
- Something is off with the type annotation of the main required symbol:
+ This 2nd argument to attempt has an unexpected type:
- 2│ requires {} { main : InternalProgram }
- ^^^^^^^^^^^^^^^
+ 15│> Task.attempt task /result ->
+ 16│> when result is
+ 17│> Ok {} -> Stdout.line "Done!"
+ 18│> # Type mismatch because the File.readUtf8 error case is not handled
+ 19│> Err {} -> Stdout.line "Problem!"
- This #UserApp.main value is a:
+ The argument is an anonymous function of type:
- Task.Task {} * [Write [Stdout]]
+ [Err {}a, Ok {}] -> Task {} *
- But the type annotation on main says it should be:
+ But attempt needs its 2nd argument to be:
- InternalProgram.InternalProgram
-
- Tip: Type comparisons between an opaque type are only ever equal if
- both types are the same opaque type. Did you mean to create an opaque
- type by wrapping it? If I have an opaque type Age := U32 I can create
- an instance of this opaque type by doing @Age 23.
-
-
- ── TYPE MISMATCH ─ ...known_bad/../../../../examples/cli/cli-platform/main.roc ─
-
- This 1st argument to toEffect has an unexpected type:
-
- 9│ mainForHost = InternalProgram.toEffect main
- ^^^^
-
- This #UserApp.main value is a:
-
- Task.Task {} * [Write [Stdout]]
-
- But toEffect needs its 1st argument to be:
-
- InternalProgram.InternalProgram
-
- Tip: Type comparisons between an opaque type are only ever equal if
- both types are the same opaque type. Did you mean to create an opaque
- type by wrapping it? If I have an opaque type Age := U32 I can create
- an instance of this opaque type by doing @Age 23.
+ Result {} [FileReadErr Path.Path InternalFile.ReadErr,
+ FileReadUtf8Err Path.Path [BadUtf8 Utf8ByteProblem Nat]*]* ->
+ Task {} *
────────────────────────────────────────────────────────────────────────────────
- 2 errors and 1 warning found in ms."#
+ 1 error and 0 warnings found in ms."#
),
);
}
diff --git a/crates/cli/tests/known_bad/TypeError.roc b/crates/cli/tests/known_bad/TypeError.roc
index 0d7e15f6d7..c07a8fb773 100644
--- a/crates/cli/tests/known_bad/TypeError.roc
+++ b/crates/cli/tests/known_bad/TypeError.roc
@@ -1,13 +1,19 @@
app "type-error"
packages { pf: "../../../../examples/cli/cli-platform/main.roc" }
- imports [pf.Stdout.{ line }, pf.Task.{ await }, pf.Program]
+ imports [pf.Stdout.{ line }, pf.Task.{ await }, pf.Path, pf.File]
provides [main] to pf
main =
- _ <- await (line "a")
- _ <- await (line "b")
- _ <- await (line "c")
- _ <- await (line "d")
- line "e"
- # Type mismatch because this line is missing:
- # |> Program.quick
+ task =
+ _ <- await (line "a")
+ _ <- await (line "b")
+ _ <- await (line "c")
+ _ <- await (line "d")
+ _ <- await (File.readUtf8 (Path.fromStr "blah.txt"))
+ line "e"
+
+ Task.attempt task \result ->
+ when result is
+ Ok {} -> Stdout.line "Done!"
+ # Type mismatch because the File.readUtf8 error case is not handled
+ Err {} -> Stdout.line "Problem!"
diff --git a/crates/compiler/alias_analysis/src/lib.rs b/crates/compiler/alias_analysis/src/lib.rs
index d3f91bb538..33a6247843 100644
--- a/crates/compiler/alias_analysis/src/lib.rs
+++ b/crates/compiler/alias_analysis/src/lib.rs
@@ -640,10 +640,13 @@ fn stmt_spec<'a>(
let jpid = env.join_points[id];
builder.add_jump(block, jpid, argument, ret_type_id)
}
- RuntimeError(_) => {
- let type_id = layout_spec(env, builder, interner, layout, &WhenRecursive::Unreachable)?;
+ Crash(msg, _) => {
+ // Model this as a foreign call rather than TERMINATE because
+ // we want ownership of the message.
+ let result_type =
+ layout_spec(env, builder, interner, layout, &WhenRecursive::Unreachable)?;
- builder.add_terminate(block, type_id)
+ builder.add_unknown_with(block, &[env.symbols[msg]], result_type)
}
}
}
diff --git a/crates/compiler/build/Cargo.toml b/crates/compiler/build/Cargo.toml
index ff6ef6d59d..de8e82e4d7 100644
--- a/crates/compiler/build/Cargo.toml
+++ b/crates/compiler/build/Cargo.toml
@@ -31,11 +31,12 @@ roc_utils = { path = "../../utils" }
wasi_libc_sys = { path = "../../wasi-libc-sys" }
+const_format.workspace = true
bumpalo.workspace = true
libloading.workspace = true
tempfile.workspace = true
target-lexicon.workspace = true
-inkwell.workspace = true
+inkwell.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
serde_json = "1.0.85"
diff --git a/crates/compiler/build/src/link.rs b/crates/compiler/build/src/link.rs
index 579d3b75fc..062fcc102f 100644
--- a/crates/compiler/build/src/link.rs
+++ b/crates/compiler/build/src/link.rs
@@ -1,4 +1,5 @@
use crate::target::{arch_str, target_zig_str};
+use const_format::concatcp;
use libloading::{Error, Library};
use roc_builtins::bitcode;
use roc_error_macros::internal_error;
@@ -59,6 +60,86 @@ pub fn link(
}
}
+const fn legacy_host_filename_ext(
+ os: roc_target::OperatingSystem,
+ opt_level: OptLevel,
+) -> &'static str {
+ use roc_target::OperatingSystem::*;
+
+ match os {
+ Wasi => {
+ // TODO wasm host extension should be something else ideally
+ // .bc does not seem to work because
+ //
+ // > Non-Emscripten WebAssembly hasn't implemented __builtin_return_address
+ //
+ // and zig does not currently emit `.a` webassembly static libraries
+ if matches!(opt_level, OptLevel::Development) {
+ "wasm"
+ } else {
+ "zig"
+ }
+ }
+ Unix => "o",
+ Windows => "obj",
+ }
+}
+
+const PRECOMPILED_HOST_EXT: &str = "rh1"; // Short for "roc host version 1" (so we can change format in the future)
+
+pub const fn preprocessed_host_filename(target: &Triple) -> Option<&'static str> {
+ match target {
+ Triple {
+ architecture: Architecture::Wasm32,
+ ..
+ } => Some(concatcp!("wasm32", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Linux,
+ architecture: Architecture::X86_64,
+ ..
+ } => Some(concatcp!("linux-x64", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Linux,
+ architecture: Architecture::Aarch64(_),
+ ..
+ } => Some(concatcp!("linux-arm64", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Darwin,
+ architecture: Architecture::Aarch64(_),
+ ..
+ } => Some(concatcp!("macos-arm64", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Darwin,
+ architecture: Architecture::X86_64,
+ ..
+ } => Some(concatcp!("macos-x64", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Windows,
+ architecture: Architecture::X86_64,
+ ..
+ } => Some(concatcp!("windows-x64", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Windows,
+ architecture: Architecture::X86_32(_),
+ ..
+ } => Some(concatcp!("windows-x86", '.', PRECOMPILED_HOST_EXT)),
+ Triple {
+ operating_system: OperatingSystem::Windows,
+ architecture: Architecture::Aarch64(_),
+ ..
+ } => Some(concatcp!("windows-arm64", '.', PRECOMPILED_HOST_EXT)),
+ _ => None,
+ }
+}
+
+/// Same format as the precompiled host filename, except with a file extension like ".o" or ".obj"
+pub fn legacy_host_filename(target: &Triple, opt_level: OptLevel) -> Option {
+ let os = roc_target::OperatingSystem::from(target.operating_system);
+ let ext = legacy_host_filename_ext(os, opt_level);
+
+ Some(preprocessed_host_filename(target)?.replace(PRECOMPILED_HOST_EXT, ext))
+}
+
fn find_zig_str_path() -> PathBuf {
// First try using the lib path relative to the executable location.
let lib_path_opt = get_lib_path();
@@ -489,6 +570,10 @@ pub fn build_swift_host_native(
.arg("swiftc")
.args(sources)
.arg("-emit-object")
+ // `-module-name host` renames the .o file to "host" - otherwise you get an error like:
+ // error: module name "legacy_macos-arm64" is not a valid identifier; use -module-name flag to specify an alternate name
+ .arg("-module-name")
+ .arg("host")
.arg("-parse-as-library")
.args(["-o", dest]);
@@ -527,26 +612,18 @@ pub fn rebuild_host(
roc_target::OperatingSystem::Wasi => "",
};
- let object_extension = match os {
- roc_target::OperatingSystem::Windows => "obj",
- roc_target::OperatingSystem::Unix => "o",
- roc_target::OperatingSystem::Wasi => "o",
- };
-
let host_dest = if matches!(target.architecture, Architecture::Wasm32) {
if matches!(opt_level, OptLevel::Development) {
- host_input_path.with_file_name("host.o")
+ host_input_path.with_extension("o")
} else {
- host_input_path.with_file_name("host.bc")
+ host_input_path.with_extension("bc")
}
} else if shared_lib_path.is_some() {
host_input_path
.with_file_name("dynhost")
.with_extension(executable_extension)
} else {
- host_input_path
- .with_file_name("host")
- .with_extension(object_extension)
+ host_input_path.with_file_name(legacy_host_filename(target, opt_level).unwrap())
};
let env_path = env::var("PATH").unwrap_or_else(|_| "".to_string());
diff --git a/crates/compiler/builtins/bitcode/src/dec.zig b/crates/compiler/builtins/bitcode/src/dec.zig
index 92738c7351..3910d98a2d 100644
--- a/crates/compiler/builtins/bitcode/src/dec.zig
+++ b/crates/compiler/builtins/bitcode/src/dec.zig
@@ -7,7 +7,7 @@ const math = std.math;
const always_inline = std.builtin.CallOptions.Modifier.always_inline;
const RocStr = str.RocStr;
const WithOverflow = utils.WithOverflow;
-const roc_panic = utils.panic;
+const roc_panic = @import("panic.zig").panic_help;
const U256 = num_.U256;
const mul_u128 = num_.mul_u128;
@@ -233,7 +233,7 @@ pub const RocDec = extern struct {
const answer = RocDec.addWithOverflow(self, other);
if (answer.has_overflowed) {
- roc_panic("Decimal addition overflowed!", 1);
+ roc_panic("Decimal addition overflowed!", 0);
unreachable;
} else {
return answer.value;
@@ -265,7 +265,7 @@ pub const RocDec = extern struct {
const answer = RocDec.subWithOverflow(self, other);
if (answer.has_overflowed) {
- roc_panic("Decimal subtraction overflowed!", 1);
+ roc_panic("Decimal subtraction overflowed!", 0);
unreachable;
} else {
return answer.value;
@@ -329,7 +329,7 @@ pub const RocDec = extern struct {
const answer = RocDec.mulWithOverflow(self, other);
if (answer.has_overflowed) {
- roc_panic("Decimal multiplication overflowed!", 1);
+ roc_panic("Decimal multiplication overflowed!", 0);
unreachable;
} else {
return answer.value;
diff --git a/crates/compiler/builtins/bitcode/src/expect.zig b/crates/compiler/builtins/bitcode/src/expect.zig
index 3e250b5b72..769f54e5b9 100644
--- a/crates/compiler/builtins/bitcode/src/expect.zig
+++ b/crates/compiler/builtins/bitcode/src/expect.zig
@@ -2,6 +2,7 @@ const std = @import("std");
const builtin = @import("builtin");
const SIGUSR1: c_int = if (builtin.os.tag.isDarwin()) 30 else 10;
+const SIGUSR2: c_int = if (builtin.os.tag.isDarwin()) 31 else 12;
const O_RDWR: c_int = 2;
const O_CREAT: c_int = 64;
@@ -87,3 +88,11 @@ pub fn expectFailedFinalize() callconv(.C) void {
_ = roc_send_signal(parent_pid, SIGUSR1);
}
}
+
+pub fn sendDbg() callconv(.C) void {
+ if (builtin.os.tag == .macos or builtin.os.tag == .linux) {
+ const parent_pid = roc_getppid();
+
+ _ = roc_send_signal(parent_pid, SIGUSR2);
+ }
+}
diff --git a/crates/compiler/builtins/bitcode/src/main.zig b/crates/compiler/builtins/bitcode/src/main.zig
index 152284aebc..5b2ebb5bef 100644
--- a/crates/compiler/builtins/bitcode/src/main.zig
+++ b/crates/compiler/builtins/bitcode/src/main.zig
@@ -3,6 +3,7 @@ const builtin = @import("builtin");
const math = std.math;
const utils = @import("utils.zig");
const expect = @import("expect.zig");
+const panic_utils = @import("panic.zig");
const ROC_BUILTINS = "roc_builtins";
const NUM = "num";
@@ -166,12 +167,13 @@ comptime {
exportUtilsFn(utils.decrefCheckNullC, "decref_check_null");
exportUtilsFn(utils.allocateWithRefcountC, "allocate_with_refcount");
- @export(utils.panic, .{ .name = "roc_builtins.utils." ++ "panic", .linkage = .Weak });
+ @export(panic_utils.panic, .{ .name = "roc_builtins.utils." ++ "panic", .linkage = .Weak });
if (builtin.target.cpu.arch != .wasm32) {
exportUtilsFn(expect.expectFailedStartSharedBuffer, "expect_failed_start_shared_buffer");
exportUtilsFn(expect.expectFailedStartSharedFile, "expect_failed_start_shared_file");
exportUtilsFn(expect.expectFailedFinalize, "expect_failed_finalize");
+ exportUtilsFn(expect.sendDbg, "send_dbg");
// sets the buffer used for expect failures
@export(expect.setSharedBuffer, .{ .name = "set_shared_buffer", .linkage = .Weak });
diff --git a/crates/compiler/builtins/bitcode/src/num.zig b/crates/compiler/builtins/bitcode/src/num.zig
index 23670f4142..cb8c2498f2 100644
--- a/crates/compiler/builtins/bitcode/src/num.zig
+++ b/crates/compiler/builtins/bitcode/src/num.zig
@@ -4,7 +4,7 @@ const math = std.math;
const RocList = @import("list.zig").RocList;
const RocStr = @import("str.zig").RocStr;
const WithOverflow = @import("utils.zig").WithOverflow;
-const roc_panic = @import("utils.zig").panic;
+const roc_panic = @import("panic.zig").panic_help;
pub fn NumParseResult(comptime T: type) type {
// on the roc side we sort by alignment; putting the errorcode last
@@ -284,7 +284,7 @@ pub fn exportAddOrPanic(comptime T: type, comptime name: []const u8) void {
fn func(self: T, other: T) callconv(.C) T {
const result = addWithOverflow(T, self, other);
if (result.has_overflowed) {
- roc_panic("integer addition overflowed!", 1);
+ roc_panic("integer addition overflowed!", 0);
unreachable;
} else {
return result.value;
@@ -343,7 +343,7 @@ pub fn exportSubOrPanic(comptime T: type, comptime name: []const u8) void {
fn func(self: T, other: T) callconv(.C) T {
const result = subWithOverflow(T, self, other);
if (result.has_overflowed) {
- roc_panic("integer subtraction overflowed!", 1);
+ roc_panic("integer subtraction overflowed!", 0);
unreachable;
} else {
return result.value;
@@ -451,7 +451,7 @@ pub fn exportMulOrPanic(comptime T: type, comptime W: type, comptime name: []con
fn func(self: T, other: T) callconv(.C) T {
const result = @call(.{ .modifier = always_inline }, mulWithOverflow, .{ T, W, self, other });
if (result.has_overflowed) {
- roc_panic("integer multiplication overflowed!", 1);
+ roc_panic("integer multiplication overflowed!", 0);
unreachable;
} else {
return result.value;
diff --git a/crates/compiler/builtins/bitcode/src/panic.zig b/crates/compiler/builtins/bitcode/src/panic.zig
new file mode 100644
index 0000000000..918f1f0e02
--- /dev/null
+++ b/crates/compiler/builtins/bitcode/src/panic.zig
@@ -0,0 +1,16 @@
+const std = @import("std");
+const RocStr = @import("str.zig").RocStr;
+const always_inline = std.builtin.CallOptions.Modifier.always_inline;
+
+// Signals to the host that the program has panicked
+extern fn roc_panic(msg: *const RocStr, tag_id: u32) callconv(.C) void;
+
+pub fn panic_help(msg: []const u8, tag_id: u32) void {
+ var str = RocStr.init(msg.ptr, msg.len);
+ roc_panic(&str, tag_id);
+}
+
+// must export this explicitly because right now it is not used from zig code
+pub fn panic(msg: *const RocStr, alignment: u32) callconv(.C) void {
+ return @call(.{ .modifier = always_inline }, roc_panic, .{ msg, alignment });
+}
diff --git a/crates/compiler/builtins/bitcode/src/utils.zig b/crates/compiler/builtins/bitcode/src/utils.zig
index 94a6190f8d..c8ab9f0039 100644
--- a/crates/compiler/builtins/bitcode/src/utils.zig
+++ b/crates/compiler/builtins/bitcode/src/utils.zig
@@ -16,9 +16,6 @@ extern fn roc_realloc(c_ptr: *anyopaque, new_size: usize, old_size: usize, align
// This should never be passed a null pointer.
extern fn roc_dealloc(c_ptr: *anyopaque, alignment: u32) callconv(.C) void;
-// Signals to the host that the program has panicked
-extern fn roc_panic(c_ptr: *const anyopaque, tag_id: u32) callconv(.C) void;
-
// should work just like libc memcpy (we can't assume libc is present)
extern fn roc_memcpy(dst: [*]u8, src: [*]u8, size: usize) callconv(.C) void;
@@ -108,11 +105,6 @@ pub fn dealloc(c_ptr: [*]u8, alignment: u32) void {
return @call(.{ .modifier = always_inline }, roc_dealloc, .{ c_ptr, alignment });
}
-// must export this explicitly because right now it is not used from zig code
-pub fn panic(c_ptr: *const anyopaque, alignment: u32) callconv(.C) void {
- return @call(.{ .modifier = always_inline }, roc_panic, .{ c_ptr, alignment });
-}
-
pub fn memcpy(dst: [*]u8, src: [*]u8, size: usize) void {
@call(.{ .modifier = always_inline }, roc_memcpy, .{ dst, src, size });
}
diff --git a/crates/compiler/builtins/roc/Str.roc b/crates/compiler/builtins/roc/Str.roc
index 1ebb83ca0a..0c3adf3352 100644
--- a/crates/compiler/builtins/roc/Str.roc
+++ b/crates/compiler/builtins/roc/Str.roc
@@ -139,58 +139,80 @@ Utf8ByteProblem : [
Utf8Problem : { byteIndex : Nat, problem : Utf8ByteProblem }
-## Returns `Bool.true` if the string is empty, and `Bool.false` otherwise.
+## Returns [Bool.true] if the string is empty, and [Bool.false] otherwise.
##
## expect Str.isEmpty "hi!" == Bool.false
## expect Str.isEmpty "" == Bool.true
isEmpty : Str -> Bool
-## Concatenate two [Str] values together.
+## Concatenates two strings together.
##
-## expect Str.concat "Hello" "World" == "HelloWorld"
+## expect Str.concat "ab" "cd" == "abcd"
+## expect Str.concat "hello" "" == "hello"
+## expect Str.concat "" "" == ""
concat : Str, Str -> Str
-## Returns a [Str] of the specified capacity [Num] without any content
+## Returns a string of the specified capacity without any content.
withCapacity : Nat -> Str
-## Combine a [List] of [Str] into a single [Str], with a separator
-## [Str] in between each.
+## Combines a [List] of strings into a single string, with a separator
+## string in between each.
##
## expect Str.joinWith ["one", "two", "three"] ", " == "one, two, three"
## expect Str.joinWith ["1", "2", "3", "4"] "." == "1.2.3.4"
joinWith : List Str, Str -> Str
-## Split a [Str] around a separator. Passing `""` for the separator is not
-## useful; it returns the original string wrapped in a list. To split a string
+## Split a string around a separator.
+##
+## Passing `""` for the separator is not useful;
+## it returns the original string wrapped in a [List]. To split a string
## into its individual [graphemes](https://stackoverflow.com/a/27331885/4200103), use `Str.graphemes`
##
## expect Str.split "1,2,3" "," == ["1","2","3"]
## expect Str.split "1,2,3" "" == ["1,2,3"]
split : Str, Str -> List Str
-## Repeat a given [Str] value [Nat] times.
+## Repeats a string the given number of times.
##
-## expect Str.repeat ">" 3 == ">>>"
+## expect Str.repeat "z" 3 == "zzz"
+## expect Str.repeat "na" 8 == "nananananananana"
+##
+## Returns `""` when given `""` for the string or `0` for the count.
+##
+## expect Str.repeat "" 10 == ""
+## expect Str.repeat "anything" 0 == ""
repeat : Str, Nat -> Str
-## Count the number of [extended grapheme clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster)
+## Counts the number of [extended grapheme clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster)
## in the string.
##
-## expect Str.countGraphemes "Roc!" == 4
-## expect Str.countGraphemes "七巧板" == 9
-## expect Str.countGraphemes "üïä" == 4
+## Note that the number of extended grapheme clusters can be different from the number
+## of visual glyphs rendered! Consider the following examples:
+##
+## expect Str.countGraphemes "Roc" == 3
+## expect Str.countGraphemes "👩👩👦👦" == 4
+## expect Str.countGraphemes "🕊" == 1
+##
+## Note that "👩👩👦👦" takes up 4 graphemes (even though visually it appears as a single
+## glyph) because under the hood it's represented using an emoji modifier sequence.
+## In contrast, "🕊" only takes up 1 grapheme because under the hood it's represented
+## using a single Unicode code point.
countGraphemes : Str -> Nat
## Split a string into its constituent grapheme clusters
graphemes : Str -> List Str
## If the string begins with a [Unicode code point](http://www.unicode.org/glossary/#code_point)
-## equal to the given [U32], return `Bool.true`. Otherwise return `Bool.false`.
+## equal to the given [U32], returns [Bool.true]. Otherwise returns [Bool.false].
##
-## If the given [Str] is empty, or if the given [U32] is not a valid
-## code point, this will return `Bool.false`.
+## If the given string is empty, or if the given [U32] is not a valid
+## code point, returns [Bool.false].
##
-## **Performance Note:** This runs slightly faster than `Str.startsWith`, so
+## expect Str.startsWithScalar "鹏 means 'roc'" 40527 # "鹏" is Unicode scalar 40527
+## expect !Str.startsWithScalar "9" 9 # the Unicode scalar for "9" is 57, not 9
+## expect !Str.startsWithScalar "" 40527
+##
+## **Performance Note:** This runs slightly faster than [Str.startsWith], so
## if you want to check whether a string begins with something that's representable
## in a single code point, you can use (for example) `Str.startsWithScalar '鹏'`
## instead of `Str.startsWith "鹏"`. ('鹏' evaluates to the [U32] value `40527`.)
@@ -200,26 +222,41 @@ graphemes : Str -> List Str
## You'd need to use `Str.startsWithScalar "🕊"` instead.
startsWithScalar : Str, U32 -> Bool
-## Return a [List] of the [unicode scalar values](https://unicode.org/glossary/#unicode_scalar_value)
-## in the given string. Strings contain only scalar values, not [surrogate code points](https://unicode.org/glossary/#surrogate_code_point),
-## so this is equivalent to returning a list of the string's [code points](https://unicode.org/glossary/#code_point).
+## Returns a [List] of the [Unicode scalar values](https://unicode.org/glossary/#unicode_scalar_value)
+## in the given string.
##
+## (Roc strings contain only scalar values, not [surrogate code points](https://unicode.org/glossary/#surrogate_code_point),
+## so this is equivalent to returning a list of the string's [code points](https://unicode.org/glossary/#code_point).)
+##
+## expect Str.toScalars "Roc" == [82, 111, 99]
+## expect Str.toScalars "鹏" == [40527]
+## expect Str.toScalars "சி" == [2970, 3007]
+## expect Str.toScalars "🐦" == [128038]
+## expect Str.toScalars "👩👩👦👦" == [128105, 8205, 128105, 8205, 128102, 8205, 128102]
## expect Str.toScalars "I ♥ Roc" == [73, 32, 9829, 32, 82, 111, 99]
+## expect Str.toScalars "" == []
toScalars : Str -> List U32
-## Return a [List] of the string's [U8] UTF-8 [code units](https://unicode.org/glossary/#code_unit).
-## To split the string into a [List] of smaller [Str] values instead of [U8] values,
-## see `Str.split`.
+## Returns a [List] of the string's [U8] UTF-8 [code units](https://unicode.org/glossary/#code_unit).
+## (To split the string into a [List] of smaller [Str] values instead of [U8] values,
+## see [Str.split].)
##
+## expect Str.toUtf8 "Roc" == [82, 111, 99]
## expect Str.toUtf8 "鹏" == [233, 185, 143]
+## expect Str.toUtf8 "சி" == [224, 174, 154, 224, 174, 191]
## expect Str.toUtf8 "🐦" == [240, 159, 144, 166]
toUtf8 : Str -> List U8
-## Encode a [List] of [U8] UTF-8 [code units](https://unicode.org/glossary/#code_unit)
-## into a [Str]
+## Converts a [List] of [U8] UTF-8 [code units](https://unicode.org/glossary/#code_unit) to a string.
##
+## Returns `Err` if the given bytes are invalid UTF-8, and returns `Ok ""` when given `[]`.
+##
+## expect Str.fromUtf8 [82, 111, 99] == Ok "Roc"
## expect Str.fromUtf8 [233, 185, 143] == Ok "鹏"
-## expect Str.fromUtf8 [0xb0] == Err (BadUtf8 InvalidStartByte 0)
+## expect Str.fromUtf8 [224, 174, 154, 224, 174, 191] == Ok "சி"
+## expect Str.fromUtf8 [240, 159, 144, 166] == Ok "🐦"
+## expect Str.fromUtf8 [] == Ok ""
+## expect Str.fromUtf8 [255] |> Result.isErr
fromUtf8 : List U8 -> Result Str [BadUtf8 Utf8ByteProblem Nat]
fromUtf8 = \bytes ->
result = fromUtf8RangeLowlevel bytes 0 (List.len bytes)
@@ -673,14 +710,14 @@ walkUtf8WithIndexHelp = \string, state, step, index, length ->
else
state
-## Enlarge the given [Str] for at least capacity additional bytes.
+## Enlarge a string for at least the given number additional bytes.
reserve : Str, Nat -> Str
## is UB when the scalar is invalid
appendScalarUnsafe : Str, U32 -> Str
-## Append a [U32] scalar to the given [Str]. If the given scalar is not a valid
-## unicode value, it will return [Err InvalidScalar].
+## Append a [U32] scalar to the given string. If the given scalar is not a valid
+## unicode value, it returns [Err InvalidScalar].
##
## expect Str.appendScalar "H" 105 == Ok "Hi"
## expect Str.appendScalar "😢" 0xabcdef == Err InvalidScalar
diff --git a/crates/compiler/builtins/src/bitcode.rs b/crates/compiler/builtins/src/bitcode.rs
index 67ee584e9a..1a77570dc1 100644
--- a/crates/compiler/builtins/src/bitcode.rs
+++ b/crates/compiler/builtins/src/bitcode.rs
@@ -426,6 +426,7 @@ pub const UTILS_EXPECT_FAILED_START_SHARED_FILE: &str =
"roc_builtins.utils.expect_failed_start_shared_file";
pub const UTILS_EXPECT_FAILED_FINALIZE: &str = "roc_builtins.utils.expect_failed_finalize";
pub const UTILS_EXPECT_READ_ENV_SHARED_BUFFER: &str = "roc_builtins.utils.read_env_shared_buffer";
+pub const UTILS_SEND_DBG: &str = "roc_builtins.utils.send_dbg";
pub const UTILS_LONGJMP: &str = "longjmp";
pub const UTILS_SETJMP: &str = "setjmp";
diff --git a/crates/compiler/can/src/annotation.rs b/crates/compiler/can/src/annotation.rs
index 15e24ea0fd..a71a2c8f66 100644
--- a/crates/compiler/can/src/annotation.rs
+++ b/crates/compiler/can/src/annotation.rs
@@ -448,6 +448,9 @@ pub fn find_type_def_symbols(
As(actual, _, _) => {
stack.push(&actual.value);
}
+ Tuple { fields: _, ext: _ } => {
+ todo!("find_type_def_symbols: Tuple");
+ }
Record { fields, ext } => {
let mut inner_stack = Vec::with_capacity(fields.items.len());
@@ -869,6 +872,9 @@ fn can_annotation_help(
}
}
+ Tuple { fields: _, ext: _ } => {
+ todo!("tuple");
+ }
Record { fields, ext } => {
let ext_type = can_extension_type(
env,
diff --git a/crates/compiler/can/src/builtins.rs b/crates/compiler/can/src/builtins.rs
index 05688ed656..087bd7e836 100644
--- a/crates/compiler/can/src/builtins.rs
+++ b/crates/compiler/can/src/builtins.rs
@@ -87,6 +87,7 @@ macro_rules! map_symbol_to_lowlevel_and_arity {
LowLevel::PtrCast => unimplemented!(),
LowLevel::RefCountInc => unimplemented!(),
LowLevel::RefCountDec => unimplemented!(),
+ LowLevel::Dbg => unimplemented!(),
// these are not implemented, not sure why
LowLevel::StrFromInt => unimplemented!(),
diff --git a/crates/compiler/can/src/copy.rs b/crates/compiler/can/src/copy.rs
index 71c18ef9dc..83e8ab9d71 100644
--- a/crates/compiler/can/src/copy.rs
+++ b/crates/compiler/can/src/copy.rs
@@ -376,6 +376,10 @@ fn deep_copy_expr_help(env: &mut C, copied: &mut Vec, expr
*called_via,
)
}
+ Crash { msg, ret_var } => Crash {
+ msg: Box::new(msg.map(|m| go_help!(m))),
+ ret_var: sub!(*ret_var),
+ },
RunLowLevel { op, args, ret_var } => RunLowLevel {
op: *op,
args: args
@@ -611,6 +615,18 @@ fn deep_copy_expr_help(env: &mut C, copied: &mut Vec, expr
lookups_in_cond: lookups_in_cond.to_vec(),
},
+ Dbg {
+ loc_condition,
+ loc_continuation,
+ variable,
+ symbol,
+ } => Dbg {
+ loc_condition: Box::new(loc_condition.map(|e| go_help!(e))),
+ loc_continuation: Box::new(loc_continuation.map(|e| go_help!(e))),
+ variable: sub!(*variable),
+ symbol: *symbol,
+ },
+
TypedHole(v) => TypedHole(sub!(*v)),
RuntimeError(err) => RuntimeError(err.clone()),
diff --git a/crates/compiler/can/src/def.rs b/crates/compiler/can/src/def.rs
index b49b888cac..c9b389cee1 100644
--- a/crates/compiler/can/src/def.rs
+++ b/crates/compiler/can/src/def.rs
@@ -88,20 +88,21 @@ pub struct Annotation {
#[derive(Debug)]
pub(crate) struct CanDefs {
defs: Vec
If you'd like to learn more about Roc, you can continue reading here, or check out one of these videos:
Print debugging is the most
+common debugging technique in the history of programming, and Roc has a dbg
+keyword to facilitate it. Here's an example of how to use dbg:
Whenever this dbg line of code is reached, the value of count
+will be printed to stderr,
+along with the source code file and line number where the dbg itself was written:
+[pluralize.roc 6:8] 5
+
+
You can give dbg any expression you like, for example:
+dbg Str.concat singular plural
+
An easy way to print multiple values at a time is to wrap them in a tag, for example
+a concise tag like T:
+
+dbg T "the value of `count` is:" count
+
+
Note that dbg is a debugging tool, and is only available when running
+your program via roc dev, roc run, or roc test. When you
+build a standalone application with roc build, any uses of dbg won't
+be included!
Currently our addAndStringify function takes two arguments. We can instead make
it take one argument like so:
@@ -504,6 +533,25 @@ inside a when, we would write Custom r g b -
Custom description -> description branch, Custom description would be a pattern. In programming, using
patterns in branching conditionals like when is known as pattern matching. You may hear people say things like "let's pattern match on Custom here" as a way to
suggest making a when branch that begins with something like Custom description ->.
+
+when myList is
+ []->0# the list is empty
+ [Foo,..]->1# it starts with a Foo tag
+ [_, ..]->2# it contains at least one element, which we ignore
+ [Foo, Bar, ..]->3# it starts with a Foo tag followed by a Bar tag
+ [Foo, Bar, Baz]->4# it has exactly 3 elements: Foo, Bar, and Baz
+ [Foo, a, ..]->5# its first element is Foo, and its second we name `a`
+ [Ok a, ..]->6# it starts with an Ok containing a payload named `a`
+ [.., Foo]->7# it ends with a Foo tag
+ [A, B, .., C, D]->8# it has certain elements at the beginning and end
+
+
This can be both more concise and more efficient (at runtime) than calling List.get
+multiple times, since each call to get requires a separate conditional to handle the different
+Results they return.
+
+
Note: Each list pattern can only have one .., which is known as the "rest pattern" because it's where the rest of the list goes.
+
Booleans
In many programming languages, true and false are special language keywords that refer to
the two boolean values. In Roc, booleans do not get special keywords; instead, they are exposed
@@ -739,7 +787,7 @@ fullName =\firstName, lastName
Comments can be valuable documentation, but they can also get out of date and become misleading.
If someone changes this function and forgets to update the comment, it will no longer be accurate.
When we have a recurring type annotation like this, it can be nice to give it its own name. We do this like
so:
Musician : { firstName : Str, lastName : Str }
@@ -779,16 +828,8 @@ simone = { firstName:name : Str as "name has the type Str,"
you can also read Musician : { firstName : Str, lastName : Str } as "Musician has the type
{ firstName : Str, lastName : Str }."
-
We can also give type annotations to tag unions:
-colorFromStr : Str-> [Red, Green, Yellow]
-colorFromStr =\string-></span>
- when string is
- "red"-> Red
- "green"-> Green
- _-> Yellow
-
-
You can read the type [Red, Green, Yellow] as "a tag union of the tags Red, Green, and Yellow."
-
When we annotate a list type, we have to specify the type of its elements:
There are some functions that work on any list, regardless of its type parameter. For example, List.isEmpty
has this type:
isEmpty : List * -> Bool
@@ -807,6 +849,7 @@ with any type of List - so, List Str, List Bool<
function that takes a List Bool. We might reasonably expect to be able to pass an empty list (that is, []) to
either of these functions. And so we can! This is because a [] value has the type List * - that is,
"a list with a wildcard type parameter," or "a list whose element type could be anything."
+
List.reverse works similarly to List.isEmpty, but with an important distinction. As with isEmpty, we can
call List.reverse on any list, regardless of its type parameter. However, consider these calls:
strings : List Str
@@ -840,6 +883,46 @@ of the type annotation, or even the function's implementation! The only way to h
List * is if it returns an empty list.
Similarly, the only way to have a function whose type is a -> a is if the function's implementation returns
its argument without modifying it in any way. This is known as the identity function.
Tag union types can accumulate more tags based on how they're used. Consider this if expression:
+\str ->
+ if Str.isEmpty str then
+ Ok "it was empty"
+ else
+ Err ["it was not empty"]
+
+
Here, Roc sees that the first branch has the type [Ok Str] and that the else branch has
+the type [Err (List Str)], so it concludes that the whole if expression evaluates to the
+combination of those two tag unions: [Ok Str, Err (List Str)].
+
This means this entire \str -> … function has the type Str -> [Ok Str, Err (List Str)].
+However, it would be most common to annotate it as Result Str (List Str) instead, because
+the Result type (for operations like Result.withDefault, which we saw earlier) is a type
+alias for a tag union with Ok and Err tags that each have one payload:
+Result ok err :[Ok ok, Err err]
+
+
We just saw how tag unions get combined when different branches of a conditional return different tags. Another way tag unions can get combined is through pattern matching. For example:
+when color is
+ Red ->"red"
+ Yellow ->"yellow"
+ Green ->"green"
+
+
Here, Roc's compiler will infer that color's type is [Red, Yellow, Green], because
+those are the three possibilities this when handles.
Roc has different numeric types that each have different tradeoffs.
They can all be broken down into two categories: fractions,
@@ -993,21 +1076,96 @@ compatible with fractions. For example:
and also Num.cos 1 and have them all work as expected; the number literal 1 has the type
Num *, which is compatible with the more constrained types Int and Frac. For the same reason,
you can pass number literals to functions expecting even more constrained types, like I32 or F64.
-
When writing a number literal in Roc you can specify the numeric type as a suffix of the literal.
-1u8 specifies 1 as an unsigned 8-bit integer, 5i32 specifies 5 as a signed 32-bit integer, etc.
-The full list of possible suffixes includes:
-i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, nat, f32, f64, dec
Integer literals can be written in hexadecimal form by prefixing with 0x followed by hexadecimal characters.
-0xFE evaluates to decimal 254
-The integer type can be specified as a suffix to the hexadecimal literal,
-so 0xC8u8 evaluates to decimal 200 as an unsigned 8-bit integer.
Integer literals can be written in binary form by prefixing with 0b followed by the 1's and 0's representing
-each bit. 0b0000_1000 evaluates to decimal 8
-The integer type can be specified as a suffix to the binary literal,
-so 0b0100u8 evaluates to decimal 4 as an unsigned 8-bit integer.
By default, a number literal with no decimal point has the type Num *—that is,
+we know it's "a number" but nothing more specific. (Number literals with decimal points have the type Frac * instead.)
+
+
You can give a number literal a more specific type by adding the type you want as a lowercase suffix.
+For example, 1u8 specifies 1 with the type U8,
+and 5dec specifies 5 with the type Dec.
Integer literals can be written in hexadecimal
+form by prefixing with 0x followed by hexadecimal characters
+(a - f in addition to 0 - 9).
+For example, writing 0xfe is the same as writing 254. Similarly,
+the prefix 0b specifies binary integers. Writing 0b0000_1000
+is the same as writing 8.
+
Ideally, Roc programs would never crash. However, there are some situations where they may. For example:
+
+
When doing normal integer arithmetic (e.g. x + y) that overflows.
+
When the system runs out of memory.
+
When a variable-length collection (like a List or Str) gets too
+ long to be representible in the operating system's address space.
+ (A 64-bit operating system's address space can represent several
+ exibytes
+ of data, so this case should not come up often.)
+
+
+
Crashes in Roc are not like
+ try/catch exceptions
+found in some other programming languages. There is no way to "catch" a crash. It immediately
+ends the program, and what happens next is defined by the platform. (For example, a command-line
+interface platform might exit with a nonzero exit code,
+whereas a web server platform might have the current request respond with a
+HTTP 500 error.)
You can intentionally crash a Roc program, for example inside a conditional branch that
+you believe is unreachable. Suppose you're certain that a particular List U8
+contains valid UTF-8 bytes, which means when you call Str.fromUtf8 on it, the
+Result it returns will always be Ok. In that scenario, you can use
+the crash keyword to handle the Err case like so:
+answer : Str
+answer =
+ when Str.fromUtf8 definitelyValidUtf8 is
+ Ok str -> str
+ Err _ ->crash"This should never happen!"
+
+
If the unthinkable happens, and somehow the program reaches this Err branch even though that
+was thought to be impossible, then it will crash - just like if the system had run out of memory.
+The string passed to crash will be provided to the platform as context; each platform may do
+something different with it.
+
+
Note:crash is a language keyword and not a function; you can't assign crash to a variable
+or pass it to a function.
The reason Roc has a crash keyword is for scenarios where it's expected that no error
+ will ever happen (like in unreachable branches),
+ or where graceful error handling is infeasible (like running out of memory).
+
+
Errors that are recoverable should be represented using normal Roc types (
+ like Result)
+ and then handled without crashing—for example, by having the application
+ report that something went wrong, and then continue running from there.
+
If you put this in a file named main.roc and run roc test, Roc will execute the two expect
expressions (that is, the two pluralize calls) and report any that returned false.
if count ==1 then
"\(countStr)\(singular)"
@@ -1045,19 +1203,6 @@ control flow. In fact, if you do roc build, they are not even inclu
If you try this code out, you may note that when an expect fails (either a top-level or inline
one), the failure message includes the values of any named variables - such as count here.
This leads to a useful technique, which we will see next.
An age-old debugging technique is printing out a variable to the terminal. In Roc you can use
-expect to do this. Here's an example:
-\arg ->
- x = arg - 1
-
- # Reports the value of `x` without stopping the program
- expect x != x
-
- Num.abs x
-
-
The failure output will include both the value of x as well as the comment immediately above it,
-which lets you use that comment for extra context in your output.