Skip to content
Halyard
Project
Source code on Codeberg (opens in new tab)

Search

Menu

Error Handling

Halyard provides comprehensive error messages with helpful suggestions to improve developer experience.

Every message starts with a tag, and the one to know is [Resolve]: it means the error is about a NAME -- one nothing declares, a module that is not imported, a value a fn may not reach, a fn signature written twice. A name error stops compilation before any type is checked, which is why a typo never produces a type error about a name you did not write: fix the names, run again, and the type errors, if there are any, follow.

Everything else is tagged [Runtime], with the phase named in the message after it -- [Runtime] Lexer error: ..., [Runtime] Parse error: ..., [Runtime] Type errors during compilation:. So the tag tells you where the error was collected rather than which phase found it, and name resolution is the one phase with a tag of its own.

Fuzzy Matching ("Did you mean?")

When you reference an undefined symbol, Halyard suggests similar names:

halyard
import IO exposing print

let userName = "Alice"

let userAge = 30

print usrName

-- Error: Variable 'usrName' not found. Did you mean 'userName' or 'userAge'?

Multiple suggestions when relevant:

halyard
import IO exposing print

let userName = "Alice"

let userAge = 30

let userEmail = "alice@example.com"

print usrNme

-- Error: Variable 'usrNme' not found. Did you mean 'userName', 'userAge', or 'userEmail'?

Suggestions work for:

  • Variables and bindings
  • Function names
  • Module names
  • Enum types and variants
  • Type aliases

Module Function Typos

Suggestions also work for module function names:

halyard
import List
List.fold [1, 2, 3] 0
-- Error: Function 'fold' is not declared in module 'List'. Did you mean 'foldl', 'foldr', or 'find'?

Parser Errors

Halyard provides clear messages for syntax errors.

Indentation Errors

halyard
fn example : Int -> Int
fn example x =
let y = 1    -- Error: Function body must be indented by at least 4 spaces
    x + y

Block Alignment

halyard
if True then
    0
  else         -- Error: 'else' must align with 'if'
    1

Block Nesting

halyard
let x =
x + 1          -- Error: the block must be indented by at least 4 spaces
               -- Hint: Indent the block to 4 spaces

Type Definition Errors

halyard
enum Direction = North | south    -- Error: Enum variant must start with uppercase

Record Syntax in Enum

Using a record literal body in an enum declaration instead of named variants:

halyard
enum Person = { name: String, age: Int }
-- Error: Expected enum variant, found record syntax
-- Hint: Use an inline record type annotation instead.

Enum Variant Parentheses

Forgetting parentheses in enum variant data:

halyard
enum Outcome a e = Good a | Bad e

-- A variant's fields are juxtaposed, like a function's arguments: `Good a` declares
-- one field of type `a`. Parentheses GROUP, so `Good (a, e)` would declare one field
-- of TUPLE type instead -- a different type, written differently on purpose.
let result : Outcome Int String = Outcome::Good 5

case result of
    Outcome::Good n -> n
    Outcome::Bad _ -> 0

Delimiter Balancing

Halyard checks for mismatched, unclosed, and unexpected delimiters before parsing, producing precise error messages:

halyard
let x = (1 + 2
-- Error: Unclosed '(' — expected ')'
halyard
let x = [1, 2)
-- Error: Mismatched delimiters — the `[` is closed by `)`
halyard
let x = 1 + 2]
-- Error: Unexpected ']' — no matching '['

Tuple Pattern Type Annotations

Annotating a tuple pattern as a whole instead of its elements:

halyard
let addPair = |(x, y): (Int, Int)| x + y
-- Error: Type annotations on tuple patterns must be on individual elements
-- Hint: Use `|(x: Int, y: Int)|` instead of `|(x, y): (Int, Int)|`.

Block Missing Indentation

A function body or block expression must be indented by at least 4 spaces relative to its parent definition:

halyard
fn greet : String -> String
fn greet name =
"Hello, " ++ name   -- Error: body must be indented by at least 4 spaces

Function Missing Type Signature

Every fn-style function definition requires a matching type signature (fn name : Type -> Type) before the implementation. A definition without a preceding signature is rejected:

halyard
fn double x =        -- Error: missing type signature
    x * 2

Else Must Align With If

The else branch must start at the same column as the corresponding if. A misaligned else produces a parser error:

halyard
let x = 10
let result =
    if x > 5 then "big"
        else "small"   -- Error: else must align with if

Name Errors (the [Resolve] phase)

Undeclared Symbols

halyard
let x = unknownVar    -- Error: Variable 'unknownVar' is not declared

Scope Violations

A binding made inside a function body is not visible outside it:

halyard
fn example : Int -> Int
fn example x =
    let inner = x + 1
    inner

inner  -- Error: Variable 'inner' is not in scope

And a fn may not reach a value from outside its own body — it sees its parameters, its own bindings and other declarations. Pass the value in, or use a lambda, which captures:

halyard
let rate = 0.2

fn scaled : Float -> Float
fn scaled x = x * rate

let alsoScaled = |x| x * rate

scaled 10.0

The let alsoScaled = |x| x * rate in that example is fine: the fn is what the resolver refuses, and the lambda beside it captures.

Compiler Errors

Where an Error Happened

An error raised in a file you did not name on the command line is located: under [Runtime] Type errors during compilation: it carries the file it is in and the byte range inside it, as <path>:<start>..<end>: before the message. Before, every message stood alone, which was a problem exactly there — a type error inside modules/user.hly read as a sentence about code you had not mentioned.

[Runtime] Type errors during compilation:
  - /home/you/p/modules/user.hly:51..56: Type mismatch: expected String, found Int
    hint: Expected type: String, but got: Int
  - Type mismatch: expected Int, found String
    hint: Expected type: Int, but got: String

The second of those two is in the file you named, and it is deliberately bare: the path adds nothing when you already know which file you ran, and an absolute path differs on every machine. The value of a located message is entirely in the files you did not name. For the located ones the path is absolute, and the two numbers are byte offsets from the start of that file, so an editor can jump to the range and select it.

What the command line does not yet print is the source line with a caret under the span, the way rustc does. The numbers are there for a tool to use; for now, reading the position yourself means counting bytes or letting your editor do it. In an editor with the Halyard language server an error in a file you did not open is reported in the file you are looking at, on the import that brought that file in, and carries a related location that jumps to the line inside it — the position comes from the same spans the command line prints. When the file you are looking at has no import for it — the mistake is in a module your module imports, two steps away — the message still names the file and still carries the jump target, but it has no line of its own to sit on and comes back at the very start of the file.

Type Mismatches

halyard
fn add : Int -> Int -> Int
fn add x y =
    x + y

add "hello" 5  -- Error: Expected Int but got String

Generic Type Annotations Required

Functions that return a generic type (like Json.parse) require a type annotation on the let binding so the compiler knows the concrete type:

halyard
import Json

let data = Json.parse "{\"x\": 1}"

-- Error: Generic function result requires a type annotation for variable 'data'

-- Hint: Add a type annotation to specify the expected type

Fix by adding a type annotation:

halyard
import Json

let data : Result { x : Int } String = Json.parse "{\"x\": 1}"

data

Helpful Suggestions for Common Mistakes

Halyard detects common syntax patterns from other languages and provides helpful suggestions.

JavaScript-Style Record Syntax

halyard
{ name: "Alice", age: 30 }
-- Error: JavaScript-style record syntax is not allowed
-- Hint: Use `=` instead of `:` for record field assignment
-- Example: `{ name = "Alice" }`

Correct syntax:

halyard
{ name = "Alice", age = 30 }

Boolean Literals from Other Languages

halyard
let x = true     -- Error: 'true' is not a Halyard keyword
                 -- Hint: Use `True` for boolean true

Correct syntax:

halyard
let x = True

let y = False

x && y

Null/Nil/None from Other Languages

halyard
let x = null     -- Error: 'null' is not a Halyard keyword
                 -- Hint: Use `Nothing` for absent values

Correct syntax:

halyard
let present = Just 42

let absent = Nothing

case present of
    Just n -> "Got a value"
    Nothing -> "Nothing"

Keywords from Other Languages

halyard
return 5         -- Hint: Halyard is expression-based; the last expression is the return value
match x of       -- Hint: Use `case ... of` for pattern matching
function add     -- Hint: Use `fn` to define functions
var x = 5        -- Hint: Use `let` for variable bindings

Correct syntax examples:

halyard
fn double : Int -> Int
fn double x =
    x * 2

-- Pattern matching uses case...of

let value = Just 5

case value of
    Just n -> n * 2
    Nothing -> 0

Pattern Matching Errors

Type Mismatch in Patterns

halyard
case 42 of
    "hello" -> 1  -- Error: Pattern type mismatch: expected Int, but pattern is String
    _ -> 0

Wrong Constructor Type

halyard
case Just 5 of
    Ok n -> n  -- Error: Ok is a Result variant, and this case scrutinises a Maybe
    _ -> 0

Guard Type Errors

halyard
let x = 2

case x of
    n if n + 1 -> "bad"  -- Error: Guard expression must be Bool, found Int
    _ -> "ok"

Correct guard syntax:

halyard
let x = 5

case x of
    n if n > 0 -> "positive"
    n if n < 0 -> "negative"
    _ -> "zero"

Branch Type Mismatch

halyard
let x = 2

case x of
    1 -> 42  -- Int
    2 -> "hello"  -- Error: Case branches have incompatible types: Int and String
    _ -> 0

Correct (all branches return same type):

halyard
let x = 2

case x of
    1 -> "one"
    2 -> "two"
    _ -> "other"

Type Errors

Function Argument Type Mismatch

When you pass the wrong type to a function, Halyard shows the expected and actual types along with the full function signature:

halyard
import List

List.map 42 [1, 2, 3]

-- Error: Type mismatch: expected a function (a -> b), found Int

-- Hint: Function signature: (a -> b) -> [a] -> [b]

-- Expected argument type: a -> b, but got: Int
halyard
import String

String.length 42

-- Error: Type mismatch: expected String, found Int

-- Hint: Function signature: String -> Int

-- Expected argument type: String, but got: Int

The function signature in the hint helps you understand what the function expects, especially for higher-order functions with type variables.

Runtime Errors

Collection Bounds

halyard
let items = [1, 2, 3]

items[10]  -- Error: Index 10 out of bounds for list of size 3

Unsafe access (use List.nth for safe access):

halyard
let items = [1, 2, 3]

items[0]  -- 1

The ? Operator

The ? postfix operator unwraps a Result value or returns the Err to the caller.

  • If the expression is Ok v, ? evaluates to v (the unwrapped value).
  • If the expression is Err e, ? returns Err e from the enclosing function.
halyard
-- Unwrap Ok with ?, short-circuit on Err
let addOne = |x: Int| Ok (x + 1)
let result = 5 |> addOne
result?

When the value is Err, ? returns the error from the function it is written in:

halyard
-- Inside a function that returns a Result, `?` on an Err returns that Err to the
-- caller (short-circuit): the rest of the function does not run.
fn mayFail : Int -> Result Int String
fn mayFail x = Err "something failed"

fn pipeline : Int -> Result Int String
fn pipeline n =
    let v = (mayFail n)?
    Ok (v + 1)

pipeline 5

The ? operator can only be applied to Result values. Applying it to any other type (such as Int, String, or Maybe) is a compile error.

Where ? can be written

? returns the Err to whatever the enclosing code returns, so that code must be able to carry it:

  • In a function declared -> Result T E, the Err must have the type E; any other declared result is a compile error (TryOutsideResult).
  • In a lambda, the first ? makes the lambda return a Result: its body must be a Result (|x| Ok ((parse x)? + 1)).
  • At the top level of the file you run, and in a REPL cell, an Err ends the script (the cell) and the error is reported; the session goes on.
  • At the top level of a module file and of a file started with run, there is no caller to return to: ? is a compile error there. Use case instead.

Composable Error Handling

Halyard provides the Result and Maybe modules for functional, composable error handling without nested pattern matching.

Result Module

Transform and chain operations that might fail:

halyard
import Result

-- Transform success values
let mapped : Result Int String = Ok 5 |> Result.map (|x| x * 2)

-- Chain operations that might fail
let chained : Result Int String =
    Ok 5 |> Result.andThen (|x| if x > 0 then
        Ok x
    else
        Err "negative")

-- Provide default values
let defaulted = Err "failed" |> Result.withDefault 0

-- Transform error values
Err "bad" |> Result.mapError (|e| "Error: " ++ e)

Maybe Module

Transform and chain optional values:

halyard
import Maybe

-- Transform present values
let mapped = Just 5 |> Maybe.map (|x| x * 2)

-- Chain operations that might return Nothing
let chained =
    Just 5 |> Maybe.andThen (|x| if x > 0 then
        Just x
    else
        Nothing)

-- Provide default values

Nothing |> Maybe.withDefault 0

Converting Between Types

halyard
import Result

-- Maybe to Result (with error message)
let a = Just 5 |> Result.fromMaybe "was nothing"

-- Result to Maybe (discards error)
let c : Maybe Int = Ok 5 |> Result.toMaybe

let d : Result Int String = Err "x"

d |> Result.toMaybe

Best Practices

  1. Read error messages carefully — they often contain the exact fix
  2. Check the hints — suggestions point to Halyard-specific syntax
  3. Use the playground — experiment with syntax in the browser
  4. Handle all cases — the compiler warns about incomplete pattern matches
  5. Use Result/Maybe modules — prefer map and andThen over nested pattern matching
  6. Understand scope — inner scopes can shadow outer variables; check for typos in variable names

Next Steps

Explore the Standard Library to see available modules and functions.