This file maps the active Zmeu surface syntax. It is descriptive, not a design promise: older planning notes do not extend the accepted language.
- Zmeu uses indentation-sensitive blocks. Child blocks use exactly four spaces.
- Top-level items are
import,from,export from,const,extern,struct,enum,impl, anddef. Importable declarations useexport;pubremains accepted as legacy syntax. - Comments are line comments with
#.
import std.fs as fs
from std.result import Result
export from .collections.hashmap import HashMap
const BUF_SIZE: usize = 4096
import path.to.moduleimports a module namespace only, requiring qualified access such asstd.fs.open_read(path).import path.to.module as aliasimports a module namespace under an explicit alias, requiring qualified access such asfs.open_read(path).from path.to.module import Item, Otherimports selected exported items into bare scope.from .child import Itemimports selected items from a child module. Parent relative imports are not part of this slice.export from .child import Itemre-exports selected accessible items as part of the current module's public API.const NAME: Type = exprdeclares a checked compile-time constant.export const NAME: Type = exprexports a constant from an imported module.export(super) const NAME: Type = exprexposes a constant to the parent module.export(package) const NAME: Type = exprexposes a constant inside the current package; the project and std are separate packages.def name(params) -> Type:declares a function.export def name(params) -> Type:exports a function from an imported module.export(super) def name(params) -> Type:exposes a function to the parent module.export(package) def name(params) -> Type:exposes a function inside the current package.unsafe def name(params) -> Type:declares a function whose callers must useunsafe:. Its body is still checked normally.export unsafe def name(params) -> Type:exports an unsafe function.- The same
export,export(super), andexport(package)visibility forms are accepted onstruct,enum, struct fields, and impl methods. Plain declarations remain private by default;pubremains accepted as a legacy alias for publicexport. def name[T, E](...) -> Type:declares an explicitly-instantiated generic function.- Function effect markers follow the return type before
::blocking,allocates,suspends, andoffloads_blocking. Public suspending APIs must spellsuspends; private helpers may infer it from their direct call graph. Source calls remain direct style, so a suspending call uses normal call syntax but must be reached through a root or structuredspawn_iogreen-task boundary. - Executable entry point
mainmay returnNonefor success exit code0, ori32when the program intentionally returns a process exit code. Usestd.process.process_exit(code)for explicit early exits frommain -> None. - Method-level type parameters such as
def method[T](...)are reserved for a later milestone. extern "C":declares bodyless C ABI functions. Raw extern declarations are module-private in this slice.unsafe:permits unsafe function calls, raw extern calls, and raw extern-call argument views inside the block.import std.time as timeexposes monotonic runtime time helpers:monotonic_nanos() -> u64andelapsed_nanos(start: u64) -> u64.import std.math as mathexposesf32/f64helpers forsqrt,abs,floor,ceil,trunc,is_nan, andis_finite.import std.fmt as fmtexposes width-suffixedto_string_*helpers for integer, float, and bool values.import std.time.reactor as time_reactorexposes reactor-backedsleep_forandsleep_untilhelpers for structured green tasks.import std.bytes as bytesexposes safeByteBufand byte-slice helpers such aszeroed,filled,from_slice,append,resize_zeroed,copy_from,equal,starts_with,ends_with,find,contains,fill, andcopy_exact.import std.ascii as asciiexposes byte-oriented ASCII classification, folding, hex conversion, and case-insensitive equality helpers.import std.json as jsonexposes validation-first JSON helpers:validate(input) -> Result[None, JsonError]andscan_structural_indexes(input) -> Result[List[usize], JsonError].count_structural_indexes(input) -> Result[usize, JsonError]validates the same string lexemes and returns the structural count without materializing the index list.validate_and_count_structural_indexes(input) -> Result[usize, JsonError]validates full JSON syntax and returns the structural count in the same parser pass.
def identity[T](value: T) -> T:
return value
extern "C":
def write(fd: c_int, buf: *const u8, len: usize) -> c_ssize
- Scalars:
i32,i64,u8,u32,u64,usize,f32,f64,bool,None. - C ABI aliases:
c_int,c_long,c_size,c_ssize,c_bool,c_float,c_double. - Text/path wrappers are nominal std/runtime types such as
String,PathBuf,Path,ByteBuf,CString, andCStr. - Borrowed text is written
view str; borrowed paths/C strings areview Pathandview CStr. - Views:
view Tfor shared non-owning access andmut view Tfor mutable non-owning access.&Tand&mut Tremain accepted compatibility syntax. - Raw pointers:
*const Tand*mut T, currently only for narrow extern C boundaries. - Fixed-width SIMD values are written
Simd[T; N]forT = u8,i32,u32,f32, orf64; masks are writtenMask[N]. SIMD values and masks are copy fixed-size values and can be locals, params, returns, and struct fields in this slice. - Borrowed slices:
[T]; fixed arrays:[T; N]. Borrowed slices are scalar integer/float/bool views in this slice. Fixed arrays support those scalar element types, concrete structs, nominal enums, and nested fixed arrays composed from supported elements. - Lists:
List[T]over supported scalar integer/float/bool types, concrete structs, nominal enums, and compiler-known owned byte wrappers. - Atomics:
Atomic[i32],Atomic[usize],Atomic[u64], andAtomic[bool]. - Optional:
T | None; float optionals are not part of this slice. - Union:
A | B | C. - Nominal generics:
Result[T, E],Box[T], etc.
- Fixed arrays and borrowed slices expose
.lenand indexing. Fixed arrays can be locals, by-value params/returns, and struct fields; arrays of structs also support indexed field reads/writes such aspoints[i].x. Borrowed slices support scalar integer/float/bool elements and concrete struct elements. Struct slices coerce from[Struct; N]andList[Struct]; shared views allowitems[i].xreads, and mutable views allowitems[i].x = value. By-value slices and slices over enums/options/owned dynamic wrappers are not supported. Mutable scalar slices can be indexed for writes when the borrow and range facts prove the access is valid. Simultaneous mutable borrows are accepted for disjoint constant or immutable-usizeindexes and for non-overlapping half-open ranges; dynamic indexes/ranges without a static proof remain conservative. List[T]supports empty literals with context (let xs: List[i32] = []), non-empty literals,.len, indexing, indexed assignment,.push(value),.clear(),.truncate(len), and borrowed-slice coercions such asview xs[:],view xs[lo:hi], ormut view xs[lo:hi]for scalar and struct element lists..contains(value) -> booland.index_of(value) -> usize | Noneare supported fori32/u8/u32/usize/u64/i64/boollists and forList[String]searched byview stror a string literal..sort()is supported fori32/u8/u32/usize/u64/i64andStringlists. Sharedview List[T]parameter and annotation syntax is accepted as source sugar for the same read-only borrowed-slice view;mut view List[T]remains unsupported, so mutable list views should use an explicit list range.List[Enum]supports literals,.len, indexing for match/inspection, indexed whole-element assignment,.push(value), and borrowed-slice coercions toview [Enum]/mut view [Enum]. Moving an owned enum payload out through borrowed or indexed enum elements remains rejected; destructure copy payload fields or overwrite the whole element.ByteBufsupportsByteBuf.new(),.len,.push(u8),.push_bytes(byte_source),.reserve(additional),.clear(),.truncate(len), indexed byte reads/writes (buf[i],buf[i] = value),.as_slice() -> view [u8], and.as_mut_slice() -> mut view [u8].StringsupportsString.new(),String.from_str(text),.push_str(text), width-suffixed.push_i32,.push_u8,.push_u32,.push_usize,.push_u64,.push_i64,.push_f32,.push_f64,.push_bool,.as_str() -> view str, and.as_bytes() -> view [u8].PathBufsupportsPathBuf.from_str(text),.push(component),.as_path() -> view Path, and.as_bytes() -> view [u8].CStringsupportsCString.from_str(text),CString.from_path(path), and.as_cstr() -> view CStr; construction rejects interior NUL bytes.- Structural mutations on owned containers are rejected while a borrowed view of the same storage is live, even when element/range borrows are otherwise proven disjoint.
- Atomics use sequentially consistent methods in this slice:
Atomic.new_i32(value),Atomic.new_u64(value),Atomic.new_usize(value),Atomic.new_bool(value),.load(),.store(value),.swap(value),.fetch_add(value), and.fetch_sub(value)where the method is valid for the element type. - SIMD construction and memory access are explicit:
Simd[T; 4](a, b, c, d),Simd[T; 4].splat(value),Simd[T; 4].load(view xs[i:i + 4]), andvalue.store(mut view xs[i:i + 4]). Load/store require the borrowed slice length to equal the lane count at runtime.Simd[u8; N].load_prefix(view xs)accepts a byte slice withxs.len <= N, copies the slice prefix, and zeroes the remaining lanes. Arithmetic is lane-wise, comparisons produceMask[N], masks are notbool, and mask results must be collapsed with.any(),.all(), or.to_bits()for masks up to 64 lanes.Mask[N].to_bits() -> u64maps lane 0 to bit 0. Masks support bitwise&,|,^, and~,.prefix(len)to clear lanes>= len, and.compress_indexes(base, mut view out)for masks up to 64 lanes; compression writes ascendingbase + laneindexes to amut view [usize], returns the count, and traps before writing ifoutis too short.Simd[u8; N],Simd[i32; N], andSimd[u32; N]support wrapping+,-,*, and bitwise&,|,^; signedness controls ordered comparisons.Simd[u8; 16].lookup16(indexes)performs a byte-lane nibble table lookup whereindexesisSimd[u8; 16],Simd[u8; 32], orSimd[u8; 64]: high-bit index lanes produce0, and other lanes readtable[index & 0x0f]. Masks do not support==or!=.mask.select(then_value, else_value)selects between two matching SIMD values lane by lane. SIMD values expose.extract(index)for a bounds-checked scalar lane read. Floating-point SIMD also exposes.reduce_add()for a deterministic left-to-right scalar sum. Integer SIMD division, remainder, shifts, integer reductions, wider integer lanes, SIMD containers, min/max or masked reductions, gather/scatter, and fast-math controls remain out of this slice.
struct Name:declares named fields.export struct Name:exports the type; fields remain private across modules unless written asexport field: Type.struct Name[T]:declares a generic struct.enum Name:declarescase Variantentries.export enum Name:exports the enum type.- Enum payloads currently use one named payload:
case Ok(value: T). - Nominal enum values can be stored in
List[Enum],[Enum; N], function params/returns, and struct fields. Shared directview Enumand borrowedview [Enum]/mut view [Enum]are supported for inspection, shared iteration, array/list coercions, and whole-element indexed assignment through mutable enum slices. Directmut view Enum, moving owned payloads out through borrowed enum elements, by-value enum slices, and recursive owned nominal graphs through struct fields, enum payloads, fixed arrays, or lists remain rejected. impl Type:declares associated functions and methods.impl Box[T]:declares methods for every concrete generic struct instance requested by the program. Methods may use the impl type parameters after substitution.Selfis accepted inside an impl method signature, body annotation, associated call, or struct literal constructor and names the concrete impl receiver type.- Owned builder-style method chains are supported when each chained method
takes
self,self: Type, orself: Selfby value and returns the next owned struct value. Borrowed receiver chaining from temporaries is reserved; bind the value to a local before callingview selformut view selfmethods. - Consuming builder methods may move direct owned storage fields such as
String,ByteBuf, andList[T]out ofselfwhen the containing builder type does not definedrop. - Inside
impl Type:the receiver type can be elided: writeselffor an owned receiver,self: viewfor a shared view, orself: mut viewfor a mutable view. ExplicitSelfor concrete receiver types remain accepted. - A
-> Nonefunction or method may fall off the end withoutreturn None. Use barereturnfor an early no-value exit. - A destructor is exactly
def drop(self: mut view) -> None:and cannot be called by user code.
export struct Point:
x: i32
export y: i32
enum Result[T, E]:
case Ok(value: T)
case Err(error: E)
impl Point:
def origin() -> Self:
return Self(x=0, y=0)
def move_x(self: mut view, dx: i32) -> None:
self.x = self.x + dx
Fields are private across module boundaries unless declared with export. Code
inside the defining module can construct, read, write, and destructure private
fields.
let name = exprdeclares an immutable local.let mut name = exprdeclares a mutable local.var name = expris sugar forlet mut name = expr.let name: Type = expradds a type annotation.var name: Type = expradds a type annotation to a mutable local.place = exprassigns to a mutable local, field, index, or auto-deref target.return expr,return,break, andcontinuecontrol flow.if condition:,elif condition:, andelse:branch.while condition:loops while a boolean condition is true.for item in iterable:iterates shared array/slice elements. Struct loop items are shared element views, soitem.xis readable and mutation throughitemis rejected.match subject:is a statement match with block arms.defer cleanup()registers aNone-returning cleanup call for the current lexical scope. Deferred calls run in reverse source order on fallthrough,return,trypropagation, loopbreak/continue, and panic cleanup. Deferred calls may borrow locals, but this first slice rejects moving non-copy owned values inside the deferred expression; prefermut view selfcleanup methods such asfile.close_best_effort(). While a defer is active, the non-copy roots it needs for cleanup cannot be moved or replaced before scope exit.use name = expr cleanup cleanup_call():declares a resource local, registers a cleanup call for the resource block, and runs that cleanup on every block exit path. The cleanup expression must reference the resource binding.use mut name = expr:is shorthand only for compiler-known std resource types with a safe best-effort cleanup method: currentlystd.fs.File,std.net.tcp.TcpListener, andstd.net.tcp.TcpStream. Shorthand cleanup requiresmutbecause closing invalidates the handle.tasks:creates a structured task scope. Inside it,let t = spawn f(args)starts CPU work,let t = spawn_blocking f(args)starts known blocking work on the blocking pool,let t = spawn_io f(args)starts structured green-task work that may suspend on the internal runtime hook or Linux reactor I/O, andjoin tconsumes a task handle.spawn_io f(args)is also accepted as a statement insidetasks:forNone-returning suspending callees; this creates a scope-owned detached green child without retaining a handle, which is useful for dynamic accept loops. Task-scope cleanup waits for both unjoined handles and detached children. Detached child failures are propagated only when the lexical task scope exits; an intentionally never-ending server scope can record a child failure without surfacing it immediately. The full destruction, borrowed-capture, happens-before, and reactor-backend contract is documented indocs/concurrency-contract.md. The MIR interpreter resumes the internal hook immediately and sequentially but does not execute reactor I/O/timer suspend points; the native MLIR path uses the runtime resumable-task boundary. On Linux,std.net.reactorexposes nonblocking TCP operations, explicit listen backlog,TCP_NODELAY, and operation-specific stream timeouts backed by the runtime reactor, whilestd.time.reactorexposes reactor sleep helpers.- Handle-returning
spawn,spawn_blocking, andspawn_iocallees may returnNone, integer/bool scalars, owned std byte/string/path buffers (ByteBuf,String,PathBuf,CString),List[T]whenTis TaskSend, and nominal structs/enums recursively composed from those TaskSend values. The same owned values may be moved intospawn,spawn_blocking, andspawn_iocalls by passing them as ordinary by-value arguments. Detached statement-formspawn_iohandlers must still returnNone. References, raw pointers, atomics, task handles, direct arrays, unions/optionals, floats, and custom user-drop values are not TaskSend in this milestone. - Values that remain live across a direct suspending call must be
frame-lowerable. Supported live-across-suspend values include scalars,
supported fixed-size arrays, references, task handles, supported owned dynamic
values such as
List[T],ByteBuf,String,PathBuf, andCString, optionals, and aggregates recursively composed from supported fields. Standalone raw pointers, atomics, slices,str,Path, andCStrare rejected as live-across-suspend frame values. zmeu check --emit-suspend-frames file.zmeuprints the stable audit report for invisible suspend points. Function rows contain the exact nativeframe_bytes; suspend-point rows contain live locals and their ABI byte sum.parallel for chunk in chunks(mut view xs[:], chunk_size):is the structured data-parallel loop surface for integer scalar slices.chunk_indexcan be bound withparallel for chunk, chunk_index in chunks(...):. The chunk size must be a positive compile-timeusizeliteral or const, andchunks(...)is compiler-known only in theparallel for ... inheader.- Parallel loop bodies may use the
chunkbinding, optionalchunk_indexbinding, module constants/functions, locals declared inside the body, and read-only captures of enclosing immutable primitive scalars or shared primitive slice/list views. Mutable locals, owned containers, task handles, blocking/allocating/suspending values, and other captures are rejected before MIR/codegen.return, top-levelbreak, top-levelcontinue, andtryare rejected inside the body; loop-localbreak/continueremain valid.deferkeeps its normal per-chunk cleanup meaning. parallel_for_chunks(mut view xs[:], chunk_size, worker)remains supported as the statement-only lower-level helper. The worker has shapedef worker(chunk: mut view [T], chunk_index: usize) -> None.
use mut file = try fs.open_read(path) cleanup file.close_best_effort():
let used: usize = try fs.file_read(file, buf)
use mut stream = try tcp.accept(listener):
try tcp.stream_write_all(stream, b"HTTP/1.1 200 OK\r\n\r\n")
parallel for chunk, chunk_index in chunks(mut view xs[:], 8):
let mut i: usize = 0
while i < chunk.len:
chunk[i] = chunk[i] + (chunk_index as i32)
i = i + 1
- Match expressions are currently accepted in
let, assignment, andreturnpositions. - Expression arms use
case Pattern => expr. - Block arms use
case Pattern:and must end withyield expr. - Statement matches use block arms and may include
else:. - Guards use
case Pattern if conditionin statement and match-expression arms. Guard false falls through to the next source arm for the same top-level pattern, then toelse:or the unmatched path. Guarded arms do not prove exhaustiveness; add an unguarded fallback arm when a pattern must be covered. Guards can read copy pattern bindings, but non-copy bindings are available only after the guard succeeds. Guards may shared-borrow the matched subject, but they cannot move, mutably borrow, or mutate it before payload binding.
let value: i32 = match result:
case Ok(x) if x > 0 => x
case Ok(x) => 0
case Err(e):
print_i32(0)
yield 42
match optional:
case Point { x, y: yy }:
print_i32(x + yy)
case None:
return
Supported pattern forms:
NoneTypeType as nameStruct { field }Struct { field: binding }VariantVariant(binding)Variant(Struct { field })
- Literals: integers, hexadecimal integers, decimal floats such as
1.0and1e-3, strings, byte literals such asb'\n', byte strings such asb"HTTP\r\n",true,false, andNone. - Names, fields, calls, method calls, indexing, and slicing:
x,p.x,f(a),x.method(a),xs[i],xs[start:end],xs[:end],xs[start:],xs[:], andxs[..]. - Array literals use either explicit elements (
[1, 2, 3]) or copy-element repeats ([0; N]) in a fixed-size array context. - Method chains may continue on indented lines that start with
.in expression-bearing statements such aslet,var, assignment,return, and expression statements. - Generic calls require explicit type arguments:
identity[i32](1)andresult.unwrap_or[i32, bool](r, 0). - Struct literals and enum constructors use named payloads:
Point(x=1, y=2),Ok(value=bytes). - Type constructors and associated calls are used for compiler-known SIMD
forms such as
Simd[i32; 4](...)andSimd[f64; 2].splat(0.0). - View expressions:
view placeandmut view place.&placeand&mut placeremain accepted compatibility syntax. - Raw extern views:
raw ptr bytes,raw mut ptr buf,raw cstr "name", andraw cstr view. - Result propagation:
try expr. - Casts:
expr as Type. - Type tests:
x is None,x is not None,x is i32,x is not Point.
Precedence is conventional:
- Unary:
-x,not x,~x. - Multiplicative:
*,/,%. - Additive:
+,-. - Shifts:
<<,>>. - Bitwise:
&,^,|. - Comparisons:
<,<=,>,>=,==,!=. - Boolean:
and,or.
Integer and float arithmetic require matching operand types; numeric literals
adapt to an expected type and otherwise default to i32 for integers and f64
for floats. Scalar integer +, -, *, and unary - wrap in the target
integer width. % is scalar integer remainder, not Euclidean modulo; for
non-trapping signed cases, a % b == a - (a / b) * b. Signed division and
remainder trap on divisor zero and MIN / -1 or MIN % -1; unsigned division
and remainder trap on divisor zero. % is not defined for floats or SIMD.
Overshifts trap deterministically unless the checker/backend proves the shift
amount is in range.
Simd[f32; N] and Simd[f64; N] support lane-wise +, -, *, /, and
comparisons. Simd[u8; N], Simd[i32; N], and Simd[u32; N] support
wrapping lane-wise +, -, *, bitwise &, |, ^, and comparisons using
unsigned u8, signed i32, or unsigned u32 ordering. .extract(index)
returns one scalar lane and traps with the
standard array-oob path when index >= N; float .reduce_add() returns a
scalar left-to-right lane sum with default IEEE behavior and no fast-math flags.
Comparison results are Mask[N]; use .any(), .all(), .to_bits(), or
.select(...) instead of treating a mask as a scalar boolean or comparing
masks directly.
Const items support f32 and f64 in the same pure scalar expression subset as
integers and bools. Float const arithmetic folds in the annotated target width
and preserves default IEEE-style results such as nan, inf, and signed zero.
Fast-math flags are not exposed in source.
std is ordinary source using the same module visibility model as user code.
Public APIs are exported from modules such as std.result, std.ascii,
std.bytes, std.io, std.fs, std.process, std.cstring, std.time,
std.fmt, std.math, std.bits, std.net.tcp, std.net.reactor, and
std.time.reactor. std.sys is an internal
export(package) unsafe capsule for std modules, not a project-code API. See
docs/std-public-api.md for the current exported std surface, including std
error-code conventions and borrowed error rendering helpers.
let mut name = exprremains accepted for compatibility, but examples should prefervar name = exprfor mutable locals.&T,&mut T,&place, and&mut placeremain accepted compatibility syntax. User-facing code should preferview T,mut view T,view place, andmut view place.*const T,*mut T,raw ptr, andraw mut ptrare intentionally explicit for FFI. The current unsafe model is narrow: std/sys capsules and raw extern-call authority only.- Explicit
cleanup ...clauses expose the current compiler model.useresource blocks improve common cleanup ergonomics while still lowering through checked defer facts. expr as Typeis compact and familiar, but all casts must remain explicit. Integers and floats can be cast explicitly; integer-to-float casts round directly to the target float width, and float-to-integer casts truncate toward zero, map NaN to0, and saturate out-of-range values.Result[T, E],Ok(value=...), andErr(error=...)are clear but verbose. Future sugar could shorten enum construction without changing Result semantics.