core
Stopping a program with a clear message, and Option for a value that may or may not be there.
import core
The core package has exactly one function, but an important one. Sometimes a program reaches a point where carrying on makes no sense: data is corrupt, or a condition that "can never happen" has happened. In that case it is better to stop right there with a clear message than to quietly hand back a wrong answer.
For ordinary errors, such as bad input from a user, declare the function throws and throw an Error instead, so that the caller decides what to do with try and catch. A panic is for when there is no correct way to continue, and catch does not stop it.
core also defines the built-in error types, Error and ErrorKind, which every program can use without an import. The error package explains how to throw, pass on and catch them.
Guarding an invariant
An invariant is something your own code promises is always true: a balance never drops below zero, a list stays sorted, an index stays in range. Checks for ordinary, expected failures return a value the caller can act on. A check for a broken invariant calls Panic, because if it fails the bug is in the program itself and any result computed after that point would be wrong.
import core
struct Account:
pub owner: str = ""
pub balance: int = 0
end
func withdraw(acc &: Account, amount: int): bool:
if amount > acc.balance:
ret false
end
acc.balance -= amount
if acc.balance < 0:
core.Panic("balance went negative for " + acc.owner)
end
ret true
end
func main:
mut acc := Account { owner = "Sara", balance = 100 }
println withdraw(acc, 30), acc.balance
println withdraw(acc, 500), acc.balance
println withdraw(acc, 70), acc.balance
endAsking for more money than the account holds is an ordinary situation, so withdraw answers false. The Panic after the subtraction can only run if someone later changes the function and breaks it; it is there so that mistake shows up at once, with the owner's name in the message, instead of as a strange number weeks later.
Marking code that should never run
A function that must return a value for every input still needs something at the end, after all the known cases. When the remaining inputs are impossible by design, a Panic with the bad value in the message is the honest way to finish it. A made up return value, such as an empty string, would hide the bug and let it travel further.
import core
func next_light(light: str): str:
switch light:
"red":
ret "green"
end
"green":
ret "yellow"
end
"yellow":
ret "red"
end
end
core.Panic("unknown light: " + light)
end
func main:
mut light := "red"
repeat 4:
nxt := next_light(light)
println light, "->", nxt
light = nxt
end
endBecause Panic never returns, the compiler accepts it as the last statement of a function with a result type. Put the unexpected value into the message: unknown light: blue tells you far more than unreachable.
When the cases are the members of an enum, prefer match: it must cover every member, so the compiler finds the missing case for you and no Panic is needed.
Panic, or a value that reports failure?
The two work together. Anything that comes from outside the program, such as user input, files, the network or another service, can be wrong in normal operation, so make the function throws and let the caller decide with try and catch, or return a value that carries the failure, such as an enum you declare yourself with an Err case, or the ? operator on one. Once the value has been checked, inner functions may treat a bad value as a programming error and panic.
import core
enum Result<T, E>:
Ok(value: T)
Err(error: E)
end
func parse_percent(text: str): Result<int, str>:
n := text.ToInt()
if n < 0 or n > 100:
ret Result.Err("a percentage must be between 0 and 100, got " + text)
end
ret Result.Ok(n)
end
func apply_discount(price: int, percent: int): int:
if percent < 0 or percent > 100:
core.Panic("apply_discount called with " + percent)
end
ret price - price * percent / 100
end
func main:
each typed in ["20", "250"]:
r := parse_percent(typed)
match r:
Ok(p): println "price after discount:", apply_discount(80, p) end
Err(msg): println "rejected:", msg end
end
end
end| Situation | Use |
|---|---|
| The user typed something invalid | throws and throw an Error |
| A file or server is missing | throws, or the Error out-parameter of that package |
| A value may be absent | Option, below, or a field written T? |
| Your own code broke a rule it promised to keep | Panic |
| A case that cannot happen by design | Panic, or match on an enum |
What a panic does
- It writes
salam panic:and your message to standard error, then calls the Cabort. The process ends with signalSIGABRT, which a shell reports as exit status 134, and the system may write a core dump. deferstatements do not run, so open files are not flushed and temporary files stay behind.- Text the program printed before the panic is written out first, even when standard output is a pipe or a file and
printlnwas still holding it in its buffer, so the panic message comes after the last printed line. - In a server, one bad request that panics takes down every other request too.
That is the main reason to keep Panic for real bugs only.
Option: a value that may or may not be there
Sometimes the answer from a function is "nothing": a search found no match, or a setting was never given. Returning minus one or an empty string for that is convenient, and later forgotten, and then it is a bug. Option<T> makes it explicit: either there is a value of type T, or there is not. T? is short for core.Option<T> and needs no import: a field written timeout: int? may be left out of a literal, plain values wrap on their own, and null means empty. See optional fields.
Optionis a plain struct with two fields,valueandpresent, not an enum: test it withis_some()or.present, not withmatch, and the?try-operator does not work on it.- Never read
.valuebefore checking. On an empty option it is the zero value ofT: 0 for numbers, but for astrit is a null pointer, and printing or measuring it crashes the program. - Build options only with
SomeandNone(or plain assignment andnullthroughT?), so the two fields always agree. - The free functions
Some,None,IsSome,IsNone,UnwrapOr,UnwrapandExpectneedimport coreand thecore.prefix; the methodsis_some(),is_none(),unwrap_or(x)andunwrap()on a value already typedT?need neither.
A lookup that may find nothing
Looking something up is the classic case for an option. Returning an empty string for a missing phone number would be ambiguous, since an empty value could also be stored on purpose. A function that returns str? says plainly in its signature that the answer may be missing, and every caller has to deal with that.
func phone_of(book: HashMap<str, str>, name: str): str?:
if book.Has(name):
ret book.Get(name)
end
ret null
end
func main:
mut book := HashMap {} as HashMap<str, str>
defer book.Free()
book.Put("Sara", "0912 111 2233")
book.Put("Omid", "0935 444 5566")
each name in ["Omid", "Neda"]:
p := phone_of(book, name)
if p.is_some():
println name + ":", p.value
else:
println name + ": no number on file"
end
end
println "call", phone_of(book, "Neda").unwrap_or("the front desk")
endis_some() followed by .value suits code that does two different things. When there is a sensible default, unwrap_or does the check and the fallback in one call, as the last line shows.
Optional settings with defaults
An optional field tells "not given" apart from a real zero or an empty string, which a plain int field cannot. Give each optional field null as its default, so a struct literal can leave it out, and apply the real default at the point of use.
struct Settings:
pub width: int? = null
pub title: str? = null
end
func describe(s: Settings): str:
w := s.width.unwrap_or(80)
t := s.title.unwrap_or("untitled")
ret t + " (" + w + " columns)"
end
func main:
println describe(Settings {})
println describe(Settings { width = 120 })
println describe(Settings { width = 0, title = "report" })
endThe third line shows why this matters: a width of 0 was given on purpose and is kept, while the first two fall back to 80.
Searching a list of structs
A search over a vector returns the first match or nothing. Here the program knows an open task must exist at that moment, so it uses core.Expect: if the assumption is ever wrong, the program stops with that sentence rather than carrying on with an empty name.
import core
struct Task:
pub name: str = ""
pub done: bool = false
end
func first_open(tasks: Vector<Task>): str?:
each t in tasks:
if not t.done:
ret t.name
end
end
ret null
end
func main:
mut tasks := Vector {} as Vector<Task>
defer tasks.Free()
tasks.Push(Task { name = "write tests", done = true })
tasks.Push(Task { name = "fix login bug" })
tasks.Push(Task { name = "update docs" })
next := first_open(tasks)
println "next up:", core.Expect(next, "there is always an open task here")
each i, t in tasks:
tasks.Set(i, Task { name = t.name, done = true })
end
println "anything left?", first_open(tasks).is_some()
endcore.Unwrap stops with a generic message when the option is empty. Prefer core.Expect, whose message tells the reader which assumption failed, and keep it for assumptions that would be a bug in your own program, the same rule as Panic above. When the caller needs to know why something failed rather than just that a value is missing, make the function throws instead, or declare your own enum with an Err case.
Types
ErrorKind
enum ErrorKind| Name | Type | Description |
|---|---|---|
Other | | Any error that fits none of the other kinds. A throw "message" gets this kind. |
Syntax | | The input does not follow its format, such as a missing comma in JSON. |
UnexpectedEnd | | The input ended in the middle of a value. |
TypeMismatch | | A value has another type than the one asked for. |
MissingKey | | A required key or field is not there. |
OutOfRange | | A number, index or size is outside the allowed range. |
InvalidUtf8 | | Text is not valid UTF-8. |
InvalidArgument | | The caller passed a value the function cannot accept. |
NotFound | | What was asked for does not exist. |
AlreadyExists | | Something that should be new is already there. |
PermissionDenied | | The operation is not allowed. |
Io | | A read or write failed; trying again may work. |
Timeout | | Time ran out; trying again may work. |
Canceled | | The work was stopped on purpose. |
Unavailable | | A service is unavailable for now; trying again may work. |
Unsupported | | The input or the request uses something that is not supported. |
Internal | | A fault inside the program itself. |
func retryable(e: Error): bool:
ret e.is(ErrorKind.Io) or e.is(ErrorKind.Timeout) or e.is(ErrorKind.Unavailable)
end
func main:
kinds := [ErrorKind.Io, ErrorKind.Timeout, ErrorKind.Unavailable, ErrorKind.NotFound, ErrorKind.PermissionDenied, ErrorKind.Internal]
each kind in kinds:
e := Error.New(kind, "failed")
if retryable(e):
println e.kind_name() + ": try again"
else:
println e.kind_name() + ": give up"
end
end
endError
struct Errorthrow sends and catch receives. It holds only text and numbers, so copying it is cheap and safe.| Name | Type | Description |
|---|---|---|
kind | ErrorKind | The general category, one of ErrorKind. |
code | str = "" | A precise code chosen by the package that threw the error, such as json.trailing_data; empty when there is none. |
message | str = "" | What went wrong, for a person to read. |
context | str = "" | The explanations added by wrap, outermost first, joined with ": ". |
path | str = "" | Where in the data the problem is, such as $.users[3].age, or a file path; empty when unknown. |
offset | int = -1 | The byte offset of the problem in the input, or -1 when unknown. |
line | int = 0 | The line of the problem, counting from 1, or 0 when unknown. |
column | int = 0 | The column of the problem, counting from 1, or 0 when unknown. |
func parse age(text: str): int throws:
if text == "":
throw Error.New(ErrorKind.MissingKey, "the age is missing")
end
n := text.ToInt()
if n < 0 or n > 150:
throw Error.New(ErrorKind.OutOfRange, "the age " + n + " is out of range").with_code("age.range")
end
ret n
end
func main:
each text in ["42", "", "200"]:
try:
println "age", parse age(text)
catch e:
println e.kind_name() + ":", e.message
println " code:", e.code, "| out of range:", e.is(ErrorKind.OutOfRange)
end
end
e := Error.At(ErrorKind.Syntax, "expected a digit", 4).with_path("$.age")
println e.ToStr()
placed := e.with_position(4, 2, 3).wrap("reading the form")
println placed.ToStr()
println placed.offset, placed.line, placed.column, placed.context
endIs
func Is(kind: ErrorKind): boolis
func is(kind: ErrorKind): boolfunc read note(name: str): str throws:
if name == "":
throw Error.New(ErrorKind.InvalidArgument, "the name is empty")
end
if name != "notes.txt":
throw Error.New(ErrorKind.NotFound, name + " does not exist")
end
ret "contents of " + name
end
func main:
each name in ["notes.txt", "todo.txt", ""]:
try:
println read note(name)
catch e:
if e.is(ErrorKind.NotFound):
println "create it first:", e.message
else:
println "cannot go on:", e.message
end
end
end
endWrap
func Wrap(message: str): Errorwrap
func wrap(message: str): Errorfunc read port(text: str): int throws:
n := text.ToInt()
if n < 1 or n > 65535:
throw Error.New(ErrorKind.OutOfRange, "port " + n + " is not valid")
end
ret n
end
func load config(text: str): int throws:
try:
ret read port(text)
catch e:
throw e.wrap("reading the port")
end
end
func main:
try:
println load config("80")
println load config("70000")
catch e:
println e.ToStr()
println "context:", e.context
println "kind:", e.kind_name()
end
endWithCode
func WithCode(code: str): Errorwith_code
func with_code(code: str): Errorfunc parse age(text: str): int throws:
n := text.ToInt()
if n < 0 or n > 150:
throw Error.New(ErrorKind.OutOfRange, "the age " + n + " is out of range").with_code("age.range")
end
ret n
end
func main:
each text in ["30", "200"]:
try:
println "age", parse age(text)
catch e:
if e.code == "age.range":
println "ask again:", e.message
end
println "code:", e.code
end
end
endWithPath
func WithPath(path: str): Errorwith_path
func with_path(path: str): Errorfunc check(user: str, age: int): int throws:
if age < 18:
throw Error.New(ErrorKind.OutOfRange, "must be at least 18").with_path("$.users[" + user + "].age")
end
ret age
end
func main:
try:
println check("sara", 31)
println check("omid", 12)
catch e:
println e.ToStr()
println "where:", e.path
end
endWithPosition
func WithPosition(offset: int, line: int, column: int): Errorwith_position
func with_position(offset: int, line: int, column: int): Errorfunc main:
text := "name = Sara\nage = ?\n"
offset := text.Find("?")
line start := text.Find("age")
column := offset - line start + 1
e := Error.New(ErrorKind.Syntax, "a number was expected").with_position(offset, 2, column)
println e.ToStr()
println e.offset, e.line, e.column
endLocate
func Locate(text: str): Errorlocate
func locate(text: str): Errorline and column worked out from offset in the given text, the input the error was found in. Lines and columns count from 1 and a column counts characters, not bytes. An error with no offset comes back unchanged.func main:
text := "name = shop\nport = eighty\n"
e := Error.At(ErrorKind.Syntax, "expected a number", 19)
println e.line, e.column
found := e.locate(text)
println found.line, found.column
println found.ToStr()
endKindName
func KindName(): strkind_name
func kind_name(): strfunc main:
each kind in [ErrorKind.NotFound, ErrorKind.OutOfRange, ErrorKind.Timeout, ErrorKind.PermissionDenied, ErrorKind.Other]:
e := Error.New(kind, "details")
println e.kind_name()
end
endToStr
func ToStr(): strto_str
func to_str(): strprintln uses it too.func main:
plain := Error.New(ErrorKind.Timeout, "the server did not answer")
println plain.ToStr()
bare := Error.New(ErrorKind.NotFound, "")
println bare.ToStr()
located := Error.New(ErrorKind.Syntax, "a comma is missing").with_path("$.items[2]").with_position(40, 3, 9)
println located.ToStr()
wrapped := located.wrap("reading the order").wrap("handling the request")
println wrapped.ToStr()
endNew
static func New(kind: ErrorKind, message: str): Errorthrow.func find user(id: int): str throws:
if id != 1:
throw Error.New(ErrorKind.NotFound, "no user with id " + id)
end
ret "Sara"
end
func main:
each id in [1, 7]:
try:
println "found", find user(id)
catch e:
println e.kind_name() + ":", e.message
end
end
endAt
static func At(kind: ErrorKind, message: str, offset: int): ErrorNew, and also records the byte offset in the input where the problem is.func digit(text: str, at: int): int throws:
c := text.Substr(at, 1)
if c < "0" or c > "9":
throw Error.At(ErrorKind.Syntax, "a digit was expected", at)
end
ret c.ToInt()
end
func main:
text := "12x4"
repeat text.Len() in i:
try:
println "digit", digit(text, i)
catch e:
println e.ToStr()
println "offset", e.offset
end
end
endThrows
type Throws = Variant<auto<T>, auto<T>>throws function returns under the hood. You never write it: try and catch take it apart for you.Tuple2
struct Tuple2<A, B>(A, B): two values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
Tuple3
struct Tuple3<A, B, C>(A, B, C): three values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
f2 | C | The third element, also written t.2. |
Tuple4
struct Tuple4<A, B, C, D>(A, B, C, D): four values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
f2 | C | The third element, also written t.2. |
f3 | D | The fourth element, also written t.3. |
Tuple5
struct Tuple5<A, B, C, D, E>(A, B, C, D, E): five values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
f2 | C | The third element, also written t.2. |
f3 | D | The fourth element, also written t.3. |
f4 | E | The fifth element, also written t.4. |
Tuple6
struct Tuple6<A, B, C, D, E, F>(A, B, C, D, E, F): six values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
f2 | C | The third element, also written t.2. |
f3 | D | The fourth element, also written t.3. |
f4 | E | The fifth element, also written t.4. |
f5 | F | The sixth element, also written t.5. |
Tuple7
struct Tuple7<A, B, C, D, E, F, G>(A, B, C, D, E, F, G): seven values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
f2 | C | The third element, also written t.2. |
f3 | D | The fourth element, also written t.3. |
f4 | E | The fifth element, also written t.4. |
f5 | F | The sixth element, also written t.5. |
f6 | G | The seventh element, also written t.6. |
Tuple8
struct Tuple8<A, B, C, D, E, F, G, H>(A, B, C, D, E, F, G, H): eight values kept together. You never write the name: (int, str) is this struct, ret a, b builds one and x, y := f() takes it apart.| Name | Type | Description |
|---|---|---|
f0 | A | The first element, also written t.0. |
f1 | B | The second element, also written t.1. |
f2 | C | The third element, also written t.2. |
f3 | D | The fourth element, also written t.3. |
f4 | E | The fifth element, also written t.4. |
f5 | F | The sixth element, also written t.5. |
f6 | G | The seventh element, also written t.6. |
f7 | H | The eighth element, also written t.7. |
Option
struct Option<T>Some or None, so that the two fields always agree. Usually written T?.| Name | Type | Description |
|---|---|---|
value | T | The value itself. When present is false this is the zero value of T; for a str that is a null pointer that crashes when used, so check present first. |
present | bool | True when there is a value. |
import core
func search(names: Vector<str>, wanted: str): core.Option<int>:
each i, name in names:
if name == wanted:
ret core.Some(i)
end
end
ret core.None()
end
func main:
mut names := Vector {} as Vector<str>
defer names.Free()
names.Push("Ali")
names.Push("Maryam")
found := search(names, "Maryam")
missing := search(names, "Reza")
println core.IsSome(found), core.IsNone(found), found.value, found.present
println core.IsSome(missing), core.IsNone(missing)
println core.Unwrap(found), core.Expect(found, "this should have been found")
println core.UnwrapOr(missing, -1)
endIsSome
func IsSome(): boolis_some
func is_some(): boolIsSome: true when there is a value.struct Client:
pub timeout: int?
end
func main:
a := Client { }
b := Client { timeout = 30 }
println a.timeout.is_some(), a.timeout.is_none(), a.timeout.unwrap_or(5)
println b.timeout.is_some(), b.timeout.is_none(), b.timeout.unwrap_or(5), b.timeout.unwrap()
endIsNone
func IsNone(): boolis_none
func is_none(): boolIsNone: true when it is empty.The example for this item is shown with the ones above: core-Methods.salam
UnwrapOr
func UnwrapOr(fallback: T): Tunwrap_or
func unwrap_or(fallback: T): TUnwrapOr: the value, or the fallback you supply when it is empty.The example for this item is shown with the ones above: core-Methods.salam
Unwrap
func Unwrap(): Tunwrap
func unwrap(): TUnwrap: the value, or a panic when it is empty.The example for this item is shown with the ones above: core-Methods.salam
Functions
Panic
func Panic(msg: str)salam panic: and the message to standard error and aborts the process (exit status 134). It never returns and defer statements do not run; standard output the program printed before it is written out first. The example below is not run here, because it deliberately kills the program; its output looks like salam panic: cannot divide by zero.import core
func divide(a: int, b: int): int:
if b == 0:
core.Panic("cannot divide by zero")
end
ret a / b
end
func main:
println divide(10, 2)
println divide(1, 0)
endSome
func Some<T>(x: T): Option<T>The example for this item is shown with the ones above: core-Option.salam
None
func None<T>(): Option<T>T comes from where the value is used, such as the return type of the function.The example for this item is shown with the ones above: core-Option.salam
IsSome
func IsSome<T>(o: Option<T>): boolThe example for this item is shown with the ones above: core-Option.salam
IsNone
func IsNone<T>(o: Option<T>): boolThe example for this item is shown with the ones above: core-Option.salam
UnwrapOr
func UnwrapOr<T>(o: Option<T>, fallback: T): TThe example for this item is shown with the ones above: core-Option.salam
Expect
func Expect<T>(o: Option<T>, msg: str): TUnwrap, but stops with a message of your own when the option is empty; a good message makes the problem easy to find.The example for this item is shown with the ones above: core-Option.salam
Unwrap
func Unwrap<T>(o: Option<T>): Tcalled Unwrap on a None value.The example for this item is shown with the ones above: core-Option.salam