Learn the language Browse docs
On this page 9 sections

Learn the language

Values and types

Bindings, numbers, strings, and lists, with examples of what the checker catches and the places where it stays silent.

This page shows how to name a value, which types and literals exist, how strings and lists behave, and where the checker cannot see a mistake. A binding is a name attached to a value (val name = "orbit"). The checker is orbit check, which reads your code for errors without building it. Each limit below says which compiler version it was verified on.

Val binds once, var mutates

val creates an immutable binding: one name, one value, forever. var binds a mutable cell, and mut marks the intent to reassign. A type annotation (the : int after the name) is optional when the compiler can work the type out:

bindings.orb
fn main() -> int {
  val name = "orbit"
  val retries: int = 3
  var mut total: int = 0
  total = total + retries
  return total + name.len()
}

name.len() is 5 and retries is 3, so this exits 8. Three habits follow:

  • Use val by default. Switch to var mut only when the value changes. The tour uses the same shape. Assigning to a val, to a name nothing declares, or a value of the wrong type is E1009.
  • A compound assignment updates a var in place: total += 2 means total = total + 2, and -=, *=, /= and %= work the same way. It is sugar, so the same checks apply.
  • Annotate when the type cannot be inferred, or when a value is passed to a function that expects a specific type. Annotate your bindings shows a program that segfaults without one.
  • Containers take an element type in the annotation, as in val names: list<string>. The checker then enforces what goes in, as lists shows.

Scalars and literals

The builtin types are int (64-bit), float, string, bool, list, result, and void. You declare your own with:

  • model for a named record (fixed fields).
  • enum for a closed set of names.
  • union for alternatives that each carry a value (see match on unions).
  • type for an alias.
types.orb
model User {
  id: string
  active: bool
}

enum Role { Admin, Member }
type UserId = string

Number literals accept binary (0b101 is 5), hex (0x1F is 31), digit separators (1_000 is 1000), and exponents (1.5e2 is 150.0, 1e-3 is 0.001):

literals.orb
val mask = 0xFF          // 255, and 0xff / 0xAbCdEf likewise
val big = 1_000_000      // one million; _ is only a separator
val ratio = 1e2          // 100.0 — an exponent is always a float, not 100

Rule: an exponent always produces a float. 1e2 is 100.0, not 100.

wrap.orb
print(2147483647 + 1)   // 2147483648
print(46341 * 46341)    // 2147488281
print(65536 * 65536)    // 4294967296

Two things to know:

  • The compiler never warns about a result that goes out of range mid-calculation. It carries on as the wrapped number.
  • An integer literal outside the 64-bit range is rejected at check time (integer literal does not fit an orbit_int). So is a literal 0 divisor, and so is INT_MIN / -1 (E1004). A zero held in a variable still reaches the hardware.

There is no wider integer type today.

Division and remainder are C semantics on negatives

Verified on orbit 0.1.0: +, -, *, / and % all agree with C on negative operands. An earlier build gave (0-7)/2 as -4. That is fixed and pinned by a test.

negdiv.orb
print((0 - 7) / 2)      // -3, C semantics.
print((0 - 7) % 2)      // -1, C semantics.

Parentheses are still required when reasoning about precedence: 0-7 / 2 parses as 0 - (7/2), a different, correct program.

Bitwise and shift operators

&, |, ^, << and >> take two ints. ~ takes one. Everything is a 64-bit int, two’s-complement like the rest of the arithmetic:

bits.orb
val a = 12 & 10   // 8
val b = 12 | 10   // 14
val c = 12 ^ 10   // 6
val d = 1 << 10   // 1024
val e = ~0        // -1
val f = -8 >> 1   // -4
  • >> is arithmetic, and << drops the bits that leave the top.
  • A shift count is masked to six bits, so x << 65 is x << 1 and x >> 64 is x. There is no undefined shift as in C.
  • Precedence is C’s, tightest first: * / %, + -, << >>, < > <= >=, == !=, &, ^, |, &&, ||. So & binds looser than ==: 12 & 10 == 8 reads as 12 & (10 == 8) and the checker refuses it. Write (12 & 10) == 8.
  • An operand that is not an int is refused: bitwise '&' takes two ints, not 'string' and 'string'.

Strings, raw strings, and interpolation

An ordinary "…" string processes escapes: \" is a quote, \n a newline, \t a tab, \\ a backslash, \r a carriage return, and \xHH a byte with two hex digits ("\x41" is "A"). Anything malformed stays literal.

A raw string is triple-quoted like Python ("""…""") and processes nothing: what you type is what you get. Use it for JSON, where escaping every quote makes the text unreadable. Compare:

raw.orb
return "{\"status\":\"ok\",\"count\":42}"   // every quote doubled
return """{"status":"ok","count":42}"""     // none of them

Three rules:

  • The first """ after the opening one closes the literal. A single quote inside is ordinary content: """a"b""" is a"b.
  • No escapes exist. A backslash is a backslash, so a Windows path needs no doubling: """C:\Users\orbit""". A literal """ cannot appear inside; split the string or use an ordinary "…" for that.
  • Newlines are kept, so a multi-line body is served the way you write it:
multiline.orb
return """{
"items": [{"id": 1}, {"id": 2}],
"total": 2
}"""

Both forms are ordinary string values at runtime, so they concatenate and compare like any string. An unterminated """ is an error; it does not swallow the rest of the file.

Interpolation puts a runtime value into a string. ${…} inside either string form is replaced by the value of the expression in the hole:

interp.orb
val n = 3
print("items: ${n}")
return ok 200 """{"count":${n},"path":"C:\dir"}"""

Rules:

  • A hole may hold a string, int, float or bool. A model, a list, a map or a result in a hole is a compile error.
  • Braces nest and quotes are tracked, so ${show("}")} is a call whose argument is }, not a hole that ended early.
  • There is no escape for $. \${ is a backslash followed by a hole.
  • "${n}" is a string, not the int it interpolates.
  • The result is an ordinary string.

Annotate your bindings

An annotation tells the checker what type a binding holds. Without one, the checker cannot see a type mismatch, and the program can crash at run time. At run time a value is one machine word with no type tag, so nothing can be checked then either. A binding you did not annotate is assumed to be a string wherever it is passed as a string. This program checks clean and crashes:

unknown.orb
fn takesStr(s: string) -> int { return s.len() }
fn g() -> int { return 11 }

fn main() -> int {
  print(takesStr(g()))   // orbit check: no errors. Run: segfault.
  return 0
}

orbit check reports no errors on a program that segfaults when run. The unannotated value is unknown to the checker, so it cannot compare it with string. Annotate the binding (or the value at the call site) and the checker catches it.

The same gap is why print truncates a float: print(1.5) gives 1, and 1.5 + 2.0 gives 3.

Toggle the fix below. With the annotation, the check that was silent reports the error:

Without annotation
fn takesStr(s: string) -> int { return s.len() }
fn g() -> int { return 11 }

fn main() -> int {
    print(takesStr(g()))
    return 0
}

Int is not a type

Type names are lower case: int, float, string, bool, void, and list/map/object/result/response. List, Map, Result and Response are also accepted capitalised and mean the same four types. Any other capitalised spelling is not a type. The checker reports it with E1006:

notatypes.orb
val n: Int = 1       // E1006: Nothing declares a type named 'Int'
val m: Float = 1.5     // E1006 the same way — types are lower case
val s: String = "x"    // E1006; Bool, Void, Any, DateTime likewise

It is not only a spelling test:

  • A capitalised name is a type only if a model, enum, union, or alias declares it, or it is one of the four container spellings above. Int is neither.
  • A lower-case name that nothing declares fails the other half of the check, which compares the annotation with the value. val n: widget = 1 gives 'n' is declared widget but the value is int. Here the fix is to declare widget.

Constants at file scope

A constant outside any function is a top-level val or const whose value is an int or bool literal. It becomes a C #define. Any other value at file scope, and a var at file scope, is rejected with E1007:

consts.orb
val CHAR_SPACE = 32
const MAX_RETRIES = 3

The other top-level declarations are fn, model, enum, union, type, and route. For a shared string or a computed value, keep it inside a function: file scope only holds what the C preprocessor can hold.

Lists: say what the list holds

A list is Orbit’s array. It holds one pointer-sized slot per element. Write the element type, and the checker holds you to it:

lists.orb
val xs: list<int> = []
xs.push(10)
xs.push("twenty")       // error[E1006]: the value is string, the slot is int

With no declaration, the first push decides the element type:

firstpush.orb
var names = []
names.push("one")        // this push decides: list<string>
names.push(2)            // error[E1006]

An int goes into a list<float> (it is converted on the way in). A float into a list<int> is refused, because that would truncate.

Use .get(i) to read an element. It is a bounds-checked read. .at(i), xs[i], and .pop() read the same element and answer with the element type:

accessors.orb
val xs = [10, 20, 30]
val n: int = xs.get(1)          // 20

val words = ["alpha", "beta", "gamma"]
print(words.get(2))             // gamma

.get(i), .at(i), xs[i] and .pop() are bounds-checked. A literal index past the end of a literal list or string is a compile error (E1002). Any other out-of-range list read aborts the process instead of answering a value. An index past the end of a string answers 0, the byte value of NUL, so guard a computed index with if i < xs.len().

Rule: a written list names its element. A bare list in a signature, a field or an annotation is refused (E1012).

Objects, and the missing map

There is no hash-map module in std/. A { key: value } literal is an object, and an object field cannot hold a map. map is a known type name but has no runtime collection or std module behind it: use models for fixed shapes and objects for dynamic ones.

objects.orb
val o = { name: "api", port: 8080, healthy: true }
val inner = { deep: { deeper: 7 } }

An object literal is a value, not text. You can read a field, nest one object in another, and pass it to a function. It works like a model whose shape the compiler learns from the source instead of from a declaration. Rules:

  • Fields may be string, int, float, bool, a list of those or of objects, or another object. A map is a compile error. So is a list inside a list, because a slot holds one pointer with no tag for object-vs-list. To put a list in a response body, make it a field: { files: [{ name: "a.txt", size: 29 }] }.
  • Key order is the order you wrote, so a response body is byte-for-byte what the source says.
  • Everything inside is escaped on the way out. A hand-written JSON string cannot promise that.
  • A key may be a keyword ({ ok: true } is fine) or a quoted string, so "content-type" works as a key. Reading a dashed key back with h."content-type" is not supported yet (verified on orbit 0.1.0): the parser turns the dash into an underscore, so the lookup misses.
  • A field’s type is learned from the writes in the same function. For an object a function returned, read a field through a declared type (val ratio: float = o.ratio); an undeclared read still takes a raw getter and can come back wrong.
  • {} is a valid empty object. Separators are optional: one field per line, or commas.

.get() on an object reads one field by key, and the answer has the type the value was stored as:

mapread.orb
val m = { "a": 1, "b": 2 }
val v: int = m.get("a")   // 1

Use a model when the fields are known up front and you want them checked. Use an object literal for a response body whose keys are data. For a body that is mostly static text, a raw string with interpolation is shorter.

What next

Next: control flow covers if, loops, and match. The full specification is the language reference.

Type to search commands, errors, modules and concepts.