Language
Language guide
current strict self-hosted Maylang; compile examples with compiler/mayc/mayc_new from the repository root.
Program structure
a .may file contains declarations and executable top-level statements; imports are expanded before type checking.
End declarations, assignments, returns and ordinary expression statements with ;; use braces for blocks. A branch/block may produce a trailing expression value, but strict functions require explicit return.
Names use letters, digits and _, starting with a letter or _; names and keywords are case-sensitive.
Comments: // to end of line; /* ... */ block comments; documentation comments use /// immediately before a declaration, in the form given by the doc comment standard.
Literals
integers such as 42 and 1_000; decimal floating values such as 3.5 and 1.0e-3; strings in double quotes; Boolean values true/false; absence nil.
Integer literals may be hexadecimal 0xff, octal 0o755 or binary 0b1010; the prefix is lowercase and hexadecimal digits take either case. A leading zero without a prefix is still decimal (007 is 7), and floating literals are decimal only.
_ separates digits in any numeric literal, including the fraction and exponent of a Float (1_000_000, 0xffff_ffff, 6.022_140e2_3); each _ must sit between two digits. Separators and prefixes are source syntax only: int("0xff") and float("1_000") still fault.
Strings support escapes \n, \t, \r, \0, \\, \" and \$; interpolation embeds ${expression}, for example "answer: ${6 * 7}".
Values are fat on every runtime and target (a type word and a payload; see docs/design/FAT_VALUES.md), and integers are signed 64-bit, in [-9223372036854775808, 9223372036854775807]. Out-of-range literals and arithmetic overflow are errors; every radix has the same range, so write -0x8000_0000_0000_0000 for the minimum and -1 or ~0 rather than 0xffff_ffff_ffff_ffff.
Floats are binary64 payloads. Float32/F32 annotations round values at typed boundaries while keeping the binary64 representation.
String len and character indexing count Unicode codepoints. Strings can carry raw bytes; use networking byte_length, bytes and from_bytes for binary payloads.
List literal: [1, 2, 3]; map literal: {"name": "May", "count": 2} or {name: "May"}; empty collections are [] and {}.
Collections and records have shared reference semantics. Assigning a list/map to another binding aliases it; mutation through either reference is visible to the other.
Bindings
let answer: Int = 42; is immutable; mut total: Int = 0; allows reassignment; omit the annotation when the initializer determines its type.
let protects the binding, not the collection contents: let xs: List<Int> = []; push(xs, 1); is allowed.
Reassignments must match the inferred/declared type. Assign with =, or use +=, -=, *=, /=; compound property/index assignments evaluate the receiver/index once.
Types
Int, fixed signed Int8/Int16/Int32/Int64, unsigned UInt8/UInt16/UInt32/UInt64, Float, Float32/Float64, Str, Bool, Nil, and Any.
Aliases: Byte = UInt8, F32 = Float32, F64 = Float64, Void = Nil; pointer annotations include Ptr<T> and RawPtr.
Generic collections: List<T>, Slice<T>, [T; N] or Array<T, N>, Map<K, V>, Tuple<T, U, ...>, Option<T>/Optional<T> and Result<T, E>.
Nullable type: Int?; function type: (Int, Int) -> Int or Fn(Int, Int) -> Int; named imported types: library.Point.
Bare generic collection names are invalid strict annotations; use List<Int> or Any rather than bare List.
Fixed-width annotations enforce range checks and Float32 rounding at typed boundaries. They do not change the storage. Fixed-size arrays check their lengths.
Any opts a boundary into dynamic checking. Calls, indexing, arithmetic and conversion involving Any can still fault at runtime.
Map lookup statically yields an optional value; handle absence with counts["key"] ?? 0.
Strict conditions require Bool; dynamic truthiness is available with bool(value) or truthy(value).
Operators
arithmetic +, -, *, /, %, **; bitwise &, |, ^, ~, <<, >>; equality ==, !=; ordering <, <=, >, >=; logical and/&&, or/||, not/!.
Comparisons
values of different types cannot be compared. Strict checking rejects comparing different static types, including Int with Float (convert with to_float, float or int); integer widths and Ptr compare with each other. At runtime, == between values of different types is false and != is true (any value may be tested against nil), while <, <=, > and >= raise a catchable type fault. match patterns of another type simply do not match.
Integer / truncates toward zero; % follows signed remainder behavior; division by zero and integer overflow fault in the full runtime.
Bitwise operators require integer operands and use signed 64-bit two's-complement words: ~ complements all 64 bits, >> is arithmetic, << wraps at 64 bits, and shift counts must be 0 through 63. With the runtime, an Int or Bool expression containing a bitwise operator, built only from integer variables, literals, operators and calls to functions with Int, Ptr or Bool signatures, is evaluated as a native-word function, so (1 << 63) & x works. Functions whose parameters, result, locals and operations are all Int, Ptr or Bool (including load*/store* and calls to functions with such signatures) compile as native-word functions with the raw 64-bit behavior and checked overflow (see the strict guide).
+ additionally handles string concatenation and list concatenation through dynamic runtime dispatch. Mixed/dynamic operations may require explicit Any boundaries in strict code.
Precedence, weakest to strongest: assignment; ??; |>; or/||; and/&&; equality; ordering; bitwise |; bitwise ^; bitwise &; ranges; shifts; +/-; *///%; unary negation/not/bitwise-not; **; postfix calls/index/property access.
Exponentiation associates right; other binary Pratt levels associate left. -2 ** 2 negates the power result. Parenthesize when grouping matters.
and, or, ?? and safe navigation short-circuit; use Bool operands for strict logical expressions.
Range a..b excludes b; a..=b includes b. Built-in range(a, b) in the full-runtime source takes exactly two arguments.
Pipeline x |> f calls f(x); x |> f(y) calls f(x, y); chaining runs from left to right.
Access
xs[i] indexes a list; text[i] returns a character string; mapping[key] performs map lookup; record.field reads a named map/record field.
Out-of-range list/string access can fault. Missing map keys yield nil; do not rely on negative-index portability between legacy and active runtimes.
Assign xs[i] = value;, mapping[key] = value; or record.field = value;; strict collection element/field types are checked.
Safe navigation value?.field returns nil when the receiver is nil and short-circuits the remaining postfix chain, including calls and their argument side effects.
Nil coalescing value ?? fallback evaluates fallback only when value is nil; false and zero remain valid values.
Branches
if (condition) { ... } else { ... }; chain else if; expression form: let n: Int = if (ready) { 1 } else { 0 };.
unless (condition) statement executes when the condition is false; an else branch is supported; useful for guard returns.
Loops
while (condition) { ... }; for item in iterable { ... }; optionally constrain inferred element types with for item: Int in values.
break; exits the innermost loop; continue; advances it. Both are invalid outside loops.
Strict return analysis is conservative about loops; put an explicit return after a loop even if it appears infinite.
Functions
fun add(a: Int, b: Int) -> Int { return a + b; }; parameters require annotations; result types may be explicit or inferred from explicit returns.
Every strict function path must return. A final expression is not an implicit function return. Use return; in a Nil-returning function.
Calls are positional and checked for arity, argument types and result use; user functions have no documented default/keyword/variadic parameter syntax.
Generic function: fun identity<T>(value: T) -> T { return value; }; the checker unifies type parameters across arguments.
Anonymous function: fun(x: Int) -> Int { return x * 2; }; closures capture surrounding bindings, including shared mutable captures.
Short lambda: |x: Int| -> Int { return x * 2; }; legacy short/arrow lambdas may use expression bodies. Prefer the fully typed anonymous form in strict examples.
Collections
comprehension [x * x for x: Int in values if (x > 0)] maps/filters eagerly; loop/comprehension binding types may be inferred.
Spread list [0, ...rest, 9]; spread map {...defaults, name: "May"}; map entries merge left to right with later keys replacing earlier keys.
Destructuring list/map declarations and loop patterns exist in legacy syntax; current strict code must expand them into individual typed bindings.
Records
struct Point { x: Int, y: Int }; construct positionally with Point(3, 4); read/write typed fields; constructors validate their argument types.
Records are tagged maps; nominal type identity includes the defining module; use library.Point for a namespaced imported record.
Enums
enum Shape { Empty, Circle(radius: Float) }; variants construct tagged values with a tag field and payload fields.
Match typed variants directly: match (shape) { Circle(radius) => radius, Rect(width, height) => width * height, Empty() => 0 }. Payload bindings have their declared types; use _ to ignore one. Enum/Result matches require exhaustiveness, and guarded arms do not cover a whole variant.
Matching
match (value) { 1 => "one", n if n > 1 => "many", _ => "other" } produces the first matching arm's value. Typed results support Ok(value) and Err(error) patterns.
Patterns include literals, negative numeric literals, identifier bindings and _; guards add Boolean tests.
Strict Bool matches must cover true and false or contain an unguarded wildcard/binding. Other nonexhaustive matches can raise a runtime fault.
Modules
import "math"; or import "math.may"; imports exported names; import "math" as math; provides qualified access; from "math" import gcd, lcm; imports selected names.
Place imports on their own lines. The active compiler expands source imports and tracks normalized absolute module identities; alternate spellings of the same resolved file expand once.
Resolution tries a path relative to the importer, then stdlib fallback; the compiler can locate stdlib sidecars in ancestors of its executable. Keep sidecars with the compiler.
pub marks exported top-level declarations. A module containing any explicit pub declarations exports only those names; otherwise its top-level declarations are available to importers.
Public enums export their type and variant constructors together; selective imports still name each desired constructor/type explicitly.
Namespace imports avoid collisions with native names such as zip, flatten, clamp, repeat, enumerate and pad_left.
Legacy README search paths/environment switches describe the old loader; the active self-hosted loader does not implement MAYLANG_STDLIB or MAYLANG_NO_PRELUDE as general search/prelude controls. Use runtime CLI options for mayc.
Fault boundaries
may { risky_expression } otherwise { fallback_expression } catches a runtime fault and evaluates fallback; a bare may returns nil on a caught fault.
Fault boundaries do not roll back side effects already performed: list mutation, output and file writes remain visible after recovery.
err inside otherwise exposes kind, message and stack; native errors can have an empty stack. Network errors additionally expose operation and errno.
fail("message") raises a fail-category error; assert(condition) and assert_eq(a, b) raise assertion failures. Parsing, I/O, arithmetic, type and indexing operations can also fault.
Errors from a fallback can propagate to an outer may boundary. return, break and continue remain control flow rather than ordinary recoverable failures.
Results and options
native Ok(value), Err(error) and Some(value) are ordinary {ok, value, error} maps; None() returns nil.
Postfix result? returns a failure/nil from the enclosing function; on success it yields the value field. Current strict checking requires an Any operand and does not connect Result<T,E> to a declared error type.
The result module's lowercase ok, error, unwrap, unwrap_or, map_result, and_then, collect and attempt operate on the same map convention.
Operator methods
dynamic record/map keys "+", "-", "*", "/" may hold functions called with (self, other); returning nil falls back to numeric dispatch. Use Any boundaries for overloaded arithmetic.
Native access
integer addresses, addr, cstr, load8/16/32/64, store8/16/32/64 and syscall expose raw machine operations; invalid addresses are not made safe by may.
Typed foreign block: extern "libm.so.6" { fun c_cos(x: Float) -> Float = "cos"; }; omitting the symbol alias uses the declared function name.
Typed C scalar types are Int, UInt, Int32, UInt32, Float, Float32, Ptr, Str, Bool and Void; Void is return-only and generic pointer annotations are rejected in extern declarations.
Foreign calls require the full Linux x86-64 native runtime; core and raw reject typed extern declarations. String arguments cross as C strings, with NUL termination semantics. In native-word functions, calls to externs with only Int, UInt, Ptr and Bool parameters and results (or a Void result) pass untagged 64-bit words.
Low-level ccall(address, args) supports up to six integer C arguments; extern_c(address) wraps a raw address with six positional parameters. These differ from typed extern calls and do not provide arbitrary C signatures.
Concurrency
spawn schedules a zero-argument function; yield() switches cooperatively and returns nil; run() drains ready fibers. The runtime uses cooperative scheduling, not parallel OS-thread execution. Each process may create at most 128 fibers with 256 KiB stacks.
Implementation boundaries
core supports maps, records, structs, enums, closures, shared captures, recoverable faults, debug traces and fibers on every native target. Floats and FFI require the full runtime. Raw omits the injected runtime; see the compiler reference.
Full-runtime GC has a documented corruption issue during sustained allocation workloads; core allocation retains chunks until process exit. These implementation limits are described in the existing compiler guide.
Read syntax catalog, runtime API, library APIs and compiler reference for complete inventories and commands.
Comments: // continues to the end of a line; /* ... */ block comments nest. Import-looking lines inside comments or multiline strings are ignored by module loading.