Introduction
A compiled language that pushes you toward doing the right thing.
- New to Brass? Start with the tour in docs/guide, then the small complete programs in docs/cookbook.
- The rules and their reasons: DESIGN.md.
- The standard library:
brass doc --std, or the*.mdfiles next to each module in compiler/runtime.
Every code example in these files is compiled, and run where it shows output,
by make test.
Status
Section titled “Status”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 buildcompiler/ the Brass compiler, written in Brassstage0/ the original bootstrap compiler in Rust (frozen)tests/ language tests shared by both compilerstools/ embed.brass (packs the C runtime into the compiler), test runnerBuilding
Section titled “Building”make # bootstrap/brass.c -> build/brass0 -> brass1 -> brass2make fixpoint # builds brass3 with brass2 and checks they emit identical Cmake test # runs the test suite against build/brass2make seed # regenerates bootstrap/brass.c from the current compilermake asan # tests + self-compile under AddressSanitizer/LeakSanitizerbuild/brass2 run examples/fib.brasscompiler/embedded.brass is generated from compiler/runtime/ by make.
Language
Section titled “Language”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,
implblocks, traits (generic too:Iterator<T>), generics with trait bounds,Box<dyn Trait>,forover anyIterator 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 canlet/let mut,if/else,while,for x in a..b/v/&v,match(with.Variantwhen the enum is known),ifandmatchas values,f"x = {x}", multi-line"""strings, rawr"..."strings,\xHHand\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, anddefer - 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 Untrustedtext,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/todoannotations test "name" { ... }blocks withassert/assert_eq, run bybrass test; property tests (test "name" for xs: Vec<i64> { ... }) with shrinking,benchblocks (brass test --bench) andbrass 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 anfs.files()permission, whichwithin(dir)narrows)os:args,env,exit,cwd,time,utc_offset,millis,sleep; anos.processes()permission withrun,run_outputandspawn(aProcessthat must be waited for or killed)net: anet.access()permission withconnect,connect_tls(verified TLS),open,listen;public_only()/only(hosts)narrow it; sockets with timeouts and fallible, size-limited readshttp:get,post,sendoverhttp://andhttps://, aClientwith timeouts, a deadline and limits; requests arrive asUntrustedtext;read_request,write_response,response,handlefor serversregex:compile(Unicode classes,(?i)), thenis_match,find,find_all,replace,replace_all,split(linear-time matching)glob:matches(&"src/**/*.brass", &p),find(&pattern)cli: declare flags, options and arguments;parsewith help texthash(SHA-256, HMAC),encoding(base64, hex),csv,gzip,sqlite(bound parameters only),template(HTML-escaping by default)io:read_line,read_all,read,write,flushrandom:seed,int(low, high),float(),shuffle; securesecure_bytes,secure_int,tokencollections:Queue,Heap(smallest first),Reverseurl:encode,decode,query,parse_query,parsemath:PI,TAU,E,gcd,lcm,close; float methods such asatan2,hypot,log(base)are onf64thread:join(f, g),each(&items, f),workers(n, f),cpus(); with built-inMutex<T>andChannel<T>yamlandtoml:parseandtext(YAML alsoparse_all), reading into and writing from the samejson.Jsontree;xml:parse,element,pretty, andchild,children_named,attr,texton anElement;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 aJsonvalue,get,at,string,int,float,boolean,list,object(each anOption,Nonewhen the value is of another kind)path:join,parent,file_name,stem,extension,is_absolute,normalizetime:Datewithtoday,date,parse_date,from_days,add_days,days_until,weekday,format;DateTimewithnow,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.