Syntax

stone’s grammar is derived from Python’s, trimmed down and changed in a few places. The full grammar is docs/grammar/stone.gram.

Compared with Python

Python

stone

if x: / while x: / for i in xs:

if x: / while x: / for i in xs:

def f(a, b):, annotations optional

fn f(a: int, b: int) -> int:, parameter types required

else: / elif x:

else: / elif x:

return x

ret x

continue

cont

True, False

true, false

None, Optional[int]

none and some(x), of type option[int]

raise, try: / except:

return a result[T, E], ok(x) or err(e), and pass an error on with ?

int("x") raises ValueError

int(s) and float(s) of a string give a result, as int(x) of a float does

Fahrenheit.from_celsius(c)

Fahrenheit(c), a conversion through impl from[Celsius] for Fahrenheit:

class Shape(Enum):

enum Shape:, whose variants can hold values, as in Rust

@dataclass class Point:

struct Point: with a typed field per line, made as Point(x=1.0, y=2.0)

match x: / case P:

match x: / case P:, which must cover every value

'single' or "double" quotes

"double" quotes only

-7 // 2 == -4

-7 / 2 == -3 (truncates)

-7 % 2 == 1

-7 % 2 == -1 (takes the dividend’s sign, like /)

2 ** -1 == 0.5, 2 ** 0.5

2.0 ** -1 == 0.5; the exponent is always an int

[1, 2] + [3] joins, [0] * 3 repeats

+ - * / % ** on lists work element by element, as in numpy; join with xs.extend(ys)

xs.insert(9, x) clamps the index

an index past either end is an error

sorted(xs), xs.sort(key=f, reverse=True)

xs.sort(), on a list of int, float, str, or an ord type, and xs.sort_by_key(f); -0.0 sorts before 0.0, and nan last

lambda x: x * 2

|x| x * 2, which may use the variables around it as copies taken where it is written

map(f, xs), filter(f, xs), any(...), min(xs, key=f)

xs.map(f), xs.filter(f), xs.any(f), xs.min_by_key(f), each a new list or value

t = 1, 2, return a, b

t = (1, 2), ret (a, b); a tuple’s values always need parentheses

(), (x,)

no empty or one-value tuples; a tuple has two or more values

t[i], t[1:]

t[1], t[-1]: a constant index only, and no slices

Keywords

These names are reserved and cannot be used for variables or functions:

keyword

meaning

fn

defines a function

enum

defines an enum

struct

defines a struct

trait

defines a trait: methods that types implement, as in trait Shape:

impl

defines the methods and associated functions of a struct, or implements a trait for a type, as in impl Shape for Circle:

pub

lets other files use the function, constant, enum, struct, or trait after it, as in pub fn f() -> int:

const

defines a constant, as in const port = 53

use, as

uses a module or one of its functions, optionally under another name

ret

returns from a function, or ends the program at the top level

if, elif, else

conditional blocks

while

loops while a condition holds

for, in

loops over a list or a range; for also names the type in impl Shape for Circle:, and in and not in test membership, as in x in xs

match, case

runs the first case whose pattern fits a value

assert

stops the program with an error unless a condition holds, as in assert x > 0

break

leaves the innermost loop

cont

skips to the next iteration of the innermost loop

and, or, not

boolean operators, with short-circuiting and and or

true, false

the bool values

none

the option that holds no value

test is a keyword only where a test block opens, at the start of a top-level line and followed by a string, so it may still name a variable, a parameter, or a function.

Lines and blocks

A statement ends at the end of its line. A statement that opens a block (fn, test, if, elif, else, while, for, case) ends in :, followed either by an indented block on the next lines or by a single simple statement on the same line. enum, struct, trait, impl, and match end in : too, and are always followed by an indented block: of variants or fields, one per line, of fns, or of cases:

for i in range(3):
    print(i)
while true: break

Indent with spaces or tabs, as long as each block is consistent. Comments start with // outside a string and run to the end of the line, and blank and comment-only lines may sit at any indentation. Comment lines directly above a function or variable definition document it, and editors show them when you hover over its name. Comment lines at the very top of a module’s file, followed by a blank line, document the module, and editors show them when you hover over the module’s name in a use or before a ..

Literals

literal

examples

int

0, 42, 9223372036854775807, 1_000_000, 0xff, 0o17, 0b1010

float

1.5, 2.5e-3, 1e9, 1E+9, 1_000.5

string

"hello", "", "x is {x}"

bytes

b"GET", b"", b"\x00\xff"

bool

true, false

option

none, some(1)

result

ok(1), err("bad")

list

[], [1, 2, 3], [[1.0], []]

map

{}, {"a": 1, "b": 2}, {1: [2.5], 3: [],}

set

{}, {1, 2, 3}, {"a",}

tuple

(1, "a"), (x, y, z,), (1, ("a", [2.5]))

struct

Point(x=1.0, y=2.0), Line(end=q, start=p)

Negative numbers are the unary - applied to a literal, as in -7. An int written with 0x, 0o, or 0b (or 0X, 0O, 0B) is in hexadecimal, octal, or binary, and must fit in an int, as every int literal must, so 0x7fff_ffff_ffff_ffff is the largest. A _ may stand between two digits of any number, or right after a base prefix, as in Python, so 1_000 and 0x_ff are numbers, while 1__000 and 1_ are errors. Strings use double quotes and must close on the line they open on. A backslash starts an escape sequence:

escape

means

\"

a double quote

\'

a single quote

\\

a backslash

\n

a line break

\t

a tab

\r

a carriage return

\xhh

the ASCII character with hex code hh, from \x01 to \x7f

So "say \"hi\"\n" holds say "hi" and a line break. Any other escape is an error, and so is \x00, since a string cannot hold a null byte. Characters outside ASCII are written as themselves, as in "café".

An expression in braces inside a string is written into it, as print writes it, so "{n} items, the first {xs[0]}" holds the values of n and xs[0]. Strings written one after another join, as in "a" "b". Inside a string:

text

means

{expression}

the value of the expression; it may hold strings, brackets, and braces of its own

{{

a {

}}

a }

A lone }, an empty {}, and a value that does not close before the end of the line are errors. A : after the expression starts a format spec, as in {x:.2f}, which runs to the } and follows Python’s format specification mini-language:

[[fill]align][sign][#][0][width][grouping][.precision][type]

A spec is written out, so a value inside one, as in {x:.{p}f}, is an error, and so is a spec that does not parse, such as {x:.f}. Types lists what each part does.

A bytes literal is a b right before a string literal’s opening quote, as in b"GET\r\n". It takes the same escapes, except that \xhh writes any byte, from \x00 to \xff. Its other characters must be ASCII, its braces are plain bytes rather than values, and bytes literals written one after another join, as in b"a" b"b", while a string and a bytes literal side by side are an error.

Statements

statement

example

expression

print(x)

assignment

x = 1, a = b = 0, items[i] = x, grid[r][c] = 0, p.x = 1.0, ps[i].y = 0.0

unpacking

q, r = divide(7, 2), a, b = (b, a), (x, (y, z)) = t

augmented assignment

x += 1, total -= cost, items[i] *= 2, grid[r][c] **= 2, p.x += 0.5

function definition

fn f(a: int, b: int) -> int: or fn first[T](xs: list[T]) -> T: plus a block

enum definition

enum Shape: or enum Tree[T]: plus a block of variants, such as Circle(float) and Empty

struct definition

struct Point: or struct Pair[A, B]: plus a block of fields, such as x: float and y: float

trait definition

trait Shape: or trait combine[R]: plus a block of fns, each with a block or none, such as fn area(self) -> float

impl block

impl Point: or impl Shape for Circle: plus a block of fns, such as fn norm(self) -> float: plus a block

match

match s: plus a block of cases, such as case Shape.Circle(r): plus a block

ret

ret, ret x, ret (a, b)

if / elif / else

if x < 0: … elif x == 0: … else: …

while

while i < 10: plus a block

for

for x in items:, for c in text:, for i in range(n):, for name, score in pairs:

assert

assert x > 0, assert xs == [1, 2], assert n > 0, "n is {n}"

test block

test "parses a point": plus a block, at the top level only

constant

const port = 53, pub const kb = 1 << 10, at the top level only

break, cont

inside a loop only

use

use util, use geometry.shapes.area as area

A for loop’s variable is a plain name, or names to unpack each tuple of a list into. Unpacking takes names only, each once, as many as the tuple has values; an element such as xs[0] is assigned on a line of its own. Functions, enums, structs, traits, and impl blocks can only be defined at the top level.

assert test stops the program with a runtime error at test, which must be a bool, unless it is true. When test is a single comparison (==, !=, <, <=, >, >=, in, or not in), the error shows both sides as print writes them, strings quoted, as in assertion failed: [1, 2] == [1, 3]; otherwise it says assertion failed. A message after a comma, assert n > 0, "n is {n}", must be a str and replaces the sides (assertion failed: n is -1), and is evaluated only if the test fails. Each side runs once, left then right, and assert works anywhere a statement does.

A test block, test "description": plus a block, holds code that checks the code around it, usually with assert:

fn double(x: int) -> int:
    ret x * 2

test "doubles negative numbers":
    assert double(-3) == -6

print(double(4))

stone run and stone build never run a test block, so this program prints 8, while stone test runs each test alone (see Testing). A test runs without the program’s top-level code, so it may not read a global, directly or through the functions it calls; it makes what it needs itself. Its description is a plain string, without values in braces, and no two tests of a file share one. Test blocks may be in any file, library modules included, and a package’s tests are left out of the programs that use it.

use statements come first in a file. See Modules for how use finds files.

Constants

const name = value defines a constant, which is worked out when the program is built and never changes:

const size = 1 << 10
const count = 4
const total = size * count
const name = "stone"
const limits = (3, 0.5)

fn kilobytes(n: int) -> int:
    ret n * size

print(total, kilobytes(2), name, limits[1])

This prints 4096 2048 stone 0.5. A constant’s value is made of literals (numbers, true and false, strings without values in braces, and bytes), other constants, math.pi, math.tau, and math.e, the operators, and tuples of them, so it is an int, float, bool, str, bytes, or a tuple of those, and its type is its value’s; it is never written. Arithmetic is computed exactly as at runtime, and an operation that would fail when the program runs, such as 1 / 0 or 1 << 64, fails the build instead. A call, a variable, a list, or a map is not known until the program runs, so it cannot be part of one (error E0050).

A constant can only be defined at the top level of a file, and code anywhere in the file reads it, before or after its line, functions and test blocks included, since a constant is not a global. It is never assigned again, and no parameter or variable takes its name. Library modules may define constants, and pub const lets other files read one, as limits.most or, after use limits.most, most.

Augmented assignment

x op= v, where op= is one of +=, -=, *=, /=, %=, **=, &=, |=, ^=, <<=, and >>=, means x = x op v, with the same types and errors as op:

total = 0
for price in [3, 4, 5]:
    total += price
total *= 2
print(total)   // 24

The target can be a variable, an element, or a field, as in counts[i] += 1, grid[r][c] **= 2, or ps[i].x += 0.5. An element’s indexes are evaluated once, from the outermost, then the element is read, so an index out of range stops the program before the value runs, then the value is evaluated and the result stored. So counts[random.randint(0, 5)] += 1 picks one position and adds 1 to it. A variable assigned with op= is assigned like any other, so inside a function it is a local, and x += 1 in a function with a global x is an error, as in Python.

+= on lists adds element by element, as + does: xs += ys is xs = xs + ys, and xs += 1 adds 1 to every element. It never appends; use xs.append(x) or xs.extend(ys) for that. Because the result replaces the list, it is computed in place when nothing else holds it. Strings join with s += t, the same as s = s + t.

Function signatures

Every parameter is written with its type after a colon, and a function that returns a value writes its type after ->:

fn mean(xs: list[float]) -> float:
    total = 0.0
    for x in xs:
        total += x
    ret total / float(xs.len())

fn report(name: str, score: float):
    print(name, score)

A type is int, float, bool, str, list[T] for any type T, such as list[list[int]], map[K, V] with keys of type K and values of type V, such as map[str, list[int]], tuple[T1, T2, ...] with a type for each of two or more values, such as tuple[str, list[int]], option[T], or a struct’s or enum’s name, such as Shape, or shapes.Shape for one of a module, followed by its types in brackets if it is generic, such as Pair[int, str], or a function type, fn(T1, ...) -> R, such as fn(int, str) -> bool, or fn(str) for a function that returns no value. Inside a generic function, struct, or enum, its type parameters, such as T, are types too. A function without -> returns no value, so a call to it can only be a statement of its own, and its ret takes no value. Types are written only in signatures: variables, including a function’s locals, never have them. See Types.

Operators

From lowest to highest precedence:

operators

operands

or

bool conditions

and

bool conditions

not

a bool condition

== != < <= > >= in not in

numbers, strings, bytes, and structs that implement ord; == and != also bools, tuples, structs, options, and enums; in and not in a value and a map, list, string, or bytes

|

two ints or two bools, or lists of ints; a struct or type parameter that implements bitor

^

two ints or two bools, or lists of ints; a struct or type parameter that implements bitxor

&

two ints or two bools, or lists of ints; a struct or type parameter that implements bitand

<< >>

an int and a count from 0 to 63, or lists of them; a struct or type parameter that implements shl or shr

+ -

two ints or two floats, or lists of them; + also joins two strings or two bytes; a struct or type parameter that implements add or sub

* / %

two ints or two floats, or lists of them; a struct or type parameter that implements mul, div, or rem

unary + - ~

an int or a float, or a list of them (~ ints only); for - and ~, a struct or type parameter that implements neg or invert

**

an int or float base and an int exponent, or lists of them

calls f(x), method calls xs.len(), fields p.x, indexing xs[i], slicing xs[i:j:k], ?

?: a result or an option, in a function that returns one

x? gives the value an ok or a some holds, and on an err or none returns it from the function, so n = int(s)? passes a parse error to the caller (see Types).

Comparisons chain, so a < b <= c means a < b and b <= c with b evaluated once. x in c tests whether the map c has the key x, the list c an element equal to x, as == compares them, or the string c the text x, and x not in c is its opposite, as c.contains(x) and not c.contains(x) are. Unlike in Python, in and not in never chain: x in xs == b is an error, written (x in xs) == b instead. ** groups right to left and binds tighter than a unary sign on its left, as in Python, so 2 ** 3 ** 2 == 512 and -2 ** 2 == -4, while 2 ** -1 raises to -1. The bitwise operators bind as in Python, looser than arithmetic and tighter than comparisons, so a & b == c means (a & b) == c, x & 1 + 1 means x & 2, and ~x binds like -x. On ints they work on the 64 bits of two’s complement: 6 & 3 == 2, 6 | 3 == 7, 6 ^ 3 == 5, and ~5 == -6. On bools, &, |, and ^ give a bool and, unlike and and or, always evaluate both sides. x << n and x >> n shift by a count n from 0 to 63, and any other count stops the program with shift count out of range (count 64). >> rounds down, as in Python, so -7 >> 1 == -4, and << stops the program with integer overflow in shift when the result does not fit in an int, so 1 << 62 is fine but 1 << 63 fails, while -1 << 63 is the smallest int. (Unlike <<, + and * wrap.) Parentheses group as usual. Operands are evaluated left to right. On a struct, an arithmetic operator calls its trait’s method with the left operand as self, so a + b is a.add(b) (see Types).

A method call such as xs.len() evaluates the value before the . first, then the arguments. A change, xs[i][j] = v, ps[i].x = v, or xs[i].append(v), evaluates the assigned value, then each index from the outermost, then the arguments, and only then checks the indexes against the lists and makes the change. A struct’s named values are evaluated in the order they are written. The builtin methods, such as len, append, split, and an option’s unwrap, are documented in Builtins. A . right after an int starts a method call, so 1. is not a float; write 1.0.

Enums and match

An enum lists its variants, one per line, each with the types of the values it holds in parentheses, or none:

enum Shape:
    Circle(float)
    Rect(float, float)
    Empty

Shape.Circle(1.0) and Shape.Empty make values of it. A variant may instead name its values, all of them, as Rect(w: float, h: float), and is then made with named values in any order, as Shape.Rect(h=2.0, w=1.0), which are evaluated in the order they are written. match runs the first case whose pattern fits a value:

match s:
    case Shape.Circle(r):
        print("a circle of radius", r)
    case Shape.Rect(w, _):
        print("a rectangle", w, "wide")
    case _:
        print("empty")

A pattern is a variant with a pattern for each of its values, such as Shape.Rect(w, _) or some(Shape.Circle(r)), a name, which matches any value and binds it, _, which matches any value and binds nothing, an int (possibly negative), a string, or a bool, which matches a value equal to it, or patterns joined by |, which matches what any of them does, as 1 | 2 or some(0 | 1), each binding the same names. A named variant’s pattern gives its values by name, Shape.Rect(w=0.0), where a field left out matches anything and a name alone, as w in Shape.Rect(w, h=0.0), is short for w=w. some(p) and none are the patterns of an option, and ok(p) and err(p) those of a result. On a trait value, a struct’s name with its fields’ patterns by name, as Circle(r=0.0) or Circle(), matches a value of that struct, and a builtin type’s name, as int(n), one of that type. p as name matches what p does and binds the whole value to name, as case Circle() as c:. match takes an enum, an int, a string, a bool, or a trait value, and the cases must cover every value, which for a trait value takes a case that matches anything. See Types.

Structs

A struct lists its fields, one per line, each with its type:

struct Point:
    x: float
    y: float

Point(x=1.0, y=2.0) makes a value of it, naming a value for every field once, in any order. p.x reads a field, and p.x = 3.0, p.x += 1.0, and ps[i].y = 0.0 change one, as long as the struct is stored in a variable. See Types.

An impl block, in the same file as the struct, holds its functions:

impl Point:
    fn origin() -> Point:
        ret Point(x=0.0, y=0.0)

    fn shift(self, dx: float):
        self.x += dx

A function whose first parameter is self, with no type, is a method, called on a value as p.shift(1.0); any other is an associated function, called on the struct as Point.origin(). self is the only parameter written without a type, and only as a method’s first. See Types.

Maps

A map literal is a key, :, and a value for each entry, separated by commas, in braces: {"ann": 31, "bob": 27}. m[k] reads the value of k’s entry, and m[k] = v sets it, adding the entry if m has none. See Types.

Sets

A set literal is its elements, separated by commas, in braces, with no colons: {1, 2, 3}. {} is an empty map or an empty set, whichever its use makes it. See Types.

Slices

xs[start:stop] is a new list of the elements from start up to but not including stop, and xs[start:stop:step] takes every stepth one, as in Python. Any of the three can be left out: start defaults to the beginning and stop to the end, or the other way around for a negative step, and step defaults to 1, so xs[1:] drops the first element and xs[::-1] is reversed. A negative start or stop counts from the end, and one past either end is clamped, so xs[-2:] is the last two elements and xs[:100] is all of a shorter list. A step of 0 stops the program with slice step cannot be zero. The list is evaluated first, then the bounds left to right.

A slice is a new list, so it cannot be assigned to or changed: xs[1:3] = ys and xs[1:].append(x) are errors.

Arithmetic on lists

The arithmetic operators work on lists of ints or floats element by element, as numpy’s arrays do. Both lists must have the same length, and a number on either side applies to every element:

a = [1.0, 2.0, 3.0]
b = [10.0, 20.0, 30.0]
print(a * 2.0 + b)   // [12.0, 24.0, 36.0]
print(-a, a ** 2)    // [-1.0, -2.0, -3.0] [1.0, 4.0, 9.0]

Each element follows the rules for single numbers: int arithmetic wraps, / on ints truncates, and dividing by zero stops the program. Lists of different lengths stop it with lists have different lengths. The operands that are not themselves arithmetic on lists are evaluated once, left to right, then the lengths are checked, then the whole expression is computed for the first element, then the second, and so on, so a / b + c / d reports the first element where either division fails.

Because of this, [0] * n is a list of one element, [0 * n], rather than n zeros as in Python, and the checker warns about it. Join two lists with xs.extend(ys).

Arithmetic on lists compiles to one loop over the elements, with no list for any intermediate result, two elements at a time where the processor allows. When the result replaces a list nothing else holds, as in xs = xs * 2.0 + ys or xs += ys, the loop writes over it in place.