Lesson 19 of 49 · Larger programs

What the compiler insists on

The Salam compiler catches a great many mistakes before the program ever runs. Every message says what is wrong, where, and usually how to fix it. This lesson goes through the rules behind the messages you will meet most.

Why so strict?

Every error the compiler catches is an error that never reaches a user. That is why Salam treats as errors several things that other languages only warn about: a variable nobody reads, a mut that never changes, a branch that can never run. Warnings tend to pile up and get ignored; an error is fixed on the spot, so a Salam program that compiles has no such leftovers in it.

Reading an error

A typical message looks like this:

[SEMANTIC][ERROR] E013: cannot reassign immutable variable 'total'; declare it 'mut' to reassign it, or assign to its elements or fields instead (app.salam:3:5)

  • E013 is the error code. It is the same in English and Persian, so it is the thing to search for.
  • Then comes the problem, and after the semicolon the usual fix. Read the message to the end; the fix is often all you need.
  • The end of the line gives the file, line and column: line 3, column 5 of app.salam.

Mistakes in the shape of the code, such as a missing end or a word that is not Salam, are reported by the parser instead. Those show the line itself with a caret under the spot, and often a help: line, for example error: '&&' is not a Salam operator; write 'and'. A Persian file gets its messages in Persian.

Fix the first error first. One mistake can cause others further down: misspell a name, and the compiler reports both the unknown name (E001) and the variable you meant, which is now unused (E059).

Nothing unused

A variable, parameter, private function or import that nothing uses is an error: E059, E062, E066 and E082. Usually the right fix is to delete it, or to notice that you forgot to use it. Starting the name with _ silences the error, but keep that for the one real case: a signature you do not control. Here every handler must take a user and a text, and Shout has no use for the user:

rules-unused.salam
interface Handler:
    func handle(user: str, text: str): str
end

struct Echo:
    pub func handle(user: str, text: str): str:
        ret user + " said " + text
    end
end

struct Shout:
    pub func handle(_user: str, text: str): str:
        ret text + "!"
    end
end

func run(h: dyn Handler):
    println h.handle("sara", "hello")
end

func main:
    run(Echo {})
    run(Shout {})
end
Outputsara said hello hello!

Without the _, the compiler would say E062: unused parameter 'user', and its message itself says to use _ only when the signature is fixed.

mut only where things change

A variable made with := cannot be reassigned (E013). Add mut when it must change, and only then: a mut that never changes is also an error (E069). Adding to a Vector or a HashMap changes the data it points to, not the variable, so push works without mut. A value fixed for the whole program is a const.

rules-mut.salam
const LIMIT := 3

func main:
    names := Vector {} as Vector<str>
    defer names.Free()
    names.Push("Sara")
    names.Push("Reza")
    names.Push("Mina")
    names.Push("Ali")
    mut shown := 0
    each n in names:
        if shown == LIMIT:
            break
        end
        println n
        shown++
    end
    println shown, "of", names.Len(), "shown"
end
OutputSara Reza Mina 3 of 4 shown

Types are never guessed

Salam does not convert between types behind your back. Putting a str where an int belongs is E002 in an assignment and E012 in a call, and a condition must be a real bool: if items: with a number is E021, so write if items > 0:. The two branches of ?: must have the same type. Convert explicitly with as, but not when the value already has that type: n as int on an int is a useless cast, E093.

Every path is checked

The compiler follows every path through a function. A function that returns a value must return it on every path (E071: function 'sign' can fall off its end), a match on an enum must cover every member or have an else (E080 names the missing ones), and code after a ret can never run (E070). The same goes for a condition that is always false (E068), an empty if branch (E060) and a statement whose value is thrown away, like n + 1 on its own line (E110).

rules-flow.salam
enum Light: Red, Yellow, Green end

func action(l: Light): str:
    ret match l:
        Red: "stop" end
        Yellow: "slow down" end
        Green: "go" end
    end
end

func sign(n: int): str:
    if n > 0:
        ret "positive"
    else n < 0:
        ret "negative"
    end
    ret "zero"
end

func main:
    println action(Light.Yellow), action(Light.Green)
    println sign(-4), sign(0), sign(9)
end
Outputslow down go negative zero positive

When a new member is added to Light later, every match that does not handle it stops compiling, which is exactly where you need to look.

Values are checked before the program runs

The compiler also follows the values that move through a function: what a counter is on each pass of a loop, how many items a Vector holds after its pushes, whether a pointer can still be null. When a line is certain to go wrong, the build stops with an error that names the value: an index past the end (E146: index out of bounds: 'i' is 3, but 'xs' has 3 elements (on pass 4 of the loop on line 3)), a signed number that overflows its type (E148), a division by a value that is 0 (E150) or a read through a null pointer (E152). When it goes wrong only for some values, you get a warning instead (W147, W149, W151, W153), and a check such as if i < xs.len(): before the line is enough to silence it. Values the compiler cannot see, such as a parameter or what a function returns, are never guessed at.

One case worth remembering: repeat 0 to n in i: counts up to and including n, so repeat 0 to xs.len() in i: reads one item past the end. Count with repeat xs.len() in i: or each i, x in xs: instead.

Errors with throw, try and catch, and main's exit code

A function that can fail says so in its signature: throws after the return type. It fails with throw, which takes an Error (or just a message). Every call to such a function is marked: try in front of the call passes the error on to the caller, which then has to be throws as well; a try: ... catch e: ... end block handles it, and the calls inside need no mark. try f() catch value gives a fallback instead. Nothing is hidden: you can see on every line where an error can come from, and defer still runs when one passes through.

rules-exit.salam
func parse age(text: str): int throws:
    n := text.ToInt()
    if n <= 0 or n > 150:
        throw Error.New(ErrorKind.OutOfRange, "'" + text + "' is not an age")
    end
    ret n
end

func oldest(texts: Vector<str>): int throws:
    mut best := 0
    each text in texts:
        age := try parse age(text)
        if age > best:
            best = age
        end
    end
    ret best
end

func main:
    each text in ["42", "abc"]:
        try:
            println text, "is a valid age:", parse age(text)
        catch e:
            println e.message
        end
    end
    fallback := try parse age("900") catch 18
    println "with a fallback:", fallback
    mut texts := Vector {} as Vector<str>
    texts.Push("30")
    texts.Push("45")
    try:
        println "oldest:", oldest(texts)
    catch e:
        printerrln "no oldest age:", e.message
        ret 1
    end
end
Output42 is a valid age: 42 'abc' is not an age with a fallback: 18 oldest: 45

Forgetting the mark is a compile error, E155, and try in a function that is not throws is E156. A bug such as an index out of bounds is not an error value: it stops the program, and catch does not see it. The error package lists the kinds of errors and what an Error carries.

The value main returns is the program's exit code: ret 1 reports failure to the shell, and no ret means 0. Calling os.Exit inside main is E109, because it would skip the cleanup that main deferred.

The errors you will meet most

CodeWhat you wroteWhat the compiler saysThe fix
E001A misspelled nameunknown identifier 'cuont'Correct the spelling
E002number = "five"cannot assign 'str' to 'i32'Use the right type, or convert with as
E012twice("4"), add(1)argument 1: cannot pass 'str' to 'i32'; 'add' expects 2 arguments, got 1Match the function's parameters
E013total := 0 then total = 5cannot reassign immutable variable 'total'Declare it with mut
E017name.shout(), a.balancestr has no method 'shout'; field 'balance' is private in struct 'Account'Call a method that exists, or make the member pub
E021if items:if condition must be bool, got 'i32'Write a comparison: if items > 0:
E059number := 5, never readunused variable 'number'Use it or remove it
E060An if with an empty bodythe 'if' branch is emptyFill it, or negate the condition with not
E062A parameter the body never readsunused parameter 'h'Remove it, or use _ for a fixed signature
E066A private function nothing callsunused function 'helper'Call it or remove it
E068if false:'if' condition is always false: its body can never runRemove the dead branch
E069mut number := 5, never changedvariable 'number' is declared 'mut' but never mutatedRemove mut
E070A statement after retunreachable codeRemove it or move it up
E071A path with no retfunction 'sign' can fall off its end without returning a 'str' valueAdd a final ret
E080A match that skips a membernon-exhaustive match on enum 'Light': missing member YellowAdd the member, or an else arm
E082import math, never usedunused import 'math'Remove the import
E084A const after a functionconstant 'RATE' must be declared before any function or type definitionMove it to the top
E087A struct after a function'P' must be declared before any function definitionMove the types above the functions
E090A variable with a function's name'total' is already the name of a function in this fileRename one of them
E093n as int on an intuseless castRemove the cast
E108An import after an include'import str' must come before every includePut the imports first
E109os.Exit(1) in maindo not call os.Exit in mainWrite ret 1
E110n + 1 alone on a linethis statement has no effectAssign the result, or remove the line
E162n = n + 1, n += 1, n = n + 5, n = n'n = n + 1' is not allowed: write 'n++'; 'n = n + 5' is not allowed: write 'n += 5'; 'n = n' does nothing: remove this statementWrite n++ to step by one, n += 5 for any other amount, and remove statements that change nothing

A few mistakes are caught by the parser and have no code: while (the loop is until, see the loops lesson), && and || (write and and or), a typed declaration like n: int = 2 (write n := 2), and a reserved word used as a name, such as a parameter called to.

A few hints

  • Fix the first message first, then build again; many of the later ones disappear with it.
  • Read every message to the end. The part after the semicolon is usually the fix.
  • Do not reach for _ or pub to make an error go away. The compiler is pointing at code that is dead, unfinished or in the wrong place.
  • Search the code, such as E071, rather than the wording: the code is the same in every language.
  • Run salam format before chasing order errors; it moves many definitions into place for you.