πΈ A compiled, statically-typed, expression-oriented language with a Cranelift JIT backend and a mark-sweep GC. Designed to be embeddable in Rust applications, fast compilation, decent runtime performance. Inspirations include Go (but better usability) and Lua.
πΈ froglang is a programming language in development. Design points:
- static types + bidirectional type inference
- mutable value semantics
- fast compilation, decent runtime performance (currently uses Cranelift)
- systems-ish (e.g., errors-as-values), but features a GC, like Go
- lightweight, ergonomic syntax
- embeddable in Rust apps or standalone (WIP)
πΈ froglang repl
>> func fib(n: Int): Int = if n <= 1 then n else fib(n - 1) + fib(n - 2)
:: Int -> Int
>> fib(30)
832040 :: Int
>> let greeting = "hello " + "world"
"hello world" :: Str
>> [1, 2, 3]
[1, 2, 3] :: List<Int>
// Named function declarations with typed parameters and return type
func fib(n: Int): Int =
if n <= 1 then n
else fib(n - 1) + fib(n - 2)
// Multi-statement block bodies β newlines and ; both separate statements
func hypotenuse(a: Int, b: Int): Int = {
let a2 = a * a
let b2 = b * b
a2 + b2
}
// There are structs and enums (value types)
// email here is of type `Str | None`, for which `Str?` is an alias
// This is a union (comparable to Typescript), rather than a "wrapper" like Option<T> in Rust
data Person(name: Str, age: Int, email: Str?)
let alice = Person(name = "alice", age = 42)
print(alice.email) // none
Supported expression forms:
-
Literals:
Int,Float(including1e100,inf,nan),Bool(true/false),Str,none -
String interpolation:
"n is ${n}"β any expression, formatted exactly asprintwould. See "String interpolation" below -
Arithmetic / comparison / logical operators with correct precedence
-
Unary
-andnot -
Let bindings with optional type annotation:
let x: Int = 5 -
Lambdas:
x -> x + 1,(x, y) -> x + y. A lambda may be passed as an argument and may capture enclosingletbindings β by value, so capturing amutis an error. See "First-class functions" below for what that does and doesn't buy -
Named function declarations:
func f(x: T, y: T): T = body -
return exprβ early exit from a function body -
Function calls:
f(x, y) -
Conditionals:
if cond then a else b.elseis optional β anelse-lessifhas an implicitelse none, so it is typedT | None, and it works in statement position (if cond then side_effect()) with the next statement on the following line -
match subject { is Pattern then expr ... }β exhaustive on declared unions, catch-all required on anonymous ones; arms must be newline-separated -
?β propagate a fallible value'sErrormember out of the enclosing function (postfix) -
!β unwrap a fallible value, calling thepanicbuiltin on itsErrormember (postfix) -
expr catch fallback/expr catch [e] -> handler_bodyβ coalesce a fallible value'sErrormember into a fallback expression or a one-argument handler -
Block expressions:
{ stmt; stmt; expr }β newlines and;both work as separators -
Lists:
[1, 2, 3], list comprehensions:[for x in xs if cond do expr] -
Ranges:
0..10 -
Type annotations:
expr : Type -
Comments:
// ... -
Statements are separated by a newline or
;, at the top level and inside{ }alike -
Multi-line expressions. A newline is whitespace in exactly two places, and a statement separator everywhere else:
- After a required delimiter β
=,then,else,->,do,in,is,catch,providesβ since the grammar demands more input, so the newline can't mean "statement over". Also before anelseor ado, for the same reason (but only when one actually follows: otherwise that newline is the separator ending anelse-lessif). - Inside
( )and[ ]β the closing bracket is an unambiguous terminator, so nothing in there could start a new statement. Covers call arguments, list literals, andfunc/dataparameter and field lists.
A newline mid-expression β after a binary operator, or before
./catchβ still ends the statement.(1 +β2)is a parse error, not a continuation. - After a required delimiter β
Bidirectional type checker with unification, over a dedicated type-expression grammar
(List<T>, unions, optionals, function types are spellable in every annotation site).
Primitive types: Int, Float, Bool, Str, None, Never (the bottom type β the
type of return, panic, and any expression that never produces a value)
Compound types:
(T1, T2 -> R)β function types, inferred for lambdas, checked against annotations. The parens wrap the whole type, arrow included:(Int -> Int),(Int, Int -> Int). That is what makes an annotation unambiguous without a lookahead βf: Int -> Intis rejected with a message telling you to add them (seeGrammar::type_annotation)List<T>β homogeneous GC-managed lists- Type variables with optional trait bounds
T1 | T2β sum / union typesT?β sugar forT | Nonedata Point(x: Int, y: Int)β nominal structs, unboxed flattened-field representationdata Shape is Circle(r: Int) | Rectangle(w: Int, h: Int)β sugar for a set of nominal structs (Shape.Circle,Shape.Rectangle) plus a closed union aliasShape; this is froglang's only sum-type mechanism β there is no separate enum construct
Built-in traits:
| Trait | Satisfying types | What it gives |
|---|---|---|
Num |
Int, Float |
+ - * / unary - |
Eq |
structural: any value type | == != |
Ord |
Int, Float, Str |
< > <= >= |
Error |
granted, not structural | ?, !, catch |
Linear |
granted, not structural | "can't be aliased" (checked) |
These are ordinary entries in the same trait registry a trait declaration lands in, so
provides accepts any of them alongside your own β but their behaviour is a compiler
intrinsic, so they can be granted, not implemented with a body. (Truthy, which decides
what if x means for a non-Bool, deliberately stays compiler-internal: making it
implementable would let any impl redefine control flow.)
Bound propagation: x -> x + x infers as (Num t) => t -> t.
Any string literal may contain ${...}, holding any expression:
let name = "Ann"
let xs = [1, 2, 3]
print("hi ${name}, ${len(xs)} items, first is ${xs[0]}") // hi Ann, 3 items, first is 1
print("${ if len(xs) > 2 then "many" else "few" }") // many
There is nothing special about what goes inside: it is parsed by the ordinary expression parser, so calls, field access, blocks, and nested interpolated strings all work, and an error inside one points at the offending token rather than at the literal.
A value formats exactly as print formats it. A Str goes in as text ("hi ${name}"
is hi Ann, not hi "Ann"); everything else uses repr (plans/DATA.md), so a struct
interpolates as P(name="Ann", age=4) and a string nested inside a list is still quoted.
Interpolating a type with no notation is the same error as calling repr on it:
func f(x: Int): Int = x
print("${f}")
// error: (Int -> Int) has no notation β interpolation needs Show
${ is the only sequence that changed meaning. A lone $ is still a dollar sign
("$5.00 and 100% $ free" needs no escaping); write \${ for a literal one. Because
repr's output must read back as source, repr escapes ${ and only ${:
print(repr("a\${x} b")) // "a\${x} b"
Data read by read is notation, not code, and does not interpolate β a ${ arriving in
data stays two ordinary characters (Parser::parse_data), so read(repr(x)) == x continues
to hold for every string.
Interpolation compiles to Str + Str concatenation, one intermediate string per piece; it
is a lexer change plus a typed-AST desugar, and codegen learns nothing new. See
plans/INTERPOLATION.md.
A function can be passed as an argument, a lambda can capture, and a func can be nested:
func apply(f: (Int -> Int), x: Int): Int = f(x)
func inc(n: Int): Int = n + 1
print(apply(inc, 2)) // 3
print(apply(y -> y * 10, 2)) // 20
let base = 100
let shift = x -> x + base // captures `base`
print(apply(shift, 2)) // 102
There is still no closure object, no function pointer, and no indirect call. Instead,
TypeChecker::lower_function_values compiles function values away before codegen sees
them: every lambda is hoisted to a top-level declaration, every captured name becomes an
ordinary by-value parameter, and a higher-order callee is cloned once per function it is
passed β so f(x) in apply's body is a direct call to whatever was passed. Same idea as
Futhark's defunctionalization or Rust's per-closure monomorphization, and it is why nothing
in the GC or the calling convention had to change.
The price is a restriction: the compiler must be able to name the callee at every call
site. A function value that escapes the scope that created it β returned from a function,
stored in a list or a struct field, or bound to a mut β is rejected, naming why:
func mk(): (Int -> Int) = x -> x + 1
// error: this function value is returned from a function β froglang can only pass a
// function where the compiler can see which one is called
mut total = 0
let f = x -> x + total
// error: closures capture by value; 'total' is a mut binding β copy it into a `let` first
Capture is by value and immutable by design, not by omission: it keeps froglang's mutable value semantics intact (no aliasing arrives through a captured variable), and it is exactly the condition under which lifting a capture into a parameter is semantics-preserving without escape analysis. A lambda sees its captures as of where it was created, not where it is called.
Escaping closures β a real (code pointer, captured environment) value, traced by the GC β
are deliberately unbuilt. See tests/test_closures.rs, whose rejection cases pin that
boundary.
See plans/TRAITS.md. Members are plain functions with an explicit Self parameter β not
methods with a receiver, which is what lets compare(a: Self, b: Self) and zero(): Self
be members at all. They live in their impl's namespace, so nothing is overloaded.
trait Shape {
func area(s: Self): Int
func doubled(s: Self): Int = s.area() * 2 // default body
}
data Circle(r: Int) provides Shape { // inline impl
func area(c: Circle): Int = c.r * c.r
}
provides Shape for Int { // standalone, for a type you don't own
func area(n: Int): Int = n
}
Circle(r=3).area() // dot form
Shape.area(Circle(r=3)) // prefix form, trait-qualified
Circle(r=3).doubled() // default body, specialized per implementing type
x.f(args) resolves in a fixed order: a field f of typeof(x), then a member f
of an impl for typeof(x), then a global func f whose first parameter accepts typeof(x).
Fields always win, so no existing program changes meaning when a trait is introduced. Each
step is a hash lookup, never a search β the ambiguities that would make it one (two impls of
one trait for one type; two traits declaring one member name for one type) are rejected at
the impl, where the error can name both, rather than at the call site.
Calling a member on a union is legal iff every member implements it, and compiles to the
same dispatch match that ?/catch build. Calling a member on a mut receiver needs
no call-site marker (c.bump(), not mut c.bump()) β the marker exists to make a hidden
mutated operand visible, and the receiver is the least hidden position there is.
Type parameters take optional bounds: func twice<T: Num>(x: T): T = x + x, and
data Box<A: Eq>(v: A). Bounds are still inferred from the body; writing them is required
once inferred (func twice<T>(x: T): T = x + x is rejected, naming the missing <T: Num>),
since a caller reads the signature and not the body.
A bound is also what lets a generic call the trait's members: func report<T: Shape>(x: T): Int = x.area() is checked once against Shape's own signature, and each instantiation
resolves area to that type's impl β including impls declared after the generic itself.
Unlike the structural traits above, Error is granted only by a provides Error clause on
a data declaration, or the error X(...) shorthand for data X(...) provides Error β it
marks "this type can flow into ?/!/catch", not "this type happens to look a certain
way". A union satisfies Error iff every member does, so provides Error on a data ... is ... union grants it to every variant and the alias gets it for free.
Union types:
- Mismatched if-else branches produce a union:
if c then 1 else "hi"has typeInt | Str - An
ifwithout anelsehas an implicitelse Noneso its type isT | None - Unions normalize (flatten, deduplicate, sort):
Str | Int | IntβInt | Str - Subtype relation:
T β€ (T | U), checked at every site a type is expected (annotatedlet,return, function args/return, struct fields,if/matchbranch joins) β this is the only way a union value comes into being; there is no explicit union constructor - Field access
u.fon a union is legal iff every member has a compatibly-typed.f is/matchnarrow a union to one member, dispatching on a runtime tag; an exhaustivematchtests every arm but the last, which needs none. Nominal and anonymous unions share one representation (plans/RUNTIME.mdPart 1): a union of at most six members that isn't self-referential is flattened into pointer-then-scalar columns with the tag in the low 3 bits of column 0, so it allocates nothing βInt | Eis a two-word register pair. Wider or self-referential unions fall back to a boxedFrogVariant
Error handling (see ERRORS.md): a fallible function returns T | E where E: Error β
there is no separate Result type, so propagating an error into a broader error union is
free widening, not a conversion:
error ParseError(msg: Str)
func parse(s: Str): Int | ParseError =
if s == "bad" then ParseError(msg="nope") else 42
func run(s: Str): Int | ParseError = parse(s)? * 2 // ? propagates ParseError out of run
func lenient(s: Str): Int = parse(s) catch 0 // catch coalesces it into a fallback
func trusted(s: Str): Int = parse(s)! // ! panics on the error member
A statement-position value whose type is or contains an Error-providing type must be
consumed (bound, matched, or handled) β silently discarding a fallible call is a type error.
Binding it to a let counts as handling (defers it to the binding's later use); a tail
position or comprehension body does too.
Compiles to native machine code via Cranelift. Two-pass compilation: all named functions are forward-declared before any body is emitted, so mutual recursion works without forward declarations in user code.
Supported in codegen:
- All arithmetic, comparison, and logical operators on
Int,Float, andBool IntβFloatwidening coercion at use sites- Let bindings and variable references
- Named and anonymous functions, including mutual recursion
- Function calls (direct and via value)
if-then-elseexpressions, includingNever-typed conditionals (every branch supplies its own terminator β atraprather than a merge block β when both arms areNever)return, and anyNever-returning call (atrapafter the call, then a fresh dead block)matchover structs, nominal unions, and anonymous unions?/!/catch(desugared entirely in the type checker into an ordinarymatch; no dedicated codegen node)- Block expressions (sequenced statements; result is the final expression)
- String allocation, concatenation, equality,
print - List allocation, indexing, push, list comprehensions
- Struct construction and field access (unboxed, flattened fields)
- Union construction via implicit widening; unboxed into tagged columns (
codegen::UnionLayout) for the inline case, boxed as aFrogVariantfor a union that is self-referential or has more thanMAX_INLINE_UNION_MEMBERSmembers
frog build program.frog -o program produces a standalone native executable β no compiler,
no Cranelift, no per-run codegen. It reuses the exact same Codegen as the JIT (Codegen<M>
is generic over Cranelift's Module; the JIT drives a JITModule, build drives a
cranelift-object ObjectModule), emits a relocatable object, and links it against the
runtime as a static library (libfroglang_core.a) with the system cc.
Two things make this work despite the runtime's GC and host-function machinery:
- Stack maps are registered at load time. The JIT files each function's GC stack maps by
its finalized address; an AOT binary doesn't know those addresses until it loads, so the
object carries a serialized stack-map table (each function's base filled by a relocation),
and a generated
maincallsfrog_register_stackmapsonce at startup before running any froglang code. Verified againstFROG_GC_STRESS=1β collecting on every allocation β so a live value held across an allocation is never lost. - The program runs for its side effects. Like every other AOT-compiled language, a built
binary's output comes from explicit
print(...); the program's final expression value is evaluated and then discarded, not printed. (frog runstill prints it, REPL-style β that is the one deliberate behavioral difference betweenrunandbuild.)
The AOT backend compiles at opt_level=speed (the JIT stays at none, where its one-time-
per-run compile cost dominates); build pays codegen once, so the optimizer is free.
Heap-allocated values (Str, List) are managed by a mark-sweep garbage collector.
Each object has a GcHeader in an intrusive linked list. The GC triggers automatically
after each JIT call when bytes_allocated > threshold (initial: 1 MB; grows with the
live set).
FrogStrβ immutable, inline bytes after the header; NUL-terminatedFrogListβ header + separatei64data buffer; grows viarealloc
FFI functions (frog_alloc_str, frog_list_push, etc.) are extern "C" symbols
resolved by the JIT linker. They always allocate into the currently-active FrogState's
heap, set via an ACTIVE_HEAP thread-local pointer during JIT execution.
Builtins callable from froglang:
| Name | Type | Description |
|---|---|---|
print(value) |
Any -> None |
Coerce a value to text and print it with a newline |
gc_dump() |
() -> None |
Dump GC heap contents to stderr |
panic(msg: Str) |
Str -> Never |
Trap the process; !'s error arm just calls this, so it's callable directly too |
The REPL maintains full state across entries β variables and functions defined in earlier entries remain in scope.
πΈ froglang repl
>> let x = 10
10 :: Int
>> func double(n: Int): Int = n * 2
:: Int -> Int
>> double(x)
20 :: Int
REPL meta-commands:
:gc β dump live GC heap objects to stderr
:help β show available commands
FrogState owns all interpreter state and is the main embedding entry point:
use froglang_core::state::{FrogState, FrogValue};
let mut state = FrogState::new();
// State persists across eval calls
state.eval("let x = 6 * 7")?;
let (value, ty) = state.eval("x")?;
assert!(matches!(value, FrogValue::Int(42)));FrogValue deep-copies strings and lists out of the GC heap on return, so the host's
lifetime is independent of the GC. Multiple FrogState instances on different threads
need no coordination β each owns its heap and JIT module (Lua model, no GIL).
Host functions β froglang code can call back into Rust via FrogState::builder() and
#[frog_fn] (see plans/EMBEDDING.md):
use froglang_core::{frog_fn, state::FrogState};
#[frog_fn]
fn shout(s: String) -> String {
format!("{}!", s.to_uppercase())
}
let mut state = FrogState::builder().func(shout_host()).build()?;
let (value, _) = state.eval(r#"shout("hi")"#)?;Parameter and return types must implement FromFrog/ToFrog (froglang_core::host) β
implemented for Int/Float/Bool/None/Str/List<T>/Dict<K,V>/Option<T>/Result<T,E>,
and for an arbitrary struct or (inline, β€ 6-variant) nominal union via #[derive(FrogData)]/
#[derive(FrogUnion)]:
use froglang_core::{frog_fn, FrogData, state::FrogState};
#[derive(FrogData)]
struct Point { x: i64, y: i64 }
#[frog_fn]
fn manhattan(p: Point) -> i64 { p.x.abs() + p.y.abs() }
let mut state = FrogState::builder().data::<Point>().func(manhattan_host()).build()?;
let (value, _) = state.eval("manhattan(Point(x=-3, y=4))")?;A boxed (self-referential or wider) nominal union isn't supported by the derive yet.
A minimal stdlib β string functions, file/stdio IO β built entirely on the host-function
embedding API above; there's no separate mechanism. FrogState::new() doesn't include it
(existing embedders/tests keep today's minimal surface); opt in with:
use froglang_core::state::FrogState;
let mut state = FrogState::with_stdlib()?;The CLI (cargo run, cargo run -- run ...) always uses with_stdlib().
len is the one exception to "everything is a host function": len(xs) / xs.len() works
on any List<T> or Str and needs no registration at all, because it's a hardcoded builtin
(alongside push/print) rather than a host function β the type system has no generics yet, so
a host function can't be polymorphic over T the way len needs to be.
String functions β Str is UTF-8 and byte-indexed throughout (len is byte length, matching
Rust's own str::len); there is deliberately no s[i] indexing operator, since mixing a
byte-based len/slice with a codepoint-based [] would make s[len(s) - 1] silently wrong on
non-ASCII input. chars is the character-level escape hatch, and yields codepoints, not grapheme
clusters β full Unicode segmentation is out of scope for a minimal stdlib.
| Function | Signature | Notes |
|---|---|---|
slice(s, start, end) |
(Str, Int, Int) -> Str | ErrMsg |
byte range [start, end); errors instead of panicking on an out-of-range or non-char-boundary split |
split(s, sep) |
(Str, Str) -> List<Str> |
|
join(items, sep) |
(List<Str>, Str) -> Str |
["a","b","c"].join(" "), not Python's backwards sep.join(items) |
trim(s) |
Str -> Str |
|
to_upper(s) / to_lower(s) |
Str -> Str |
|
contains(s, pat) / starts_with(s, pat) / ends_with(s, pat) |
(Str, Str) -> Bool |
|
index_of(s, pat) |
(Str, Str) -> Int | ErrMsg |
first byte offset, or Err if absent |
chars(s) |
Str -> List<Str> |
one codepoint per element |
to_int(s) / to_float(s) / to_bool(s) |
Str -> Int|ErrMsg / Str -> Float|ErrMsg / Str -> Bool|ErrMsg |
|
int_to_str(n) / float_to_str(f) / bool_to_str(b) |
_ -> Str |
infallible |
Every one of these works as a method too (UFCS: x.f(...) resolves to any free function whose
first parameter accepts typeof(x), no trait/impl machinery involved) β "3".to_int(),
" hi ".trim(), ["a","b"].join("-").
File and stdio functions β blocking, thin wrappers over std::fs/std::io. plans/CONCURRENCY.md
eventually makes I/O a swappable value in the ambient context, but there's no scheduler for it to
swap into yet, so today's contract is just "call, block, get an answer."
| Function | Signature | Notes |
|---|---|---|
read_file(path) |
Str -> Str | ErrMsg |
|
write_file(path, contents) |
(Str, Str) -> Int | ErrMsg |
truncates/creates; returns bytes written |
append_file(path, contents) |
(Str, Str) -> Int | ErrMsg |
creates if missing |
file_exists(path) |
Str -> Bool |
|
write_stdout(s) / write_stderr(s) |
Str -> Int | ErrMsg |
raw bytes, no trailing newline and no Debug-style quoting β print's lower-level sibling, for a TUI or a partial line built up across calls |
flush_stdout() |
() -> Bool |
|
read_line() |
() -> Str | ErrMsg |
newline stripped; Err("EOF") at end of input |
read_stdin_all() |
() -> Str | ErrMsg |
reads to EOF, for piped input |
Errors are a real T \| ErrMsg union, not a sentinel value or a Rust-side panic β ErrMsg
(error ErrMsg(msg: Str)) is the stdlib's shared error type, usable with catch/?/match like
any other error type:
let content = read_file(path) catch [e] -> {
print("couldn't read " + path + ": " + e.msg)
""
}
write_file/append_file return the byte count on success rather than None β not a style
choice: a Result<T, E> whose Ok is () isn't representable in today's marshalling (see
froglang_core::host's ToFrog for Result<T, E> doc comment), so returning something real sidesteps
it rather than routing around it with a placeholder.
Not yet built: generic map/filter/fold β frog already has for/list-comprehension
syntax covering much of what they'd buy in the meantime. Dict/Map is done (see "Dict/Map"
below). Struct/nominal-union marshalling beyond ErrMsg's one fixed shape, and host functions
that mutate their arguments, are embedding-API gaps (plans/EMBEDDING.md), not stdlib gaps.
benches/run_comparisons.sh [fib|orders|life|words|all] runs each benchmark in froglang and
in Rust, Go, Python, LuaJIT and Lua, and prints wall-clock time per language.
Every implementation is a line-by-line translation of the froglang one, and all
of them must print the same result β a differing row means one of them is wrong.
fibβ naive recursivefib(35). Pure call overhead and integer arithmetic, no allocation.ordersβ an order-pricing pipeline over 2000Itemstructs, repeated 2000 rounds. Each round filters the catalogue into a fresh list, classifies every item into aDiscountunion variant, matches on that variant, and runs the result through a fallibleprice_itemusing?andcatch. Exercises structs, unions +match, error propagation, list construction, and the GC. The other four implementations have no equivalent of?/catch, but since the error branch is never actually taken on this data, all five implementations must still print the same total.lifeβ Conway's Game of Life on a 48x48 grid for 40 generations, over aList<List<Int>>. Every inner-loop read is a double index and each generation rebuilds the whole grid from nested comprehensions, so this covers the nested-list layoutordersnever touches. Writing it is what turned up the copy-on-write work (MUTABILITY.md Stage 7): passing the grid to a function used to deep-copy it, which made this benchmark ~80x slower than it needed to be and hid three value-semantics bugs behind the cost of fixing them.wordsβ builds a 400-word document from a fixed vocabulary, splits it back apart and folds over the words, 800 times. The only benchmark that allocatesStrs, so it is the one that covers variable-size GC objects, byte-wise string comparison, and theStrstdlib (split/join/to_upper/starts_with) β which, being host functions, means it also covers the embedding boundary in a hot loop.
To profile any of them, FROG_JIT_SYMBOLS=syms.txt makes codegen write out
where each compiled function landed, and benches/symbolize.py syms.txt prof.txt attributes a sample/perf profile's addresses back to froglang
function names β without it a profile of a froglang program is entirely
??? (in <unknown binary>).
nb. the result times change often, do not record them here, they are likely to go stale. In general froglang should be within ~2x of LuaJIT, otherwise we are doing something Wrong
# Interactive REPL
cargo run
# Run an expression or .frog file
cargo run -- run '1 + 2 * 3'
cargo run -- run program.frog
# Type-check only
cargo run -- check program.frog
# Ahead-of-time compile to a standalone native executable
cargo run -- build program.frog -o program
./program
# Run all tests
cargo test
# Verbose GC tracing (allocations, marks, frees to stderr)
cargo test --features gc_trace
# Dump the Cranelift IR codegen emitted, per function, to stderr
FROG_DUMP_CLIF=1 cargo run -- run program.frogRoughly in priority order:
Better error messagesβ done: span-aware, rustc-style rendered errors, with a caret under the offending source (src/diagnostics.rs). The one place still printing a rawDebugform isfrog check's own twoprintln!s inmain.rs.β done, see "Types and constructs" below.Dict/Map
Cheaper primitive-member union matchesβ done. The boxing half was already gone when this was written:plans/RUNTIME.mdPart 1's tagged-pointer representation flattens every non-recursive union of at mostcodegen::MAX_INLINE_UNION_MEMBERSmembers intoUnionLayout's columns, soInt | Eis a(tag+ptr, scalar)register pair and?/catchallocate nothing at all (tests/test_union_repr.rs, and thefallible/infalliblebenchmark pair, which now run within noise of each other). Two real things were left, both fixed: amatch/?/!/catchon a union with aFloatmember aborted in Cranelift's verifier (the unreachable branch's placeholder was built with the integer-onlyiconst, and the merge block isF64); and an exhaustivematchemitted a tag test on its rightmost arm, which cannot fail β dropping it takes a two-member union's dispatch from two branches to one, andordersfrom 496 to 463 CLIF instructions across 80 blocks instead of 91. Wall-clock is unchanged: the redundant branch predicted perfectly. Still open here is the six-member inline ceiling and the boxed self-referential case, both deliberate (plans/RUNTIME.md, "As built").Flow narrowing andβ done: narrowing a union after a bindlessTruthyisarm, theTruthytrait for condition-position coercion (if/for/matchguards,and/or/notshort-circuit, including on a union whose members are allTruthyβ desugared to a per-member tag dispatch incoerce_truthy), andError-trait match arms with exhaustiveness all ship and are tested (test_truthy_and_narrowing.rs). Error return traces are still unbuilt.lower_match's guard-clause cloning, previously flagged here as exponential, is fixed.User-defined traits and implsβ done, see "Traits" above (plans/TRAITS.mdStage 5), including calling a member through a bound (func f<T: Shape>(x: T) = x.area()). Still missing from the trait system: operators desugaring to member calls (sodata Vec2 provides Numcan't give you+), structuralShowand thereforeError.message, and impls for generic types (data Box<A> provides Shape).Qualified variant names in type positionβ done:ParseError.UnexpectedEofis spellable in aTypeExprannotation and resolvable as anis/matchpattern nested inside a further anonymous union.Modulesβ done, undocumented above:import "./path.frog" { name }(named) andimport "./path.frog" as alias(qualified) both work, including import cycles, diamond imports, and cross-module structs/traits β seefroglang-core/tests/programs/modules/.User-definable genericsβ done: both generic functions and generic structs (data Pair<A, B>(...)) work with real monomorphization (plans/TRAITS.mdStage 3). This was previously the top blocker forDict/Mapand for self-hosting; see "Embedding" below.β done:Dict/Map["key": value]literal ([:]empty), backed by ahashbrown-basedFrogDictswappable viaFrogStateBuilder::dict_backend.Int/Float/Bool/Strkeys only for now (a new structuralTrait::Hash, deliberately narrower thanEq/Showβ there's no runtime polymorphic hashing to widen it to compound keys with). Indexing,.get,k in d,==,len, mutation,.keys()/.values()/for,.remove, andrepr/read/JSON round-trip all ship (tests/test_dict.rs).
β done, seeFrogState::builder()plans/EMBEDDING.md: host Rust functions are registered before the JIT module is created (JITBuilder::symbolonly accepts new symbols at construction), then installed into the type checker's scope, so froglang code can call back into the host with full type-checker support. Covers scalars/Str/List<T>today; struct/union marshalling and generic host functions are listed as follow-ups there.Minimal stdlibβ done for strings/file IO, see "Standard library" above:FrogState::with_stdlib(),Result<T, E>βT | Emarshalling (ToFrog for Result<T, E>infroglang_core::host), and the sharedErrMsgerror type.HashMap<K, V>βDict<K, V>marshalling ships too (host.rs). Still needed for a real self-hosting compiler: genericmap/filter/fold, and nominal struct/union marshalling beyondErrMsg's one fixed shape (plans/EMBEDDING.md's follow-ups).