Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Patina by Example

Patina is a statically typed programming language for the BEAM virtual machine, focusing on type safety and easy interop with broader Elixir ecosystem. Its syntax, type semantics, and much of its compiler code, is directly derived from Rust.

Patina by Example is a collection of examples that illustrate various Patina concepts. It is a fork of the excellent Rust By Example (RBE), with many parts unchanged - where Patina and Rust syntax match exactly.

Now let’s begin!

  • Hello World - Start with a traditional Hello World program.

  • Primitives - Learn about signed integers, unsigned integers and other primitives.

  • Custom Types - struct and enum.

  • Variable Bindings - mutable bindings, scope, shadowing.

  • Types - Learn about changing and defining types.

  • Conversion - Convert between different types, such as strings, integers, and floats.

  • Expressions - Learn about Expressions & how to use them.

  • Flow of Control - if/else, for, and others.

  • Functions - Learn about Methods, Closures and Higher Order Functions.

  • Modules - Organize code using modules.

  • Packages - Organize modules into distributable packages.

  • Attributes - An attribute is metadata applied to some module or item.

  • Generics - Learn about writing a function or data type which can work for multiple types of arguments.

  • Traits - A trait is a collection of methods defined for an unknown type: Self

  • Macros - Macros are a way of writing code that writes other code, which is known as metaprogramming.

  • Error handling - Learn Patina way of handling failures.

  • Unsafe Operations - Learn about entering a block of unsafe operations.

Hello World

This is the source code of the traditional Hello World program.

// hello.pt

// This is a comment, and is ignored by the compiler.
// You can test this code by clicking the "Run" button over there ->
// or if you prefer to use your keyboard, you can use the "Ctrl + Enter"
// shortcut.

// This code is editable, feel free to hack it!
// You can always return to the original code by clicking the "Reset" button ->

// This is the main function.
pub fn main() {
    // Statements here are executed when the compiled binary is called.

    // Print text to the console.
    println!("Hello World!");
}

println! is a macro that prints text to the console.

A BEAM module can be generated using the Patina compiler: patinac.

$ patinac hello.pt

patinac will produce a .beam file that can be executed with patina run.

$ patina run -m Hello
Hello World!

Comments

Any program requires comments, and Patina supports a few different varieties:

Regular Comments

These are ignored by the compiler:

  • Line comments: Start with // and continue to the end of the line
  • Block comments: Enclosed in /* ... */ and can span multiple lines

Documentation Comments

These are exported to the generated BEAM modules:

  • /// - Generates docs for the item that follows it
  • //! - Generates docs for the enclosing item (typically used at the top of a file or module)
pub fn main() {
    // Line comments start with two slashes.
    // Everything after the slashes is ignored by the compiler.

    // Example: This line won't execute
    // println!("Hello, world!");

    // Try removing the slashes above and running the code again.

    /*
     * Block comments are useful for temporarily disabling code.
     * They can also be nested: /* like this */ which makes it easy
     * to comment out large sections quickly.
     */

    /*
    Note: The asterisk column on the left is just for style - 
    it's not required by the language.
    */

    // Block comments make it easy to toggle code on/off by adding
    // or removing just one slash:

    /* <- Add a '/' here to uncomment the entire block below

    println!("Now");
    println!("everything");
    println!("executes!");
    // Line comments inside remain unaffected

    // */

    // Block comments can also be used within expressions:
    let x = 5 + /* 90 + */ 5;
    println!("Is `x` 10 or 100? x = {}", x);
}

Primitives

Patina provides access to a variety of primitives, most of them mapping directly to BEAM primitive types. A sample includes:

Scalar Types

  • atom Literal constants with name
  • int Signed variable-size integers (up to 2^(2^31))
  • float Floating point values (64-bit)
  • char Unicode scalar values like 'a', 'α' and '∞'
  • bool either true or false
  • bits Bit String - a contiguous store of a number of bits not necessarily divisible by 8
  • bin Binary; a subtype of bits with length divisible by 8
  • str UTF-8 encoded string; a subtype of bin
  • fnref() Stateless function reference, similar to Elixir’s &Foo.bar/1
  • fn() Callable function, may be a stateless reference or a closure
  • pid, port and ref native BEAM types that have no literals
  • record The BEAM Native Record type
  • The unit type (), whose only possible value is an empty tuple: ()

Despite the value of a unit type being a tuple, it is not considered a compound type because it does not contain multiple values.

Compound Types

  • Lists like [1, 2, 3]
  • Tuples like (1, true)
  • Maps like #{"foo" => 1, "bar" => 2}

Variables can always be type annotated. Note that Patina can also infer types from context.

pub fn main() {
    // Variables can be type annotated.
    let logical: bool  = true;
    let a_float: float = 1.0;
    let an_atom: atom = a"hello";

    // A type can also be inferred from context.
    let inferred_type; // Type float is inferred from another line.
    inferred_type = add_floats(12.0, 3.14);

    // A mutable variable's value can be changed - rebound to a new value.
    let mut mutable = 12; // Mutable `int`
    mutable = 21;

    // Error! The type of a variable can't be changed.
    // mutable = true;

    // Variables can be overwritten with shadowing.
    let mutable = true;

    /* Compound types - List, Tuple and Maps */

    // List's signature consists of type T as [T].
    let my_list: [int] = [1, 2, 3, 4, 5];

    // Tuple is a collection of values of different types
    // and is constructed using parentheses ().
    let my_tuple = (5, true, -5.04);

    // Map's signature consists of Key type K and Value type V as #{K => V}
    let my_map: #{float => str} = #{3.14 => "pi", 0.0 => "zero"};

    /* Function types */

    let add_ref: fnref(float, float) -> float = add_floats;
    // fnref is implicitly convertible to fn
    let add_fn: fn(float, float) -> float = add_ref;
}

fn add_floats(a: float, b: float) -> float {
    a + b
}

Runtime representation

  • bits, bin and str are all the same Erlang binary data type. While some values of these types are distinguishable (an Erlang binary that doesn’t contain valid UTF-8 data is definitely not a str), in general you can’t rely on runtime checks to differentiate a bin from a str or bits.

  • char values are represented by single integers

  • bool values are represented as atoms a"true" and a"false"

  • all of the other primitive types are directly represented in BEAM

See also:

mut, inference, and shadowing

Literals and operators

Integers 1, floats 1.2, characters 'a', strings "abc", booleans true and the unit type () can be expressed using literals.

Integers can, alternatively, be expressed using hexadecimal, octal or binary notation using these prefixes respectively: 0x, 0o or 0b.

Underscores can be inserted in numeric literals to improve readability, e.g. 1_000 is the same as 1000, and 0.000_001 is the same as 0.000001.

Patina also supports scientific E-notation, e.g. 1e6, 7.6e-4. The associated type is float.

The operators available and their precedence in Patina are similar to Rust and other C-like languages.

pub fn main() {
    // Integer addition
    println!("1 + 2 = {}", 1 + 2);

    // Integer subtraction
    println!("1 - 2 = {}", 1 - 2);

    // Scientific notation
    println!("1e4 is {}, -2.5e-3 is {}", 1e4, -2.5e-3);

    // Short-circuiting boolean logic
    println!("true AND false is {}", true && false);
    println!("true OR false is {}", true || false);
    println!("NOT true is {}", !true);

    // Bitwise operations
    println!("0011 AND 0101 is {:04b}", 0b0011 & 0b0101);
    println!("0011 OR 0101 is {:04b}", 0b0011 | 0b0101);
    println!("0011 XOR 0101 is {:04b}", 0b0011 ^ 0b0101);
    println!("1 << 5 is {}", 1 << 5);
    println!("0x80 >> 2 is 0x{:x}", 0x80 >> 2);

    // Use underscores to improve readability!
    println!("One million is written as {}", 1_000_000);
}

Tuples

A tuple is a collection of values of different types. Tuples are constructed using parentheses (), and each tuple itself is a value with type signature (T1, T2, ...), where T1, T2 are the types of its members. Functions can use tuples to return multiple values, as tuples can hold any number of values.

// Tuples can be used as function arguments and as return values.
fn reverse(pair: (int, bool)) -> (bool, int) {
    // `let` can be used to bind the members of a tuple to variables.
    let (int_param, bool_param) = pair;

    (bool_param, int_param)
}

// The following struct is for the activity.
#[derive(Debug)]
struct Matrix(float, float, float, float);

pub fn main() {
    // A tuple with a bunch of different types.
    let long_tuple = (1, 0.1, 'a', true, "hello", b"world");

    // Values can be extracted from the tuple using tuple indexing.
    println!("Long tuple first value: {}", long_tuple.0);
    println!("Long tuple second value: {}", long_tuple.1);

    // Tuples can be tuple members.
    let tuple_of_tuples = ((1, 2, 3), (4.0, -1), -2);

    // Tuples are printable.
    println!("tuple of tuples: {:?}", tuple_of_tuples);

    let pair = (1, true);
    println!("Pair is {:?}", pair);

    println!("The reversed pair is {:?}", reverse(pair));

    // To create one element tuples, the comma is required to tell them apart
    // from a literal surrounded by parentheses.
    println!("One element tuple: {:?}", (5,));
    println!("Just an integer: {:?}", (5));

    // Tuples can be destructured to create bindings.
    let tuple = (1, "hello", 4.5, true);

    let (a, b, c, d) = tuple;
    println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);

    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
    println!("{:?}", matrix);
}

Lists

A list is an ordered collection of elements of the same type T. Lists are created using brackets []. The number of elements is said to be the length of the list.

A list is a recursive data structure: List[T] ::= Empty | Cons(T, List[T]). In other words, a list is either the empty list [], or consists of a head (first element) and a tail (remainder of the list) (see the Erlang documentation on lists).

Note that lists on BEAM platform are not random-access. This means that to get Nth element of a list, you need to traverse the previous N-1 elements. For this reason, Patina does not provide a bracket access operator (ex. lst[0]).

pub fn main() {
    // List (type signature is superfluous).
    let xs: [int] = [1, 2, 3, 4, 5];

    // Indexing starts at 0.
    // `.get(n)` can be used to traverse to and return the nth element of the list
    // as an `Option`.
    match xs.get(0) {
        Some(xval) => println!("elem 0: {}", xval),
        None => println!("the list is empty!"),
    }

    // `len` returns the count of elements in the list.
    // Internally, it does that by traversing the list and counting all elements.
    println!("Number of elements in array: {}", xs.len());

    // The head and tail of a list can be retrieved with `head` and `tail`
    // `head` is an `Option`, and is None for empty lists; `tail` always succeeds.
    println!("First element of the list: {}", xs.head());
    println!("Rest of the list: {:?}", xs.tail());

    // Lists can be prepended in constant time using the following syntax:
    let more_xs = [-1, 0, ..xs];
    // This creates a new list, but the tail is not duplicated - `xs`
    // and `more_xs.tail().tail()` are internally the same VM object.
    println!("more_xs.tail().tail() is equal to xs: {}", more_xs.tail().tail() == xs);

    // Lists can also be destructured using a similar syntax
    let [first, second, third, rest @ ..] = more_xs else { return };
    println!("Sum of first three elements is {}", first + second + third);
    println!("...and the rest: {:?}", rest);
}

Maps

A map is an unordered collection of unique key -> value mappings. Maps are created using #{k => v, ...} syntax, with #{} being an empty map.

Map keys can be booleans, integers, strings, or any other type. Every term on BEAM VM is hashable, and that hash is used for BEAM maps as well.

fn call(number: str) -> str {
    match number {
        "798-1364" => "We're sorry, the call cannot be completed as dialed.
            Please hang up and try again.",
        "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
            What can I get for you today?",
        _ => "Hi! Who is this again?"
    }
}

pub fn main() {
    let mut contacts = #{
        "Daniel" => "798-1364",
        "Ashley" => "645-7689",
        "Katie" => "435-8291",
        "Robert" => "956-1745",
    };

    // Returns Option<str>
    match contacts.get("Daniel") {
        Some(number) => println!("Calling Daniel: {}", call(number)),
        _ => println!("Don't have Daniel's number."),
    }

    // `.insert()` returns an updated map.
    // The value must be used, otherwise it will emit a compilation warning.
    contacts = contacts.insert("Daniel", "164-6743");

    match contacts.get("Ashley") {
        Some(number) => println!("Calling Ashley: {}", call(number)),
        _ => println!("Don't have Ashley's number."),
    }

    contacts = contacts.remove("Ashley");

    // Like structs, maps can also be updated using the special `..` syntax
    contacts = #{"Laura" => "132-8372", ..contacts};

    // `for` will iterate over the (key, value) pairs in arbitrary order.
    for (contact, number) in contacts {
        println!("Calling {}: {}", contact, call(number));
    }
}

Term

term is a special type that represents any BEAM term. Any Patina object can be cast to Term with x as term. term has limited use in Patina; you will primarily encounter it as a result type of external BEAM functions, e.g. defined in Erlang or Elixir.

While individual types can define From<term> or TryFrom<term> traits, or provide custom coercing functions, out of the box there are three things you can do with a term value:

  • match it as a basic Erlang type (int, float, bits, atom, list, map, tuple, pid, port, ref, fn),
  • use unsafe { match } to match it against Patina types based on their runtime representation,
  • use unsafe cast_unchecked to assert - without checking - that it’s a specific Patina type.

unsafe { match }

The unsafe { match } is unsafe because Patina types and their runtime representations are not bijective. Consider this snippet:

let v = a"nil" as term;

unsafe {
    match v {
        Option::<str>::None(v) => "no integer"
        Option::<int>::None(v) => "no string"
        _ => "invalid value"
    }
}

Was v intended to be an Option<str>, Option<int>, an atom, or something else entirely? unsafe { match } cannot answer that, as it only matches the runtime representation, which can be shared by different types.

cast_unchecked

When you know the real type of a term in a given situation (for example, unicode:characters_to_binary/1 always returns a valid str), cast_unchecked lets you inform Patina of the type without adding a runtime check.

extern mod erlang;

pub fn main() {
    // External functions return a `term`, but `erlang:length/1` always returns an integer.
    let len = unsafe { erlang::length([1, 2, 3]).cast_unchecked::<int>() };

    println!("{}", len * 2);
}

cast_unchecked needs an unsafe block because, if the term isn’t really of the asserted type, the types in the source can mismatch reality with a cascading effect. When you’re not sure, match the term instead.

use Elixir::ExApp::Events;

enum UserEvent {
    Click(int, int),
    Exit
};

fn next_event(seqnum: int, prev_event: UserEvent) -> Result<UserEvent, DecodeError> {
    // External functions can take any type as input, and return `term` as a result.
    let next_event: term = Events.get_next_event(seqnum, prev_event);

    // `term` can be refined to another type using `unsafe_from_term` or `term::try_cast_into`.
    // These two produce equivalent results:
    let next_event_res: Result<UserEvent, DecodeError> = next_event.try_cast_into<UserEvent>();
    let next_event_res: Result<UserEvent, DecodeError> = UserEvent::unsafe_from_term(next_event);

    // Usually, you will write this all in one go.
    // Inside functions returning Result<_, DecodeError>, you will be able to use the ? operator
    // to immediately return the error result. Note that the type here is not `Result<UserEvent>`.
    // More on this later!
    let next_event: UserEvent = Events.get_next_event(seqnum, prev_event).try_cast_into<UserEvent>()?;

    Ok(next_event)
}

pub fn main() {
    match next_event(1, UserEvent::Click(3, 4)) {
        Ok(Click(x, y)) => println!("Clicked x={} y={}", x, y),
        Ok(Exit) => println!("Exited"),
        Err(err) => println!("Failed to decode Elixir result {:?}", err),
    }
}

Please note the unsafe in unsafe_from_term/try_cast_into - these functions only verify that runtime representation matches the type. This can violate invariants of your types, for example when a runtime tuple {a"kelvin", -1} is converted into Kelvin(int). For this reason, you should prefer implementing TryFrom<Term> for your types, and only use try_cast_into for low level plumbing. –>

Custom Types

Patina custom data types are formed mainly through the two keywords:

  • struct: define a structure
  • enum: define an enumeration

Constants can also be created via the const keyword.

Structures

There are three types of structures (“structs”) that can be created using the struct keyword:

  • Most commonly, structs with named fields.
  • Tuple structs, whose fields are unnamed and accessed by position.
  • Unit structs, which are field-less, are useful for generics.
// An attribute to hide warnings for unused code.
#![allow(dead_code)]

struct Person {
    name: str,
    age: int,
}

// A unit struct
struct Unit;

// A tuple struct
struct Pair(int, float);

// A struct with two fields
struct Point {
    x: float,
    y: float,
}

// Structs can be reused as fields of another struct
struct Rectangle {
    // A rectangle can be specified by where the top left and bottom right
    // corners are in space.
    top_left: Point,
    bottom_right: Point,
}

pub fn main() {
    // Create struct with field init shorthand
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // Print debug struct
    println!("{:?}", peter);

    // Instantiate a `Point`
    let point: Point = Point { x: 5.2, y: 0.4 };
    let another_point: Point = Point { x: 10.3, y: 0.2 };

    // Access the fields of the point
    println!("point coordinates: ({}, {})", point.x, point.y);

    // Make a new point by using struct update syntax to use the fields of our
    // other one
    let bottom_right = Point { x: 10.3, ..another_point };

    // `bottom_right.y` will be the same as `another_point.y` because we used that field
    // from `another_point`
    println!("second point: ({}, {})", bottom_right.x, bottom_right.y);

    // Destructure the point using a `let` binding
    let Point { x: left_edge, y: top_edge } = point;

    let _rectangle = Rectangle {
        // struct instantiation is an expression too
        top_left: Point { x: left_edge, y: top_edge },
        bottom_right,
    };

    // Instantiate a unit struct
    let _unit = Unit;

    // Instantiate a tuple struct
    let pair = Pair(1, 0.1);

    // Access the fields of a tuple struct
    println!("pair contains {:?} and {:?}", pair.0, pair.1);

    // Destructure a tuple struct
    let Pair(integer, decimal) = pair;

    println!("pair contains {:?} and {:?}", integer, decimal);
}

See also

attributes, destructuring, runtime representation

Enums

The enum keyword allows the creation of a type which may be one of a few different variants. Any variant which is valid as a struct is also valid in an enum.

// Create an `enum` to classify a web event. Note how both
// names and type information together specify the variant:
// `PageLoad != PageUnload` and `KeyPress(char) != Paste(str)`.
// Each is different and independent.
enum WebEvent {
    // An `enum` variant may either be `unit-like`,
    PageLoad,
    PageUnload,
    // like tuple structs,
    KeyPress(char),
    Paste(str),
    // or structs with named fields.
    Click { x: int, y: int },
}

// A function which takes a `WebEvent` enum as an argument and
// returns nothing.
fn inspect(event: WebEvent) {
    match event {
        WebEvent::PageLoad => println!("page loaded"),
        WebEvent::PageUnload => println!("page unloaded"),
        // Destructure `c` from inside the `enum` variant.
        WebEvent::KeyPress(c) => println!("pressed '{}'.", c),
        WebEvent::Paste(s) => println!("pasted \"{}\".", s),
        // Destructure `Click` into `x` and `y`.
        WebEvent::Click { x, y } => {
            println!("clicked at x={}, y={}.", x, y);
        },
    }
}

pub fn main() {
    let pressed = WebEvent::KeyPress('x');
    let pasted  = WebEvent::Paste("my text");
    let click   = WebEvent::Click { x: 20, y: 80 };
    let load    = WebEvent::PageLoad;
    let unload  = WebEvent::PageUnload;

    inspect(pressed);
    inspect(pasted);
    inspect(click);
    inspect(load);
    inspect(unload);
}

Type aliases

If you use a type alias, you can refer to each enum variant via its alias. This might be useful if the enum’s name is too long or too generic, and you want to rename it.

enum VeryVerboseEnumOfThingsToDoWithNumbers {
    Add,
    Subtract,
}

// Creates a type alias
type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;

pub fn main() {
    // We can refer to each variant via its alias, not its long and inconvenient
    // name.
    let x = Operations::Add;
}

The most common place you’ll see this is in impl blocks using the Self alias.

enum VeryVerboseEnumOfThingsToDoWithNumbers {
    Add,
    Subtract,
}

impl VeryVerboseEnumOfThingsToDoWithNumbers {
    fn run(self, x: int, y: int) -> int {
        match self {
            Self::Add => x + y,
            Self::Subtract => x - y,
        }
    }
}

See also:

match, fn, runtime representation

use

The use declaration can be used to avoid typing the full module path to access a name:

// An attribute to hide warnings for unused code.
#![allow(dead_code)]

enum Stage {
    Beginner,
    Advanced,
}

enum Role {
    Student,
    Teacher,
}

pub fn main() {
    // Explicitly `use` each name so they are available without
    // manual scoping.
    use Stage::{Beginner, Advanced};
    // Automatically `use` each name inside `Role`.
    use Role::*;

    // Equivalent to `Stage::Beginner`.
    let stage = Beginner;
    // Equivalent to `Role::Student`.
    let role = Student;

    match stage {
        // Note the lack of scoping because of the explicit `use` above.
        Beginner => println!("Beginners are starting their learning journey!"),
        Advanced => println!("Advanced learners are mastering their subjects..."),
    }

    match role {
        // Note again the lack of scoping.
        Student => println!("Students are acquiring knowledge!"),
        Teacher => println!("Teachers are spreading knowledge!"),
    }
}

See also:

match and use

Literal enums

Patina’s enum can be used to enumerate literals, as long as:

  • all of the literals are of the same type, and
  • all of the literals are unique, and
  • all of the enum variants are units.

Literal enum definitions use = syntax to provide the literal value.

enum AtomEnum {
    Foo = a"hello_foo",
    Bar = a"hello_bar",
}

enum IntEnum {
    Ok = 200,
    NotFound = 404,
}

enum StrEnum {
    Peter = "Peter",
    Paul = "Paul",
}

pub fn main() {
    // literal enums can be safely cast to their underlying type
    println!("{:?}", AtomEnum::Foo as atom);
    // a"hello_foo"

    println!("{:?}", IntEnum::NotFound as int);
    // 404

    println!("{:?}", StrEnum::Peter as str);
    // "Peter"
}

Because all unit variants are represented as atoms, an enum comprised solely of unit variants is also a literal enum of type atom.

enum AllUnits {
    Foo,
    Bar,
    Baz,
}

pub fn main() {
    println!("{:?}", AllUnits::Foo as atom);
    // a"Elixir.Patina.ByExample.AllUnits.Foo"
}

Constants

Patina has one type of constant, const, which can be declared in any scope including global. It requires an explicit type annotation.

A constant is by default only accessible in the current module. pub const can be used to allow access from other modules.

// Globals are declared outside all other scopes.
const THRESHOLD: int = 10;

fn is_big(n: int) -> bool {
    // Access constant in some function
    n > THRESHOLD
}

pub fn main() {
    let n = 16;

    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // Error! Cannot modify a `const`.
    THRESHOLD = 5;
}

Runtime representation

pub const will be persisted in the Erlang Abstract Format. It’s roughly equivalent to Elixir’s persistent attributes, and will show up in runtime in __info__(:attributes) callback for the module that defines them.

Runtime representation

Patina has multiple possible runtime representations for its structs and enum variants, to adequately model existing usage patterns in the BEAM ecosystem. The same rules apply to both; the main difference is that an enum’s top-level #[repr(...)] sets the default for its variants.

You can explicitly set a representation by annotating the struct/variant with a #[repr(...)] attribute. If you don’t, Patina will choose an efficient representation for your data, which can change between language versions. This is equivalent to setting #[repr(Patina)].

If you need a particular representation, it’s a good idea to explicitly opt-in via #[repr(...)], even if it’s the default - Patina compiler will help you maintain the invariant.

Module

Every struct and enum in patina gets its own Erlang module. By default, the module name is Elixir.Patina.{fully-qualified definition path}, but it can be set manually through #[module = "mymod"] attribute. All enum variants share one module.

mod my_mod {
    // This struct's module name is `Elixir.Patina.ByExample.MyMod.MyStruct`.
    struct MyStruct;

    // This struct's module name is `my_other_struct`.
    #[module = "my_other_struct"]
    struct MyOtherStruct;
}

Tag

Some structs and variant representations use tag. By default, the tag is equal to the module (as above) for atom and tagged reprs, and to the short variant name for native_struct. It can be set manually through #[repr(tag="mytag")].

mod my_mod {
    #[repr(tagged)]
    struct MyStruct(int, int);

    #[repr(tagged, tag = "my_tag")]
    struct MyOtherStruct(int, int);

    // `tag_style` can be set to automatically derive a snake case tag.
    #[repr(tagged, tag_style = "snake_case")]
    struct MySnakeCaseStruct(int, int);

    pub fn main() {
        println!("{:?}", MyStruct(1, 2) as term);
        // (a"Elixir.Patina.ByExample.MyMod.MyStruct", 1, 2)

        println!("{:?}", MyOtherStruct(1, 2) as term)
        // (a"my_tag", 1, 2)

        println!("{:?}", MySnakeCaseStruct(1, 2) as term)
        // (a"my_snake_case_struct", 1, 2)
    }
}

Optimized representation

Unit (struct Foo;) and newtype (struct Foo(int)) structs/variants are eligible for optimized representation. Unit structs/variants can be represented by atoms (#[repr(atom)]), while newtypes can be transparently represented by the value they wrap (#[repr(transparent)]). These optimizations are the default for #[repr(Patina)].

#[repr(atom)]

Can only be set on unit structs/variants. Encodes the value as a single atom equal to the tag. This is the default for unit structs/variants.

struct Unit;

#[repr(atom, tag = "custom_name")]
struct CustomNameUnit;

// repr settings on an enum are inherited by variants
#[repr(tag_style = "snake_case")]
enum NotJustUnits {
    VariantA,
    #[repr(tag = "variantB")]
    VariantB,
    VariantC(int),
}

// Explicitly setting `#[repr(atom)]` will ensure that only unit variants
// are ever added to an enum.
#[repr(atom, tag_style = "snake_case")]
enum OnlyUnits {
    VariantA,
    VariantB,
    VariantC,
}

pub fn main() {
    println!("{:?}", Unit as term);
    // a"Elixir.Patina.ByExample.Unit"

    println!("{:?}", CustomNameUnit as term);
    // a"custom_name"

    println!("{:?}", NotJustUnits::VariantA as term);
    // a"variant_a"

    println!("{:?}", NotJustUnits::VariantB as term);
    // a"variantB"
}

Tagged

Encoded as tagged tuples, where the first element is the atom uniquely identifying the struct or variant name, and the following tuple fields are the fields. This is similar to how Erlang’s records are modeled.

Structs

#[repr(tagged)]
struct Pair(int, float);

#[repr(tagged, tag = "Elixir.BarBar")]
struct Bar;

pub fn main() {
    println!("{:?}", Pair(42, 3.14) as term);
    // (a"Elixir.Patina.ByExample.Pair", 42, 3.14)

    println!("{:?}", Bar as term);
    // (a"Elixir.BarBar")
}

Enums

#[repr(tagged)]
enum TaggedEnum {
    Unit,
    TupleStyle(str),
    StructStyle{x: int, y: int},

    #[repr(atom)]
    UnitWithAtomOverride,

    #[repr(tag = "custom_tag")]
    WithCustomTag(int),
}

pub fn main() {
    use TaggedEnum::*;

    // Unit inherits #[repr(tagged)] from the enum setting.
    println!("{:?}", Unit as term);
    // (a"Elixir.Patina.ByExample.TaggedEnum.Unit")

    // UnitWithAtomOverride overrides the enum repr.
    println!("{:?}", UnitWithAtomOverride as term);
    // a"Elixir.Patina.ByExample.TaggedEnum.UnitWithAtomOverride"

    // Both tuple- and struct-style variants are represented as tagged tuples.
    println!("{:?}", TaggedEnum::TupleStyle("hello") as term);
    // (a"Elixir.Patina.ByExample.TaggedEnum.TupleStyle", "hello")

    println!("{:?}", TaggedEnum::StructStyle{x: 1, y: 2} as term);
    // (a"Elixir.Patina.ByExample.TaggedEnum.StructStyle", 1, 2)

    // You can set a custom tag by specifying it with `#[repr(tag = "...")]`.
    println!("{:?}", TaggedEnum::WithCustomTag(42) as term);
    // (a"custom_tag", 42)
}

Snake Case style

For easier interop with the wider ecosystem, the repr(tagged) attribute also takes a tag_style setting that can be set to snake_case. When set, the atom tags are the snake case version of the variant names.

#[repr(tagged, tag_style = "snake_case")]
enum SnakeCaseEnum {
    #[repr(atom)]
    UnitVariant,
    StructHTTPStyle{code: int, body: str},
}

pub fn main() {
    println!("{:?}", SnakeCaseEnum::UnitVariant as term);
    // a"unit_variant"

    println!("{:?}", SnakeCaseEnum::StructHTTPStyle{code: 200, body: "hi"} as term);
    // (a"struct_http_style", 200, "hi")
}

Transparent

Structs

By default, single-element structs are represented in runtime as the element itself.

// Omitting repr is equivalent to `#[repr(Patina)]`.
// In a special case of a single-element struct, it's also equivalent to `#[repr(transparent)]`.
struct Celsius(float);

pub fn main() {
    println!("{:?}", Celsius(2.345) as term);
    // 2.345
}

Enums

Like with structs, #[repr(transparent)] can only be set for single-element variants. The variants explicitly marked with transparent have to be uniquely distinguishable by their runtime shape, otherwise they will be rejected by the compiler.

Under the default #[repr(Patina)], single-field variants will be transparent by default, but they’ll silently fall back to native_record representation if their shapes are not unique. Thus, adding new variants to an enum can change existing variants’ representation! To guarantee stable representation, use explicit #[repr(...)] attributes.

#[repr(Elixir)]
struct Point {
    x: int,
    y: int,
}

#[repr(transparent)]
enum TransparentEnum {
    IntVariant(int),
    PointVariant{point: Point},
}

// Compiling this enum will result in an error, as the variants
// are not uniquely distinguishable at runtime:
//
// #[repr(transparent)]
// enum InvalidTransparentEnum {
//     MyName,
//     OrAtom(atom)
// }

pub fn main() {
    use TransparentEnum::*;

    println!("{:?}", IntVariant(200) as term);
    // 200

    println!("{:?}", PointVariant{point: Point{x: 1, y: 2}} as term);
    // #{ a"__struct__" => a"Elixir.Patina.ByExample.Point", a"x" => 1, a"y" => 2 }
}

repr(transparent) and generic open shape

Because Patina doesn’t monomorphize types, the unique-shape check described above can’t be performed at compilation time for variants that contain a generic type T.

Instead, a transparent variant holding T (an “open-shape” variant) will become tagged at runtime construction if its value can overlap any other variant of the enum. There can also be only one transparent open-shape variant per enum - because the compiled code doesn’t know the shape a-priori, it can assign unknown shapes only to a single variant.

Under #[repr(Patina)], the same value rules apply.

#[repr(transparent)]
enum TransparentWithTags<T> {
    Untagged(str),

    // `MaybeUntagged(T)` values are represented as themselves, except
    // for values that could be mistaken for another variant.
    // This behaviour has to be opted in with `dynamic_wrap` attribute.
    #[repr(dynamic_wrap, tag = "othertag")]
    MaybeUntagged(T),

    // Individual enum variants can have their own representation set.
    // Tagged(int) will always be tagged with `(a"mytag", _)`.
    #[repr(tagged, tag = "mytag")]
    Tagged(int),
}

pub fn main() {
    use TransparentWithTags::*;

    // A `str` payload could be mistaken for Untagged, so it's wrapped.
    println!("{:?}", MaybeUntagged("hello") as term);
    // (a"othertag", "hello")

    // An int payload cannot be mistaken for anything - it stays transparent.
    println!("{:?}", MaybeUntagged(42) as term);
    // 42

    // The decision is per-value, not per-type. Most terms stay transparent...
    println!("{:?}", MaybeUntagged(a"hi" as term) as term);
    // a"hi"

    // ...but a term that looks like another variant is wrapped, too.
    println!("{:?}", MaybeUntagged((a"othertag", 1) as term) as term);
    // (a"othertag", (a"othertag", 1))
}

Only the open-shaped variant can be wrapped in this situation. All other transparent variants have stable representation that’s checked for uniqueness at compilation time.

Native Records

Native Records are another possible representation of structs and enum variants. Under the default #[repr(Patina)], they are how all non-unit-or-newtype structs and variants are encoded.

#[repr(native_record)]
enum NativeRecordEnum {
    Point(int, int),

    #[repr(tag = "custom_name")]
    WithCustomName(float),
}

// For structs (not enums!) you can reference an existing, external native record.
// The record's existence and fields will be checked on module load.
// Note that `#[repr(record_module = "...")]` does *not* influence the name of the
// module that will hold the struct's implementation.
// For that, use `#[module = "..."]`.
#[repr(native_record, record_module = "external_module", tag = "custom_name")]
struct NativeRecordStruct{
    foo: str,
}

extern mod records;
pub fn main() {
    let point = NativeRecordEnum::Point(1, 2);
    // The field names of a tuple-structs and -variants are atomized integers.
    println!("{:?}", records::get_field_names(point));
    // [a"0", a"1"]

    let rect = NativeRecordStruct{ foo: "bar" };
    println!("{:?}", records::get_field_names(rect));
    // [a"foo"]
}

Elixir-style structs

Structs only. These are encoded as fully Elixir-compatible structs, with atom fields, a __struct__: module field, and a module that implements __struct__/0, __struct__/1 and __info__(:struct) callbacks.

#[repr(Elixir)]
struct Point {
    x: float,
    y: float,
}

pub fn main() {
    println!("{:?}", Point{x: 5.2, y: 0.4} as term);
    // #{ a"__struct__" => a"Elixir.Patina.ByExample.Point", a"x" => 5.2, a"y" => 0.4 }
}

Consequences for BEAM interop

The rules specified above let Patina directly use enum types to represent tagged tuples commonly used in the BEAM ecosystem.

Case study: Result

Patina’s Result type is one prominent example of tagged enum use:

#[repr(tagged)]
pub enum Result<T, E> {
    #[repr(tag = "ok")]
    Ok(T),

    #[repr(tag = "error")]
    Err(E),
}

pub fn main() {
    println!("{:?}", Result::<int, str>::Ok(42) as term);
    // (a"ok", 42)

    println!("{:?}", Result::<int, str>::Err("reason") as term);
    // (a"error", "reason")

    // Note that `Result<T, E>` can't represent a bare `:ok` by itself,
    // but we have helpers for that.
    println!("{:?}", Result::<(), str>::Ok(()).into::<Compat::BareOkResult>() as term);
    // a"ok"
}

Case study: Option

With #[repr(transparent)], Patina’s Option can cleanly represent most of the common t() | nil combinations:

#[repr(transparent)]
pub enum Option<T> {
    #[repr(dynamic_wrap, tag = "some")]
    Some(T),

    #[repr(atom, tag = "nil")]
    None,
}

pub fn main() {
    println!("{:?}", Option::<int>::Some(42) as term);
    // 42

    println!("{:?}", Option::<int>::None as term);
    // a"nil"

    // `Option<atom>` is transparent as long as the atom itself is not `nil`.
    println!("{:?}", Option::<atom>::Some(a"hi") as term);
    // a"hi"
    println!("{:?}", Option::<atom>::Some(a"nil") as term);
    // (a"some", a"nil")

    // Nested options stay distinguishable: only the values that would be
    // mistaken for `None` are wrapped.
    println!("{:?}", Option::<Option<int>>::Some(Option::Some(42)) as term);
    // 42
    println!("{:?}", Option::<Option<int>>::Some(Option::None) as term);
    // (a"some", a"nil")
    println!("{:?}", Option::<Option<int>>::None as term);
    // a"nil"
}

Case study: keyword list

Typing most keyword lists also becomes easy. For example, we could type options for erlang:term_to_binary like this:

extern mod erlang;

#[repr(tagged, tag_style = "snake_case")]
pub enum TermToBinaryOpts {
    Compressed(int),
    #[repr(atom)]
    Deterministic,
    MinorVersion(int),
    #[repr(atom)]
    Local,
}

pub fn main() {
    let opts: [TermToBinaryOpts] = [Deterministic, MinorVersion(2)];
    println!("{:?}", opts as term);
    // [a"deterministic", (a"minor_version", 2)]

    println!("{:?}", erlang::term_to_binary(42, opts));
    // <<131, 97, 42>>
}

Variable Bindings

Patina provides type safety via static typing. Variable bindings can be type annotated when declared. However, in most cases, the compiler will be able to infer the type of the variable from the context, heavily reducing the annotation burden.

Values (like literals) can be bound to variables, using the let binding.

pub fn main() {
    let an_integer = 1;
    let a_boolean = true;
    let unit = ();

    // copy `an_integer` into `copied_integer`
    let copied_integer = an_integer;

    println!("An integer: {:?}", copied_integer);
    println!("A boolean: {:?}", a_boolean);
    println!("Meet the unit value: {:?}", unit);

    // The compiler warns about unused variable bindings; these warnings can
    // be silenced by prefixing the variable name with an underscore
    let _unused_variable = 3;

    let noisy_unused_variable = 2;
    // FIXME ^ Prefix with an underscore to suppress the warning
}

Mutability

Variable bindings are immutable by default, but this can be overridden using the mut modifier.

Note that this does not mean the values themselves are mutable! Like other languages on BEAM VM, Patina’s values are immutable; the mut modifier only allows to assign a new value to an existing variable.

pub fn main() {
    let _immutable_binding = 1;
    let mut mutable_binding = 1;

    println!("Before mutating the binding: {}", mutable_binding);

    // Ok
    mutable_binding += 1;

    println!("After mutating the binding: {}", mutable_binding);

    // Error! Cannot assign a new value to an immutable variable
    _immutable_binding += 1;

    // Inside closures (lambda functions) and `try` blocks, `let mut` variables
    // defined in outer scopes lose their `mut` modifier
    let my_fun = || {
        // Error! Cannot assign a new value to a variable defined outside closure
        mutable_binding += 1;

        // You must define a new variable to modify it inside your closure
        let mut inner_mutable_binding = mutable_binding;
        inner_mutable_binding += 1;
        println!("{} == {} + 1", inner_mutable_binding, mutable_binding);
    };
}

Scope and Shadowing

Variable bindings have a scope, and are constrained to live in a block. A block is a collection of statements enclosed by braces {}.

pub fn main() {
    // This binding lives in the main function
    let long_lived_binding = 1;

    // This is a block, and has a smaller scope than the main function
    {
        // This binding only exists in this block
        let short_lived_binding = 2;

        println!("inner short: {}", short_lived_binding);
    }
    // End of the block

    // Error! `short_lived_binding` doesn't exist in this scope
    println!("outer short: {}", short_lived_binding);
    // FIXME ^ Comment out this line

    println!("outer long: {}", long_lived_binding);
}

Also, variable shadowing is allowed.

pub fn main() {
    let shadowed_binding = 1;

    {
        println!("before being shadowed: {}", shadowed_binding);

        // This binding *shadows* the outer one
        let shadowed_binding = "abc";

        println!("shadowed in inner block: {}", shadowed_binding);
    }
    println!("outside inner block: {}", shadowed_binding);

    // This binding *shadows* the previous binding
    let shadowed_binding = 2;
    println!("shadowed in outer block: {}", shadowed_binding);
}

Declare first

It is possible to declare variable bindings first and initialize them later, but all variable bindings must be initialized before they are used: the compiler forbids use of uninitialized variable bindings, as it would lead to undefined behavior.

It is not common to declare a variable binding and initialize it later in the function. It is more difficult for a reader to find the initialization when initialization is separated from declaration. It is common to declare and initialize a variable binding near where the variable will be used.

pub fn main() {
    // Declare a variable binding
    let a_binding;

    {
        let x = 2;

        // Initialize the binding
        a_binding = x * x;
    }

    println!("a binding: {}", a_binding);

    let another_binding;

    // Error! Use of uninitialized binding
    println!("another binding: {}", another_binding);
    // FIXME ^ Comment out this line

    another_binding = 1;

    println!("another binding: {}", another_binding);
}

Types

Patina provides several mechanisms to change or define the type of primitive and user defined types. The following sections cover:

Casting

Patina provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the as keyword.

pub fn main() {
    let decimal = 65.4321;

    // Error! No implicit conversion
    let integer: int = decimal;

    // Explicit conversion
    let integer = decimal as int; // casting float to integer is equivalent to decimal.trunc()
    let character = integer as char;

    // Error! There are limitations in conversion rules.
    // A float cannot be directly converted to a char.
    let character = decimal as char;
    // FIXME ^ Comment out this line

    println!("Casting: {} -> {} -> {}", decimal, integer, character);

    // str can be cast to bin or bits
    let string = "hello";
    let binary = string as bin;
    let bitstring = string as bits;

    // bin can be cast to bits
    let bitstring = binary as bits;

    // PATINA TODO: how useful is the byte type, really?
    // integer literal can be cast to a byte
    // let byte_val = 123 as byte;

    // byte can be cast to an integer, but not the other way around!
    let integer_from_byte = byte_val as int;
    // Error! Byte cannot be cast from an arbitrary integer
    let byte_from_integer = integer_from_byte as byte;
}

Inference

The type inference engine is pretty smart. It does more than looking at the type of the value expression during an initialization. It also looks at how the variable is used afterwards to infer its type. Here’s an advanced example of type inference:

pub fn main() {
    // The compiler knows that `elem` has type `int`.
    let elem = 1;

    // Create an empty list.
    let mut lst = [];
    // At this point the compiler doesn't know the exact type of `lst`, it
    // just knows that it's a list of something (`[_]`).

    // Prepend `elem` to the list.
    lst = [elem, ..lst]
    // Aha! Now the compiler knows that `lst` is a list of `int`s (`[int]`)
    println!("{:?}", lst);

    // Error! `str` does not fit in `[int]`
    lst = ["hi", ..lst]
}

No type annotation of variables was needed, the compiler is happy and so is the programmer!

Aliasing

The type statement can be used to give a new name to an existing type. Types must have UpperCamelCase names, or the compiler will raise a warning.

// `NanoSecond`, `Inch`, and `Int` are new names for `int`.
type NanoSecond = int;
type Inch = int;
type Int = int;

pub fn main() {
    // `NanoSecond` = `Inch` = `Int` = `int`.
    let nanoseconds: NanoSecond = 5 as int;
    let inches: Inch = 2 as Int;

    // Note that type aliases *don't* provide any extra type safety, because
    // aliases are *not* new types
    println!("{} nanoseconds + {} inches = {} unit?",
             nanoseconds,
             inches,
             nanoseconds + inches);
}

The main use of aliases is to reduce boilerplate; for example the io::Result<T> type is an alias for the Result<T, io::Error> type.

See also:

Attributes

Conversion

Primitive types can be converted to each other through casting.

Patina addresses conversion between custom types (i.e., struct and enum) by the use of traits. The generic conversions will use the From and Into traits. However there are more specific ones for the more common cases, in particular when converting to and from strs.

From and Into

The From and Into traits are inherently linked, and this is actually part of its implementation. If you are able to convert type A from type B, then it should be easy to believe that we should be able to convert type B to type A.

From

The From trait allows for a type to define how to create itself from another type, hence providing a very simple mechanism for converting between several types. There are numerous implementations of this trait within the standard library for conversion of primitive and common types.

For example we can easily convert a str into a bin

let my_str = "hello";
let my_bin = bin::from(my_str);

We can do something similar for defining a conversion for our own type.

use Std::Convert::From;

#[derive(Debug)]
struct Number {
    value: int,
}

impl From<int> for Number {
    fn from(item: int) -> Self {
        Number { value: item }
    }
}

pub fn main() {
    let num = Number::from(30);
    println!("My number is {:?}", num);
}

Into

The Into trait is simply the reciprocal of the From trait. It defines how to convert a type into another type.

Calling into() typically requires us to specify the result type as the compiler is unable to determine this most of the time.

use Std::Convert::Into;

#[derive(Debug)]
struct Number {
    value: int,
}

impl Into<Number> for int {
    fn into(self) -> Number {
        Number { value: self }
    }
}

pub fn main() {
    let integer = 5;
    // Try removing the type annotation
    let num: Number = integer.into();
    println!("My number is {:?}", num);
}

From and Into are interchangeable

From and Into are designed to be complementary. We do not need to provide an implementation for both traits. If you have implemented the From trait for your type, Into will call it when necessary. Note, however, that the converse is not true: implementing Into for your type will not automatically provide it with an implementation of From.

use Std::Convert::From;

#[derive(Debug)]
struct Number {
    value: int,
}

// Define `From`
impl From<int> for Number {
    fn from(item: int) -> Self {
        Number { value: item }
    }
}

pub fn main() {
    let integer = 5;
    // use `Into`
    let num: Number = integer.into();
    println!("My number is {:?}", num);
}

TryFrom and TryInto

Similar to From and Into, TryFrom and TryInto are generic traits for converting between types. Unlike From/Into, the TryFrom/TryInto traits are used for fallible conversions, and as such, return Results.

use Std::Convert::TryFrom;
use Std::Convert::TryInto;

#[derive(Debug, PartialEq)]
struct EvenNumber(int);

impl TryFrom<int> for EvenNumber {
    type Error = ();

    fn try_from(value: int) -> Result<Self, Self::Error> {
        if value % 2 == 0 {
            Ok(EvenNumber(value))
        } else {
            Err(())
        }
    }
}

pub fn main() {
    // TryFrom

    assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
    assert_eq!(EvenNumber::try_from(5), Err(()));

    // TryInto

    let result: Result<EvenNumber, ()> = 8.try_into();
    assert_eq!(result, Ok(EvenNumber(8)));
    let result: Result<EvenNumber, ()> = 5.try_into();
    assert_eq!(result, Err(()));
}

To and from strs

Converting to str

To convert any type to a str is as simple as implementing the ToStr trait for the type. Rather than doing so directly, you should implement the Fmt::Display trait which automatically provides ToStr and also allows printing the type.

use Std::Fmt;

struct Circle {
    radius: int
}

impl Fmt::Display for Circle {
    fn fmt(self, f: Fmt::Formatter) -> Fmt::Result {
        write!(f, "Circle of radius {}", self.radius)
    }
}

pub fn main() {
    let circle = Circle { radius: 6 };
    println!("{}", circle.to_str());
}

Parsing a str

It’s useful to convert strings into many types, but one of the more common string operations is to convert them from string to number. The idiomatic approach to this is to use the parse function and either to arrange for type inference or to specify the type to parse using the ‘turbofish’ syntax. Both alternatives are shown in the following example.

This will convert the string into the type specified as long as the FromStr trait is implemented for that type. This is implemented for numerous types within the standard library.

pub fn main() {
    let parsed: int = "5".parse().unwrap();
    let turbo_parsed = "10".parse::<int>().unwrap();

    let sum = parsed + turbo_parsed;
    println!("Sum: {:?}", sum);
}

To obtain this functionality on a user defined type simply implement the FromStr trait for that type.

use Std::Num::ParseIntError;
use str::FromStr;

#[derive(Debug)]
struct Circle {
    radius: int,
}

impl FromStr for Circle {
    type Err = ParseIntError;
    fn from_str(s: str) -> Result<Self, Self::Err> {
        match s.trim().parse() {
            Ok(num) => Ok(Circle{ radius: num }),
            Err(e) => Err(e),
        }
    }
}

pub fn main() {
    let radius = "    3 ";
    let circle: Circle = radius.parse().unwrap();
    println!("{:?}", circle);
}

Expressions

A Patina program is (mostly) made up of a series of statements:

pub fn main() {
    // statement
    // statement
    // statement
}

There are a few kinds of statements in Patina. The most common two are declaring a variable binding, and using a ; with an expression:

pub fn main() {
    // variable binding
    let x = 5;

    // expression;
    x;
    x + 1;
    15;
}

Blocks are expressions too, so they can be used as values in assignments. The last expression in the block will be assigned to the place expression such as a local variable. However, if the last expression of the block ends with a semicolon, the return value will be ().

pub fn main() {
    let x = 5;

    let y = {
        let x_squared = x * x;
        let x_cube = x_squared * x;

        // This expression will be assigned to `y`
        x_cube + x_squared + x
    };

    let z = {
        // The semicolon suppresses this expression and `()` is assigned to `z`
        2 * x;
    };

    println!("x is {:?}", x);
    println!("y is {:?}", y);
    println!("z is {:?}", z);
}

Flow of Control

An integral part of any programming language are ways to modify control flow: if/else, for, and others. Let’s talk about them in Patina.

Variable rebinding inside flow control

Unlike many other languages on BEAM, in most control flow blocks Patina code can rebind variables in a way that is visible outside of the block.

pub fn main() {
    // only `mut` bindings can be rebound
    let mut n = 5;

    if n > 4 {
        n = 4;
    }

    println!("{:?}", n);
    // 4
}

This also works inside loops! However, there are two notable exceptions: function closures and try blocks. Inside these, a let mut variable behaves as an immutable let.

pub fn main() {
    let mut n = 1;

    while n < 10 {
        n += n;
    }

    println!("{:?}", n);
    // 16

    let fun = ||{
        n = 20;
        // ^ERROR! External variable `n` cannot be rebound inside a closure
    };

    try {
        n = 30;
        // ^ERROR! External variable `n` cannot be rebound inside a try block
    } catch {
        Throw(1) => println!("caught 1!");
    }
}

if/else

Branching with if-else is similar to other languages. Unlike many of them, the boolean condition doesn’t need to be surrounded by parentheses, and each condition is followed by a block. if-else conditionals are expressions, and, all branches must return the same type.

pub fn main() {
    let n = 5;

    if n < 0 {
        print!("{} is negative", n);
    } else if n > 0 {
        print!("{} is positive", n);
    } else {
        print!("{} is zero", n);
    }

    let big_n =
        if n < 10 && n > -10 {
            println!(", and is a small number, increase ten-fold");

            // This expression returns an `int`.
            10 * n
        } else {
            println!(", and is a big number, halve the number");

            // This expression must return an `int` as well.
            n / 2
            // TODO ^ Try suppressing this expression with a semicolon.
        };
    //   ^ Don't forget to put a semicolon here! All `let` bindings need it.

    println!("{} -> {}", n, big_n);
}

loop

Patina provides a loop keyword to indicate an infinite loop.

The break statement can be used to exit a loop at anytime, whereas the continue statement can be used to skip the rest of the iteration and start a new one.

pub fn main() {
    let mut count = 0;

    println!("Let's count until infinity!");

    // Infinite loop
    loop {
        count += 1;

        if count == 3 {
            println!("three");

            // Skip the rest of this iteration
            continue;
        }

        println!("{}", count);

        if count == 5 {
            println!("OK, that's enough");

            // Exit this loop
            break;
        }
    }
}

Returning from loops

One of the uses of a loop is to retry an operation until it succeeds. If the operation returns a value though, you might need to pass it to the rest of the code: put it after the break, and it will be returned by the loop expression.

pub fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    assert_eq!(result, 20);
}

while

The while keyword can be used to run a loop while a condition is true.

Let’s write the infamous FizzBuzz using a while loop.

pub fn main() {
    // A counter variable
    let mut n = 1;

    // Loop while `n` is less than 101
    while n < 101 {
        if n % 15 == 0 {
            println!("fizzbuzz");
        } else if n % 3 == 0 {
            println!("fizz");
        } else if n % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", n);
        }

        // Increment counter
        n += 1;
    }
}

for loops

for and range

The for in construct can be used to iterate through an Iterator. One of the easiest ways to create an iterator is to use the range notation a..b. This yields values from a (inclusive) to b (exclusive) in steps of one.

Let’s write FizzBuzz using for instead of while.

pub fn main() {
    // `n` will take the values: 1, 2, ..., 100 in each iteration
    for n in 1..101 {
        if n % 15 == 0 {
            println!("fizzbuzz");
        } else if n % 3 == 0 {
            println!("fizz");
        } else if n % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", n);
        }
    }
}

Alternatively, a..=b can be used for a range that is inclusive on both ends. The above can be written as:

pub fn main() {
    // `n` will take the values: 1, 2, ..., 100 in each iteration
    for n in 1..=100 {
        if n % 15 == 0 {
            println!("fizzbuzz");
        } else if n % 3 == 0 {
            println!("fizz");
        } else if n % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", n);
        }
    }
}

for and iterators

The for in construct is able to interact with an Iterator in several ways. As discussed in the section on the Iterator trait, by default the for loop will apply the iter function to the collection.

pub fn main() {
    let names = ["Bob", "Frank", "Ferris"];

    for name in names.iter() {
        match name {
            "Ferris" => println!("There is a rustacean among us!"),
            _ => println!("Hello {}", name),
        }
    }

    println!("names: {:?}", names);
}

See also:

Iterator

match

Patina provides pattern matching via the match keyword, which can be used like Erlang’s or Elixir’s case. The first matching arm is evaluated and all possible values must be covered.

pub fn main() {
    let number = 13;
    // TODO ^ Try different values for `number`

    println!("Tell me about {}", number);
    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // TODO ^ Try adding 13 to the list of prime values
        // Match an inclusive range
        13..=19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
        // TODO ^ Try commenting out this catch-all arm
    }

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => 0,
        true => 1,
        // TODO ^ Try commenting out one of these arms
    };

    println!("{} -> {}", boolean, binary);

    let expected_value = 42;
    match 123 {
        // You can use the pin operator (^) to match against bound variables
        ^expected_value => println!("found expected value"),
        value => println!("found unexpected value {}", value),
    }
}

Destructuring

A match block can destructure items in a variety of ways.

tuples

Tuples can be destructured in a match as follows:

pub fn main() {
    let triple = (0, -2, 3);
    // TODO ^ Try different values for `triple`

    println!("Tell me about {:?}", triple);
    // Match can be used to destructure a tuple
    match triple {
        // Destructure the second and third elements
        (0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z),
        (1, ..)  => println!("First is `1` and the rest doesn't matter"),
        (.., 2)  => println!("last is `2` and the rest doesn't matter"),
        (3, .., 4)  => println!("First is `3`, last is `4`, and the rest doesn't matter"),
        // `..` can be used to ignore the rest of the tuple
        _      => println!("It doesn't matter what they are"),
        // `_` means don't bind the value to a variable
    }
}

See also:

Tuples

lists

Like tuples, lists can be destructured this way:

pub fn main() {
    // Try changing the values in the list!
    let list = [1, -2, 6];

    match list {
        // Binds the second and the third elements to the respective variables
        [0, second, third] =>
            println!("list[0] = 0, list[1] = {}, list[2] = {}", second, third),

        // Single values can be ignored with _
        [1, _, third] => println!(
            "list[0] = 1, list[2] = {} and list[1] was ignored",
            third
        ),

        // You can also bind some and ignore the rest
        [-1, second, ..] => println!(
            "list[0] = -1, list[1] = {} and all the other ones were ignored",
            second
        ),
        // The code below would not compile
        // [-1, second] => ...

        // Or store them in another list (the type depends on
        // that of the value that is being matched against)
        [3, second, tail @ ..] => println!(
            "list[0] = 3, list[1] = {} and the other elements were {:?}",
            second, tail
        ),

        // We have to include a catch-all for match exhaustiveness.
        _ => println!("no list pattern matched"),
    }
}

See also:

Lists and Binding for @ sigil

enums

An enum is destructured similarly:

// `allow` required to silence warnings because only
// one variant is used.
#[allow(dead_code)]
enum Color {
    // These 3 are specified solely by their name.
    Red,
    Blue,
    Green,
    // These likewise tie `int` tuples to different names: color models.
    RGB(int, int, int),
    HSV(int, int, int),
    HSL(int, int, int),
    CMY(int, int, int),
    CMYK(int, int, int, int),
}

pub fn main() {
    let color = Color::RGB(122, 17, 40);
    // TODO ^ Try different variants for `color`

    println!("What color is it?");
    // An `enum` can be destructured using a `match`.
    match color {
        Color::Red   => println!("The color is Red!"),
        Color::Blue  => println!("The color is Blue!"),
        Color::Green => println!("The color is Green!"),
        Color::RGB(r, g, b) =>
            println!("Red: {}, green: {}, and blue: {}!", r, g, b),
        Color::HSV(h, s, v) =>
            println!("Hue: {}, saturation: {}, value: {}!", h, s, v),
        Color::HSL(h, s, l) =>
            println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
        Color::CMY(c, m, y) =>
            println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y),
        Color::CMYK(c, m, y, k) =>
            println!("Cyan: {}, magenta: {}, yellow: {}, key (black): {}!",
                c, m, y, k),
        // Don't need another arm because all variants have been examined
    }
}

structs

Similarly, a struct can be destructured as shown:

pub fn main() {
    struct Foo {
        x: (int, int),
        y: int,
    }

    // Try changing the values in the struct to see what happens
    let foo = Foo { x: (1, 2), y: 3 };

    match foo {
        Foo { x: (1, b), y } => println!("First of x is 1, b = {},  y = {} ", b, y),

        // you can destructure structs and rename the variables,
        // the order is not important
        Foo { y: 2, x: i } => println!("y is 2, i = {:?}", i),

        // and you can also ignore some variables:
        Foo { y, .. } => println!("y = {}, we don't care about x", y),
        // this will give an error: pattern does not mention field `x`
        //Foo { y } => println!("y = {}", y),
    }

    let faa = Foo { x: (1, 2), y: 3 };

    // You do not need a match block to destructure structs:
    let Foo { x : x0, y: y0 } = faa;
    println!("Outside: x0 = {x0:?}, y0 = {y0}");

    // Destructuring works with nested structs as well:
    struct Bar {
        foo: Foo,
    }

    let bar = Bar { foo: faa };
    let Bar { foo: Foo { x: nested_x, y: nested_y } } = bar;
    println!("Nested: nested_x = {nested_x:?}, nested_y = {nested_y:?}");
}

See also:

Structs

Guards

A match guard can be added to filter the arm. Only Erlang guard expressions are allowed in the if guards.

#[allow(dead_code)]
enum Temperature {
    Celsius(int),
    Fahrenheit(int),
}

pub fn main() {
    let temperature = Temperature::Celsius(35);
    // ^ TODO try different values for `temperature`

    match temperature {
        Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t),
        // The `if condition` part ^ is a guard
        Temperature::Celsius(t) => println!("{}C is equal to or below 30 Celsius", t),

        Temperature::Fahrenheit(t) if t > 86 => println!("{}F is above 86 Fahrenheit", t),
        Temperature::Fahrenheit(t) => println!("{}F is equal to or below 86 Fahrenheit", t),
    }
}

Note that the compiler won’t take guard conditions into account when checking if all patterns are covered by the match expression.

pub fn main() {
    let number: int = 4;

    match number {
        i if i == 0 => println!("Zero"),
        i if i > 0 => println!("Greater than zero"),
        // _ => unreachable!("Should never happen."),
        // TODO ^ uncomment to fix compilation
    }
}

See also:

Tuples Enums

Binding

Indirectly accessing a variable makes it impossible to branch and use that variable without re-binding. match provides the @ sigil for binding values to names:

// A function `age` which returns an `int`.
fn age() -> int {
    15
}

pub fn main() {
    println!("Tell me what type of person you are");

    match age() {
        0             => println!("I haven't celebrated my first birthday yet"),
        // Could `match` 1 ..= 12 directly but then what age
        // would the child be?
        // Could `match` n and use an `if` guard, but would
        // not contribute to exhaustiveness checks.
        // (Although in this case that would not matter since
        // a "catch-all" pattern is present at the bottom)
        // Instead, bind to `n` for the sequence of 1 ..= 12.
        // Now the age can be reported.
        n @ 1  ..= 12 => println!("I'm a child of age {:?}", n),
        n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n),
        // A similar binding can be done when matching several values.
        n @ (1 | 7 | 15 | 13) => println!("I'm a teen of age {:?}", n),
        // Nothing bound. Return the result.
        n             => println!("I'm an old person of age {:?}", n),
    }
}

You can also use binding to “destructure” enum variants, such as Option:

fn some_number() -> Option<int> {
    Some(42)
}

pub fn main() {
    match some_number() {
        // Got `Some` variant, match if its value, bound to `n`,
        // is equal to 42.
        // Could also use `Some(42)` and print `"The Answer: 42!"`
        // but that would require changing `42` in 2 spots should
        // you ever wish to change it.
        // Could also use `Some(n) if n == 42` and print `"The Answer: {n}!"`
        // but that would not contribute to exhaustiveness checks.
        // (Although in this case that would not matter since
        // the next arm is a "catch-all" pattern)
        Some(n @ 42) => println!("The Answer: {}!", n),
        // Match any other number.
        Some(n)      => println!("Not interesting... {}", n),
        // Match anything else (`None` variant).
        _            => (),
    }
}

See also:

functions, enums and Option

Binary matching

A match can destructure strings, binaries, and bitstrings directly.

Like in Erlang’s bit syntax, binaries are matched in segments. A binary pattern only matches if every segment matches, and the whole value is consumed.

pub fn main() {
    let payload = <<1, 17, 42, 99>>;

    match payload {
        <<prefix: int(16), tag: int(8), rest @ ..>> =>
            println!("prefix = {}, tag = {}, rest = {:?}", prefix, tag, rest),

        _ => println!("did not match"),
    }
}

Like all match patterns, binary patterns can bind values to names, ignore parts with _, and be combined with guards when you need extra checks after destructuring.

Segments

There can be zero or more segments in a binary match arm. Each segment can have a type annotation describing how it is matched. An example segment is of the form var: int(size=^x, signed, little, unit=8), where:

  • the segment’s type follows a colon: one of int, float, char, str, bin or bits

  • size can be 0 or more, and can be given through a pinned variable, like size=^x - including a variable bound by a previous segment of the pattern

  • unit has to be a constant in range 1..=256

  • all parameters are optional

    • size and unit default to:
      • for ints, unit=1, size=8
      • for floats, unit=1, size=64; if set, size must be a literal 16, 32 or 64
      • for bits, unit=1; size expands to consume the whole unclaimed space
      • for bins, unit=8 and must be a multiple of 8; size expands as above
      • for str, unit=8 and cannot be set; size expands as above
      • for chars, neither can be set: the size depends on the character and its encoding
    • signedness is unsigned by default (can be signed or unsigned)
    • endianness is big by default (can be big, little, or native)
    • the encoding of a char is utf8 by default (can be utf8, utf16, or utf32); endianness only applies to utf16 and utf32
    • a string literal can be encoded the same way, e.g. "łącko": str(utf16, little); other str values are always UTF-8
  • the size= prefix is optional; int(size=64) is more commonly written as int(64)

  • only the last segment can be unsized, and unit specifies its granularity, e.g. rest: bits(unit=4) matches a rest whose size is a multiple of 4 bits

    • most of the time, you’ll match the rest with rest @ .. instead
  • there are no alignment rules: segments of any size can follow each other

Short form

If the only parameter you want to set is a fixed size, you can use a shortform syntax x:16, with an integer literal. For matched variables, the type defaults to int. When the size is provided by a variable, it needs the full form, e.g. x: int(^len).

// For matched variables, the type is assumed to be `int`.
// This line is equivalent to `<<x: int(16)>>`.
if let <<x:16>> = data {
    println!("data is a two-byte integer {}", x);
}

// The shorthand syntax comes in handy to match data with standard layout.
if let <<unix_ts_ms:48, ver:4, rand_a:12, var:2, rand_b:62>> = uuidv7_id {
    println!("{} {} {} {} {}", unix_ts_ms, ver, rand_a, var, rand_b);
}

If the type is omitted altogether, the size defaults to 8 as per the list above. In that case <<x>> is equivalent to <<x: int()>> is equivalent to <<x: int(8)>>.

The rest

The last segment of the matched binary can be rest @ .. (which binds whatever is left of the value), or just .. (which ignores it). The rest needs no type annotation; it gets the narrowest type it is guaranteed to have:

  • a str, when matching a str, and every segment before it is valid UTF-8
  • a bin, when matching a str or a bin and the segments before it add up to whole bytes
  • a bits otherwise

An explicit type can still be given. On a bits, rest: bin() acts as an additional check and only matches when the rest is a whole number of bytes.

Example

pub fn main() {
    let bin = <<16, 5, 6, 7>>;

    match bin {
        // Bind `len`, then use it as the size of `payload`
        <<kind:8, len: int(8), payload: bin(^len), rest @ ..>> =>
            println!("kind = {}, payload = {:?}, rest = {:?}", kind, payload, rest),
        
        // The size can also be a guard expression
        <<kind:8, len: int(8), payload: bin(len / 2), rest @ ..>> =>
            println!("kind = {}, payload = {:?}, rest = {:?}", kind, payload, rest),

        _ => println!("invalid packet"),
    }

    let packet: bits = <<3:4, 5:4, 7:3>>;

    match packet {
        // The tail expands to match the whole rest of the binary.
        // Only the last segment can be unsized.
        // After an 8-bit header, the rest of a `bits` is a `bits`.
        <<header: int(8), tail @ ..>> =>
            println!("header = {}, tail = {:?}", header, tail),

        _ => println!("did not match"),
    }
}

Literals

Literal segments can also be mixed directly into a binary pattern, whatever kind of value you are matching. str and b"…" literals match their bytes, char literals are encoded as UTF-8 (unless overridden), and integer and float literals are matched like int and float segments.

A literal that doesn’t fit its segment, like 256:8, can never match, and gets a compiler warning.

pub fn main() {
    let text: str = "Patina!";
    let bytes: bin = <<b"PNG", '!', "rest">>;
    // For literals, types are optional unless you want to override a default.
    // Like with bindings, you set the type after a colon.
    let packet: bits = <<b"PT", '!', "ok", 5: int(3)>>;

    match text {
        // Every segment before the rest is valid UTF-8, so `rest` is a `str`.
        <<"Pa", 't', rest @ ..>> => println!("text rest {:?}", rest),
        _ => println!("unknown text"),
    }

    match bytes {
        <<b"PNG", '!', rest @ ..>> => println!("png data {:?}", rest),
        _ => println!("unknown binary"),
    }

    match packet {
        // The shorthand form can also be used with literals. 
        <<b"PT", '!', "ok", 5:3, rest @ ..>> =>
            println!("packet tail {:?}", rest),
        _ => println!("unknown packet"),
    }
}

Bound variables

You can match against already bound variables’ values using the pin operator ^.

pub fn main() {
    let png_prefix = "PNG";
    let jpg_prefix = "JPG";

    match "PNG!rest" {
        <<^png_prefix, rest @ ..>> => println!("png data {:?}", rest),
        <<^jpg_prefix, rest @ ..>> => println!("jpg data {:?}", rest),
        _ => println!("unknown data"),
    }

    let bit_prefix = 7;

    match <<119>> {
        // Like with literals, you can give the segment a type.
        <<^bit_prefix: int(16, little), rest @ ..>> => println!("expected {:?}", rest),
        // Or use the shorthand syntax.
        <<^bit_prefix:4, rest @ ..>> => println!("expected {:?}", rest),
        _ => println!("unexpected prefix"),
    }
}

Building binaries

The same syntax as above can be used to build the binaries. Each segment is an expression, with an optional type and spec. Without one, the type of the segment is determined by the type of its value:

  • ints become 8-bit integers
  • floats become 64-bit floats
  • chars and strs are encoded as UTF-8
  • bin and bits are copied whole

Arithmetic in a segment needs parentheses, like (len + 1):16.

A built binary gets the narrowest type it is guaranteed to have:

  • str if every segment is valid UTF-8 on its own
  • bin if its size is a whole number of bytes
  • bits otherwise.
pub fn main() {
    let name = "Patina";
    let version = 3;

    // Every segment is valid UTF-8, so this is a `str`.
    let greeting: str = <<"Hello, ", name, '!'>>;

    // The size is a whole number of bytes, so this is a `bin`.
    let header: bin = <<b"PT", version:16, 1.5: float(32), 'é': char(utf16)>>;

    // Anything else is a `bits`.
    let flags: bits = <<1:1, 0:1, (version + 1): int(3)>>;

    println!("{:?} {:?} {:?}", greeting, header, flags);
}

See also:

match, Guards, and Primitives

unsafe { match }

Ordinary match can safely destructure structs and distinguish enums, because Patina type system guarantees that there’s a unique mapping between the match runtime value and its type.

term is an exception: it can still be matched, because it’s very useful to do so, but in safe Patina code we can only destructure it to BEAM-level primitives.

That’s where unsafe { match } comes in. It uses the same arm syntax as match, but it maches on types’ runtime representation instead of source-level identity.

pub fn main() {
    let v = Option::<int>::None as term;

    let safe_description = match v {
        a"nil" => "the atom nil",
        (a"some", val) => "some value (tagged?)",
        int(_) => "some integer value (untagged?)",
        val => "some value (untagged?)",
        // Option<str>::None => "string option (none)",
        // ^ERROR - can't safely match by runtime representation!
    };

    let unsafe_description = unsafe {
        match v {
            Option::<str>::None => "an empty string option",
            Option::<int>::None => "an empty integer option",
            a"nil" => "the atom nil",
            _ => "something else",
        }
    };

    println!("{}, {}", safe_description, unsafe_description);
    // "the atom nil, an empty string option"
}

unsafe { match } is unsafe, because multiple Patina types may lower to the same BEAM value. In the example above, all three of Option::<str>::None, Option::<int>::None, and a"nil" may share the same runtime representation. unsafe { match } can only see that representation; it cannot recover which Patina type the value was meant to have.

It’s best practice to only use unsafe { match } as glue, for interop with external BEAM libraries and features implemented in other languages.

See also:

unsafe, term, and unsafe { receive }

receive

receive is a match-like expression over incoming mailbox values.

Like BEAM receive, it scans the mailbox from oldest to newest, consumes the first message that matches one of its arms, and leaves all non-matching messages in the mailbox. If there is no message that matches any of the arms, receive blocks the current process until one arrives, or until a timeout is hit, whichever comes first.

Aside from literals and destructuring, Patina lets you match whole BEAM primitive classes in a single arm. For example, int(n) matches any integer and binds it to n, while atom(a) matches any atom and binds it to a.

pub fn main() {
    receive {
        int(n) => println!("received integer {:?}", n),
        // like in `match`, literals can also be used
        a"ping" => println!("received ping"),
        atom(a) => println!("received atom {:?}", a),
    } after Timeout::from_seconds(5) {
        println!("timeout (5 seconds with no matching message)")
    }

    receive {
        val => println!("received any message {:?}", val),
    }
}

The receive arms work the same way they do in ordinary match:

  • patterns narrow the matched message
  • the value of the whole receive expression is the value of the chosen arm
  • every catch arm, and the timeout block if present, must all have the same result type.

unsafe receive

unsafe { receive } is to receive what unsafe { match } is to match.

Like receive, it scans the mailbox using normal selective-receive rules. Unlike receive, it can match not only BEAM-level primitives such as int(n) and atom(a), but also Patina types based only on their runtime representation.

pub fn main() {
    unsafe {
        receive {
            int(n) => println!("got integer {:?}", n),
            atom(a) => println!("got atom {:?}", a),
            Option::<str>::None => println!("got an empty string option"),
            Option::<int>::None => println!("got an empty integer option"),
            _ => println!("got something else"),
        } after Timeout::from_seconds(5) {
            println!("timeout")
        }
    }
}

unsafe { receive } is unsafe for the same reason unsafe { match } is unsafe: different Patina types can lower to the same BEAM value. The message matched above might have been intended as Option::<str>::None, Option::<int>::None, an ordinary atom, or something else entirely.

It’s best practice to only use unsafe { receive } as a glue, for interop with BEAM libraries and features implemented in other languages.

See also:

unsafe, term, and unsafe { match }

try/catch/after

Patina code strongly prefers handling errors with Result<T, E>, but it lives within a wider BEAM environment, where process errors are reported with exception-like signals. Similarly, many existing BEAM libraries leverage exceptions for their error handling, or thrown values for flow control.

The try/catch/after construct can be used to interact with these throwables in Patina.

If the try block completes normally, its value becomes the value of the whole expression. If it fails with a catchable outcome, the catch arms may handle it. The after block is for cleanup and runs when the try expression finishes, whether it completed normally or not.

As with match and receive, the try block and every catch arm must all have the same result type. Unlike match, but similarly to receive, catch does not have to cover the whole set of possibilities - anything unmatched will just pass through to the parent catch block, if any.

fn open_resource() -> atom {
    a"ok"
}

pub fn main() {
    try {
        open_resource();
    } catch {
        error(a"badarg") =>
            println!("badarg!"),

        error(reason @ #{a"__struct__" => a"Elixir.MyElixirException", ..}) =>
            println!("An Elixir exception {:?}", reason),

        // a second pattern after the comma binds the stacktrace
        error(reason), stacktrace =>
            println!("other error: {:?} from {:?}", reason, stacktrace),

        throw(value) =>
            println!("thrown: {:?}", value),

        exit(reason) =>
            println!("exit: {:?}", reason),
    } after {
        println!("cleaning up");
    };
}

Catchable classes

A catch arm can destructure the following throwables:

  • error(reason) / error(reason), stacktrace - the BEAM error class. Erlang’s badarg is error(a"badarg"), and an Elixir exception is a struct map with __exception__ set to true, e.g. error(#{a"__struct__" => a"Elixir.ArgumentError", ..});

  • throw(value) / throw(value), stacktrace - thrown values;

  • exit(reason) / exit(reason), stacktrace - BEAM process exit signals that propagate over process links.

  • any(class, value) / any(class, value), stacktrace - any BEAM exception class. class gets bound to error, throw, or exit.

Matching on the caught value

The value caught by each class is a term, so it can be destructured like in any other match on a term:

extern mod erlang;

pub fn main() {
    let value = try {
        erlang::error((a"badmatch", 42));
        0
    } catch {
        // Match a `badmatch` tuple with an `int` value.
        error((a"badmatch", int(n))) => n,
    };

    println!("{}", value);
}

See also:

Result, panic, and flow of control

if let

For some use cases, when matching enums, match is awkward. For example:

// Make `optional` of type `Option<int>`
let optional = Some(7);

match optional {
    Some(i) => println!("This is a really long string and `{:?}`", i),
    _ => {},
    // ^ Required because `match` is exhaustive. Doesn't it seem
    // like wasted space?
};

if let is cleaner for this use case and in addition allows various failure options to be specified:

pub fn main() {
    // All have type `Option<int>`
    let number = Some(7);
    let letter: Option<int> = None;
    let emoticon: Option<int> = None;

    // The `if let` construct reads: "if `let` destructures `number` into
    // `Some(i)`, evaluate the block (`{}`).
    if let Some(i) = number {
        println!("Matched {:?}!", i);
    }

    // If you need to specify a failure, use an else:
    if let Some(i) = letter {
        println!("Matched {:?}!", i);
    } else {
        // Destructure failed. Change to the failure case.
        println!("Didn't match a number. Let's go with a letter!");
    }

    // Provide an altered failing condition.
    let i_like_letters = false;

    if let Some(i) = emoticon {
        println!("Matched {:?}!", i);
    // Destructure failed. Evaluate an `else if` condition to see if the
    // alternate failure branch should be taken:
    } else if i_like_letters {
        println!("Didn't match a number. Let's go with a letter!");
    } else {
        // The condition evaluated false. This branch is the default:
        println!("I don't like letters. Let's go with an emoticon :)!");
    }
}

In the same way, if let can be used to match any enum value:

// Our example enum
enum Foo {
    Bar,
    Baz,
    Qux(int)
}

pub fn main() {
    // Create example variables
    let a = Foo::Bar;
    let b = Foo::Baz;
    let c = Foo::Qux(100);

    // Variable a matches Foo::Bar
    if let Foo::Bar = a {
        println!("a is foobar");
    }

    // Variable b does not match Foo::Bar
    // So this will print nothing
    if let Foo::Bar = b {
        println!("b is foobar");
    }

    // Variable c matches Foo::Qux which has a value
    // Similar to Some() in the previous example
    if let Foo::Qux(value) = c {
        println!("c is {}", value);
    }

    // Binding also works with `if let`
    if let Foo::Qux(value @ 100) = c {
        println!("c is one hundred");
    }
}

Another benefit is that if let allows us to match non-parameterized enum variants. This is true even in cases where the enum doesn’t implement or derive PartialEq. In such cases if Foo::Bar == a would fail to compile, because instances of the enum cannot be equated, however if let will continue to work.

Would you like a challenge? Fix the following example to use if let:

// This enum purposely neither implements nor derives PartialEq.
// That is why comparing Foo::Bar == a fails below.
enum Foo {Bar}

pub fn main() {
    let a = Foo::Bar;

    // Variable a matches Foo::Bar
    if Foo::Bar == a {
    // ^-- this causes a compile-time error. Use `if let` instead.
        println!("a is foobar");
    }
}

See also:

enum, Option

let-else

With let-else, a refutable pattern can match and bind variables in the surrounding scope like a normal let, or else diverge (e.g. break, return, panic!) when the pattern doesn’t match.

use str::FromStr;

fn get_count_item(s: str) -> (int, str) {
    let it = s.split(' ');
    let (it, first) = it.next();
    let (it, second) = it.next();

    let (Some(count_str), Some(item)) = (first, second) else {
        panic!("Can't segment count item pair: '{s}'");
    };
    let Ok(count) = int::from_str(count_str) else {
        panic!("Can't parse integer: '{count_str}'");
    };
    (count, item)
}

pub fn main() {
    assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
}

See also:

option, match, if let.

while let

Similar to if let, while let can make awkward match sequences more tolerable. Consider the following sequence that increments i:

// Make `optional` of type `Option<int>`
let mut optional = Some(0);

// Repeatedly try this test.
loop {
    match optional {
        // If `optional` destructures, evaluate the block.
        Some(i) => {
            if i > 9 {
                println!("Greater than 9, quit!");
                optional = None;
            } else {
                println!("`i` is `{:?}`. Try again.", i);
                optional = Some(i + 1);
            }
            // ^ Requires 3 indentations!
        },
        // Quit the loop when the destructure fails:
        _ => { break; }
        // ^ Why should this be required? There must be a better way!
    }
}

Using while let makes this sequence much nicer:

pub fn main() {
    // Make `optional` of type `Option<int>`
    let mut optional = Some(0);

    // This reads: "while `let` destructures `optional` into
    // `Some(i)`, evaluate the block (`{}`). Else `break`.
    while let Some(i) = optional {
        if i > 9 {
            println!("Greater than 9, quit!");
            optional = None;
        } else {
            println!("`i` is `{:?}`. Try again.", i);
            optional = Some(i + 1);
        }
        // ^ Less rightward drift and doesn't require
        // explicitly handling the failing case.
    }
    // ^ `if let` had additional optional `else`/`else if`
    // clauses. `while let` does not have these.
}

See also:

enum, Option

Functions

A function is declared using the fn keyword. Its arguments are type annotated, just like variables, and, if the function returns a value, the return type must be specified after an arrow ->.

The final expression in the function will be used as return value. Alternatively, the return statement can be used to return a value earlier from within the function, even from inside loops or if statements.

Let’s rewrite FizzBuzz using functions!

// There's no restriction on the order of function definitions
pub fn main() {
    // We can use this function here, and define it somewhere later
    fizzbuzz_to(100);
}

// Function that returns a boolean value
fn is_divisible_by(lhs: int, rhs: int) -> bool {
    // Corner case, early return
    if rhs == 0 {
        return false;
    }

    // This is an expression, the `return` keyword is not necessary here
    lhs % rhs == 0
}

// Functions that "don't" return a value, actually return the unit type `()`
fn fizzbuzz(n: int) -> () {
    if is_divisible_by(n, 15) {
        println!("fizzbuzz");
    } else if is_divisible_by(n, 3) {
        println!("fizz");
    } else if is_divisible_by(n, 5) {
        println!("buzz");
    } else {
        println!("{}", n);
    }
}

// When a function returns `()`, the return type can be omitted from the
// signature
fn fizzbuzz_to(n: int) {
    for n in 1..=n {
        fizzbuzz(n);
    }
}

Associated functions & Methods

Some functions are connected to a particular type. These come in two forms: associated functions, and methods. Associated functions are functions that are defined on a type generally, while methods are associated functions that are called on a particular instance of a type.

struct Point {
    x: float,
    y: float,
}

// Implementation block, all `Point` associated functions & methods go in here
impl Point {
    // This is an "associated function" because this function is associated with
    // a particular type, that is, Point.
    //
    // Associated functions don't need to be called with an instance.
    // These functions are generally used like constructors.
    fn origin() -> Point {
        Point { x: 0.0, y: 0.0 }
    }

    // Another associated function, taking two arguments:
    fn new(x: float, y: float) -> Point {
        Point { x: x, y: y }
    }
}

struct Rectangle {
    p1: Point,
    p2: Point,
}

impl Rectangle {
    // This is a method
    // `self` is sugar for `self: Self`, where `Self` is the type of the
    // caller object. In this case `Self` = `Rectangle`
    fn area(self) -> float {
        // `self` gives access to the struct fields via the dot operator
        let Point { x: x1, y: y1 } = self.p1;
        let Point { x: x2, y: y2 } = self.p2;

        // `abs` is a `float` method that returns the absolute value of the
        // caller
        ((x1 - x2) * (y1 - y2)).abs()
    }

    fn perimeter(self) -> float {
        let Point { x: x1, y: y1 } = self.p1;
        let Point { x: x2, y: y2 } = self.p2;

        2.0 * ((x1 - x2).abs() + (y1 - y2).abs())
    }

    // Values in BEAM are immutable, so traditionally "mut" methods return
    // the new value instead.
    fn translate(self, x: float, y: float) -> Self {
        Rectangle {
            p1: Point { x: self.p1.x + x, y: self.p1.y + y },
            p2: Point { x: self.p2.x + x, y: self.p2.y + y },
        }
    }
}

pub fn main() {
    let rectangle = Rectangle {
        // Associated functions are called using double colons
        p1: Point::origin(),
        p2: Point::new(3.0, 4.0),
    };

    // Methods are called using the dot operator
    // Note that the first argument `self` is implicitly passed, i.e.
    // `rectangle.perimeter()` === `Rectangle::perimeter(rectangle)`
    println!("Rectangle perimeter: {}", rectangle.perimeter());
    println!("Rectangle area: {}", rectangle.area());

    // `mut` keyword lets us rebind the variable in the next statement.
    let mut square = Rectangle {
        p1: Point::origin(),
        p2: Point::new(1.0, 1.0),
    };

    square = square.translate(1.0, 1.0);
}

Closures

Closures are functions that can capture the enclosing environment. For example, a closure that captures the x variable:

|val| val + x

The syntax and capabilities of closures make them very convenient for on the fly usage. Calling a closure is exactly like calling a function. However, both input and return types can be inferred and input variable names must be specified.

Other characteristics of closures include:

  • using || instead of () around input variables.
  • optional body delimitation ({}) for a single line expression (mandatory otherwise).
  • the ability to capture the outer environment variables.
pub fn main() {
    let outer_var = 42;

    // A regular function can't refer to variables in the enclosing environment
    //fn function(i: int) -> int { i + outer_var }
    // TODO: uncomment the line above and see the compiler error. The compiler
    // suggests that we define a closure instead.

    // Closures are anonymous, here we are binding them to references.
    // Annotation is identical to function annotation but is optional
    // as are the `{}` wrapping the body. These nameless functions
    // are assigned to appropriately named variables.
    let closure_annotated = |i: int| -> int { i + outer_var };
    let closure_inferred  = |i     |          i + outer_var  ;

    // Call the closures.
    println!("closure_annotated: {}", closure_annotated(1));
    println!("closure_inferred: {}", closure_inferred(1));
    // Once closure's type has been inferred, it cannot be inferred again with another type.
    //println!("cannot reuse closure_inferred with another type: {}", closure_inferred(42.0));
    // TODO: uncomment the line above and see the compiler error.

    // A closure taking no arguments which returns an `int`.
    // The return type is inferred.
    let one = || 1;
    println!("closure returning one: {}", one());

    // A closure cannot modify the enclosing variables
    let mut outer_mut_var = 42;
    let add = |x|{ outer_mut_var += x; }
    // Error! Cannot assign a new value to a variable defined outside closure
}

Functions as input and output parameters

Input parameters

Closures and functions may both be used as function arguments. Simple function references are typed with fnref(), while closures are typed with fn() - with former implicitly convertible to the latter.

fn call_me_ref(f: fnref(int) -> int) {
    f(1);
}

fn call_me(f: fn(int) -> int) {
    f(2);
}

fn function(x: int) -> int {
    x + 1
}

pub fn main() {
    let closure = |x| x + 42;

    call_me(function);
    call_me(closure);

    call_me_ref(function);
    // call_me_ref(closure);
    // ^ ERROR! `fn(int) -> int` cannot be used as `fnref(int) -> int`
}

Output parameters

Just as fn and fnref can be used as input parameters, they can also be returned from other functions.

fn lazy_add(fx: fn() -> int, fy: fn() -> int) -> fn() -> int {
    || fx() + fy()
}

fn add(x: int, y: int) -> int {
    x + y
}

fn mul(x: int, y: int) -> int {
    x * y
}

enum MathOp {
    Add,
    Mul,
}

fn choose_op(op: MathOp) -> fnref(int, int) -> int {
    match op {
        MathOp::Add => add,
        MathOp::Mul => mul,
    }
}

pub fn main() {
    let fx = || {
        println!("fx evaluated!");
        3
    };

    let fy = || {
        println!("fy evaluated!");
        5
    };

    // won't print anything
    let lazy_result = lazy_add(fx, fy);

    let op = choose_op(MathOp::Add);
    println!("{} op {} = {}", 3, 5, op(3, 5))
}

Diverging functions

Diverging functions never return. They are marked using !, which is an empty type.

fn foo() -> ! {
    panic!("This call never returns.");
}

As opposed to all the other types, this one cannot be instantiated, because the set of all possible values this type can have is empty. Note that, it is different from the () type, which has exactly one possible value.

For example, this function returns as usual, although there is no information in the return value.

fn some_fn() {
    ()
}

pub fn main() {
    let _a: () = some_fn();
    println!("This function returns and you can see this line.");
}

As opposed to this function, which will never return the control back to the caller.

#![feature(never_type)]

fn some_fn() -> ! {
    panic!("This call never returns.");
}

pub fn main() {
    let _a = some_fn();
    println!("You will never see this line!");
}

Although this might seem like an abstract concept, it is actually very useful and often handy. The main advantage of this type is that it can be cast to any other type, making it versatile in situations where an exact type is required, such as in match branches. This flexibility allows us to write code like this:

pub fn main() {
    fn sum_odd_numbers(up_to: int) -> int {
        let mut acc = 0;
        for i in 0..up_to {
            // Notice that the return type of this match expression must be int
            // because of the type of the "addition" variable.
            let addition: int = match i%2 == 1 {
                // The "i" variable is of type int, which is perfectly fine.
                true => i,
                // On the other hand, the "continue" expression does not return
                // int, but it is still fine, because it never returns and therefore
                // does not violate the type requirements of the match expression.
                false => continue,
            };
            acc += addition;
        }
        acc
    }
    println!("Sum of odd numbers up to 9 (excluding): {}", sum_odd_numbers(9));
}

It is also the return type of functions that loop forever (e.g. loop {}) like network servers or functions that terminate the process (e.g. exit()).

Extern calls

In Patina, all calls to functions are local by default - if at all possible. This means that the Erlang-level calls to functions defined in the same Erlang module do not use fully-qualified module path, even if the path is fully-qualified in Patina source code.

However, in some advanced usage we want to explicitly refer to another function using its fully-qualified path. For these cases, you can use #[extern_call] attribute on the call expression.

fn priv_function() -> int {
    42
}

pub fn public_function() -> int {
    42
}

pub fn main() {
    // Local call: `public_function()`
    public_function();

    // Qualified, but still a local call: `public_function()`
    self::public_function();

    // Remote call: `'Elixir.Patina.MyPkg':public_function()`
    #[extern_call]
    public_function();

    // Always a local call: `priv_function` is not exported!
    // Prepending `#[extern_call]` would result in a compilation error.
    priv_function();
}

Modules

Patina provides a powerful module system that can be used to hierarchically split code in logical units (modules), and manage visibility (public/private) between them.

A Patina module is a collection of items: functions, structs, traits, impl blocks, and even other modules.

Every Patina module uniquely maps to a BEAM module, but not every Patina-created BEAM module maps to a Patina module. For example, every struct and enum gets its own BEAM module.

Visibility

By default, the items in a module have private visibility, but this can be overridden with the pub modifier. Only the public items of a module can be accessed from outside the module scope.

// A module named `my_mod`.
// On the BEAM side, module names are converted to PascalCase.
// This makes calling Patina code from Elixir significantly more ergonomic.
mod my_mod {
    // On BEAM side, module `my_mod` will be saved as `Elixir.Patina.MyPkg.MyMod.beam` .
    // However, this is configurable so you can name your BEAM module anything.
    // For example, to replace an Elixir `MyMod` module:
    #![beam_module("Elixir.MyMod")]
    // Note that this only changes the BEAM module name for the current
    // Patina module, and doesn't affect the names of its submodules!

    // Items in modules default to private visibility.
    fn private_function() {
        println!("called `my_mod::private_function()`");
    }

    // Use the `pub` modifier to override default visibility.
    pub fn function() {
        println!("called `my_mod::function()`");
    }

    // Items can access other items in the same module,
    // even when private.
    pub fn indirect_access() {
        print!("called `my_mod::indirect_access()`, that\n> ");
        private_function();
    }

    // Modules can also be nested
    pub mod nested {
        pub fn function() {
            println!("called `my_mod::nested::function()`");
        }

        #[allow(dead_code)]
        fn private_function() {
            println!("called `my_mod::nested::private_function()`");
        }

        // Functions declared using `pub(in path)` syntax are only visible
        // within the given path. `path` must be a parent or ancestor module.
        pub(in pkg::my_mod) fn public_function_in_my_mod() {
            print!("called `my_mod::nested::public_function_in_my_mod()`, that\n> ");
            public_function_in_nested();
        }

        // Functions declared using `pub(self)` syntax are only visible within
        // the current module, which is the same as leaving them private - except
        // they *will* be exported by the generated BEAM module.
        pub(self) fn public_function_in_nested() {
            println!("called `my_mod::nested::public_function_in_nested()`");
        }

        // Functions declared using `pub(super)` syntax are only visible within
        // the parent module. The same caveats apply - these functions are still
        // exported in the BEAM module.
        pub(super) fn public_function_in_super_mod() {
            println!("called `my_mod::nested::public_function_in_super_mod()`");
        }
    }

    pub fn call_public_function_in_my_mod() {
        print!("called `my_mod::call_public_function_in_my_mod()`, that\n> ");
        nested::public_function_in_my_mod();
        print!("> ");
        nested::public_function_in_super_mod();
    }

    // pub(pkg) makes functions visible only within the current package.
    pub(pkg) fn public_function_in_pkg() {
        println!("called `my_mod::public_function_in_pkg()`");
    }

    // Nested modules follow the same rules for visibility
    mod private_nested {
        #[allow(dead_code)]
        pub fn function() {
            println!("called `my_mod::private_nested::function()`");
        }

        // Private parent items will still restrict the visibility of a child item,
        // even if it is declared as visible within a bigger scope.
        #[allow(dead_code)]
        pub(pkg) fn restricted_function() {
            println!("called `my_mod::private_nested::restricted_function()`");
        }
    }
}

fn function() {
    println!("called `function()`");
}

pub fn main() {
    // Modules allow disambiguation between items that have the same name.
    function();
    my_mod::function();

    // Public items, including those inside nested modules, can be
    // accessed from outside the parent module.
    my_mod::indirect_access();
    my_mod::nested::function();
    my_mod::call_public_function_in_my_mod();

    // pub(pkg) items can be called from anywhere in the same pkg
    my_mod::public_function_in_pkg();

    // pub(in path) items can only be called from within the module specified
    // Error! function `public_function_in_my_mod` is private
    //my_mod::nested::public_function_in_my_mod();
    // TODO ^ Try uncommenting this line

    // Private items of a module cannot be directly accessed, even if
    // nested in a public module:

    // Error! `private_function` is private
    //my_mod::private_function();
    // TODO ^ Try uncommenting this line

    // Error! `private_function` is private
    //my_mod::nested::private_function();
    // TODO ^ Try uncommenting this line

    // Error! `private_nested` is a private module
    //my_mod::private_nested::function();
    // TODO ^ Try uncommenting this line

    // Error! `private_nested` is a private module
    //my_mod::private_nested::restricted_function();
    // TODO ^ Try uncommenting this line
}

Visibility within BEAM

Non-pub functions are simply not exported from the generated BEAM modules.

Otherwise, all pub functions are exported - whether pub(self), pub(super), pub(pkg), or any other. In these cases, Patina enforces visibility locally.

Struct visibility

Structs have an extra level of visibility with their fields. The visibility defaults to private, and can be overridden with the pub modifier. This visibility only matters when a struct is accessed from outside the module where it is defined, and has the goal of hiding information (encapsulation).

mod my {
    // On BEAM side, struct `RenamedStruct` and its functions will live
    // in their own BEAM module `Elixir.Patina.MyPkg.My.RenamedStruct.beam` .
    // However, this is configurable so you can name your BEAM module anything.
    #[beam_module("Elixir.RenamedStruct")]
    pub struct RenamedStruct {
    }

    // A public struct with a public field of generic type `T`
    pub struct OpenBox<T> {
        pub contents: T,
    }

    // A public struct with a private field of generic type `T`
    pub struct ClosedBox<T> {
        contents: T,
    }

    impl<T> ClosedBox<T> {
        // A public constructor method
        pub fn new(contents: T) -> ClosedBox<T> {
            ClosedBox {
                contents: contents,
            }
        }
    }
}

pub fn main() {
    // Public structs with public fields can be constructed as usual
    let open_box = my::OpenBox { contents: "public information" };

    // and their fields can be normally accessed.
    println!("The open box contains: {}", open_box.contents);

    // Public structs with private fields cannot be constructed using field names.
    // Error! `ClosedBox` has private fields
    //let closed_box = my::ClosedBox { contents: "classified information" };
    // TODO ^ Try uncommenting this line

    // However, structs with private fields can be created using
    // public constructors
    let _closed_box = my::ClosedBox::new("classified information");

    // and the private fields of a public struct cannot be accessed.
    // Error! The `contents` field is private
    //println!("The closed box contains: {}", _closed_box.contents);
    // TODO ^ Try uncommenting this line
}

See also:

generics and methods

The use declaration

The use declaration can be used to bind a full path to a new name, for easier access. It is often used like this:

use pkg::deeply::nested::{
    my_first_function,
    my_second_function,
    AndATraitType
};

pub fn main() {
    my_first_function();
}

You can use the as keyword to bind imports to a different name:

// Bind the `deeply::nested::function` path to `other_function`.
use deeply::nested::function as other_function;

fn function() {
    println!("called `function()`");
}

mod deeply {
    pub mod nested {
        pub fn function() {
            println!("called `deeply::nested::function()`");
        }
    }
}

pub fn main() {
    // Easier access to `deeply::nested::function`
    other_function();

    println!("Entering block");
    {
        // This is equivalent to `use deeply::nested::function as function`.
        // This `function()` will shadow the outer one.
        use pkg::deeply::nested::function;

        // `use` bindings have a local scope. In this case, the
        // shadowing of `function()` is only in this block.
        function();

        println!("Leaving block");
    }

    function();
}

super and self

The super and self keywords can be used in the path to remove ambiguity when accessing items and to prevent unnecessary hardcoding of paths.

fn function() {
    println!("called `function()`");
}

mod cool {
    pub fn function() {
        println!("called `cool::function()`");
    }
}

mod my {
    fn function() {
        println!("called `my::function()`");
    }

    mod cool {
        pub fn function() {
            println!("called `my::cool::function()`");
        }
    }

    pub fn indirect_call() {
        // Let's access all the functions named `function` from this scope!
        print!("called `my::indirect_call()`, that\n> ");

        // The `self` keyword refers to the current module scope - in this case `My`.
        // Calling `self::function()` and calling `function()` directly both give
        // the same result, because they refer to the same function.
        self::function();
        function();

        // We can also use `self` to access another module inside `My`:
        self::cool::function();

        // The `super` keyword refers to the parent scope (outside the `My` module).
        super::function();

        // This will bind to the `cool::function` in the *pkg* scope.
        // In this case the pkg scope is the outermost scope.
        {
            use pkg::cool::function as root_function;
            root_function();
        }
    }
}

pub fn main() {
    my::indirect_call();
}

File hierarchy

Modules can be mapped to a file/directory hierarchy. Let’s break down the visibility example in files:

$ tree .
.
├── my_mod
│   └── inaccessible.rs
│   └── nested.rs
├── my_mod.rs
└── split.rs

In split.rs:

// This declaration will look for a file named `my_mod.rs` and will
// insert its contents inside a module named `my_mod` under this scope
mod my_mod;

fn function() {
    println!("called `function()`");
}

pub fn main() {
    my_mod::function();

    function();

    my_mod::indirect_access();

    my_mod::nested::function();
}

In my_mod.rs:

// Similarly `mod inaccessible` and `mod nested` will locate the `nested.rs`
// and `inaccessible.rs` files and insert them here under their respective
// modules
mod inaccessible;
pub mod nested;

pub fn function() {
    println!("called `my_mod::function()`");
}

fn private_function() {
    println!("called `my_mod::private_function()`");
}

pub fn indirect_access() {
    print!("called `my_mod::indirect_access()`, that\n> ");

    private_function();
}

In my_mod/nested.rs:

pub fn function() {
    println!("called `my_mod::nested::function()`");
}

#[allow(dead_code)]
fn private_function() {
    println!("called `my_mod::nested::private_function()`");
}

In my_mod/inaccessible.rs:

#[allow(dead_code)]
pub fn public_function() {
    println!("called `my_mod::inaccessible::public_function()`");
}

Let’s check that things still work as before:

$ patinac split.pt && patina run -m Split
called `my_mod::function()`
called `function()`
called `my_mod::indirect_access()`, that
> called `my_mod::private_function()`
called `my_mod::nested::function()`

Packages

A package (pkg) is the basic unit of distribution for Patina libraries. It’s what you publish to the package manager like Hex.pm, what you specify in your dependencies list, and what you reference when calling these dependencies.

Creating a package

patina new my_json_lib creates a new package in the my_json_lib directory:

my_json_lib/
├── Patina.toml
├── rebar.config.script
└── src/
    ├── my_json_lib.pt
    └── my_json_lib.app.src.script

The two .script files make the package a regular rebar3-compatible project.

Naming conventions

A package has three top-level names:

  • The package name itself: this is the snake_case name that Patina code uses to reference the package, e.g. my_json_lib in my_json_lib::decoder::parse(input). It must be a valid identifier, and core and std are reserved. For most packages, this is the only name that’s set explicitly.

  • The OTP Application name: every package is compiled into an OTP application, which defaults to the package name by default.

  • The Hex package name: if the package is published to Hex.pm, this is the name

  • it’s published under. It defaults to the OTP Application name.

Package manifest

The root directory of a Patina package must contain a Patina.toml file:

[package]
name = "my_json_lib"
version = "0.1.0"
description = "A JSON library" # optional
otp_app_name = "my_json_lib"   # optional and discouraged; defaults to the package name
path = "src/my_json_lib.pt"    # optional; defaults to src/<name>,pt

[dependencies]
# A package from Hex.pm, with a version requirement.
my_utils = "~> 1.0"
# A package from a git repository, optionally at a branch, tag, or commit.
my_parser = { git = "https://example.com/my_parser.git", ref = "v0.2.0" }
# A package from a local directory.
my_helpers = { path = "../my_helpers" }

Package file

The package file is the root source file of the package. By default, its path relative to Patina.toml is src/<pkg name>.pt, but it can be set in Patina.toml. Patina compiler will start reading from that file, and, when it encounters mod declarations, contents of the module files will be inserted in their place. Files that are not referenced by the tree rooted in the package file will not be read or compiled.

Attributes

An attribute is metadata applied to some module or item. This metadata can be used to/for:

Attributes look like #[outer_attribute] or #![inner_attribute], with the difference between them being where they apply.

  • #[outer_attribute] applies to the item immediately following it. Some examples of items are: a function, a module declaration, a constant, a structure, an enum. Here is an example where attribute #[derive(Debug)] applies to the struct Rectangle:

    #[derive(Debug)]
    struct Rectangle {
        width: int,
        height: int,
    }
  • #![inner_attribute] applies to the enclosing item (typically a module). In other words, this attribute is interpreted as applying to the entire scope in which it’s placed. Here is an example where #![beam_module("Elixir.MyMod")] applies to the enclosing module:

    mod MyMod {
      #![beam_module("Elixir.MyMod")]
    
      fn inner() {
        println!("inner called!");
      }
    }
    
    pub fn main() {
      MyMod::inner();
    }

Attributes can take arguments with different syntaxes:

  • #[attribute = "value"]
  • #[attribute(key = "value")]
  • #[attribute(value)]

Attributes can have multiple values and can be separated over multiple lines, too:

#[attribute(value, value2)]


#[attribute(value, value2, value3,
            value4, value5)]

Generics

Generics is the topic of generalizing types and functionalities to broader cases. This is extremely useful for reducing code duplication in many ways, but can call for rather involved syntax. Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid. The simplest and most common use of generics is for type parameters.

A type parameter is specified as generic by the use of angle brackets and upper camel case: <Aaa, Bbb, ...>. “Generic type parameters” are typically represented as <T>. In Patina, “generic” also describes anything that accepts one or more generic type parameters <T>. Any type specified as a generic type parameter is generic, and everything else is concrete (non-generic).

For example, defining a generic function named foo that takes an argument T of any type:

fn foo<T>(arg: T) { ... }

Because T has been specified as a generic type parameter using <T>, it is considered generic when used here as (arg: T). This is the case even if T has previously been defined as a struct.

This example shows some of the syntax in action:

// A concrete type `A`.
struct A;

// In defining the type `Single`, the first use of `A` is not preceded by `<A>`.
// Therefore, `Single` is a concrete type, and `A` is defined as above.
struct Single(A);
//            ^ Here is `Single`s first use of the type `A`.

// Here, `<T>` precedes the first use of `T`, so `SingleGen` is a generic type.
// Because the type parameter `T` is generic, it could be anything, including
// the concrete type `A` defined at the top.
struct SingleGen<T>(T);

pub fn main() {
    // `Single` is concrete and explicitly takes `A`.
    let _s = Single(A);

    // Create a variable `_char` of type `SingleGen<char>`
    // and give it the value `SingleGen('a')`.
    // Here, `SingleGen` has a type parameter explicitly specified.
    let _char: SingleGen<char> = SingleGen('a');

    // `SingleGen` can also have a type parameter implicitly specified:
    let _t    = SingleGen(A); // Uses `A` defined at the top.
    let _int  = SingleGen(6); // Uses `int`.
    let _char = SingleGen('a'); // Uses `char`.
}

See also:

structs

Functions

The same set of rules can be applied to functions: a type T becomes generic when preceded by <T>.

Using generic functions sometimes requires explicitly specifying type parameters. This may be the case if the function is called where the return type is generic, or if the compiler doesn’t have enough information to infer the necessary type parameters.

A function call with explicitly specified type parameters looks like: fun::<A, B, ...>().

struct A;          // Concrete type `A`.
struct S(A);       // Concrete type `S`.
struct SGen<T>(T); // Generic type `SGen`.

// Define a function `reg_fn` that takes an argument `_s` of type `S`.
// This has no `<T>` so this is not a generic function.
fn reg_fn(_s: S) {}

// Define a function `gen_spec_t` that takes an argument `_s` of type `SGen<T>`.
// It has been explicitly given the type parameter `A`, but because `A` has not
// been specified as a generic type parameter for `gen_spec_t`, it is not generic.
fn gen_spec_t(_s: SGen<A>) {}

// Define a function `gen_spec_int` that takes an argument `_s` of type `SGen<int>`.
// It has been explicitly given the type parameter `int`, which is a specific type.
// Because `int` is not a generic type, this function is also not generic.
fn gen_spec_int(_s: SGen<int>) {}

// Define a function `generic` that takes an argument `_s` of type `SGen<T>`.
// Because `SGen<T>` is preceded by `<T>`, this function is generic over `T`.
fn generic<T>(_s: SGen<T>) {}

pub fn main() {
    // Using the non-generic functions
    reg_fn(S(A));          // Concrete type.
    gen_spec_t(SGen(A));   // Implicitly specified type parameter `A`.
    gen_spec_int(SGen(6)); // Implicitly specified type parameter `int`.

    // Explicitly specified type parameter `char` to `generic()`.
    generic::<char>(SGen('a'));

    // Implicitly specified type parameter `char` to `generic()`.
    generic(SGen('c'));
}

See also:

functions and structs

Implementation

Similar to functions, implementations require care to remain generic.

struct S; // Concrete type `S`
struct GenericVal<T>(T); // Generic type `GenericVal`

// impl of GenericVal where we explicitly specify type parameters:
impl GenericVal<float> {} // Specify `float`
impl GenericVal<S> {} // Specify `S` as defined above

// `<T>` Must precede the type to remain generic
impl<T> GenericVal<T> {}
struct Val {
    val: int,
}

struct GenVal<T> {
    gen_val: T,
}

// impl of Val
impl Val {
    fn value(self) -> int {
        self.val
    }
}

// impl of GenVal for a generic type `T`
impl<T> GenVal<T> {
    fn value(self) -> T {
        self.gen_val
    }
}

pub fn main() {
    let x = Val { val: 3 };
    let y = GenVal { gen_val: 42 };

    println!("{}, {}", x.value(), y.value());
}

See also:

impl, and struct

Traits

Of course traits can also be generic. Here we define a SeededHash trait that hashes itself and an input.

extern mod erlang;

struct Empty;
struct StaticSeed;

// A trait generic over `T`.
trait SeededHash<T> {
    // Define a method on the caller type which takes an
    // additional single parameter `T`.
    fn seeded_hash(self, seed: T) -> int;
}

// Implement `SeededHash<T>` for any generic parameter `T` and
// caller `U`.
impl<T, U> SeededHash<T> for U {
    fn seeded_hash(self, seed: T) -> int {
        erlang::phash2((seed, self)).unsafe_cast::<int>()
    }
}

pub fn main() {
    let empty = Empty;
    let seed  = StaticSeed;

    // hash `empty` with static seed
    empty.seeded_hash(seed);
}

See also:

struct, and trait

Bounds

When working with generics, the type parameters often must use traits as bounds to stipulate what functionality a type implements. For example, the following example uses the trait Display to print and so it requires T to be bound by Display; that is, T must implement Display.

// Define a function `printer` that takes a generic type `T` which
// must implement trait `Display`.
fn printer<T: Display>(t: T) {
    println!("{}", t);
}

Bounding restricts the generic to types that conform to the bounds. That is:

struct S<T: Display>(T);

pub fn main() {
    // Error! `(T)` does not implement `Display`. This
    // specialization will fail.
    let s = S((1));
}

Another effect of bounding is that generic instances are allowed to access the methods of traits specified in the bounds. For example:

// A trait which implements the print marker: `{:?}`.
use Std::Fmt::Debug;

trait HasArea {
    fn area(self) -> float;
}

impl HasArea for Rectangle {
    fn area(self) -> float { self.length * self.height }
}

#[derive(Debug)]
struct Rectangle { length: float, height: float }
#[allow(dead_code)]
struct Triangle  { length: float, height: float }

// The generic `T` must implement `Debug`. Regardless
// of the type, this will work properly.
fn print_debug<T: Debug>(t: T) {
    println!("{:?}", t);
}

// `T` must implement `HasArea`. Any type which meets
// the bound can access `HasArea`'s function `area`.
fn area<T: HasArea>(t: T) -> float { t.area() }

pub fn main() {
    let rectangle = Rectangle { length: 3.0, height: 4.0 };
    let _triangle = Triangle  { length: 3.0, height: 4.0 };

    print_debug(rectangle);
    println!("Area: {}", area(rectangle));

    //print_debug(_triangle);
    //println!("Area: {}", area(_triangle));
    // ^ TODO: Try uncommenting these.
    // | Error: Does not implement either `Debug` or `HasArea`.
}

As an additional note, where clauses can also be used to apply bounds in some cases to be more expressive.

See also:

structs, and traits

Testcase: empty bounds

A consequence of how bounds work is that even if a trait doesn’t include any functionality, you can still use it as a bound. Eq is one example of such traits from the std library.

struct Cardinal;
struct BlueJay;
struct Turkey;

trait Red {}
trait Blue {}

impl Red for Cardinal {}
impl Blue for BlueJay {}

// These functions are only valid for types which implement these
// traits. The fact that the traits are empty is irrelevant.
fn red<T: Red>(_: T)   -> str { "red" }
fn blue<T: Blue>(_: T) -> str { "blue" }

pub fn main() {
    let cardinal = Cardinal;
    let blue_jay = BlueJay;
    let _turkey   = Turkey;

    // `red()` won't work on a blue jay nor vice versa
    // because of the bounds.
    println!("A cardinal is {}", red(cardinal));
    println!("A blue jay is {}", blue(blue_jay));
    //println!("A turkey is {}", red(_turkey));
    // ^ TODO: Try uncommenting this line.
}

See also:

Std::cmp::Eq, and traits

Multiple bounds

Multiple bounds for a single type can be applied with a +. Like normal, different types are separated with ,.

use Std::Fmt::{Debug, Display};

fn compare_prints<T: Debug + Display>(t: T) {
    println!("Debug: `{:?}`", t);
    println!("Display: `{}`", t);
}

fn compare_types<T: Debug, U: Debug>(t: T, u: U) {
    println!("t: `{:?}`", t);
    println!("u: `{:?}`", u);
}

pub fn main() {
    let string = "words";
    let list = [1, 2, 3];
    let tuple = (1, 2, 3);

    compare_prints(string);
    //compare_prints(list);
    // TODO ^ Try uncommenting this.

    compare_types(list, tuple);
}

See also:

traits

Where clauses

A bound can also be expressed using a where clause immediately before the opening {, rather than at the type’s first mention. Additionally, where clauses can apply bounds to arbitrary types, rather than just to type parameters.

Some cases that a where clause is useful:

  • When specifying generic types and bounds separately is clearer:
impl <A: TraitB + TraitC, D: TraitE + TraitF> MyTrait<A, D> for YourType {}

// Expressing bounds with a `where` clause
impl <A, D> MyTrait<A, D> for YourType where
    A: TraitB + TraitC,
    D: TraitE + TraitF {}
  • When using a where clause is more expressive than using normal syntax. The impl in this example cannot be directly expressed without a where clause:
use Std::Fmt::Debug;

trait PrintInOption {
    fn print_in_option(self);
}

// Because we would otherwise have to express this as `T: Debug` or
// use another method of indirect approach, this requires a `where` clause:
impl<T> PrintInOption for T where
    Option<T>: Debug {
    // We want `Option<T>: Debug` as our bound because that is what's
    // being printed. Doing otherwise would be using the wrong bound.
    fn print_in_option(self) {
        println!("{:?}", Some(self));
    }
}

pub fn main() {
    let list = [1, 2, 3];

    list.print_in_option();
}

See also:

struct, and trait

New Type Idiom

The newtype idiom gives compile time guarantees that the right type of value is supplied to a program.

For example, an age verification function that checks age in years, must be given a value of type Years.

struct Years(int);

struct Days(int);

impl Years {
    pub fn to_days(self) -> Days {
        Days(self.0 * 365)
    }
}

impl Days {
    /// truncates partial years
    pub fn to_years(self) -> Years {
        Years(self.0 / 365)
    }
}

fn is_adult(age: Years) -> bool {
    age.0 >= 18
}

pub fn main() {
    let age = Years(25);
    let age_days = age.to_days();
    println!("Is an adult? {}", is_adult(age));
    println!("Is an adult? {}", is_adult(age_days.to_years()));
    // println!("Is an adult? {}", is_adult(age_days));
}

Uncomment the last print statement to observe that the type supplied must be Years.

To obtain the newtype’s value as the base type, you may use the tuple or destructuring syntax like so:

struct Years(int);

pub fn main() {
    let years = Years(42);
    let years_as_primitive_1: int = years.0; // Tuple
    let Years(years_as_primitive_2) = years; // Destructuring
}

See also:

structs

Associated items

“Associated Items” refers to a set of rules pertaining to items of various types. It is an extension to trait generics, and allows traits to internally define new items.

One such item is called an associated type, providing simpler usage patterns when the trait is generic over its container type.

The Problem

A trait that is generic over its container type has type specification requirements - users of the trait must specify all of its generic types.

In the example below, the Contains trait allows the use of the generic types A and B. The trait is then implemented for the Container type, specifying int for A and B so that it can be used with fn difference().

Because Contains is generic, we are forced to explicitly state all of the generic types for fn difference(). In practice, we want a way to express that A and B are determined by the input C. As you will see in the next section, associated types provide exactly that capability.

struct Container(int, int);

// A trait which checks if 2 items are stored inside of container.
// Also retrieves first or last value.
trait Contains<A, B> {
    fn contains(self, _: A, _: B) -> bool; // Explicitly requires `A` and `B`.
    fn first(self) -> int; // Doesn't explicitly require `A` or `B`.
    fn last(self) -> int;  // Doesn't explicitly require `A` or `B`.
}

impl Contains<int, int> for Container {
    // True if the numbers stored are equal.
    fn contains(self, number_1: int, number_2: int) -> bool {
        (self.0 == number_1) && (self.1 == number_2)
    }

    // Grab the first number.
    fn first(self) -> int { self.0 }

    // Grab the last number.
    fn last(self) -> int { self.1 }
}

// `C` contains `A` and `B`. In light of that, having to express `A` and
// `B` again is a nuisance.
fn difference<A, B, C>(container: C) -> int where
    C: Contains<A, B> {
    container.last() - container.first()
}

pub fn main() {
    let number_1 = 3;
    let number_2 = 10;

    let container = Container(number_1, number_2);

    println!("Does container contain {} and {}: {}",
        number_1, number_2,
        container.contains(number_1, number_2));
    println!("First number: {}", container.first());
    println!("Last number: {}", container.last());

    println!("The difference is: {}", difference(container));
}

See also:

structs, and traits

Associated types

The use of “Associated types” improves the overall readability of code by moving inner types locally into a trait as output types. Syntax for the trait definition is as follows:

// `A` and `B` are defined in the trait via the `type` keyword.
// (Note: `type` in this context is different from `type` when used for
// aliases).
trait Contains {
    type A;
    type B;

    // Updated syntax to refer to these new types generically.
    fn contains(self, _: Self::A, _: Self::B) -> bool;
}

Note that functions that use the trait Contains are no longer required to express A or B at all:

// Without using associated types
fn difference<A, B, C>(container: C) -> int where
    C: Contains<A, B> { ... }

// Using associated types
fn difference<C: Contains>(container: C) -> int { ... }

Let’s rewrite the example from the previous section using associated types:

struct Container(int, int);

// A trait which checks if 2 items are stored inside of container.
// Also retrieves first or last value.
trait Contains {
    // Define generic types here which methods will be able to utilize.
    type A;
    type B;

    fn contains(self, _: Self::A, _: Self::B) -> bool;
    fn first(self) -> int;
    fn last(self) -> int;
}

impl Contains for Container {
    // Specify what types `A` and `B` are. If the `input` type
    // is `Container(int, int)`, the `output` types are determined
    // as `int` and `int`.
    type A = int;
    type B = int;

    // `Self::A` and `Self::B` are also valid here.
    fn contains(self, number_1: int, number_2: int) -> bool {
        (self.0 == number_1) && (self.1 == number_2)
    }
    // Grab the first number.
    fn first(self) -> int { self.0 }

    // Grab the last number.
    fn last(self) -> int { self.1 }
}

fn difference<C: Contains>(container: C) -> int {
    container.last() - container.first()
}

pub fn main() {
    let number_1 = 3;
    let number_2 = 10;

    let container = Container(number_1, number_2);

    println!("Does container contain {} and {}: {}",
        number_1, number_2,
        container.contains(number_1, number_2));
    println!("First number: {}", container.first());
    println!("Last number: {}", container.last());

    println!("The difference is: {}", difference(container));
}

Traits

A trait is a collection of methods defined for an unknown type: Self. They can access other methods declared in the same trait.

Traits can be implemented for any data type. In the example below, we define Animal, a group of methods. The Animal trait is then implemented for the Sheep data type, allowing the use of methods from Animal with a Sheep.

struct Sheep { naked: bool, name: str }

trait Animal {
    // Associated function signature; `Self` refers to the implementor type.
    fn new(name: str) -> Self;

    // Method signatures; these will return a string.
    fn name(self) -> str;
    fn noise(self) -> str;

    // Traits can provide default method definitions.
    fn talk(self) {
        println!("{} says {}", self.name(), self.noise());
    }
}

impl Sheep {
    fn is_naked(self) -> bool {
        self.naked
    }

    fn shear(self) -> Self {
        if self.is_naked() {
            // Implementor methods can use the implementor's trait methods.
            println!("{} is already naked...", self.name());
            self
        } else {
            println!("{} gets a haircut!", self.name);
            Sheep { naked: true, ..self }
        }
    }
}

// Implement the `Animal` trait for `Sheep`.
impl Animal for Sheep {
    // `Self` is the implementor type: `Sheep`.
    fn new(name: str) -> Sheep {
        Sheep { name: name, naked: false }
    }

    fn name(self) -> str {
        self.name
    }

    fn noise(self) -> str {
        if self.is_naked() {
            "baaaaah?"
        } else {
            "baaaaah!"
        }
    }

    // Default trait methods can be overridden.
    fn talk(self) {
        // For example, we can add some quiet contemplation.
        println!("{} pauses briefly... {}", self.name, self.noise());
    }
}

pub fn main() {
    // Type annotation is necessary in this case.
    let dolly: Sheep = Animal::new("Dolly");
    // TODO ^ Try removing the type annotations.

    dolly.talk();
    dolly.shear();
    dolly.talk();
}

Derive

The compiler is capable of providing basic implementations for some traits via the #[derive] attribute. These traits can still be manually implemented if a more complex behavior is required.

The following is a list of derivable traits:

  • Comparison traits: Eq, PartialEq, Ord, PartialOrd.
  • Hash, to compute a hash from T.
  • Default, to create an empty instance of a data type.
  • Debug, to format a value using the {:?} formatter.
// `Centimeters`, a tuple struct that can be compared
#[derive(PartialEq, PartialOrd)]
struct Centimeters(float);

// `Inches`, a tuple struct that can be printed
#[derive(Debug)]
struct Inches(int);

impl Inches {
    fn to_centimeters(self) -> Centimeters {
        let Inches(inches) = self;

        Centimeters(inches as float * 2.54)
    }
}

// `Seconds`, a tuple struct with no additional attributes
struct Seconds(int);

pub fn main() {
    let _one_second = Seconds(1);

    // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait
    //println!("One second looks like: {:?}", _one_second);
    // TODO ^ Try uncommenting this line

    // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait
    //let _this_is_true = (_one_second == _one_second);
    // TODO ^ Try uncommenting this line

    let foot = Inches(12);

    println!("One foot equals {:?}", foot);

    let meter = Centimeters(100.0);

    let cmp =
        if foot.to_centimeters() < meter {
            "smaller"
        } else {
            "bigger"
        };

    println!("One foot is {} than one meter.", cmp);
}

Returning Traits with dyn

Patina tries to represent structs and enums efficiently. For example, single-field structs are by default represented in runtime as that field alone, removing the overhead associated with (un)wrapping values. struct Celcius(int) will just be an integer in the BEAM VM runtime, and let c = Celcius(10); c.is_freezing will statically dispatch the call to the Celcius module.

This is why, similarly to Rust, all your functions have to return a concrete type. Just like Rust, if you have a trait like Animal, you can’t write a function that returns Animal, because Patina may not have enough runtime information to dispatch function calls to the concrete implementation.

However, you can make Patina store enough information by using the dyn keyword. Objects returned as dyn Animal will be represented with additional runtime information, and calling Animal methods will require an additional dynamic dispatch - this is why dyn is clearly marked in code, instead of being an implicit behaviour.

struct Sheep {}
struct Cow {}

trait Animal {
    // Instance method signature
    fn noise(self) -> str;
}

// Implement the `Animal` trait for `Sheep`.
impl Animal for Sheep {
    fn noise(self) -> str {
        "baaaaah!"
    }
}

// Implement the `Animal` trait for `Cow`.
impl Animal for Cow {
    fn noise(self) -> str {
        "moooooo!"
    }
}

// Returns some struct that implements Animal, but we don't know which one at compile time.
fn random_animal(random_number: float) -> dyn Animal {
    if random_number < 0.5 {
        Sheep {}
    } else {
        Cow {}
    }
}

pub fn main() {
    let random_number = 0.234;
    let animal = random_animal(random_number);
    println!("You've randomly chosen an animal, and it says {}", animal.noise());
}

Operator Overloading

In Patina, many of the operators can be overloaded via traits. That is, some operators can be used to accomplish different tasks based on their input arguments. This is possible because operators are syntactic sugar for method calls. For example, the + operator in a + b calls the add method (as in a.add(b)). This add method is part of the Add trait. Hence, the + operator can be used by any implementor of the Add trait.

use Std::Ops;

struct Foo;
struct Bar;

#[derive(Debug)]
struct FooBar;

#[derive(Debug)]
struct BarFoo;

// The `Std::Ops::Add` trait is used to specify the functionality of `+`.
// Here, we make `Add<Bar>` - the trait for addition with a RHS of type `Bar`.
// The following block implements the operation: Foo + Bar = FooBar
impl Ops::Add<Bar> for Foo {
    type Output = FooBar;

    fn add(self, _rhs: Bar) -> FooBar {
        println!("> Foo.add(Bar) was called");

        FooBar
    }
}

// By reversing the types, we end up implementing non-commutative addition.
// Here, we make `Add<Foo>` - the trait for addition with a RHS of type `Foo`.
// This block implements the operation: Bar + Foo = BarFoo
impl Ops::Add<Foo> for Bar {
    type Output = BarFoo;

    fn add(self, _rhs: Foo) -> BarFoo {
        println!("> Bar.add(Foo) was called");

        BarFoo
    }
}

pub fn main() {
    println!("Foo + Bar = {:?}", Foo + Bar);
    println!("Bar + Foo = {:?}", Bar + Foo);
}

Iterators

The Iterator trait is used to implement iterators over collections such as arrays.

The trait requires only a method to be defined for the next element, which may be manually defined in an impl block or automatically defined (as in arrays and ranges).

As a point of convenience for common situations, the for construct turns some collections into iterators using the .iter() method.

struct Fibonacci {
    curr: int,
    next: int,
}

// Implement `Iterator` for `Fibonacci`.
// The `Iterator` trait only requires a method to be defined for the `next` element,
// and an `associated type` to declare the return type of the iterator.
impl Iterator for Fibonacci {
    // We can refer to this type using Self::Item
    type Item = int;

    // Here, we define the sequence using `.curr` and `.next`.
    // The return type is `Option<T>`:
    //     * When the `Iterator` is finished, `None` is returned.
    //     * Otherwise, the next value is wrapped in `Some` and returned.
    // We use Self::Item in the return type, so we can change
    // the type without having to update the function signatures.
    fn next(self) -> (Self, Option<Self::Item>) {
        let next_self = Fibonacci { curr: self.next, next: self.curr + self.next }

        // Since there's no endpoint to a Fibonacci sequence, the `Iterator`
        // will never return `None`, and `Some` is always returned.
        (next_self, Some(self.curr))
    }
}

// Returns a Fibonacci sequence generator
fn fibonacci() -> Fibonacci {
    Fibonacci { curr: 0, next: 1 }
}

pub fn main() {
    // `0..3` is an `Iterator` that generates: 0, 1, and 2.
    let mut sequence = 0..3;
    let mut val: Option<int> = None;

    println!("Four consecutive `next` calls on 0..3");
    (sequence, val) = sequence.next();
    println!("> {:?}", val);
    (sequence, val) = sequence.next();
    println!("> {:?}", val);
    (sequence, val) = sequence.next();
    println!("> {:?}", val);
    (sequence, val) = sequence.next();
    println!("> {:?}", val);

    // `for` works through an `Iterator` until it returns `None`.
    // Each `Some` value is unwrapped and bound to a variable (here, `i`).
    println!("Iterate through 0..3 using `for`");
    for i in 0..3 {
        println!("> {}", i);
    }

    // The `take(n)` method reduces an `Iterator` to its first `n` terms.
    println!("The first four terms of the Fibonacci sequence are: ");
    for i in fibonacci().take(4) {
        println!("> {}", i);
    }

    // The `skip(n)` method shortens an `Iterator` by dropping its first `n` terms.
    println!("The next four terms of the Fibonacci sequence are: ");
    for i in fibonacci().skip(4).take(4) {
        println!("> {}", i);
    }

    let list = [1, 3, 3, 7];

    // The `iter` method produces an `Iterator` over a list
    println!("Iterate the following list {:?}", list);
    for i in list.iter() {
        println!("> {}", i);
    }
    // For implicitly calls `iter()` if the supplied value is not an iterator
    println!("Iterate the following list {:?} with implicit .iter()", list);
    for i in list {
        println!("> {}", i);
    }
}

impl Trait

impl Trait can be used in two locations:

  1. as an argument type
  2. as a return type

As an argument type

If your function is generic over a trait but you don’t mind the specific type, you can simplify the function declaration using impl Trait as the type of the argument.

For example, consider the following code:

fn parse_csv_document<R: Std::Io::BufRead>(src: R) -> Std::Io::Result<[[str]]> {
    src.lines()
        .map(|line| {
            // For each line in the source
            line.map(|line| {
                // If the line was read successfully, process it, if not, return the error
                line.split(',') // Split the line separated by commas
                    .map(|entry| entry.trim()) // Remove leading and trailing whitespace
                    .collect() // Collect all strings in a row into a [str]
            })
        })
        .collect() // Collect all lines into a [[str]]
}

parse_csv_document is generic, allowing it to take any type which implements BufRead, such as BufReader<File> or bin, but it’s not important what type R is, and R is only used to declare the type of src, so the function can also be written as:

fn parse_csv_document(src: impl Std::Io::BufRead) -> Std::Io::Result<[[str]]> {
    src.lines()
        .map(|line| {
            // For each line in the source
            line.map(|line| {
                // If the line was read successfully, process it, if not, return the error
                line.split(',') // Split the line separated by commas
                    .map(|entry| entry.trim()) // Remove leading and trailing whitespace
                    .collect() // Collect all strings in a row into a [str]
            })
        })
        .collect() // Collect all lines into a [[str]]
}

Note that using impl Trait as an argument type means that you cannot explicitly state what form of the function you use, i.e. parse_csv_document::<Std::Io::Empty>(Std::Io::empty()) will not work with the second example.

As a return type

If your function returns a type that implements MyTrait, you can write its return type as -> impl MyTrait. This can help simplify your type signatures quite a lot!

use Std::Iter;
use list::IntoIter;

// This function combines two `[int]` and returns an iterator over it.
// Look how complicated its return type is!
fn combine_lists_explicit_return_type(
    v: [int],
    u: [int],
) -> Iter::Cycle<Iter::Chain<IntoIter<int>, IntoIter<int>>> {
    v.iter().chain(u.iter()).cycle()
}

// This is the exact same function, but its return type uses `impl Trait`.
// Look how much simpler it is!
fn combine_lists(
    v: [int],
    u: [int],
) -> impl Iterator<Item=int> {
    v.iter().chain(u.iter()).cycle()
}

pub fn main() {
    let v1 = [1, 2, 3];
    let v2 = [4, 5];

    let mut (iter, item) = combine_lists(v1, v2).next();
    assert_eq!(Some(1), item);
    (iter, item) = iter.next();
    assert_eq!(Some(2), item);
    (iter, item) = iter.next();
    assert_eq!(Some(3), item);
    (iter, item) = iter.next();
    assert_eq!(Some(4), item);
    (iter, item) = iter.next();
    assert_eq!(Some(5), item);
    println!("all done");
}

Supertraits

Patina doesn’t have “inheritance”, but you can define a trait as being a superset of another trait. For example:

trait Person {
    fn name(self) -> str;
}

// Person is a supertrait of Student.
// Implementing Student requires you to also impl Person.
trait Student: Person {
    fn university(self) -> str;
}

trait Programmer {
    fn fav_language(self) -> str;
}

// CompSciStudent (computer science student) is a subtrait of both Programmer
// and Student. Implementing CompSciStudent requires you to impl both supertraits.
trait CompSciStudent: Programmer + Student {
    fn git_username(self) -> str;
}

fn comp_sci_student_greeting(student: dyn CompSciStudent) -> str {
    format!(
        "My name is {} and I attend {}. My favorite language is {}. My Git username is {}",
        student.name(),
        student.university(),
        student.fav_language(),
        student.git_username()
    )
}

struct CSStudent {
    name: str,
    university: str,
    fav_language: str,
    git_username: str
}

impl Programmer for CSStudent {
    fn fav_language(self) -> str {
        self.fav_language
    }
}

impl Student for CSStudent {
    fn university(self) -> str {
        self.university
    }
}

impl Person for CSStudent {
    fn name(self) -> str {
        self.name
    }
}

impl CompSciStudent for CSStudent {
    fn git_username(self) -> str {
        self.git_username
    }
}

pub fn main() {
    let student = CSStudent {
        name: "Alice",
        university: "MIT",
        fav_language: "Rust",
        git_username: "alice_codes",
    };

    let greeting = comp_sci_student_greeting(student);
    println!("{}", greeting);
}

Disambiguating overlapping traits

A type can implement many different traits. What if two traits both require the same name for a function? For example, many traits might have a method named get(). They might even have different return types!

Good news: because each trait implementation gets its own impl block, it’s clear which trait’s get method you’re implementing.

What about when it comes time to call those methods? To disambiguate between them, we have to use Fully Qualified Syntax.

trait UsernameWidget {
    // Get the selected username out of this widget
    fn get(self) -> str;
}

trait AgeWidget {
    // Get the selected age out of this widget
    fn get(self) -> int;
}

// A form with both a UsernameWidget and an AgeWidget
struct Form {
    username: str,
    age: int,
}

impl UsernameWidget for Form {
    fn get(self) -> str {
        self.username
    }
}

impl AgeWidget for Form {
    fn get(self) -> int {
        self.age
    }
}

pub fn main() {
    let form = Form {
        username: "rustacean",
        age: 28,
    };

    // If you uncomment this line, you'll get an error saying
    // "multiple `get` found". Because, after all, there are multiple methods
    // named `get`.
    // println!("{}", form.get());

    let username = <Form as UsernameWidget>::get(form);
    assert_eq!("rustacean", username);
    let age = <Form as AgeWidget>::get(form);
    assert_eq!(28, age);
}

macro_rules!

Patina provides a powerful macro system that allows metaprogramming. As you’ve seen in previous chapters, macros look like functions, except that their name ends with a bang !, but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Like macros in Rust and Elixir, Patina macros are expanded into abstract syntax trees, rather than string preprocessing, so you don’t get unexpected precedence bugs.

Macros are created using the macro_rules! macro.

// This is a simple macro named `say_hello`.
macro_rules! say_hello {
    // `()` indicates that the macro takes no argument.
    () => {
        // The macro will expand into the contents of this block.
        println!("Hello!")
    };
}

pub fn main() {
    // This call will expand into `println!("Hello!")`
    say_hello!()
}

So why are macros useful?

  1. Don’t repeat yourself. There are many cases where you may need similar functionality in multiple places but with different types. Often, writing a macro is a useful way to avoid repeating code. (More on this later)

  2. Domain-specific languages. Macros allow you to define special syntax for a specific purpose. (More on this later)

  3. Variadic interfaces. Sometimes you want to define an interface that takes a variable number of arguments. An example is println! which could take any number of arguments, depending on the format string. (More on this later)

Syntax

In following subsections, we will show how to define macros in Patina. There are three basic ideas:

Designators

The arguments of a macro are prefixed by a dollar sign $ and type annotated with a designator:

macro_rules! create_function {
    // This macro takes an argument of designator `ident` and
    // creates a function named `$func_name`.
    // The `ident` designator is used for variable/function names.
    ($func_name:ident) => {
        fn $func_name() {
            // The `stringify!` macro converts an `ident` into a string.
            println!("You called {:?}()",
                     stringify!($func_name));
        }
    };
}

// Create functions named `foo` and `bar` with the above macro.
create_function!(foo);
create_function!(bar);

macro_rules! print_result {
    // This macro takes an expression of type `expr` and prints
    // it as a string along with its result.
    // The `expr` designator is used for expressions.
    ($expression:expr) => {
        // `stringify!` will convert the expression *as it is* into a string.
        println!("{:?} = {:?}",
                 stringify!($expression),
                 $expression);
    };
}

pub fn main() {
    foo();
    bar();

    print_result!(1 + 1);

    // Recall that blocks are expressions too!
    print_result!({
        let x = 1;

        x * x + 2 * x - 1
    });
}

These are some of the available designators:

  • block
  • expr is used for expressions
  • ident is used for variable/function names
  • item
  • literal is used for literal constants
  • pat (pattern)
  • path
  • stmt (statement)
  • tt (token tree)
  • ty (type)
  • vis (visibility qualifier)

Overload

Macros can be overloaded to accept different combinations of arguments. In that regard, macro_rules! can work similarly to a match block:

// `test!` will compare `$left` and `$right`
// in different ways depending on how you invoke it:
macro_rules! test {
    // Arguments don't need to be separated by a comma.
    // Any template can be used!
    ($left:expr; and $right:expr) => {
        println!("{:?} and {:?} is {:?}",
                 stringify!($left),
                 stringify!($right),
                 $left && $right)
    };
    // ^ each arm must end with a semicolon.
    ($left:expr; or $right:expr) => {
        println!("{:?} or {:?} is {:?}",
                 stringify!($left),
                 stringify!($right),
                 $left || $right)
    };
}

pub fn main() {
    test!(1 + 1 == 2; and 2 * 2 == 4);
    test!(true; or false);
}

Repeat

Macros can use + in the argument list to indicate that an argument may repeat at least once, or *, to indicate that the argument may repeat zero or more times.

In the following example, surrounding the matcher with $(...),+ will match one or more expression, separated by commas. Also note that the semicolon is optional on the last case.

// `find_min!` will calculate the minimum of any number of arguments.
macro_rules! find_min {
    // Base case:
    ($x:expr) => ($x);
    // `$x` followed by at least one `$y,`
    ($x:expr, $($y:expr),+) => (
        // Call `find_min!` on the tail `$y`
        Std::Cmp::min($x, find_min!($($y),+))
    )
}

pub fn main() {
    println!("{}", find_min!(1));
    println!("{}", find_min!(1 + 2, 2));
    println!("{}", find_min!(5, 2 * 3, 4));
}

Domain Specific Languages (DSLs)

A DSL is a mini “language” embedded in a Patina macro. It is completely valid Patina because the macro system expands into normal Patina constructs, but it looks like a small language. This allows you to define concise or intuitive syntax for some special functionality (within bounds).

Suppose that I want to define a little calculator API. I would like to supply an expression and have the output printed to console.

macro_rules! calculate {
    (eval $e:expr) => {
        {
            let val: int = $e; // Force types to integers
            println!("{} = {}", stringify!{$e}, val);
        }
    };
}

pub fn main() {
    calculate! {
        eval 1 + 2 // hehehe `eval` is _not_ a Patina keyword!
    }

    calculate! {
        eval (1 + 2) * (3 / 4)
    }
}

Output:

1 + 2 = 3
(1 + 2) * (3 / 4) = 0

Note the two pairs of braces in the macro. The outer ones are part of the syntax of macro_rules!, in addition to () or [].

Variadic Interfaces

A variadic interface takes an arbitrary number of arguments. For example, println! can take an arbitrary number of arguments, as determined by the format string.

We can extend our calculate! macro from the previous section to be variadic:

macro_rules! calculate {
    // The pattern for a single `eval`
    (eval $e:expr) => {
        {
            let val: int = $e; // Force types to be integers
            println!("{} = {}", stringify!{$e}, val);
        }
    };

    // Decompose multiple `eval`s recursively
    (eval $e:expr, $(eval $es:expr),+) => {{
        calculate! { eval $e }
        calculate! { $(eval $es),+ }
    }};
}

pub fn main() {
    calculate! { // Look ma! Variadic `calculate!`!
        eval 1 + 2,
        eval 3 + 4,
        eval (2 * 3) + 1
    }
}

Output:

1 + 2 = 3
3 + 4 = 7
(2 * 3) + 1 = 7

Error handling

Error handling is the process of handling the possibility of failure. For example, failing to read a file and then continuing to use that bad input would clearly be problematic. Noticing and explicitly managing those errors saves the rest of the program from various pitfalls.

There are various ways to deal with errors in Patina, which are described in the following subchapters. They all have more or less subtle differences and different use cases. As a rule of thumb:

An explicit panic is mainly useful for tests and dealing with unrecoverable errors. For prototyping it can be useful, for example when dealing with functions that haven’t been implemented yet, but in those cases the more descriptive unimplemented is better. In tests panic is a reasonable way to explicitly fail.

The Option type is for when a value is optional or when the lack of a value is not an error condition. For example the parent of a directory - / and C: don’t have one. When dealing with Options, unwrap is fine for prototyping and cases where it’s absolutely certain that there is guaranteed to be a value. However expect is more useful since it lets you specify an error message in case something goes wrong anyway.

When there is a chance that things do go wrong and the caller has to deal with the problem, use Result. You can unwrap and expect them as well (please don’t do that unless it’s a test or quick prototype).

panic

The simplest error handling mechanism we will see is panic. It prints an error message, starts unwinding the stack, and usually exits the BEAM process. Here, we explicitly call panic on our error condition:

fn drink(beverage: str) {
    // You shouldn't drink too many sugary beverages.
    if beverage == "lemonade" { panic!("AAAaaaaa!!!!"); }

    println!("Some refreshing {} is all I need.", beverage);
}

pub fn main() {
    drink("water");
    drink("lemonade");
    drink("still water");
}

The first call to drink works. The second panics and thus the third is never called.

Patina’s panic is a BEAM error.

See also:

try/catch/after

Option & unwrap

In the last example, we showed that we can induce program failure at will. We told our program to panic if we drink a sugary lemonade. But what if we expect some drink but don’t receive one? That case would be just as bad, so it needs to be handled!

We could test this against the null string ("") as we do with a lemonade. Since we’re using Patina, let’s instead have the compiler point out cases where there’s no drink.

An enum called Option<T> in the Std library is used when absence is a possibility. It manifests itself as one of two “options”:

  • Some(T): An element of type T was found
  • None: No element was found

These cases can either be explicitly handled via match or implicitly with unwrap. Implicit handling will either return the inner element or panic.

Note that it’s possible to manually customize panic with expect, but unwrap otherwise leaves us with a less meaningful output than explicit handling. In the following example, explicit handling yields a more controlled result while retaining the option to panic if desired.

// The adult has seen it all, and can handle any drink well.
// All drinks are handled explicitly using `match`.
fn give_adult(drink: Option<str>) {
    // Specify a course of action for each case.
    match drink {
        Some("lemonade") => println!("Yuck! Too sugary."),
        Some(inner)      => println!("{}? How nice.", inner),
        None             => println!("No drink? Oh well."),
    }
}

// Others will `panic` before drinking sugary drinks.
// All drinks are handled implicitly using `unwrap`.
fn drink(drink: Option<str>) {
    // `unwrap` returns a `panic` when it receives a `None`.
    let inside = drink.unwrap();
    if inside == "lemonade" { panic!("AAAaaaaa!!!!"); }

    println!("I love {}s!!!!!", inside);
}

pub fn main() {
    let water    = Some("water");
    let lemonade = Some("lemonade");
    let void     = None;

    give_adult(water);
    give_adult(lemonade);
    give_adult(void);

    let coffee = Some("coffee");
    let nothing = None;

    drink(coffee);
    drink(nothing);
}

Unpacking options with ?

You can unpack Options by using match statements, but it’s often easier to use the ? operator. If x is an Option, then evaluating x? will return the underlying value if x is Some, otherwise it will terminate whatever function is being executed and return None.

fn next_birthday(current_age: Option<int>) -> Option<str> {
    // If `current_age` is `None`, this returns `None`.
    // If `current_age` is `Some`, the inner `int` value + 1
    // gets assigned to `next_age`
    let next_age: int = current_age? + 1;
    Some(format!("Next year I will be {}", next_age))
}

You can chain many ?s together to make your code much more readable.

struct Person {
    job: Option<Job>,
}

struct Job {
    phone_number: Option<PhoneNumber>,
}

#[allow(dead_code)]
struct PhoneNumber {
    area_code: Option<int>,
    number: int,
}

impl Person {
    // Gets the area code of the phone number of the person's job, if it exists.
    fn work_phone_area_code(self) -> Option<int> {
        // This would need many nested `match` statements without the `?` operator.
        // It would take a lot more code - try writing it yourself and see which
        // is easier.
        self.job?.phone_number?.area_code
    }
}

pub fn main() {
    let p = Person {
        job: Some(Job {
            phone_number: Some(PhoneNumber {
                area_code: Some(61),
                number: 439222222,
            }),
        }),
    };

    assert_eq!(p.work_phone_area_code(), Some(61));
}

Combinators: map

match is a valid method for handling Options. However, you may eventually find heavy usage tedious, especially with operations only valid with an input. In these cases, combinators can be used to manage control flow in a modular fashion.

Option has a built in method called map(), a combinator for the simple mapping of Some -> Some and None -> None. Multiple map() calls can be chained together for even more flexibility.

In the following example, process() replaces all functions previous to it while staying compact.

#![allow(dead_code)]

#[derive(Debug)] enum Food { Apple, Carrot, Potato }

#[derive(Debug)] struct Peeled(Food);
#[derive(Debug)] struct Chopped(Food);
#[derive(Debug)] struct Cooked(Food);

// Peeling food. If there isn't any, then return `None`.
// Otherwise, return the peeled food.
fn peel(food: Option<Food>) -> Option<Peeled> {
    match food {
        Some(food) => Some(Peeled(food)),
        None       => None,
    }
}

// Chopping food. If there isn't any, then return `None`.
// Otherwise, return the chopped food.
fn chop(peeled: Option<Peeled>) -> Option<Chopped> {
    match peeled {
        Some(Peeled(food)) => Some(Chopped(food)),
        None               => None,
    }
}

// Cooking food. Here, we showcase `map()` instead of `match` for case handling.
fn cook(chopped: Option<Chopped>) -> Option<Cooked> {
    chopped.map(|Chopped(food)| Cooked(food))
}

// A function to peel, chop, and cook food all in sequence.
// We chain multiple uses of `map()` to simplify the code.
fn process(food: Option<Food>) -> Option<Cooked> {
    food.map(|f| Peeled(f))
        .map(|Peeled(f)| Chopped(f))
        .map(|Chopped(f)| Cooked(f))
}

// Check whether there's food or not before trying to eat it!
fn eat(food: Option<Cooked>) {
    match food {
        Some(food) => println!("Mmm. I love {:?}", food),
        None       => println!("Oh no! It wasn't edible."),
    }
}

pub fn main() {
    let apple = Some(Food::Apple);
    let carrot = Some(Food::Carrot);
    let potato = None;

    let cooked_apple = cook(chop(peel(apple)));
    let cooked_carrot = cook(chop(peel(carrot)));
    // Let's try the simpler looking `process()` now.
    let cooked_potato = process(potato);

    eat(cooked_apple);
    eat(cooked_carrot);
    eat(cooked_potato);
}

Combinators: and_then

map() was described as a chainable way to simplify match statements. However, using map() on a function that returns an Option<T> results in the nested Option<Option<T>>. Chaining multiple calls together can then become confusing. That’s where another combinator called and_then(), known in some languages as flatmap, comes in.

and_then() calls its function input with the wrapped value and returns the result. If the Option is None, then it returns None instead.

In the following example, cookable_v3() results in an Option<Food>. Using map() instead of and_then() would have given an Option<Option<Food>>, which is an invalid type for eat().

#![allow(dead_code)]

#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }
#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }

// We don't have the ingredients to make Sushi.
fn have_ingredients(food: Food) -> Option<Food> {
    match food {
        Food::Sushi => None,
        _           => Some(food),
    }
}

// We have the recipe for everything except Cordon Bleu.
fn have_recipe(food: Food) -> Option<Food> {
    match food {
        Food::CordonBleu => None,
        _                => Some(food),
    }
}

// To make a dish, we need both the recipe and the ingredients.
// We can represent the logic with a chain of `match`es:
fn cookable_v1(food: Food) -> Option<Food> {
    match have_recipe(food) {
        None       => None,
        Some(food) => have_ingredients(food),
    }
}

// This can conveniently be rewritten more compactly with `and_then()`:
fn cookable_v3(food: Food) -> Option<Food> {
    have_recipe(food).and_then(have_ingredients)
}

// Otherwise we'd need to `flatten()` an `Option<Option<Food>>`
// to get an `Option<Food>`:
fn cookable_v2(food: Food) -> Option<Food> {
    have_recipe(food).map(have_ingredients).flatten()
}

fn eat(food: Food, day: Day) {
    match cookable_v3(food) {
        Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
        None       => println!("Oh no. We don't get to eat on {:?}?", day),
    }
}

pub fn main() {
    let (cordon_bleu, steak, sushi) = (Food::CordonBleu, Food::Steak, Food::Sushi);

    eat(cordon_bleu, Day::Monday);
    eat(steak, Day::Tuesday);
    eat(sushi, Day::Wednesday);
}

Unpacking options and defaults

There is more than one way to unpack an Option and fall back on a default if it is None. To choose the one that meets our needs, we need to consider the following:

  • do we need eager or lazy evaluation?
  • do we need to keep the original empty value intact, or modify it in place?

or() is chainable, evaluates eagerly, keeps empty value intact

or()is chainable and eagerly evaluates its argument, as is shown in the following example. Note that because or’s arguments are evaluated eagerly, the variable passed to or is moved.

#[derive(Debug)]
enum Fruit { Apple, Orange, Banana, Kiwi, Lemon }

pub fn main() {
    let apple = Some(Fruit::Apple);
    let orange = Some(Fruit::Orange);
    let no_fruit: Option<Fruit> = None;

    let first_available_fruit = no_fruit.or(orange).or(apple);
    println!("first_available_fruit: {:?}", first_available_fruit);
    // first_available_fruit: Some(Orange)

    // `or` moves its argument.
    // In the example above, `or(orange)` returned a `Some`, so `or(apple)` was not invoked.
    // But the variable named `apple` has been moved regardless, and cannot be used anymore.
    // println!("Variable apple was moved, so this line won't compile: {:?}", apple);
    // TODO: uncomment the line above to see the compiler error
}

or_else() is chainable, evaluates lazily, keeps empty value intact

Another alternative is to use or_else, which is also chainable, and evaluates lazily, as is shown in the following example:

#[derive(Debug)]
enum Fruit { Apple, Orange, Banana, Kiwi, Lemon }

pub fn main() {
    let no_fruit: Option<Fruit> = None;
    let get_kiwi_as_fallback = || {
        println!("Providing kiwi as fallback");
        Some(Fruit::Kiwi)
    };
    let get_lemon_as_fallback = || {
        println!("Providing lemon as fallback");
        Some(Fruit::Lemon)
    };

    let first_available_fruit = no_fruit
        .or_else(get_kiwi_as_fallback)
        .or_else(get_lemon_as_fallback);
    println!("first_available_fruit: {:?}", first_available_fruit);
    // Providing kiwi as fallback
    // first_available_fruit: Some(Kiwi)
}

get_or_insert() evaluates eagerly, modifies empty value in place

To make sure that an Option contains a value, we can use get_or_insert to modify it in place with a fallback value, as is shown in the following example. Note that get_or_insert eagerly evaluates its parameter, so variable apple is moved:

#[derive(Debug)]
enum Fruit { Apple, Orange, Banana, Kiwi, Lemon }

pub fn main() {
    let mut my_fruit: Option<Fruit> = None;
    let apple = Fruit::Apple;
    let first_available_fruit = my_fruit.get_or_insert(apple);
    println!("first_available_fruit is: {:?}", first_available_fruit);
    println!("my_fruit is: {:?}", my_fruit);
    // first_available_fruit is: Apple
    // my_fruit is: Some(Apple)
    //println!("Variable named `apple` is moved: {:?}", apple);
    // TODO: uncomment the line above to see the compiler error
}

get_or_insert_with() evaluates lazily, modifies empty value in place

Instead of explicitly providing a value to fall back on, we can pass a closure to get_or_insert_with, as follows:

#[derive(Debug)]
enum Fruit { Apple, Orange, Banana, Kiwi, Lemon }

pub fn main() {
    let mut my_fruit: Option<Fruit> = None;
    let get_lemon_as_fallback = || {
        println!("Providing lemon as fallback");
        Fruit::Lemon
    };
    let first_available_fruit = my_fruit
        .get_or_insert_with(get_lemon_as_fallback);
    println!("first_available_fruit is: {:?}", first_available_fruit);
    println!("my_fruit is: {:?}", my_fruit);
    // Providing lemon as fallback
    // first_available_fruit is: Lemon
    // my_fruit is: Some(Lemon)

    // If the Option has a value, it is left unchanged, and the closure is not invoked
    let mut my_apple = Some(Fruit::Apple);
    let should_be_apple = my_apple.get_or_insert_with(get_lemon_as_fallback);
    println!("should_be_apple is: {:?}", should_be_apple);
    println!("my_apple is unchanged: {:?}", my_apple);
    // The output is a follows. Note that the closure `get_lemon_as_fallback` is not invoked
    // should_be_apple is: Apple
    // my_apple is unchanged: Some(Apple)
}

Result

Result is a richer version of the Option type that describes possible error instead of possible absence.

That is, Result<T, E> could have one of two outcomes:

  • Ok(T): An element T was found
  • Err(E): An error was found with element E

By convention, the expected outcome is Ok while the unexpected outcome is Err.

Like Option, Result has many methods associated with it. unwrap(), for example, either yields the element T or panics. For case handling, there are many combinators between Result and Option that overlap.

In working with Patina, you will likely encounter methods that return the Result type, such as the parse() method. It might not always be possible to parse a string into the other type, so parse() returns a Result indicating possible failure.

Let’s see what happens when we successfully and unsuccessfully parse() a string:

fn multiply(first_number_str: str, second_number_str: str) -> int {
    // Let's try using `unwrap()` to get the number out. Will it bite us?
    let first_number = first_number_str.parse::<int>().unwrap();
    let second_number = second_number_str.parse::<int>().unwrap();
    first_number * second_number
}

pub fn main() {
    let twenty = multiply("10", "2");
    println!("double is {}", twenty);

    let tt = multiply("t", "2");
    println!("double is {}", tt);
}

In the unsuccessful case, parse() leaves us with an error for unwrap() to panic on. Additionally, the panic exits our program and provides an unpleasant error message.

To improve the quality of our error message, we should be more specific about the return type and consider explicitly handling the error.

Using Result in main

The Result type can also be the return type of the main function if specified explicitly. Typically the main function will be of the form:

pub fn main() {
    println!("Hello World!");
}

However main is also able to have a return type of Result. If an error occurs within the main function it will return an error code and print a debug representation of the error (using the Debug trait). The following example shows such a scenario and touches on aspects covered in the following section.

use Std::Num::ParseIntError;

pub fn main() -> Result<(), ParseIntError> {
    let number_str = "10";
    let number = match number_str.parse::<int>() {
        Ok(number)  => number,
        Err(e) => return Err(e),
    };
    println!("{}", number);
    Ok(())
}

map for Result

Panicking in the previous example’s multiply does not make for robust code. Generally, we want to return the error to the caller so it can decide what is the right way to respond to errors.

We first need to know what kind of error type we are dealing with. To determine the Err type, we look to parse(), which is implemented with the FromStr trait for int. As a result, the Err type is specified as ParseIntError.

In the example below, the straightforward match statement leads to code that is overall more cumbersome.

use Std::Num::ParseIntError;

// With the return type rewritten, we use pattern matching without `unwrap()`.
fn multiply(first_number_str: str, second_number_str: str) -> Result<int, ParseIntError> {
    match first_number_str.parse::<int>() {
        Ok(first_number)  => {
            match second_number_str.parse::<int>() {
                Ok(second_number)  => {
                    Ok(first_number * second_number)
                },
                Err(e) => Err(e),
            }
        },
        Err(e) => Err(e),
    }
}

fn print(result: Result<int, ParseIntError>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    // This still presents a reasonable answer.
    let twenty = multiply("10", "2");
    print(twenty);

    // The following now provides a much more helpful error message.
    let tt = multiply("t", "2");
    print(tt);
}

Luckily, Option’s map, and_then, and many other combinators are also implemented for Result.

use Std::Num::ParseIntError;

// As with `Option`, we can use combinators such as `map()`.
// This function is otherwise identical to the one above and reads:
// Multiply if both values can be parsed from str, otherwise pass on the error.
fn multiply(first_number_str: str, second_number_str: str) -> Result<int, ParseIntError> {
    first_number_str.parse::<int>().and_then(|first_number| {
        second_number_str.parse::<int>().map(|second_number| first_number * second_number)
    })
}

fn print(result: Result<int, ParseIntError>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    // This still presents a reasonable answer.
    let twenty = multiply("10", "2");
    print(twenty);

    // The following now provides a much more helpful error message.
    let tt = multiply("t", "2");
    print(tt);
}

aliases for Result

How about when we want to reuse a specific Result type many times? Recall that Patina allows us to create aliases. Conveniently, we can define one for the specific Result in question.

At a module level, creating aliases can be particularly helpful. Errors found in a specific module often have the same Err type, so a single alias can succinctly define all associated Results. This is so useful that the Std library even supplies one: Io::Result!

Here’s a quick example to show off the syntax:

use Std::Num::ParseIntError;

// Define a generic alias for a `Result` with the error type `ParseIntError`.
type AliasedResult<T> = Result<T, ParseIntError>;

// Use the above alias to refer to our specific `Result` type.
fn multiply(first_number_str: str, second_number_str: str) -> AliasedResult<int> {
    first_number_str.parse::<int>().and_then(|first_number| {
        second_number_str.parse::<int>().map(|second_number| first_number * second_number)
    })
}

// Here, the alias again allows us to save some space.
fn print(result: AliasedResult<int>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    print(multiply("10", "2"));
    print(multiply("t", "2"));
}

Early returns

In the previous example, we explicitly handled the errors using combinators. Another way to deal with this case analysis is to use a combination of match statements and early returns.

That is, we can simply stop executing the function and return the error if one occurs. For some, this form of code can be easier to both read and write. Consider this version of the previous example, rewritten using early returns:

use Std::Num::ParseIntError;

fn multiply(first_number_str: str, second_number_str: str) -> Result<int, ParseIntError> {
    let first_number = match first_number_str.parse::<int>() {
        Ok(first_number)  => first_number,
        Err(e) => return Err(e),
    };

    let second_number = match second_number_str.parse::<int>() {
        Ok(second_number)  => second_number,
        Err(e) => return Err(e),
    };

    Ok(first_number * second_number)
}

fn print(result: Result<int, ParseIntError>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    print(multiply("10", "2"));
    print(multiply("t", "2"));
}

At this point, we’ve learned to explicitly handle errors using combinators and early returns. While we generally want to avoid panicking, explicitly handling all of our errors is cumbersome.

In the next section, we’ll introduce ? for the cases where we simply need to unwrap without possibly inducing panic.

Introducing ?

Sometimes we just want the simplicity of unwrap without the possibility of a panic. Until now, unwrap has forced us to nest deeper and deeper when what we really wanted was to get the variable out. This is exactly the purpose of ?.

Upon finding an Err, there are two valid actions to take:

  1. panic! which we already decided to try to avoid if possible
  2. return because an Err means it cannot be handled

? is almost1 exactly equivalent to an unwrap which returns instead of panicking on Errs. Let’s see how we can simplify the earlier example that used combinators:

use Std::Num::ParseIntError;

fn multiply(first_number_str: str, second_number_str: str) -> Result<int, ParseIntError> {
    let first_number = first_number_str.parse::<int>()?;
    let second_number = second_number_str.parse::<int>()?;

    Ok(first_number * second_number)
}

fn print(result: Result<int, ParseIntError>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    print(multiply("10", "2"));
    print(multiply("t", "2"));
}

  1. It actually means unwrap or return Err(From::from(err)). Since From::from is a conversion utility between different types, this means that if you ? where the error is convertible to the return type, it will convert automatically. ↩

Multiple error types

The previous examples have always been very convenient; Results interact with other Results and Options interact with other Options.

Sometimes an Option needs to interact with a Result, or a Result<T, Error1> needs to interact with a Result<T, Error2>. In those cases, we want to manage our different error types in a way that makes them composable and easy to interact with.

In the following code, two instances of unwrap generate different error types. list::first returns an Option, while parse::<int> returns a Result<int, ParseIntError>:

fn double_first(list: [str]) -> int {
    let first = list.first().unwrap(); // Generate error 1
    2 * first.parse::<int>().unwrap() // Generate error 2
}

pub fn main() {
    let numbers = ["42", "93", "18"];
    let empty = [];
    let strings = ["tofu", "93", "18"];

    println!("The first doubled is {}", double_first(numbers));

    println!("The first doubled is {}", double_first(empty));
    // Error 1: the input list is empty

    println!("The first doubled is {}", double_first(strings));
    // Error 2: the element doesn't parse to a number
}

Over the next sections, we’ll see several strategies for handling these kind of problems.

Pulling Results out of Options

The most basic way of handling mixed error types is to just embed them in each other.

use Std::Num::ParseIntError;

fn double_first(list: [str]) -> Option<Result<int, ParseIntError>> {
    list.first().map(|first| {
        first.parse::<int>().map(|n| 2 * n)
    })
}

pub fn main() {
    let numbers = ["42", "93", "18"];
    let empty = [];
    let strings = ["tofu", "93", "18"];

    println!("The first doubled is {:?}", double_first(numbers));

    println!("The first doubled is {:?}", double_first(empty));
    // Error 1: the input list is empty

    println!("The first doubled is {:?}", double_first(strings));
    // Error 2: the element doesn't parse to a number
}

There are times when we’ll want to stop processing on errors (like with ?) but keep going when the Option is None. The transpose function comes in handy to swap the Result and Option.

use Std::Num::ParseIntError;

fn double_first(list: [str]) -> Result<Option<int>, ParseIntError> {
    let opt = list.first().map(|first| {
        first.parse::<int>().map(|n| 2 * n)
    });

    opt.transpose()
}

pub fn main() {
    let numbers = ["42", "93", "18"];
    let empty = [];
    let strings = ["tofu", "93", "18"];

    println!("The first doubled is {:?}", double_first(numbers));
    println!("The first doubled is {:?}", double_first(empty));
    println!("The first doubled is {:?}", double_first(strings));
}

Defining an error type

Sometimes it simplifies the code to mask all of the different errors with a single type of error. We’ll show this with a custom error.

Patina allows us to define our own error types. In general, a “good” error type:

  • Represents different errors with the same type
  • Presents nice error messages to the user
  • Is easy to compare with other types
    • Good: Err(EmptyList)
    • Bad: Err("Please use a list with at least one element")
  • Can hold information about the error
    • Good: Err(BadChar(c, position))
    • Bad: Err("+ cannot be used here")
  • Composes well with other errors
use Std::Fmt;

type Result<T> = Std::Result::Result<T, DoubleError>;

// Define our error types. These may be customized for our error handling cases.
// Now we will be able to write our own errors, defer to an underlying error
// implementation, or do something in between.
#[derive(Debug)]
struct DoubleError;

// Generation of an error is completely separate from how it is displayed.
// There's no need to be concerned about cluttering complex logic with the display style.
//
// Note that we don't store any extra info about the errors. This means we can't state
// which string failed to parse without modifying our types to carry that information.
impl Fmt::Display for DoubleError {
    fn fmt(self, f: Fmt::Formatter) -> Fmt::Result {
        write!(f, "invalid first item to double")
    }
}

fn double_first(list: [str]) -> Result<int> {
    list.first()
        // Change the error to our new type.
        .ok_or(DoubleError)
        .and_then(|s| {
            s.parse::<int>()
                // Update to the new error type here also.
                .map_err(|_| DoubleError)
                .map(|i| 2 * i)
        })
}

fn print(result: Result<int>) {
    match result {
        Ok(n) => println!("The first doubled is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    let numbers = ["42", "93", "18"];
    let empty = [];
    let strings = ["tofu", "93", "18"];

    print(double_first(numbers));
    print(double_first(empty));
    print(double_first(strings));
}

Dynamic errors

A way to write simple code while preserving the original errors is to return them with dyn. The drawback is that the underlying error type is only known at runtime and not statically determined.

The stdlib helps in dynamically returning our errors by defining an Std::Error::Error trait. It’s already implemented for all standard errors.

use Std::Error;
use Std::Fmt;

// Change the alias to use `dyn Error::Error`.
type Result<T> = Std::Result::Result<T, dyn Error::Error>;

#[derive(Debug)]
struct EmptyList;

impl Fmt::Display for EmptyList {
    fn fmt(self, f: Fmt::Formatter) -> Fmt::Result {
        write!(f, "invalid first item to double")
    }
}

impl Error::Error for EmptyList {}

fn double_first(list: [str]) -> Result<int> {
    list.first()
        .ok_or_else(|| EmptyList)
        .and_then(|s| {
            s.parse::<int>()
                .map(|i| 2 * i)
        })
}

fn print(result: Result<int>) {
    match result {
        Ok(n) => println!("The first doubled is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

pub fn main() {
    let numbers = ["42", "93", "18"];
    let empty = [];
    let strings = ["tofu", "93", "18"];

    print(double_first(numbers));
    print(double_first(empty));
    print(double_first(strings));
}

Wrapping errors

An alternative to returning dynamic errors is to wrap them in your own error type.

use Std::Error;
use Std::Error::Error;
use Std::Num::ParseIntError;
use Std::Fmt;

type Result<T> = Std::Result::Result<T, DoubleError>;

#[derive(Debug)]
enum DoubleError {
    EmptyList,
    // We will defer to the parse error implementation for their error.
    // Supplying extra info requires adding more data to the type.
    Parse(ParseIntError),
}

impl Fmt::Display for DoubleError {
    fn fmt(self, f: Fmt::Formatter) -> Fmt::Result {
        match self {
            DoubleError::EmptyList =>
                write!(f, "please use a list with at least one element"),
            // The wrapped error contains additional information and is available
            // via the source() method.
            DoubleError::Parse(..) =>
                write!(f, "the provided string could not be parsed as int"),
        }
    }
}

impl Error::Error for DoubleError {
    fn source(self) -> Option<dyn Error::Error> {
        match self {
            DoubleError::EmptyList => None,
            // The cause is the underlying implementation error type. Is implicitly
            // cast to the trait object `Error::Error`. This works because the
            // underlying type already implements the `Error` trait.
            DoubleError::Parse(ref e) => Some(e),
        }
    }
}

// Implement the conversion from `ParseIntError` to `DoubleError`.
// This will be automatically called by `?` if a `ParseIntError`
// needs to be converted into a `DoubleError`.
impl From<ParseIntError> for DoubleError {
    fn from(err: ParseIntError) -> DoubleError {
        DoubleError::Parse(err)
    }
}

fn double_first(list: [str]) -> Result<int> {
    let first = list.first().ok_or(DoubleError::EmptyList)?;
    // Here we implicitly use the `ParseIntError` implementation of `From` (which
    // we defined above) in order to create a `DoubleError`.
    let parsed = first.parse::<int>()?;

    Ok(2 * parsed)
}

fn print(result: Result<int>) {
    match result {
        Ok(n)  => println!("The first doubled is {}", n),
        Err(e) => {
            println!("Error: {}", e);
            if let Some(source) = e.source() {
                println!("  Caused by: {}", source);
            }
        },
    }
}

pub fn main() {
    let numbers = ["42", "93", "18"];
    let empty = [];
    let strings = ["tofu", "93", "18"];

    print(double_first(numbers));
    print(double_first(empty));
    print(double_first(strings));
}

Iterating over Results

An Iter::map operation might fail, for example:

pub fn main() {
    let strings = ["tofu", "93", "18"];
    let numbers: [_] = strings
        .into_iter()
        .map(|s| s.parse::<int>())
        .collect();
    println!("Results: {:?}", numbers);
}

Let’s step through strategies for handling this.

Ignore the failed items with filter_map()

filter_map calls a function and filters out the results that are None.

pub fn main() {
    let strings = ["tofu", "93", "18"];
    let numbers: [_] = strings
        .into_iter()
        .filter_map(|s| s.parse::<int>().ok())
        .collect();
    println!("Results: {:?}", numbers);
}

Fail the entire operation with collect()

Result implements FromIterator so that a list of results ([Result<T, E>]) can be turned into a result with a list (Result<[T], E>). Once an Result::Err is found, the iteration will terminate.

pub fn main() {
    let strings = ["tofu", "93", "18"];
    let numbers: Result<[_], _> = strings
        .into_iter()
        .map(|s| s.parse::<int>())
        .collect();
    println!("Results: {:?}", numbers);
}

This same technique can be used with Option.

Collect all valid values and failures with partition()

pub fn main() {
    let strings = ["tofu", "93", "18"];
    let (numbers, errors): ([_], [_]) = strings
        .into_iter()
        .map(|s| s.parse::<int>())
        .partition(Result::is_ok);
    println!("Numbers: {:?}", numbers);
    println!("Errors: {:?}", errors);
}

When you look at the results, you’ll note that everything is still wrapped in Result. A little more boilerplate is needed for this.

pub fn main() {
    let strings = ["tofu", "93", "18"];
    let (numbers, errors): ([_], [_]) = strings
        .into_iter()
        .map(|s| s.parse::<int>())
        .partition(Result::is_ok);
    let numbers: [_] = numbers.into_iter().map(Result::unwrap).collect();
    let errors: [_] = errors.into_iter().map(Result::unwrap_err).collect();
    println!("Numbers: {:?}", numbers);
    println!("Errors: {:?}", errors);
}

Unsafe Operations

As an introduction to this section, to borrow from the official Rust docs, “one should try to minimize the amount of unsafe code in a code base.” With that in mind, let’s get started! Unsafe annotations in Patina are used to bypass protections put in place by the compiler; specifically, there are two primary things that unsafe is used for:

  • calling functions or methods which are unsafe
  • matching term type into Patina types by their runtime representation

Calling Unsafe Functions

Some functions can be declared as unsafe, meaning it is the programmer’s responsibility to ensure correctness instead of the compiler’s. One example of this is term::try_cast_into, which will attempt to convert a runtime value into a Patina type based only on its non-unique runtime representation.

struct Celcius(int);
struct Fahrenheit(int);

pub fn main() {
    let degrees_term = Celcius(10) as term;

    unsafe {
        // Celcius(10) and Fahrenheit(10) have the same runtime representation,
        // so `try_cast_into` will succeed.
        // But `degrees_term` wasn't Fahrenheit! Even with some guardrails,
        // this circumvents the type system - which is why it's unsafe.
        let fahrenheit = degrees_term.try_cast_into::<Fahrenheit>().unwrap();
    }
}

Matching term by runtime representation

This is different syntax, but is unsafe for the same reason as try_cast_into above.

In safe code, match and receive can only destructure terms into BEAM-native types. When wrapped in unsafe, both of these blocks can try to destructure into Patina types by their runtime representation, similarly to try_cast_into:

pub fn main() {
    let v = Option::<int>::None as term;

    let safe_description = match v {
        a"nil" => "the atom nil",
        (a"some", val) => "some value (tagged?)",
        val => "some value (untagged?)",
        // Option<str>::None => "string option (none)",
        // ^ERROR - can't safely match by runtime representation!
    };

    let unsafe_description = unsafe {
        match v {
            Option::<str>::None => "an empty string option",
            Option::<int>::None => "an empty integer option",
            a"nil" => "the atom nil",
            _ => "something else",
        }
    };

    println!("{}, {}", safe_description, unsafe_description);
    // "the atom nil, an empty string option"
}

See also:

term, unsafe { match }, unsafe { receive }