Sakura Lang

Types

Records, variants, Option instead of null, typed errors, refinements, generics and pattern matching in Sakura Lang.

Types describe the shape of your data. Sakura Lang has records (named fields), variants (one of several cases) and Option instead of null, and the compiler makes you handle every case.

type User = { name: String, email: String }
type Shape = Circle(Float) | Rect(Float, Float) | Empty

fn area(s: Shape) -> Float {
  match s {
    Circle(r) => 3.14159 * r * r
    Rect(w, h) => w * h
    Empty => 0.0
  }
}

fn find(users: List<User>, email: String) -> Option<User> {
  List.find(users, fn(u) { u.email == email })
}

test "shapes and lookups" {
  expect_eq(area(Rect(2.0, 3.0)), 6.0)
  let ada = User { name: "Ada", email: "ada@x.co" }
  expect_eq(find([ada], "ada@x.co"), Some(ada))
  expect_eq(find([ada], "bob@x.co"), None)
}
  • User is a record: a value with named fields.
  • Shape is a variant type: a value is exactly one of Circle, Rect or Empty.
  • match must handle every case. Add a Triangle to Shape and every match that misses it stops compiling.
  • find returns Option<User>: either Some(user) or None. There is no null.

Top-level signatures are always written out; inside a function body the compiler infers types. Nothing converts implicitly: an Int is never silently a Float.

Records

A record type lists its fields. To build one, name the type and give every field. A field whose value is a local of the same name can be written once. { ..u, field: x } copies a record and changes some fields.

type User = { id: Int, email: String, name: String }

test "records" {
  let id = 7
  let u = User { id, email: "a@b.co", name: "Ada" }
  let moved = User { ..u, email: "ada@new.co" }
  expect_eq(moved.email, "ada@new.co")
  expect_eq(u.email, "a@b.co")
}

The copy never changes u. Records are nominal: two record types with the same fields are still different types. There are no anonymous records.

Tuples

(A, B) is a tuple type, (1, "one") a tuple value, and .0, .1 its fields. (e,) is a one-element tuple and () is Unit.

Variants

A variant type lists its cases with |. A case can carry values, by position: Circle(Float). Each case is also a function, so Circle has type fn(Float) -> Shape. See area at the top of this page.

No null: Option

A value that may be missing has type Option<T>, which is Some(value) or None.

type User = { id: Int, email: String, name: String }

fn find_user(users: List<User>, email: String) -> Option<User> {
  List.find(users, fn(u) { u.email == email })
}

fn display_name(users: List<User>, email: String) -> String {
  find_user(users, email).map(fn(u) { u.name }).unwrap_or("guest")
}

The Option module has map, unwrap_or, is_some, or_fail (turns None into a typed error) and expect. Option.expect on None is a defect (D030), a bug that stops the program, so use it only where a missing value really is a bug.

Errors and Result

A function that can fail lists Fail<E> after !, where E names the possible errors. You declare each error with error.

error ParseError(input: String)

fn parse_age(s: String) -> Int ! {Fail<ParseError>} {
  match String.parse_int(s) {
    Some(n) if n >= 0 => n
    _ => fail ParseError { input: s }
  }
}

test "bad age is a typed failure" {
  let r = try { parse_age("x") }
  expect_eq(r, Err(ParseError { input: "x" }))
}
  • fail ParseError { … } stops the function with that error.
  • try { … } without catch turns a failure into a Result: Ok(value) or Err(error).
  • r? turns a Result back into a failure.
  • type SignupError = EmailTaken | Banned combines error tags. Only error tags can be combined this way.

Effects covers failure and try/catch in full.

Refinement types

A refinement is a type plus a rule. Percent below is an Int from 0 to 100. Inside the rule, it is the value being checked.

type Email = String where String.len(it) <= 254 && String.contains(it, "@")
type Percent = Int where it >= 0 && it <= 100
type NonEmpty<T> = List<T> where List.len(it) > 0

A value gets into a refined type only through a check:

  • Percent.validate(n) returns Ok(percent) or Err(violation). Use it for input you don't control.
  • Percent.from(n) returns the value, and stops the program with defect D010 if the rule fails. Use it only where a failure would be a bug; sakura audit lists each use.
  • Decoding JSON, a request body or model output checks the rules of every nested field and returns a typed DecodeError on failure.
  • A literal, as in let p: Percent = 50, is checked at compile time when possible.

A Percent can be used anywhere an Int is expected, but not the other way round. Because values never change in place, a checked value stays valid. (Assigning one field of a refined record through a var, x.n = -1, would skip the check, so it is V2034; rebuild it with Pos.from(…) or Pos.validate(…) instead.)

Contracts goes further: rules on function inputs and outputs.

Generics and constraints

A type parameter in angle brackets, like A, lets one function work for many types. A constraint like A: Ord says what the type must support.

type Pair<A, B> = { left: A, right: B }

fn swap<A, B>(p: Pair<A, B>) -> Pair<B, A> {
  Pair { left: p.right, right: p.left }
}

fn largest<A: Ord>(xs: List<A>) -> Option<A> {
  List.last(List.sort(xs))
}

fn render<A: Eq + Show>(xs: List<A>, highlight: A) -> String {
  List.join(List.map(xs, fn(x) { if x == highlight { "[{x}]" } else { "{x}" } }), ", ")
}

There are five constraints, and the compiler derives them from a type's shape. You never write them by hand, and there are no traits or interfaces.

ConstraintGives youNot available for
Eq== and !=functions, handlers, resources, Secret
Ord<, <=, >, >= (and Eq)Map, Set, functions, Secret
Hashuse as a Map key or Set elementas Eq, plus Float
Show"{x}" and show(x)functions, handlers, resources, Secret
SchemaJson.encode and Json.decodefunctions, handlers, resources, Secret, Graph, an opaque type outside its module (V2033)

Ord orders Int, Float (NaN last), String, Bytes, and tuples, records and variants of Ord parts in declaration order. A type that lacks a needed constraint is V2032. Lowercase type parameters are effect-row variables; see Effects.

Pattern matching

match must cover every case. A missing case is V4001, and the error shows an example value you missed. A branch that can never match is V4002. Guards (if …) never count toward coverage.

type User = { id: Int, email: String, name: String }

fn summary(xs: List<Int>) -> String {
  match xs {
    [] => "empty"
    [x] => "one item: {x}"
    [x, y] => "two items: {x}, {y}"
    [first, ..rest] => "{first} and {List.len(rest)} more"
  }
}

fn size(n: Int) -> String {
  match n {
    0 => "none"
    1 | 2 | 3 => "a few"
    _ if n < 0 => "negative"
    _ => "many"
  }
}

fn is_admin(u: User) -> Bool {
  match u {
    User { name: "root", .. } => true
    _ => false
  }
}
  • Patterns: _, names, literals (including -5), constructors Some(x), records User { id, .. }, tuples (a, b), lists [], [x, ..rest], [first, second, ..], and alternatives A | B.
  • Matching on Int, String or Float literals needs a _ branch.
  • Record patterns need .. to skip the other fields.
  • Every alternative in A | B must bind the same names with the same types (V4003).
  • A match on an error type covers its error tags.

Tagged templates

A tagged string like sql"…" passes each inserted value to the tag as a value, never as pasted text. That is what stops SQL and HTML injection.

import std/sql.{Sql, SqlError}
type Email = String where String.contains(it, "@")
type User = { id: Int, email: Email, name: String }

fn find_by_email(email: Email) -> List<User> ! {Sql, Fail<SqlError>} {
  Sql.query(sql"select id, email, name from users where email = {email}")
}

Here {email} becomes a bound query parameter. html"<p>{name}</p>" escapes text. The prelude tags are sql, html, url and shell. Under the hood, tag"…" calls tag.template(parts, values) and type-checks each value against what the tag accepts. Because Query<R> and Html are opaque types, a template is the only way to build one. See Capabilities.

Opaque types

pub type exports a type with its fields and constructors. pub opaque type exports only the name: other modules can hold, pass, compare and show its values, but building one or reading its fields elsewhere is V1006.

// src/tokens.sak
pub opaque type Token = Token(String)

pub fn issue(user: Int) -> Token ! {Random} {
  Token("{user}-{Random.uuid()}")
}

Other modules can only get a Token from tokens.issue. The standard library uses the same trick: a SQL Query<R> comes only from sql"…", Html only from escaping code, and UrlPart only from UrlPart.from. Opaque types get Schema only inside their own module, so decoding cannot create one elsewhere (V2033); decode the plain data and call the constructor instead.

Aliases and distinct types

type Meters = Float is an alias: Meters and Float are the same type. For a separate type, use a single-case variant or a refinement:

import std/request.{Request}
import std/response.{Response}
import std/sql.{Sql}

type Meters = Float                              // alias
type UserId = UserId(Int)                        // distinct: UserId(7) is not an Int
type Route = fn(Request) -> Response ! {Sql, Log} // alias for a function type

Two refinements with the same rule are still different types.

Reference

Primitive types

TypeValuesNotes
Unit()Result of a function that only does something.
Booltrue, false&& and || short-circuit.
Int64-bit signedChecked: overflow is defect D001, division by zero D002. / and % round toward zero. On the JavaScript backend, values beyond ±(2^53−1) are defect D003, never silently wrong.
FloatIEEE-754 binary64NaN != NaN. Not Hash, so not a Map key.
Stringimmutable UTF-8 textNo integer indexing. String.len is the byte length; String.chars and String.graphemes give lists.
Bytesimmutable bytesBytes.get(b, i) -> Option<Int>; Bytes.slice and Bytes.concat copy.
NevernoneType of fail e, return e, break, continue.

Conversions are explicit functions: Int.to_float, Float.round (defect on NaN or out of range), Float.to_int_checked -> Option<Int>, Int.to_string, String.parse_int -> Option<Int>. Parsing never stops the program: String.parse_int returns None for text that is not a number and for a number the backend cannot represent. Decimal (std) is a library type for money with Decimal.add and friends; it has no operators.

Other built-in types

  • Collections: List<T> ([1, 2, 3]), Map<K, V> and Set<T> (keys need Hash, iteration is insertion order), and Range (0..n, end not included).
  • Functions: fn(A, B) -> C ! row. Without ! the function is pure.
  • Handlers: Handler<Eff, r>; see Handlers.
  • External types: a type declared without a body, such as pub type Scope, belongs to the host. It has no constructors; only @external functions produce its values.
  • Resources: Fs.File, Sql.Conn, Http.Body, Task.Fiber<T>, which only live inside a scope; see Memory model. Dir is a capability type. To limit network access, use Http.scoped(hosts).
  • Secret<T> and Untrusted<T>: see Capabilities.
  • Graph<N> with NodeId keys, for data with cycles; see Memory model.
  • Types with effect rows: Tool<e>, Agent<T, e> and Router<e> carry the effects of the callbacks they store. A concrete row is written Tool<{Http}>.

Bytes and text

String.to_bytes and String.from_bytes are the strict UTF-8 path (the web's TextEncoder and a fatal TextDecoder). std/bytes adds Base64 and std/encoding adds other encodings, each failure a typed error:

import std/bytes.{Alphabet, Base64Error}
import std/encoding.{Encoding, EncodingError, Errors}

test "Base64 and decoding are values with typed errors" {
  let b = String.to_bytes("héllo")
  let text = Bytes.to_base64(b, Alphabet.Standard, true)          // btoa
  expect_eq(text, "aMOpbGxv")
  expect_eq(Bytes.from_base64(text, Alphabet.Standard), Ok(b))    // strict
  expect_eq(Bytes.from_base64_lenient(" aMOp\nbGxv "), Ok(b))     // atob
  expect_eq(Bytes.from_base64("aMOpbGx", Alphabet.Standard), Err(Base64Error { offset: 7, reason: "invalid padding" }))
  let latin1 = Encoding.parse("iso-8859-1").unwrap_or(Encoding.Utf8)
  expect_eq(Encoding.decode(Bytes.from_list([0x63, 0x61, 0x66, 0xE9]), latin1, Errors.Fatal), Ok("café"))
  expect_eq(Encoding.decode(Bytes.from_list([0x61, 0xFF]), Encoding.Utf8, Errors.Replace), Ok("a\u{FFFD}"))
  expect_eq(Encoding.parse("shift_jis").is_err(), true)
}

Errors.Fatal reports the byte offset of the first bad sequence; Errors.Replace substitutes U+FFFD as browsers do. For a stream, thread a Decoder through Encoding.push and Encoding.finish: a character split across chunks comes out whole.

Inference

  • Top-level functions are fully annotated, and the body is checked against the signature.
  • let, var and lambda parameters are inferred.
  • Top-level functions may call each other recursively. Local lambdas may not recurse (V1020).
  • You must annotate pub let constants, property parameters, and empty collections whose element type cannot be worked out (V2010).
  • You cannot write type arguments at a call (V0011). A function that needs a target type gets it from the binding's annotation:
import std/json.{DecodeError}
type User = { id: Int, email: String, name: String }

fn start() -> List<Int> {
  let xs: List<Int> = List.empty()   // not List<Int>.empty()
  List.push(xs, 1)
}

fn load(text: String) -> User ! {Fail<DecodeError>} {
  let u: User = Json.decode(text)?   // not Json.decode<User>(text)
  u
}

Only three kinds of implicit widening exist: a refined type fits where its base is expected, a smaller set of errors fits a larger one, and a function with fewer effects fits where more are allowed.

Method-call resolution

e.f(args) is resolved in this order; the first match wins:

  1. e is a record and f is a field: field access.
  2. e names an effect: Eff.op(args) performs the operation. If op is not an operation, Eff.f is a function of the effect's module, which is how handler constructors such as Console.host() and Clock.fixed(t) are found.
  3. e names a type: Type.f is function f in the type's home module (the module that declared it; for built-in types, std/<lowercase name>, so List.map is std/list.map). Type.Name is a variant of the type or a type declared in its home module: Json.String(s), Level.Warn, Task.Fiber<T>.
  4. e names an imported module: mod.f is that module's exported f.
  5. Otherwise e is a value of type T, and e.f(args) means T.f(e, args), with f looked up in T's home module.

So a function gets dot syntax on a type only by living in that type's module:

// src/shapes.sak, the home module of Shape
pub type Shape = Circle(Float) | Rect(Float, Float) | Empty

pub fn area(s: Shape) -> Float {
  match s {
    Circle(r) => 3.14159 * r * r
    Rect(w, h) => w * h
    Empty => 0.0
  }
}
// src/report.sak, in package `app`
import app/shapes.{Shape}

fn total_area(xs: List<Shape>) -> Float {
  List.fold(xs, 0.0, fn(acc, s) { acc + s.area() })   // s.area() is Shape.area(s)
}

On a generic A with no constraint, x.len() is an error with a fix suggesting a constraint.

Show output

String interpolation uses Show. Its output is valid Sakura Lang syntax, the same on every backend, and the format snapshot tests use:

ValueShows as
Int, Bool, Unit42, true, ()
Floatalways with . or an exponent: 2.0, 0.1, 1.0e21, -0.0, NaN, Infinity
Stringraw at the top level of an interpolation, quoted with escapes inside any container
tuple, List(1, "a"), (1,), [1, 2]
Map, Set, BytesMap.of([("a", 1)]), Set.of([1]), Bytes.of([1, 2])
recordUser { id: 1, email: "a@b" }
variantunqualified constructor: None, Some("x"), Warn, String("x")
error tagForbidden, NotFound { id: "u1" }

So "{name}" with name = "Ada" prints Ada, while "{[name]}" prints ["Ada"].

Schema keywords of a refinement

Json.schema(witness) returns a type's JSON Schema (draft 2020-12), and a Tool's parameters use the same schema. A refinement adds the bounds JSON Schema can state, read from the top-level && parts of its where: String.len(it) <= n and >= n become maxLength and minLength, List.len(it) <= n and >= n become maxItems and minItems, and it <= n and it >= n on Int and Float become maximum and minimum. type Percent = Int where it >= 0 && it <= 100 states {"type":"integer","minimum":0,"maximum":100}. Any other part (it % 2 == 0, it < 10, an ||) states nothing. String.len counts UTF-8 bytes and JSON Schema counts characters, so maxLength is the byte bound and minLength is ⌈n/4⌉: both admit every string the where admits. The schema is a hint; decoding still checks every where.

What the compiler checks

  • Every expression has one type. No implicit conversions; Int and Float never mix.
  • Matches cover every case (V4001) with no unreachable branches (V4002).
  • There is no null and no uninitialized value. Missing values are Option.
  • Building a record supplies every field.
  • Refined values are checked when they are created: validate returns a Result, from stops on failure (D010), decoding returns DecodeError.
  • Constraints are derived, never declared, so Secret, functions and resources can never be shown, compared or serialized by accident.

Next

Effects: how every side effect and error shows up in the signature.

Details for contributors: design §4.3, §4.8, §4.9, §7.1.

Edit on GitHub

Last updated

On this page