Skip to content

Introduction

A compiled language that pushes you toward doing the right thing.

Every code example in these files is compiled, and run where it shows output, by make test.

Brass is self-hosting. The compiler in compiler/ is written in Brass and compiles itself.

bootstrap/ brass.c: the compiler's own C output, used to start the build
compiler/ the Brass compiler, written in Brass
stage0/ the original bootstrap compiler in Rust (frozen)
tests/ language tests shared by both compilers
tools/ embed.brass (packs the C runtime into the compiler), test runner
Terminal window
make # bootstrap/brass.c -> build/brass0 -> brass1 -> brass2
make fixpoint # builds brass3 with brass2 and checks they emit identical C
make test # runs the test suite against build/brass2
make seed # regenerates bootstrap/brass.c from the current compiler
make asan # tests + self-compile under AddressSanitizer/LeakSanitizer
build/brass2 run examples/fib.brass

compiler/embedded.brass is generated from compiler/runtime/ by make.

See DESIGN.md for the rules and their reasons. In short:

  • i8..i64, u8..u64 (checked, no implicit conversions), f64, f32, bool, Str (UTF-8; bytes(), codepoints(), graphemes())
  • structs, enums with payloads, impl blocks, traits (generic too: Iterator<T>), generics with trait bounds, Box<dyn Trait>, for over any Iterator
  • Vec<T>, Map<K, V>, Set<T>, Option<T>, Box<T>, &T, &mut T; literals [1, 2], Map { "a": 1 }, Set { 1, 2 }; structs and enums compare with == by value when all their parts can
  • let/let mut, if/else, while, for x in a..b / v / &v, match (with .Variant when the enum is known), if and match as values, f"x = {x}", multi-line """ strings, raw r"..." strings, \xHH and \u{...} escapes, +=, -=, *=, /=, %=, &=, |=, ^=
  • Zig-style errors that carry data: fn f() -> T ! A | B, try f(), f() catch 0, f() catch { NotFound(n) => ... }, error IoError = A | B, and defer
  • tuples: (i64, Str), t.0, let (a, b) = f(), for (k, v) in &map
  • bit operations on integers (&, |, ^, <<, >>, !x, 0xff, 0b1010, count_ones, rotate_left, …), with checked shift amounts
  • operators for your own types (Add, Sub, Mul, Div, Rem, Neg, Equal, Order), loop labels (outer: for ..., break outer), and string patterns ("GET " + path => ...)
  • closures with explicit captures: fn(x: i64) -> i64 [offset] => x + offset
  • impl Drop for T { fn drop(&mut self) { ... } } runs cleanup exactly once; impl Finish for T {} makes forgetting to finish a value a compile error
  • struct fields are private to their module unless marked pub
  • Untrusted text, time.Duration, and permissions (net.access(), os.processes()) made only in the main file
  • calling C: foreign "math.h" link "m" { fn cos(x: f64) -> f64 }, with owned C handle types freed automatically
  • modules (import a.b, pub), constants, because/todo annotations
  • test "name" { ... } blocks with assert/assert_eq, run by brass test; property tests (test "name" for xs: Vec<i64> { ... }) with shrinking, bench blocks (brass test --bench) and brass test --coverage
  • builtins: print, eprint, panic; modules:
    • fs: read, write, append, exists, is_dir, read_dir, create_dir_all, remove, rename, copy, metadata, walk, remove_dir_all, temp_dir (removed when dropped) (directly in the main file; other modules get an fs.files() permission, which within(dir) narrows)
    • os: args, env, exit, cwd, time, utc_offset, millis, sleep; an os.processes() permission with run, run_output and spawn (a Process that must be waited for or killed)
    • net: a net.access() permission with connect, connect_tls (verified TLS), open, listen; public_only()/only(hosts) narrow it; sockets with timeouts and fallible, size-limited reads
    • http: get, post, send over http:// and https://, a Client with timeouts, a deadline and limits; requests arrive as Untrusted text; read_request, write_response, response, handle for servers
    • regex: compile (Unicode classes, (?i)), then is_match, find, find_all, replace, replace_all, split (linear-time matching)
    • glob: matches(&"src/**/*.brass", &p), find(&pattern)
    • cli: declare flags, options and arguments; parse with help text
    • hash (SHA-256, HMAC), encoding (base64, hex), csv, gzip, sqlite (bound parameters only), template (HTML-escaping by default)
    • io: read_line, read_all, read, write, flush
    • random: seed, int(low, high), float(), shuffle; secure secure_bytes, secure_int, token
    • collections: Queue, Heap (smallest first), Reverse
    • url: encode, decode, query, parse_query, parse
    • math: PI, TAU, E, gcd, lcm, close; float methods such as atan2, hypot, log(base) are on f64
    • thread: join(f, g), each(&items, f), workers(n, f), cpus(); with built-in Mutex<T> and Channel<T>
    • yaml and toml: parse and text (YAML also parse_all), reading into and writing from the same json.Json tree; xml: parse, element, pretty, and child, children_named, attr, text on an Element; ini: parse, get, set, entries, to_str. YAML anchors and XML DOCTYPEs are refused, so entity and alias bombs cannot happen.
    • json: parse, text, pretty, num, float; on a Json value, get, at, string, int, float, boolean, list, object (each an Option, None when the value is of another kind)
    • path: join, parent, file_name, stem, extension, is_absolute, normalize
    • time: Date with today, date, parse_date, from_days, add_days, days_until, weekday, format; DateTime with now, now_local, from_unix, parse_datetime, format (strftime codes)

The compiler checks types, mutability, visibility, exhaustiveness, error handling, ownership (moves) and borrows, and warns about dead code. Memory is freed automatically when values go out of scope, with no garbage collector.

make bench times the programs in bench/ and the compiler compiling itself. brass doc writes Markdown reference pages; make site builds the documentation site with Starlight (cd site && npm install once).

Commands: run, test, build [-o out] [--release], check, emit-c, fmt [--check], lsp; --time reports how long each compiler phase took.

Projects: brass new app, brass add geo <git url> v1.0.0, brass fetch; see DESIGN.md.

brass lsp is a language server (stdin/stdout): diagnostics as you type, formatting, document symbols, hover, go-to-definition, find-references, rename and completion. Point your editor’s generic LSP client at the command brass lsp for *.brass files, e.g. in Neovim vim.lsp.start({ name = "brass", cmd = { "brass", "lsp" } }). --strict turns expired todos into errors. BRASS_MEMCHECK=1 reports any memory a program leaves allocated at exit. make install puts the compiler at ~/.local/bin/brass.

tests/run/*.brass must print *.out (reading *.in if present), tests/fail/*.brass must fail with an error containing *.err, and tests/warn/*.brass must compile with a warning containing *.warn. make test runs them against build/brass2; make test-stage0 runs stage0’s frozen suite.