1.2.0 draft

  • Version: 1.2.0
  • Status: Draft
  • Date: 2026-10-11
  • Last updated: 2026-10-22
  • Java version: 25

This specification defines the syntax and semantics of Kalm 1.2.0. The words “must” and “must not” state normative requirements. Kalm source compiles to JVM class files and interoperates with Java types and code as described in §7. This draft extends the final 1.1.0 edition. It defines the 1.2.0 target contract, including requirements for future compiler, library, and documentation tooling; it does not imply that current releases implement every requirement. Examples illustrate the surrounding context unless identified as a complete file. Intentional changes are listed in §12.

1. The shape of Kalm

Kalm is a statically typed, object-oriented JVM language. It has Java’s class model, predictable execution, explicit types at API boundaries, and direct access to Java libraries. Everyday syntax uses Java-style braces, Kalm keywords, inferred local types, and concise expression-bodied functions. Blocks use either braces or a colon followed by an inline or indented body. Simple statements end with a semicolon or a logical newline; semicolons are recommended.

Kalm source files use UTF-8 and the .kalm extension. A JDK 25 or newer is required to compile Kalm programs; generated programs run on Java 25 or newer.

Kalm does not bundle Java libraries. Any library available to the host Java project is available to Kalm, subject to normal Java visibility, classpath, module readability, and module export rules.

Kalm and Kalm Script

Kalm (.kalm) is for applications, reusable libraries, and mixed Java/Kalm projects: declarations form a compiled API, the build supplies dependencies, and an application explicitly selects an entry point. Kalm Script (.kalms, also called kalms) is for small sequential programs, automation, experiments, and interactive exploration. It permits top-level statements and declarations without project setup or a main function. Both use the same statically typed language, nullability, expression rules, Java interoperability, and standard library. Kalm Script is an execution mode, not a dynamically typed dialect. Choose .kalm when publishing APIs or integrating a project build; choose .kalms when directly running a sequence of operations. Script and shell rules are defined in §11.

Kalm bundles its own runtime and standard library in CLI distributions, but does not bundle arbitrary third-party Java dependencies. Application builds can supply those dependencies; the baseline script host supplies only the JDK and bundled Kalm libraries.

A small taste

Kalm
space studio.greetings;
use java.time.LocalDate;
use java.util.ArrayList;

pub class Greeter {
    fun greet(name: Text) -> Text = @"Hey, $name. Glad you're here.";
}

pub fun main(args: Array<Text>) -> void {
    fix today = LocalDate.now();
    fix names = ArrayList<Text>();
    names.add("Tim");
    sayLine(Greeter().greet(names.get(0)));
}

Kalm uses Java classes and interfaces, supports direct calls to Java APIs, and provides both brace-delimited and indentation-delimited blocks.

2. Source files and lexical rules

A .kalm file contains an optional space declaration, zero or more use declarations, then declarations. Top-level executable statements are not allowed in this mode; .kalms follows §11. A source file may contain at most one pub fun main(args: Array<Text>) -> void or zero-argument pub fun main() -> void entry point. The compatible -> Unit spelling is also accepted. The compiler must reject multiple selected entry points for one application. The compiler generates the JVM-required public static void main(String[] args) launcher; for the argument-taking form, the Kalm entry point receives the original Java String[] as Array<Text> without copying. A compiler gives each source file with top-level definitions a deterministic Java facade named <SourceBase>Kalm. Public top-level classes and contracts live in same-named .kalm files.

If space is omitted, the file uses the unnamed package. A filename that cannot produce a unique Java identifier for its Java facade is a compile error. An omitted result arrow on a block-bodied entry point means void and is accepted. Entrypoint signatures are otherwise exact: defaults, asynchronous entry points, or nullable results do not create additional launcher forms.

Tokens, whitespace, and comments

Identifiers are case-sensitive, start with a Unicode letter or underscore, and continue with Unicode letters, digits, or underscores. The lexer recognizes multi-character operators before their prefixes using longest-match tokenization. @ introduces an annotation use.

Simple statements terminate with ;, a logical newline, or immediately before the end of a block or file. Separate simple statements on the same physical line require ;. Semicolons are recommended but optional. A completed return followed by a logical newline is a bare return. Expressions continue inside parentheses, indexing, collection literals, and generic type arguments, and after an unfinished operator, comma, or member-access operator. The ? and separating : of a conditional expression continue an unfinished expression. A logical newline after a completed true branch and before its required : is also continuation, not a statement terminator. To begin a ? on a later physical line after a complete condition, enclose the whole conditional in parentheses.

Additional semicolons are empty separators: sayLine("Hi");;;, a line containing only ;;, and separators before or after a declaration are valid. They are accepted in files, member/contract/variant/annotation/augment bodies, ordinary blocks, and match-arm lists. They have no value and do not introduce a scope. A separator cannot repair incomplete syntax: var a = ;; is an error, as is if ready; without a body. A colon suite must still contain at least one statement or declaration other than empty separators; use {} for an empty body. Separators do not affect expression continuation inside delimiters or change which else, elif, handle, or finally belongs to a compound statement.

Except for conditional branch blocks (§4), which require braces, every block body may use { ... } or : .... A colon followed by a newline requires a nonempty indented body, terminated by dedentation. Blank and comment-only lines do not affect indentation. Tabs expand to eight-column stops; ambiguous tab/space indentation and inconsistent dedentation are errors. An inline colon suite contains simple statements or declarations separated by semicolons and ends at its logical newline. Nested compound bodies require a multiline suite. Empty bodies use {}. Brace blocks and colon blocks may nest freely; indentation is structural only in colon suites. Literal delimiters retain their existing grammar.

Control-flow headers accept either parenthesized or unparenthesized conditions and loop bindings. Colon-bodied lambdas use parenthesized parameters to distinguish the body colon from parameter type annotations. For example:

Kalm
pub fun main() -> void {
    fix ready = true
    if ready:
        sayLine("Ready");
    else {
        sayLine("Waiting")
    }
}

The word fixed is not a declaration modifier in Kalm 1.2.0; use fix. It may be an ordinary identifier.

Comments use # to end a line and ## ... ## for a block comment. Documentation comments begin with ### and continue to the end of that line. The lexer recognizes ### first, then the two-character block opener ##, then the single-character line comment #. Block comments do not nest. Consecutive documentation lines form KalmDoc, whose attachment, tag language, validation, and required Javadoc conversion are defined in §7.

Literal words true, false, and null are reserved and cannot name declarations. The following are contextual keywords, recognized only where their grammar construct is applicable: space, use, class, contract, fun, var, fix, pub, internal, private, protected, implements, inherits, base, needs, closed, extendable, singleton, data, choice, alias, given, generate, augment, read, write, lazy, late, constant, forward, to, match, case, yield, if, elif, else, while, for, in, next, stop, return, self, super, with, defer, async, await, task, guard, try, handle, finally, raise, expect, require, ensure, external, bridge, annotation, target, legacy, test, before, after, init, override, and, or, not, as, and is. self designates the current instance in expression position and cannot be rebound in an instance scope. super selects parent construction or an inherited implementation only in the forms defined in §6. Built-in type spellings are recognized in type position and cannot be redeclared as types or aliases, but may name functions or members. The result spelling void is recognized only in result annotations and cannot be redeclared as a type or alias. Java identifiers remain usable in interop; Java words that are not Kalm syntax have no special lexical meaning.

The lexer retains a word's spelling; it must not reject a legal name merely because that spelling appears above. After fun, in a parameter/binding name slot, and after . or ?., contextual words are identifiers. Thus fun and() -> boolean = true, and(), fun test() {}, and object.test() are valid. A test declaration starts with test followed by a text literal and a block; a call test() does not start a test declaration. In an operand position, a contextual name followed by a call is an identifier unless the tokens form a complete compound construct such as if (condition) { ... } or task { ... }. Infix and, or, as, and is retain their operator roles between operands. At prefix position, not followed by ( (regardless of whitespace) is a call, not negation of a grouped expression; use not paused, not !paused, or !(paused) for negation. An unresolved not(...) reports an unknown callable. Other prefix operators such as await retain their operator role when followed by a non-call operand. A misplaced construct is diagnosed at its actual syntax position; once a keyword-led construct is selected, malformed structure must not be rescued by reinterpreting its tokens as a call.

Text literals use double quotes. Supported escapes are \\, \", \n, \r, \t, and \u{HEX} for a Unicode scalar value. Interpolated text uses @"..."; $name inserts a name and ${expression} inserts an expression. A literal dollar sign is $$. Character literals also accept \' for a single quote. Unicode escapes must denote a scalar value, not a surrogate or a value above U+10FFFF; a character literal additionally requires exactly one resulting UTF-16 code unit.

Decimal integer literals have type int, or long with an L suffix, and must fit their signed 32-bit or 64-bit range. Floating literals default to double; an f/ F suffix gives float. Numeric separators and hexadecimal or octal integer literals are not part of Kalm 1.2.0. A character literal uses single quotes and contains exactly one UTF-16 code unit and has type char. The magnitude immediately following unary minus may denote the minimum signed int or long value; the same out-of-range positive literal is invalid. Boolean literals have type boolean.

Kalm
fix note = @"Today is ${LocalDate.now()}";
fix quoted = "She said: \"hello\"";

3. Types, values, and Java mapping

Kalm’s built-in types map directly to Java’s primitive and reference model. Java signatures remain unchanged at the boundary.

Kalm type Java representation Meaning
void void result Preferred no-result spelling; not an ordinary value
Unit void result; Void in Task<Unit> Compatible no-result spelling; retained for task result arguments
boolean / Bool boolean / java.lang.Boolean Primitive / non-null wrapper of true or false
byte / Byte byte / java.lang.Byte Primitive / wrapper; signed 8-bit integer
short / Short short / java.lang.Short Primitive / wrapper; signed 16-bit integer
int / Int int / java.lang.Integer Primitive / wrapper; signed 32-bit integer
long / Long long / java.lang.Long Primitive / wrapper; signed 64-bit integer
float / Float float / java.lang.Float Primitive / wrapper; IEEE 754 binary32
double / Double double / java.lang.Double Primitive / wrapper; IEEE 754 binary64
char / Char char / java.lang.Character Primitive / wrapper; unsigned 16-bit UTF-16 code unit
Text java.lang.String Immutable Unicode text
Any java.lang.Object Non-null reference top type; primitives box on assignment
Array<T> T[] Fixed-size reference array; T must be a reference type
Task<T> kalm.runtime.Task<T>, a Java subtype of CompletionStage<T> Asynchronous result handle
BoolArray … CharArray Matching Java primitive array Fixed-size primitive arrays, including ShortArray for Java short[]
List<T> java.util.List<T> Ordered mutable list
Map<K,V> java.util.Map<K,V> Mutable map with non-null keys
T? Nullable reference type T must be a reference type; null is its null value

Primitive and reference boundaries

Lowercase types always denote JVM primitives; capitalized numeric/Boolean/character types always denote the listed Java wrapper classes. Bool and Int are aliases for java.lang.Boolean and java.lang.Integer, not primitive aliases. Qualified wrapper names have the same Kalm nullability rules. Primitives have no null value: int?, boolean?, and the other nullable primitive spellings are compile errors with a suggestion to use the corresponding wrapper, such as Int?. Any excludes null; Any? includes it. Null is never implicitly converted to a primitive or non-null wrapper.

Assignment, arguments, and returns follow Java widening, boxing, and unboxing rules, subject to Kalm nullability. For example, var n: Int = 5 boxes, fix p: int = n unboxes, and fix wide: long = p widens. Widening followed by boxing to a different wrapper is not an implicit conversion: assigning an int expression directly to Long is an error; use a long expression. Java's representable constant narrowing to byte, short, or char (and their boxed counterparts in assignment contexts) is supported; arbitrary runtime narrowing still needs a checked conversion. Nullable wrappers must be refined or coalesced before unboxing. A platform value admitted from Java is checked on entry to a non-null Kalm reference slot; a null value raises NullPointerException, never a silent primitive default. Java overload resolution distinguishes primitive and wrapper signatures, as described in §7.

Generic type arguments must be reference types: List<Int> and Array<Int> are valid, while List<int> and Array<int> are errors. Use IntArray for Java int[], with corresponding primitive arrays for all eight types. An inferred list literal boxes primitive elements ([1, 2] has type List<Int>); an inferred map similarly boxes primitive keys and values. Wrapper annotations preserve wrapper storage, including for non-null values. Non-null wrapper fields require initialization; Java zero defaults apply only to primitive var fields.

void is the recommended explicit function/method result when no value is produced. -> Unit remains supported with identical completion and Java signature behavior; use of Unit alone does not require a deprecation warning. void is result-only: void?, aliases to void, ordinary bindings/parameters, and generic arguments such as Task<void> are errors. An async fun with body result void exposes Task<Unit>, not Task<void>.

Unit is allowed as a function/method result and as the direct argument in Task<Unit> or the equivalent imported Java CompletionStage<Unit> type. Both task forms map their result parameter to java.lang.Void; successful no-result completion carries Java null internally. await on either produces no Kalm value. Unit?, List<Unit>, Array<Unit>, ordinary Unit bindings/parameters, and storing a no-result expression are errors. Nested ordinary generic arguments remain subject to these restrictions; List<Task<Unit>> is valid. Generic helper instantiation with Unit is allowed only when substitution uses it exclusively in these task/result positions; it cannot create an ordinary value parameter, record component, or collection of Unit.

List literals [a, b] create mutable java.util.ArrayList values; map literals create insertion-ordered java.util.LinkedHashMap values. Generic arguments are invariant in Kalm; Java generic declarations retain their bounds and wildcard information during interop.

Arithmetic unboxes non-null wrappers and follows Java numeric promotion: byte, short, and char first promote to int; a binary operation then promotes both operands to double, float, long, or int, in that priority order. The result is a primitive. Boolean values are not numeric. There are no implicit runtime narrowing conversions. Explicit conversions are toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble(), and toChar(). Integral narrowing is checked and throws ArithmeticException; floating-to-integral conversion truncates toward zero and rejects NaN, infinity, and out-of-range values. Integer overflow wraps at the result width. Integer division truncates toward zero. Each conversion returns the matching lowercase primitive; boxing can then satisfy a wrapper target. Integral division or remainder by zero raises ArithmeticException; floating-point arithmetic follows Java IEEE 754 behavior, including NaN and infinity.

true and false are primitive Boolean literals. null requires a nullable reference target (including Any?), except for the literal no-result return form in §4. A nullable receiver uses safe navigation (value?.name). Safe indexing uses value?[index]; it evaluates the receiver once and, if it is null, returns null without evaluating the index. The receiver must be nullable. It is supported for arrays, Text, List, and Map; the result is nullable, boxing a primitive element where necessary, and a missing map key also yields null. Ordinary map indexing likewise returns a nullable value for an absent key, even if the map's value argument is non-null. The null-coalescing operator left ?? right evaluates left once and evaluates right only when left is null. Its left operand must be nullable, and the result type is the common type of the non-null left type and the right type (and is nullable when the right type is nullable). ??= assigns a fallback only when a writable nullable target is null, including a mutable local/field, writable property, or supported indexed target (§4); the target location is evaluated once, its current value is read once, and the fallback is evaluated at most once. As an expression, ??= yields the existing non-null value or the newly assigned fallback; its result is nullable if the fallback can be null. These are syntax-level operations and add no runtime library dependency. Inside if (value != null) { ... }, a stable fix local or field is refined to non-null. Mutable var values are not smart-cast. Values of type Any require as Type before specialized use; failed casts raise ClassCastException. is Type checks and refines a stable value.

The same stable-value refinements apply in the true/false branches of ?: and in short-circuit operands: for example, value != null ? value.length() : 0, value != null and value.length() > 0, and value == null or value.length() == 0 may use a stable nullable value as non-null where the condition proves it. A field access is stable only through a stable receiver and a non-lazy, non-late fix field; an overridable getter or mutable access path is not stable. Null checks in the opposite branch and is Type refinements follow the same path-sensitive rule. Refinement does not cross a nested function/lambda/task boundary.

value as? Type is a safe runtime cast. Its operand must be a reference (nullable or non-null); its target must be a non-null JVM-reifiable reference type: a non-generic class/interface or an array with a reifiable reference component. Primitive-array types are also reifiable reference targets. Type parameters and parameterized targets such as List<Text> are not reifiable in this syntax. Evaluate the operand once; a compatible instance is returned unchanged, and null or an incompatible instance yields null. The result type is Type?. Primitive, nullable, and no-result targets are errors; exceptions from evaluating the operand propagate. as? is one contiguous operator at the same non-associative precedence as as and is; it never performs a numeric conversion.

Postfix value!! evaluates a nullable reference once and returns that same reference with its non-null type, or raises NullPointerException when it is null. The result may then unbox under ordinary conversion rules; for example an Int? assertion has type Int, not int. Primitive, already non-null, and no-result operands are errors. Prefer a check or fallback when absence is expected; an assertion does not refine later reads of a mutable binding.

Kalm
fix input: Any? = "Mira";
fix name: Text? = input as? Text;
fix length: int = name != null ? name.length() : 0;
fix requiredName: Text = name!!;

Local fix/var types may be inferred when initialized. Parameters and fields require explicit types. Public value-producing functions require explicit results; omitted results on block bodies are explicit no-result intent, including for public functions. Non-public expression-bodied functions may infer their result. Task<T> is a public Kalm runtime interface that extends java.util.concurrent.CompletionStage<T>. Generated Java methods keep Task<T> as their return type, and Java callers can use or assign it as a CompletionStage<T>. await accepts either Task<T> or any Java CompletionStage<T>. An empty collection or null requires a target type, except for the standalone shell null-result case (§11). Kalm lambdas require a target type from context and may target Kalm or Java single-abstract-method contracts (SAMs).

4. Bindings, expressions, and functions

fix declares an immutable binding; var declares a mutable one. In type or member modifier position, fix means that a class cannot be subclassed or a member cannot be overridden. Fields use the same binding words. Definite assignment is checked at compile time.

Multiple bindings

Independent comma declarations repeat the name, optional local type, and initializer after a single binding word:

Kalm
var a = 5, b: int = 7, c: Int = 8;
fix low: int = 1, high = low + 9;
var [first, second, third] = [5, 7, 8];
fix [left: Int, right: Int] = [5, 7];

Each independent declarator is equivalent to a separate declaration in source order. Its initializer is evaluated once, left to right, and subsequent initializers can refer to preceding bindings. Forward references and duplicate names in the same scope are errors. Every local declarator requires an initializer. Fields may use comma declarations, but each field must state its own type and follow §6 initialization rules; omitted types do not inherit from another declarator. Modifiers and declaration annotations apply to every field in the group. Destructuring is limited to local and script bindings; it is not available for fields, parameters, for bindings, match patterns, or assignment targets.

A bracket binding has a nonempty, flat list of distinct names with optional individual types. Its right side must be a list literal, a non-null List<T>, a reference array, or a primitive array; arbitrary Iterable values are not accepted. For a literal, the compiler checks arity and infers each binding directly from its corresponding expression. Thus var [count, label] = [5, "five"] infers int and Text without requiring a tuple type or a common list element type. This contextual literal form evaluates each element expression once in source order into temporary values; outside a bracket binding, the same brackets still construct a homogeneous list with a common element type (§3). For a list/array expression, evaluate the receiver once, check its length, and read elements once in index order; each inferred binding uses the element type (a primitive for primitive arrays, a reference for generic collections).

Exactly as many source elements as names are required. A literal arity/type mismatch is a compile error; a runtime length mismatch raises IllegalArgumentException before element extraction or binding initialization. Extraction, assignment conversions, and Java-boundary null checks must all complete before any destination binding is initialized. If one fails, none of the new names becomes initialized. Effects of evaluating the receiver/elements are not rolled back. New names are unavailable within the right side; existing outer names still resolve there. No rest elements, nested patterns, skipped slots, or bracket reassignment are supported. A null source is a type error in Kalm and a NullPointerException if received unchecked from Java; concurrent source mutation follows the source collection's ordinary Java behavior and does not guarantee an atomic snapshot.

Kalm
# Compile errors:
# var [a, b] = [1];              # Too few elements.
# var [a: Text, b: int] = [1, 2]; # Incompatible first element.
# var [a, a] = [1, 2];           # Duplicate name.
# [a, b] = [3, 4];               # Destructuring assignment is not supported.
Kalm
fix startValue: Int = 3;
var score = startValue + 4;
score += 1;

fun square(value: Int) -> Int = value * value;
fun greet(name: Text) -> Text {
    return @"Hey, $name!";
}

fun name(...) declares a named function or method; fun item => expression introduces a context-typed lambda expression. Named functions are allowed in declaration positions and use fun name(...); lambda expressions appear in expression positions and use fun parameters => ... or fun parameters { ... }. Function parameters are immutable. Expression-bodied functions use = expression. Kalm user functions cannot be manually overloaded: one source function name per declaring scope is permitted. Java/library overloads and compiler-generated default-argument overloads are specified separately. Calls are positional; named arguments and user-declared varargs are not part of 1.2.0.

A named function may also be declared in an ordinary executable block. Its name is visible from its declaration to the end of that lexical block, including its own body for recursion; it is not hoisted and cannot refer to later local declarations. Captures follow the effectively-final rule for lambdas. Local functions have no visibility, inheritance, or override modifiers and are not instance members. Public member/top-level declarations retain the signature rules below; local expression bodies may infer results. Script-level functions remain script declarations under §11.

A nonempty comma-separated list inside parentheses, brackets, braces for a map/annotation array, or generic angle brackets may end with one trailing comma. This applies to parameters (including defaults and parenthesized lambda parameters), call arguments, data components, generic parameters/arguments, bracket bindings, list/map literals, and annotation arguments/arrays. A trailing comma creates no extra element and does not change arity or evaluation order. Empty lists stay empty (f() is valid, f(,) is not); doubled commas and missing elements are errors. Unparenthesized comma declarations, bare lambda parameters, inheritance lists, and resource lists do not gain trailing commas.

Kalm
fun add(left: int, right: int,) -> int = left + right;
fix values: List<Int,> = [1, 2,];
fix total = add(values[0], values[1],);

Function results and completion

Result contract return value Bare return Falling through the body
Omitted arrow on a block body, explicit void, or compatible Unit Only literal return null is accepted, as no-result completion No-result completion No-result completion
Explicit nullable reference T? A value assignable to T?, including null Error Error on a reachable completing path
Explicit non-null T or primitive A value assignable to T Error Error on a reachable completing path

return null in a no-result body is normalized to Java return;; it does not create a nullable result or a Java Void value. Returning a variable or computation that happens to evaluate to null is still an error in that body. For both nullable and non-null value results, only reachable normal completion needs a result; paths that always raise or never terminate need no return. The compiler must not insert an implicit null result for a nullable body. No implicit return of the last expression occurs in a block body. An expression body must have a compatible result; a no-result expression body may evaluate a no-result call but cannot discard an ordinary value.

These rules also govern property getters, target-typed block lambdas, and the body result of async fun/task (§5). Constructors, setters, test hooks, and no-result SAM bodies use the void completion rules. A return inside a nested function/lambda/task belongs to that nested body, not the outer function. defer forbids control transfer (§5).

Kalm
pub fun notify():
    sayLine("Ready") # No explicit result and no return are required.

pub fun skip():
    return null     # Valid no-result completion.

pub fun notifyExplicit() -> void {
    sayLine("Ready");
    return;
}

fun compatible() -> Unit {} # Still valid; prefer void in new result annotations.

pub fun nickname(known: Bool) -> Text?:
    if known:
        return "Mira"
    return null     # Nullable results still require an explicit result on each completing path.

# Invalid: pub fun broken() -> Text { return; }
# Invalid: pub fun broken() -> int { return "one"; }
# Invalid: pub fun broken() { return 1; }
# Invalid: pub fun broken() -> Text? { return; }
# Invalid: pub fun broken() -> Text? {}
# Invalid: fix noValue = notifyExplicit();

Default arguments

A concrete named function, method, or constructor may declare trailing parameter defaults using = expression. The expression must be assignable to that parameter's type and may refer to earlier parameters, accessible lexical names, and self in an instance method; constructor defaults cannot access self before construction. It must not refer to its own or a later parameter. Default expressions follow ordinary checked-exception rules and cannot contain await; asynchronous body execution begins after defaults are evaluated.

Kalm
pub fun loud(name: Text? = "hello", suffix: Text = "!") -> Text:
    return (name ?? "guest").upper() + suffix

loud()             # "HELLO!"
loud("Mira")       # "MIRA!"
loud(null)         # "GUEST!": explicit null does not trigger a default.
loud("Mira", "?") # "MIRA?"

All required parameters must precede defaulted parameters. A call may omit only a suffix of the parameter list. Evaluate the receiver and supplied arguments once, left to right, then evaluate omitted defaults once in parameter order for that invocation. Defaults are not precomputed at declaration time, nor evaluated for explicitly supplied arguments. Errors in arguments/defaults prevent invocation; preceding effects remain. There is no undefined value.

An override inherits defaults and cannot redeclare or change them. Defaults belong to the originally declaring method and are selected through that declaration; the resulting full-argument invocation uses normal virtual dispatch. Generated omission overloads for instance methods are final forwarding methods, preventing an override from changing omission behavior. Abstract (needs/contract) signatures and external fun cannot introduce defaults. A Java method without Kalm-declared defaults has no default arguments. Data components, accessors, and lambda parameters cannot declare defaults in this edition.

Java receives the full declared signature plus an overload for each omitted trailing suffix. Constructors receive forwarding constructor overloads; omission of all defaulted constructor arguments supplies a no-argument overload. These generated methods/constructors have the original visibility and compatible checked-exception declarations. Reject an erased-signature collision with a declared or inherited method, a generated helper/launcher, or another generated overload, except for inheriting the same default's existing forwarding method. This generation does not permit user-defined Kalm overloads or change Java's ordinary overload selection rules.

Operands evaluate left to right according to the expression tree and precedence below; and/&& and or/|| short-circuit. Boolean operators and conditions accept boolean or a non-null Bool, unboxing the latter. Nullable Bool? must first be refined or coalesced. Equality uses primitive value equality, text value equality, and Java equals for other references. Two wrappers use their Java value equality, never reference identity; mixed primitive/wrapper numeric comparison unboxes and promotes, with nullable wrappers prohibited from that numeric operation. Null-to-reference equality is a null check; two nullable references compare equal if both are null, unequal if exactly one is null, and otherwise compare their values. Two different numeric wrapper classes follow Java equals (Int(1) is not value-equal to Long(1)); comparisons needing numeric promotion use primitive operands or conversions. Relational comparisons support numbers, char/Char, and Text in UTF-16 order. + adds numbers or joins two Text values. Operators &&, ||, and ! are accepted as aliases for and, or, and not. Assignment targets include mutable Kalm bindings/fields, writable properties, assignable Java fields, and ordinary array/list/map index locations. A fix reference cannot be reassigned but its mutable contents may be updated. Ordinary array/list indexing requires an int index and returns the component/element type; Text indexing requires an int and returns char. They use Java bounds behavior. Map indexing requires a compatible non-null key and returns the nullable value type (§3). Text indexes, safe indexes, safe member accesses, and read-only properties are not writable targets.

Evaluate an assignment's receiver and index once, left to right, before the right-hand side. Simple = writes without reading the previous value and yields the assigned value after assignment conversion, not a previous map entry. Compound assignment reads the location once before evaluating its right operand, applies the corresponding operator and ordinary assignment conversion, and writes once. It does not introduce implicit runtime narrowing. Numeric compound writes require a non-null readable element; a map lookup remains nullable even for non-null map values and therefore cannot directly use += for numeric addition. Use an explicit fallback or ??= instead. Coalescing assignment on a missing map entry may install a value compatible with the declared map value type; the absence read is not a stored null. A read/conversion failure prevents the write; earlier effects are not rolled back.

Safe navigation requires a nullable reference receiver, evaluates it once, and skips call arguments when it is null. A value member/call result becomes nullable, boxing primitives and flattening existing nullability. A no-result safe call remains no-result: it executes or skips the call and cannot be stored as a nullable Void/Unit value.

Precedence high to low Operators Associativity
Postfix call, member ., safe member ?., safe index ?[...], index [], assertion !! left
Unary not, !, unary +, unary -, await right
Multiplicative *, /, % left
Additive +, - left
Relational/type <, <=, >, >=, is, as, as? non-associative
Equality ==, != non-associative
Logical conjunction and, && left, short-circuit
Logical disjunction or, || left, short-circuit
Coalescing ?? right
Conditional ? : right, selected branch only
Assignment =, +=, -=, *=, /=, %=, ??= right

A method call to Java uses Java overload resolution. If overload resolution is ambiguous, compilation fails and the diagnostic identifies the candidate signatures. An explicit type annotation or cast can resolve the ambiguity. Kalm does not support operator overloading.

Kalm
fun active(age: int, paused: boolean) -> boolean = age >= 18 && !paused;
fun activeWords(age: int, paused: boolean) -> boolean = age >= 18 and not paused;
# a or b and c means a or (b and c), with either spelling.
fun and() -> boolean = true;
fun test() { sayLine("ordinary function"); }
fix ready = and();
test();;;
Kalm
var names: List<Text>? = findNames();
fix firstName = names?[0] ?? "Guest";

var title: Text? = findTitle();
title ??= "Untitled";

Conditional expressions and execution

condition ? whenTrue : whenFalse is a conditional expression. The condition must be boolean or non-null Bool; nullable conditions require a check or fallback. Evaluate it once, then evaluate only the selected branch once. Both branches are type-checked, even when a condition is constant. The operator associates to the right, so a ? x : b ? y : z means a ? x : (b ? y : z). Coalescing binds more tightly and assignment less tightly: flag ?? false ? x : y tests (flag ?? false), and result = ready ? x : y assigns the selected value.

In value context, both branches must supply a compatible common result using the same rules as value matches (§5). A branch may be an ordinary expression or a braced block. Every normally completing path through a value block must execute yield expression. yield supplies the result to the nearest enclosing value-producing match arm or conditional block branch and runs that branch's cleanup first. It cannot cross a function/lambda/task boundary. return instead exits the enclosing function/lambda/task; a throwing or otherwise non-completing path needs no yield. No-result expressions cannot be used as values or mixed into a value-producing conditional.

When a conditional is the whole expression of an expression statement (optionally parenthesized), it is used for execution: discard the selected expression branch's result, or execute the selected block with ordinary statement completion. Its branches may mix value-returning and no-result calls; their discarded types need no common value type. The conditional itself produces no stored result in this context, including in the script host. Nested conditionals used as the whole branch inherit execution context. yield is invalid in execution-only branches; return, stop, and next retain their ordinary enclosing-body/loop meaning. Both branches are required, although an empty {} is a valid execution branch.

Conditional branch blocks require braces, even inside a colon suite. A brace directly starting a branch always introduces a block; a map value must be parenthesized, for example ready ? ({"state": 1}) : ({"state": 0}). Braced branches do not make arbitrary blocks into expressions. After a conditional block, the separating : belongs to ?:, not to a colon suite. Nested expression branches consume their own paired ?/: before the outer separator.

Kalm
fun activeLabel(isActive: boolean) -> Text {
    return isActive ? "Active" : "Inactive";
}

fun report(isActive: boolean) -> void {
    isActive ? sayLine("Active") : sayLine("Inactive");

    # Prefer multiline formatting for block branches.
    isActive ? {
        sayLine("Starting");
        sayLine("Running");
    } : {
        sayLine("Waiting");
    };
}

fun measuredLabel(isActive: boolean) -> Text:
    return isActive ? {
        sayLine("Preparing active label");
        yield "Active";
    } : {
        yield "Inactive";
    };

# Invalid: fix missing = true ? 1;
# Invalid: fix noValue = true ? sayLine("yes") : sayLine("no");
# Invalid: fix incomplete = true ? { sayLine("yes"); } : { yield "no"; };

5. Flow, lambdas, and errors

if, elif, else if, and else branch on boolean or non-null Bool conditions; while repeats as long as its condition is true. elif and the two-token spelling else if are identical, associate with the nearest unmatched if, and may be mixed within one chain. Their headers and bodies support both brace and colon styles. for item in items accepts Iterable<T> or an array and creates an immutable loop variable. stop exits the innermost loop; next advances to its next iteration.

Kalm
if (score > 0) {
    sayLine("Ready.");
} elif (score == 0) {
    sayLine("Waiting for input.");
} else {
    sayLine("Let's reset.");
}

while (score < 10) {
    score += 1;
}

for (name in names) {
    sayLine(name);
}

Java SAM lambdas use a lightweight Kalm form. Their target and parameter types come from the selected method signature, and captures follow Java’s effectively-final rule.

Kalm
fix loud: java.util.function.Function<Text, Text> = fun name => name.toUpperCase();
fix loudNames = names.stream().map(fun name => name.toUpperCase()).toList();

A block lambda uses braces (fun item { ... }) or a colon with parenthesized parameters (fun (item): ...); its target's result/nullability determines completion under §4. Every value-returning lambda, including a nullable target, uses an explicit compatible return on every normally completing path. Only no-result targets allow bare return or fallthrough. The compiler rejects an ambiguous SAM overload unless a target type or cast resolves it. Named functions use fun name(...); lambdas use fun parameters => expression or a braced lambda body.

Kalm uses JVM exceptions. try, handle, finally, and raise map directly to Java. A handle parameter must have a Java exception subtype. A try block must have at least one handle or a finally clause. Checked Java exceptions must be handled at ordinary Kalm call sites, except where a Java overriding/SAM signature permits propagation; ordinary Kalm functions do not declare throws clauses. When an override fun, accessor, forward, or external fun corresponds to a Java method with checked exceptions, generated Java preserves the compatible Java throws clause. raise may rethrow unchecked exceptions freely; a checked exception may be raised only within a try whose handle clause catches it, or an overriding body/SAM lambda whose Java target declares that checked exception. A checked exception cannot escape an ordinary Kalm function. Other unhandled exceptions behave as they do in Java.

Kalm
try {
    sayLine(Files.readString(Path.of("greeting.txt")));
} handle (error: java.io.IOException) {
    sayLine(error.getMessage());
} finally {
    sayLine("done");
}

Matching and checks

choice declares a finite set of named variants and compiles to a Java enum; variants carry no payload or type parameters in 1.2.0. match evaluates its subject once and tests case arms in source order. The first matching arm runs once; there is no fallthrough. Patterns are enum/choice constants, non-null closed-hierarchy types (matching their instances/subtypes), compatible literals, null for nullable subjects, or _ as the explicit catch-all. Matching uses the equality rules in §4 for value patterns and a runtime type check for type patterns. A null subject matches only null or _; before comparing a non-null value pattern, the subject is treated as non-null for that comparison. There are no guards, pattern bindings, payload patterns, or destructuring patterns in this edition. A _ arm must be last; a provably unreachable arm, including a duplicate constant, is a compile error. An unrelated type/value pattern is a type error.

A match used as a value must be exhaustive over the subject's static domain. Covering all choice/Java enum variants establishes exhaustiveness. For an abstract closed root, cover every permitted child, directly by its type pattern or recursively by exhaustive coverage of that child's domain. A type pattern covering a non-sealed permitted child covers all of that child's descendants. A concrete closed root can also have direct instances, which require coverage by a root type pattern or _; enumerating children alone does not cover those instances. boolean and Bool need both true and false; a nullable subject also needs null coverage. An open type, numeric type, or text needs _ unless earlier patterns establish full finite coverage. A standalone statement match may be partial; if no arm matches, it completes without effects. In statement context an expression arm is evaluated and discarded, and a block arm follows ordinary statement rules. In value context expression arms supply a compatible common result type; every normally completing block-arm path must execute yield expression. yield exits the nearest value-producing match arm or conditional block branch, runs its cleanup, and supplies its result; return exits the enclosing function/lambda/task. yield is invalid in statement matches, outside a value arm or value conditional block branch, or across a nested function/lambda/task boundary. A throwing/non-completing path does not need to yield. For null plus non-null reference arms the common type is nullable; primitive arms box when null requires a nullable common result. A context type may determine conversions. A value match cannot produce void/Unit. These common-result rules also apply to value conditionals: an expected result type must accept every completing branch; without one, identical types are retained, differing numeric primitive types use binary numeric promotion, and reference results use their Java least upper bound with Kalm nullability preserved. Mixed primitive/reference results box before finding a reference common type. No implicit runtime narrowing or ordinary Unit value is created.

Kalm
choice Status {
    Ready;
    Failed;
}

fix message = match status {
    case Status.Ready => "Ready to continue";
    case Status.Failed => "Please retry";
};
Kalm
fun caption(status: Status) -> Text:
    return match status:
        case Status.Ready => "Ready"
        case Status.Failed => {
            sayLine("Preparing retry");
            yield "Retry";
        }

match status {
    case Status.Failed => sayLine("Failure recorded");
} # A partial statement match is valid.
# Invalid value: fix caption = match status { case Status.Ready => "Ready"; };

expect condition raises AssertionError when false. require condition validates a function precondition and raises IllegalArgumentException; ensure condition validates a postcondition and raises IllegalStateException. Optional messages follow a comma. These checks are always active and are not removed by build settings.

Resource and scope management

with name = expression { ... } requires an AutoCloseable result and closes it when the block exits, including exceptional exits. Multiple resources close in reverse declaration order. defer { ... } registers a cleanup block for the end of the current function or block; deferred blocks run in reverse registration order on normal return or exception. Control transfer (return, yield, stop, or next) is not allowed inside a deferred block. Here “current block” means the innermost lexical block containing the registration; a registration in a function's outer body therefore runs at function completion. Resource closing follows Java try-with-resources suppression rules. All registered defers still run if one fails: an existing body exception remains primary with cleanup failures suppressed; after successful body completion, the first cleanup failure becomes primary and later failures are suppressed. Cleanup completes before a return/yield/fallthrough result is delivered. A failing cleanup overrides successful completion, but does not restore earlier mutations.

The same cleanup ordering applies to a conditional branch's yield or enclosing control transfer. A defer registered inside a braced branch belongs to that branch block and runs before its selected result is delivered; the unselected branch registers no cleanup.

Kalm
with reader = Files.newBufferedReader(path) {
    return reader.readLine();
}

defer {
    transaction.rollbackIfOpen();
}

Tasks and synchronization

async fun runs a function body on the Kalm virtual-thread executor and returns Task<T>, whose public Java interface extends java.util.concurrent.CompletionStage<T>. Its declared result type T is the value produced by the body. For a primitive body result, its task type boxes the result (async fun count() -> int is exposed as Task<Int>). For void or compatible Unit it returns Task<Unit> (Java Task<Void>), and for nullable results the task's result argument is nullable. The task handle itself is non-null. Omitted block result arrows follow §4's no-result rule. Argument/default evaluation occurs synchronously before the body is scheduled; body exceptions fail the returned task instead of the call itself. await task waits for completion and returns its value; it is permitted only inside an async fun or a task { ... } block. Awaiting rethrows runtime exceptions and errors, and wraps checked failures in TaskFailureException with the original cause. Interruption restores the interrupt flag and raises TaskInterruptedException.

task { ... } starts an asynchronous block and returns Task<T>. An expected Task<T> supplies its body-result contract. Without an expected type, compatible value-return expressions infer a result (boxing primitive results). Once any ordinary value is returned, every normally completing path must explicitly return a compatible value; literal null may make the result nullable, but bare return and reachable fallthrough are errors. A body containing only no-result completion forms infers Task<Unit>; literal return null with no ordinary value returns is the no-result form. Inference fails for incompatible value returns. An expected nullable task result still requires explicit values, including explicit null, on every normal completion path under §4. A guard lock { ... } block uses the Java monitor for lock; await is prohibited inside a guard so a task never suspends while holding a monitor. Each async fun or task executes on a Java virtual thread.

Kalm
async fun loadProfile(id: Text) -> Profile {
    return await profileClient.fetch(id);
}

fix refresh = task {
    return await loadProfile("42");
};

guard cache {
    cache.put("profile", refresh);
}

The public kalm.runtime.Task<T> interface extends CompletionStage<T> and adds cancel() and isCancelled(). Cancelling a task requests cancellation and may interrupt its virtual thread. Java methods that return Task<T> remain directly usable as CompletionStage<T>; await also accepts ordinary Java completion stages.

6. Classes, contracts, and visibility

class declares a JVM class. contract declares a JVM interface. init declares a constructor. If none is present, the compiler follows the default-constructor rule below. self refers to the current instance. Calling ClassName(arguments) constructs Kalm and Java classes. A Kalm class may declare at most one constructor; named factory functions can provide additional construction forms. Fields initialize in declaration order. A fix field is assigned exactly once in its declaration or constructor. Every non-null reference field must be initialized or definitely assigned by every constructor; nullable references default to null, and uninitialized primitive var fields use their Java zero value. A no-argument constructor is generated only when all required fields can be initialized without parameters; otherwise a missing constructor is a compile error. Wrapper fields are reference fields and do not receive primitive zero initialization. A constructor with defaults remains the single source constructor; its generated omission overloads do not violate that source restriction (§4).

An ordinary class constructor may explicitly call its direct superclass constructor with super(arguments); as its first nonempty statement, in either block style. Empty separators may precede it; declarations, effects, nested blocks, and a second constructor invocation may not. Resolve the call using normal accessibility, argument conversion, Java overload, and Kalm default-argument rules. Before this invocation, arguments may use constructor parameters and accessible non-instance names, but not self, instance members, or super.method. Without an explicit invocation, the compiler inserts super(); the implicit direct superclass is java.lang.Object. If no accessible applicable no-argument constructor exists, compilation fails. Generated no-argument constructors follow the same rule.

After successful superclass construction, evaluate the subclass's eager field initializers in declaration order, then execute the rest of its constructor body. Lazy initializers retain their on-first-access behavior. If superclass construction fails, subclass initializers and the remaining body do not run. super(...) is a constructor statement, not an expression; it cannot appear in functions, lambdas, tasks, data records, choices, or singletons. Delegation to another constructor of the same class and qualified interface-super calls are not supported in this edition.

super.method(arguments) directly invokes an accessible concrete instance implementation found through the direct superclass, bypassing overrides on the current object for that invocation. Ordinary overload, default-argument, conversion, nullability, and checked-exception rules apply. It is allowed in instance methods/accessors, after parent construction in a constructor body, and in lexically nested lambdas capturing that instance; it is not available in top-level/augment/static contexts, local named functions, or task bodies. An abstract/private/inaccessible or static target is invalid. Bare super, parent field access, and storing/passing super are invalid. In the complete super(...) and super.name(...) forms, parent-call parsing takes precedence over a contextual identifier. When arguments are omitted on a parent method call, evaluate defaults from the selected superclass declaration and directly invoke its full implementation; do not use a generated virtual forwarding invocation that could reenter an override on the current object.

Kalm
class NamedService {
    fix name: Text;
    init(name: Text) { self.name = name; }
    fun label() -> Text = name;
}

class ActiveService inherits NamedService {
    init(name: Text) {
        super(name);
    }
    override fun label() -> Text = super.label() + " (active)";
}
Kalm
pub class Person {
    fix name: Text;
    var mood: Text;

    init(name: Text) {
        self.name = name;
        self.mood = "easy";
    }

    fun hello() -> Text = @"Hi, I'm $name!";
}

contract Greeter {
    fun greet(name: Text) -> Text;
}

class FriendlyGreeter implements Greeter {
    override fun greet(name: Text) -> Text = @"Hey, $name. Glad you're here.";
}

Kalm classes compile to Java classes and contracts compile to Java interfaces. A class may inherits one accessible non-final Kalm class (only an explicitly permitted child may inherit a closed class), or any accessible non-final Java class. It may implements one or more contracts or Java interfaces.

A base class is abstract and inheritable. Only a base class may declare needs fun members without bodies; concrete subclasses must implement them. A needs fun declaration is an abstract requirement and is implicitly overridable until implemented. A concrete implementation must use override fun; its eligible instance methods remain overridable unless marked fix. Contract signatures are also abstract requirements: implementing a Kalm contract or Java interface requires override fun, and the resulting method remains overridable unless marked fix.

A closed class must declare every allowed direct child as a nested declaration; the compiler emits a Java sealed hierarchy with an explicit permits list. Nested Kalm classes are static nested Java types; nested classes do not capture an enclosing instance. In a closed hierarchy, every direct child must explicitly state fix, extendable, closed, or base; an unmarked child is a compile error with a modifier suggestion. A fix child is Java final; an extendable child is Java non-sealed; and a closed child is Java sealed and declares its own permits list. A base child is abstract and is also emitted as non-sealed unless combined with closed.

Ordinary Kalm classes and eligible instance methods are open to inheritance or overriding by default, as in Java. fix class and fix fun map to Java final; extendable explicitly leaves a class or eligible method open; base maps to abstract; and closed maps to Java sealed. base closed is allowed. fix cannot be combined with base, closed, or extendable; closed cannot be combined with extendable. An override may be marked fix to close that method again. override fun must match the inherited signature after generic substitution.

Private methods do not override, and methods in a final class cannot be overridden by a subclass. Constructors and top-level facade functions do not participate in overriding. Marking an ineligible method extendable is an error; fix is a class/method modifier, not a return type or a change to field mutability. Data records and singletons remain final; choices retain Java enum inheritance restrictions. closed restricts permitted subclasses rather than making all inherited methods final. Methods generated by forward are overridable unless their owning class is final; default-argument forwarding overloads have the special final rule in §4.

Kalm
class Parent {
    fun label() -> Text = "parent";
    fix fun stable() -> Text = "stable";
}
class Child inherits Parent {
    override fun label() -> Text = "child";
    # override fun stable() -> Text = "changed"; # Error: final method.
}
fix class Leaf {}
# class Invalid inherits Leaf {} # Error: final class.

closed class State {
    fix class Ready inherits State {}
    extendable class Waiting inherits State {}
    base class Failed inherits State {}
}

data declares an immutable Java record with components, accessors, and Java record value equality. Each record component is available as a read-only Kalm property and its Java record accessor retains the component name. choice declares a finite set of named variants and compiles to a Java enum; variants carry no payload or type parameters in 1.2.0. singleton declares one globally accessible instance, generated as a final Java class with a private constructor and INSTANCE field. alias Name = Type creates a compile-time type alias and no new JVM type. given adds bounds to type parameters, for example fun sort<T>(items: List<T>) -> List<T> given T: Comparable<T>. The clause is required when a type parameter has a bound.

generate Display overrides a data record’s generated toString() with a stable TypeName[field=value, ...] form, using component declaration order and Kalm text formatting for each value. Java record equality and hashing remain those provided by the record model; they are not separately generated. augment Type { ... } declares Kalm-only extension functions. Inside an augment function, self is the receiver value; calls are rewritten to generated static helpers whose first parameter is that receiver, and do not add methods to the Java class. bridge augment also emits a public Java helper facade for those functions. forward Contract to field generates contract methods that delegate to that field; the field must implement the contract. Generated forwarding methods preserve the Java contract’s checked-exception declarations.

Kalm
use java.io.Closeable;
use java.io.InputStream;

pub data User(name: Text, id: Long) generate Display;

alias UserId = Long;

augment Text {
    fun initials() -> Text = self.substring(0, 1);
}

class FileStore implements Closeable {
    fix stream: InputStream;

    init(stream: InputStream) {
        self.stream = stream;
    }

    forward Closeable to stream;
}

read and write declare property accessors. Kalm member access rewrites to the accessor; Java receives conventional getX/setX methods. lazy fix declares a read-only field evaluated once on first access and safely publishes the cached value. The initializer runs at most once, including when it throws; subsequent reads rethrow the same failure. late var is a non-null reference field assigned after construction; reads from both Kalm and Java use a runtime guard that throws IllegalStateException until assignment. Setters reject null, and subsequent assignments are allowed. The compiler does not verify that a late field is assigned before use. constant declares a public static final Java compile-time constant restricted to primitive or Text values; the compiler emits a Java constant variable where Java permits it. A constant initializer must be a Java-compatible compile-time expression yielding a primitive or Text value; boxed wrappers and nullable types cannot be constant types. Constants are implicitly pub and top-level in 1.2.0. legacy marks a declaration deprecated in Kalm diagnostics and emits Java @Deprecated.

Kalm
use java.time.ZoneId;

class Profile {
    var first: Text;
    var last: Text;

    init(firstName: Text, lastName: Text) {
        first = firstName;
        last = lastName;
    }

    read fullName: Text = @"$first $last";
    write displayName(value: Text) {
        fix pieces = value.split(" ");
        first = pieces[0];
        last = pieces[1];
    }

    lazy fix zone: ZoneId = ZoneId.systemDefault();
}

constant DEFAULT_LIMIT: int = 100;

Visibility words map to Java access as closely as Java permits:

Kalm word Meaning
pub Public to Java and other modules
internal Current Kalm module; enforced by Kalm compilation. Java callers may see generated public members because JVM bytecode has no Kalm-module visibility.
private Source-file private at top level and class-private for members. Java has no private top-level declarations, so the compiler enforces file privacy and emits package-private Java declarations; same-package Java source can therefore access those generated declarations.
protected Java protected visibility for class members
omitted Top-level declarations are internal; fields are private; methods and constructors are pub

Kalm classes do not declare static members. Java static members remain directly accessible. In the data/alias example above, Long intentionally uses wrapper storage. Use long for a primitive component or alias.

7. Packages and Java interoperability

space gives a Java-compatible package name. use imports a Java or Kalm type; wildcard uses are supported. Name resolution checks local declarations, same package, explicit uses, wildcard uses, then java.lang. Ambiguity is an error and can be resolved by a qualified name.

Kalm can use public Java classes, constructors, fields, methods, enums, arrays, and generic types found on the compile classpath or readable module path. Kalm primitive names map to matching Java primitives. Calls follow Java visibility, overload resolution, primitive widening, boxing/unboxing, and varargs rules. Narrowing needs an explicit checked conversion. Java annotations describing nullability are honored; unannotated Java reference types are platform types and produce a warning on assignment to a non-null Kalm type, with the runtime boundary check defined in §3. Lowercase primitives keep primitive JVM descriptors; wrappers keep reference descriptors even when non-null. A change from 1.1.0 Int to 1.2.0 Int therefore changes a Java signature; preserve its old descriptor by migrating to int (§12). Java wrapper constructors, static members, and generic references are usable through qualified names and Kalm aliases. Java annotations require primitive element types or the other Java-supported annotation types, not boxed numeric types.

Java and Kalm declarations in the same module may call one another. Java code can call public top-level Kalm functions through the Java facade for their source file (for example, GreetingApiKalm.greeting("Tim")); Kalm code can call accessible Java declarations in the same module. Java and Kalm declarations are resolved together, while compiler-generated analysis artifacts are not visible to source code.

Kalm
space studio.greetings;
use java.nio.file.Files;
use java.nio.file.Path;

pub fun readGreeting() -> Text {
    try {
        return Files.readString(Path.of("greeting.txt"));
    } handle (error: java.io.IOException) {
        return "Could not read greeting";
    }
}

external fun declares a Kalm-named wrapper around a public Java static method. Its right-hand qualified name is resolved against the project's Java model, and its signature must be invocation-compatible with the target. Java libraries themselves remain directly usable without wrappers.

Kalm
external fun parseCount(value: Text) -> int = java.lang.Integer.parseInt;

bridge augment emits a Java helper facade for Kalm extension functions. An ordinary augment is usable only from Kalm; a bridged one also exposes static methods such as TextExtensions.initials(value) for Java callers.

annotation declares a Java annotation type. target lists where it may appear (type, function, field, property, or parameter). Java has no ElementType.PROPERTY: a Kalm property target maps to ElementType.METHOD and is emitted on the generated getter; use field to annotate the backing field. Other targets map to the matching Java ElementType. Annotation members use Java's supported annotation value types, and generated annotations default to RetentionPolicy.CLASS; Java meta-annotations such as @Retention, @Target, and @Repeatable may configure them. @Name or @Name(arguments) applies an annotation to a declaration. Parameters use @Name parameter: Type; type uses use parameter: @Name Type, including nested generic and array types. Type parameters and record components accept annotations. The target shorthand also supports constructor, localVariable, annotationType, typeUse, typeParameter, and recordComponent; conflicting shorthand and explicit @Target are rejected. Arguments must be Java annotation constant values, enum constants, class literals, arrays, or nested annotations; positional syntax is allowed only for a single member named value. legacy emits @Deprecated and a Kalm compiler warning at use sites.

KalmDoc documentation language

KalmDoc is the documentation-comment language for Kalm and Kalm Script. It is designed for future documentation tools and for lossless semantic conversion to Javadoc wherever a declaration has a generated Java API. It adds no executable language construct. Each consecutive line beginning with ### contributes its text after the marker and one optional space. An empty documentation line is written ###; ordinary blank lines end the comment group. Documentation inside an ordinary # or ## ... ## comment is not KalmDoc.

One group attaches to the next declaration at the same structural level. Annotations and modifiers between the group and the declaration are part of that declaration and do not detach it. An ordinary statement, unrelated comment, blank line, or scope boundary ends attachment and makes the group orphaned. Attachment is permitted on types, named functions, constructors, fields, constants, aliases, properties/accessors, enum variants, annotation types/elements, and tests; comments on locals and script-only definitions may be shown in editor/script documentation without a public Java target. For a comma field declaration, one attached group documents every field; individual documentation uses separate declarations. The group cannot attach to an annotation use instead of its annotated declaration.

Descriptions use the standard Javadoc text/HTML and inline-tag syntax; this edition does not define Markdown as a second doc-comment dialect. The first descriptive sentence is the summary. A block tag begins with @ at the start of a documentation line, optionally after whitespace, and continues until the next block tag or the end of the group. Description and tag text must be preserved; conversion must not silently drop tags or substitute plain comments.

Tag Contract and Javadoc conversion
@param name description Documents an existing value parameter; emits Javadoc @param using the generated parameter name.
@param <T> description Documents an existing generic parameter; emits @param <T>.
@return description Documents a value result, including nullable and asynchronous body results; emits Javadoc @return. Invalid on constructors or synchronous void/Unit results.
@throws Type description Documents an exception without permitting it to escape; resolves and emits its qualified Java exception type.
@see symbol Resolves a Kalm/Java symbol and emits the corresponding Javadoc reference; quoted text and HTML links retain standard Javadoc meaning.
@since version Emits the version text as Javadoc @since.
@deprecated description Emits Javadoc @deprecated; marks documentation only. Use legacy or Java @Deprecated for executable deprecation diagnostics.
{@link symbol label} Resolves to a generated Java type/member reference; emits {@link ...} with the optional label.
{@code text} / {@literal text} Emits the same tag; content is literal and not symbol-translated.
{@inheritDoc} Uses documentation inherited from the corresponding overridden Java member; invalid without an inherited target.

Symbol references use Type, Type#member, Type#method(Type, ...), or #member for the current owner. Top-level functions are referenced using their source facade, such as GreetingApiKalm#loud(Text). Kalm type arguments and nullability are resolved before producing a Javadoc signature: Text becomes java.lang.String, Int becomes java.lang.Integer, int stays int, IntArray becomes int[], and Array<Text> becomes java.lang.String[]. Overloaded references must resolve uniquely or include parameter types. References to aliases resolve to the aliased Java type, while alias documentation remains available in Kalm documentation. Unbridged extensions, tests, and script-only definitions have no public Java API target; a Javadoc reference to one reports an unresolved-target warning and preserves the visible label as escaped text. Bridged extensions refer to their generated static helper.

When generating Java source or a Javadoc input stub, a documentation-capable generator must emit a valid traditional /** ... */ group immediately before the corresponding Java declaration and its annotations. It must escape a literal */ as *&#47; in prose (or equivalent valid tag content) so documentation cannot terminate the Java comment. Content inside a {@code}/{@literal} tag retains its rendered literal meaning. Java-keyword Kalm declaration names that cannot be emitted directly in Java use the generator's documented deterministic name mapping; all doc references must use the same mapping. Tooling must expose this mapping alongside the generated API, not guess names from raw comment text.

Top-level functions/constants attach to the source facade's methods/fields; top-level type docs attach to their types. A read property's docs attach to its getter and a write accessor's docs to its setter. A @param for a setter must name its actual setter parameter. Data component parameters document the corresponding record components and generated constructor parameters; Java's standard doclet supplies accessor documentation from record components. A source function's full signature and default-argument overloads all receive documentation: each overload retains only present @param tags and adds an API note explaining its omitted defaults. Descriptions and relevant throws/deprecation tags remain.

Generated notes must preserve Kalm information that Java signatures alone lose: which references exclude/permit null, whether completion can return null, and the source spelling of parameter defaults with their invocation-time evaluation. For an async result, distinguish the non-null task handle from its body value (or no-result completion) in the return documentation. Use @apiNote text in generated Javadoc and register that custom block tag with the standard doclet using -tag "apiNote:a:API Note:" (or render equivalent API-note HTML in the main description for a bare doclet invocation). It must not be assumed to be a built-in doclet tag. Tools may support other standard Javadoc tags without changing the required subset above. Unknown tags are reported and preserved for a configured doclet; invalid targets, duplicate singleton tags, nonexistent parameters, and malformed inline tags are diagnosed rather than silently corrected.

Complete conversion example (GreetingApi.kalm):

Kalm
space studio.greetings;

### Builds a greeting.
### @param name recipient, or null for a guest
### @return greeting text
### @since 1.2.0
pub fun loud(name: Text? = "hello") -> Text:
    return (name ?? "guest").upper()

Corresponding Java documentation surface (implementation and runtime nullability annotations omitted in this Javadoc input stub):

Java
package studio.greetings;

public final class GreetingApiKalm {
    /**
     * Builds a greeting.
     * @param name recipient, or null for a guest
     * @return greeting text
     * @since 1.2.0
     * @apiNote Kalm parameter name: Text? permits null. The Text result excludes null.
     * @apiNote Omitting name evaluates the Kalm default "hello" for that invocation.
     */
    public static String loud(String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * Builds a greeting.
     * @return greeting text
     * @since 1.2.0
     * @apiNote This overload evaluates the omitted name default "hello" for each invocation.
     * @apiNote The Kalm Text result excludes null.
     */
    public static String loud() {
        throw new UnsupportedOperationException();
    }
}

The stub bodies above are documentation placeholders; an executable generator instead emits the function and default forwarder defined by §4. KalmDoc validation warnings do not change program behavior or waive type/exception checking. Saved as studio/greetings/GreetingApiKalm.java, the example is valid input for the standard JDK 25 doclet:

sh
javadoc -encoding UTF-8 -Xdoclint:all,-missing -tag "apiNote:a:API Note:" -d docs studio/greetings/GreetingApiKalm.java

A test "description" { ... } block declares one test case. A failed expect check fails that test. File-level before { ... } and after { ... } hooks run before and after each test in the file; after runs even when a test fails. expect checks are always active inside tests.

Kalm
before {
    TestDatabase.openShared();
}

test "a user can be loaded" {
    fix user = TestSupport.repository().find("42");
    expect user.name == "Ari";
}

after {
    TestDatabase.closeShared();
}

8. Standard library

The standard prelude is automatically available in every Kalm source file. Prelude functions follow the same overload resolution and generic rules as Java methods, and declarations in the current Kalm scope take precedence over prelude names.

Kalm runtime types include Task<T>, TaskFailureException, and TaskInterruptedException. Kalm uses Java APIs for collections, I/O, time, mathematics, and concurrency.

Kalm API Behavior
say(value), sayLine(value) Write formatted value, optionally followed by the platform newline
len(value) Length/size of Text, arrays, List, or Map
arrayOf(values...) Construct a reference array when component type is reifiable
boolArrayOf … charArrayOf Construct the matching Java primitive arrays
range(end), range(start, end) Lazy java.lang.Iterable<Int>; int boundaries, exclusive end
exit(code) Delegate to System.exit
abs, min, max Numeric overloads for int, long, float, and double
sqrt, pow, round Delegate to java.lang.Math

Formatting uses Java-compatible null, true, and false spellings and formats other values through String.valueOf. Interpolation uses the same formatting. upper() and lower() use locale-independent Locale.ROOT. Lists and maps are Java mutable collections. Java APIs such as Objects, Collections, Files, and Math remain directly importable.

Library signatures and availability

The APIs below define the 1.2.0 standard-library contract, including additions for future implementations. A conforming 1.2.0 distribution must implement them; an older compiler/library may not. They are ordinary library functions, contracts, and records, not parser special cases. The default prelude is exported by kalm.stdlib.Prelude for Java callers; everyday APIs below are automatically available in .kalm and .kalms. File, time, task-composition, and advanced-collection APIs require importing their facade type with use and calling its static methods. Generic arguments denote reference types; primitive arguments/results are boxed where generic storage requires it. In the signature tables, values...: T denotes Java varargs metadata, not new Kalm parameter syntax. Iterable<T> denotes java.lang.Iterable<T> and must be imported when named explicitly in source. Java-facing references carry Kalm runtime nullability annotations; omitted ? excludes null unless a Java platform declaration explicitly lacks annotations.

Library callbacks are public SAM contracts and have these Kalm views:

Kalm
# The following types live in space kalm.stdlib.
pub contract Mapper<T, R> { fun apply(value: T) -> R; }
pub contract Predicate<T> { fun test(value: T) -> boolean; }
pub contract Folder<A, T> { fun apply(accumulator: A, value: T) -> A; }
pub contract Supplier<T> { fun get() -> T; }
pub data Partition<T>(matching: List<T>, remaining: List<T>);
pub data Timed<T>(value: T, elapsed: java.time.Duration);

Unless stated otherwise, a helper validates structural arguments (non-null receiver, sizes, bounds) before traversing input or invoking callbacks. Ordinary callback exceptions propagate unchanged, stopping synchronous traversal; previous callback effects remain. Null callback results are permitted only when the corresponding generic result argument is nullable. Lists returned by helpers are fresh mutable ArrayList snapshots containing the original element references, never views; helpers do not mutate their input. Iterators/streams/resources remain subject to their owning Java APIs. Concurrent mutation during a synchronous traversal has the input's ordinary Java behavior.

Console, text, and parsing

Signature Required behavior
text(value: Any?) -> Text Same formatting as interpolation and say; null becomes "null".
say(value: Any?) -> void, sayLine(value: Any?) -> void Write to standard output, with no/one platform newline.
sayLine() -> void Write one platform newline.
readLine() -> Text? Read one standard-input line without its terminator; null at EOF; UTF-8 decoding; an I/O failure raises UncheckedIOException.
readLine(prompt: Text) -> Text? Write and flush the prompt without a newline, then read as above.
upper() / lower() on Text Locale.ROOT case conversion; return Text.
trimmed() on Text Return Text using Java String.strip() Unicode whitespace rules.
isBlank() on Text Return primitive boolean using Java String.isBlank().
splitOn(separator: Text) on Text Return List<Text> using a literal, nonempty separator; preserve empty leading/interior/trailing pieces. Empty input yields [""]; empty separator raises IllegalArgumentException.
replaceText(old: Text, replacement: Text) on Text Return Text replacing non-overlapping literal occurrences left to right; empty old raises IllegalArgumentException.
parseByte/parseShort/parseInt/parseLong(value: Text) Return Byte?/Short?/Int?/Long?; decimal signed parsing, null on invalid text or range overflow.
parseFloat/parseDouble(value: Text) Return Float?/Double?; finite decimal floating parsing, null for malformed text, NaN, infinity, or overflow.
parseBool(value: Text) -> Bool? Accept true/false case-insensitively with Locale.ROOT; otherwise null.

Parsers strip surrounding whitespace using String.strip(); they never throw for malformed input. Integer parsers accept one optional leading sign followed by ASCII decimal digits. Floating parsers accept an optional sign, decimal digits with an optional decimal point (at least one digit total), and an optional e/E exponent with optional sign and at least one digit. Suffixes, embedded whitespace, separators, and hexadecimal forms are invalid. Finite underflow follows Java rounding, possibly to signed zero. Parsing null is a type error, or a boundary NullPointerException from Java. Text operations do not mutate strings and use UTF-16 indexing where applicable. A real instance method wins over an extension of the same name; kalm.stdlib.Texts exposes the same named static operations, taking the receiver as their first argument, to Java and for explicit selection. splitOn and replaceText deliberately have distinct names from existing Java methods so their documented literal/validation behavior is available without overload ambiguity.

len returns int; text length counts UTF-16 code units, arrays count elements, and collections/maps report Java size. It accepts every primitive array, reference arrays, Text, java.util.Collection, and Map. exit(code: int) delegates to System.exit. Console calls share standard streams; hosts may redirect them. The baseline shell receives EOF as evaluated-code input (§11), so readLine returns null there after printing any prompt.

Collections, ranges, and math

Signature Required behavior
listOf<T>(values...: T) -> List<T> Fresh ordered mutable list.
setOf<T>(values...: T) -> java.util.Set<T> Fresh mutable LinkedHashSet; first-occurrence order and Java equality.
mapOf<K,V>(keys: List<K>, values: List<V>) -> Map<K,V> Fresh insertion-ordered map; equal lengths required, non-null keys; duplicate keys keep their first position and last value.
arrayOf<T>(values...: T) -> Array<T> Fresh fixed-size reference array; a reifiable component type is required.
boolArrayOf … charArrayOf Fresh matching primitive arrays; arguments undergo the matching primitive assignment conversions.
map<T,R>(items: Iterable<T>, mapper: Mapper<T,R>) -> List<R> Map in encounter order, once per item.
filter<T>(items: Iterable<T>, predicate: Predicate<T>) -> List<T> Keep items for which the callback returns true, in encounter order.
fold<T,A>(items: Iterable<T>, initial: A, folder: Folder<A,T>) -> A Left fold in encounter order; empty input returns initial.
firstOrNull<T>(items: Iterable<T>) -> T? First item or null for empty input; traverse at most one item.
firstOrNull<T>(items: Iterable<T>, predicate: Predicate<T>) -> T? First matching item or null; stop at the first match.
any<T>(items: Iterable<T>, predicate: Predicate<T>) -> boolean Short-circuit on the first true; false for empty input.
all<T>(items: Iterable<T>, predicate: Predicate<T>) -> boolean Short-circuit on the first false; true for empty input.
join<T>(items: Iterable<T>, separator: Text = ", ") -> Text Format each item with text; separator only between items; empty input gives "".
range(end: int) -> Iterable<Int> Equivalent to range(0, end, 1).
range(start: int, end: int) -> Iterable<Int> Equivalent to range(start, end, 1).
range(start: int, end: int, step: int) -> Iterable<Int> Lazy reusable range with an exclusive end; zero step raises IllegalArgumentException.
clamp(value: N, low: N, high: N) -> N Overloads for primitive int, long, float, double; return min(max(value, low), high), rejecting low > high.

map/filter on empty input return empty lists without calling callbacks. fold on empty input never calls its folder; predicates in any/all likewise do not run. mapOf validates key nullability and both lengths before constructing its result. Empty collection factories require a target/explicit generic type. Nullable list elements, set elements, and map values are permitted with nullable generic arguments; map keys remain non-null (§3). firstOrNull cannot distinguish an absent element from a first element whose value is null; callers needing that distinction should retain the collection/index. Array helpers copy varargs storage and preserve Java array store/bounds checks. Arrays can participate in Iterable helpers through kalm.stdlib.Collections.asList overloads for reference and all primitive arrays, returning fresh boxed snapshots; they are not implicitly treated as Java Iterable arguments.

Ranges with a positive step are empty if start >= end; negative-step ranges are empty if start <= end. Compute progression in widened long arithmetic so an int counter cannot wrap; stop before crossing the exclusive end. A range iterator at exhaustion raises NoSuchElementException on next. Its advertised elements are boxed Int; loop arithmetic unboxes/promotes normally. clamp rejects NaN bounds; a NaN value returns NaN for floating overloads, and signed-zero behavior follows Java Math.min/Math.max. Infinity is accepted if bounds are ordered. Preserved abs, min, and max use Java Math behavior for the four primitive families, including abs of the minimum signed integer wrapping to that same value. sqrt(double)/pow(double, double) return double; round(float) returns int, and round(double) returns long, with Java NaN/infinity/rounding behavior.

Kalm
fix ages: List<Int> = [16, 21, 34];
fix adults = filter(ages, fun age => age >= 18);
sayLine(join(map(adults, fun age => @"age=$age"), "; "));
fix parsed: Int? = parseInt(" 42 ");
fix count: int = parsed ?? 0;
for number in range(5, 0, -2):
    sayLine(number) # 5, 3, 1.

Files and paths

Import kalm.stdlib.FileOps. Its static methods are ordinary Java-callable library APIs. Path and Charset below mean java.nio.file.Path and java.nio.charset.Charset; charset defaults use StandardCharsets.UTF_8.

Static method Contract
path(value: Text) -> Path Java Path.of(value); relative paths remain relative.
resolve(base: Path, child: Text) -> Path Java base.resolve(child).normalize(); an absolute child follows Java behavior.
exists(path: Path) -> boolean Java Files.exists(path) following links; false also when existence cannot be determined.
readText(path: Path, charset: Charset = UTF_8) -> Text Read the entire file via Java Files.readString.
readLines(path: Path, charset: Charset = UTF_8) -> List<Text> Fresh lines without terminators, via Files.readAllLines; empty file gives an empty list.
writeText(path: Path, value: Text, charset: Charset = UTF_8) -> void Java Files.writeString with create/truncate/write; close the resource before completing.
appendText(path: Path, value: Text, charset: Charset = UTF_8) -> void Create/write/append; do not add an implicit newline.

Helpers close internally opened resources on every path and wrap checked IOException in UncheckedIOException with its original cause. Java invalid-path, security, and argument exceptions propagate unchanged. They neither create parent directories nor promise atomic writes or rollback after a partial write. exists intentionally retains Java's false-on-indeterminate behavior rather than throwing a hidden I/O error. No project discovery, dependency download, or network/file sandbox is implied by this API.

Time and task composition

Import kalm.stdlib.Time or kalm.stdlib.Tasks. Duration, Instant, and LocalDate are Java time types.

Static method Contract
Time.now() -> Instant Current UTC timeline instant from Instant.now().
Time.todayUtc() -> LocalDate Current calendar date using Clock.systemUTC().
Time.millis(value: long) -> Duration, Time.seconds(value: long) -> Duration Java duration factories; signed durations allowed.
Time.timed<T>(operation: Supplier<T>) -> Timed<T> Invoke once; return result and nonnegative elapsed Duration from System.nanoTime, not wall-clock subtraction.
Tasks.all<T>(tasks: List<Task<T>>) -> Task<List<T>> Snapshot handles; asynchronously collect results in input order; empty input completes with an empty list.
Tasks.withTimeout<T>(task: Task<T>, timeout: Duration) -> Task<T> Complete with the source's result/failure, or fail with TaskFailureException caused by TimeoutException at the deadline.
Tasks.mapConcurrent<T,R>(items: Iterable<T>, limit: int, mapper: Mapper<T,R>) -> Task<List<R>> Snapshot items once before scheduling; execute at most limit mapper invocations at a time on virtual threads; results retain input order.

timed propagates an operation exception unchanged and returns no measurement record on failure; result references are retained without copying. It is synchronous and does not support Supplier<Unit> (use a value callback). The returned elapsed duration describes the callback, excluding construction of the Timed record.

Tasks.all and mapConcurrent return non-null task handles. Null handles/items are subject to declared generic nullability; structurally invalid input (including limit <= 0) throws before starting tasks. An input enumeration exception prevents scheduling; effects of enumeration remain. Empty concurrent input completes successfully with an empty result without calling the mapper. Once scheduled, callback exceptions fail the returned task according to §5. On the first observed failure, request cancellation of unfinished child tasks; already completed effects remain. If failures race, the reported first observed failure is not deterministic. Cancelling the aggregate requests cancellation of all unfinished children. all likewise may cancel unfinished supplied tasks after failure; callers must account for their possible sharing. Completion/cancellation cannot promise interruption of code that ignores it.

Timeouts must be strictly positive; zero/negative durations raise IllegalArgumentException before scheduling. An already completed source wins without scheduling a timeout. Otherwise the first observed source-completion or deadline event wins exactly once; late events cannot overwrite it. A timeout requests cancellation of the source. Cancelling the wrapper also requests source cancellation. Deadline measurement is monotonic, and timing can be delayed by host scheduling; positive durations must not wrap into an immediate deadline through integer overflow. A timeout does not roll back source effects. Tasks.all<Unit> and mapConcurrent with a Unit generic argument are invalid because List<Unit>/ordinary SAM Unit arguments are invalid (§3); use value tasks or individually await no-result tasks. withTimeout also accepts Task<Unit> as the no-result specialization.

Collection conveniences

Import kalm.stdlib.Collections for these static APIs (including the array asList overloads described above):

Static method Contract
windowed<T>(items: Iterable<T>, size: int, step: int = 1, partial: boolean = false) -> List<List<T>> Snapshot input once; windows start at indexes 0, step, 2*step, ...; positive size/step required.
partition<T>(items: Iterable<T>, predicate: Predicate<T>) -> Partition<T> Single traversal/callback per item; matching contains true results and remaining false results, each in input order.

windowed includes only full windows unless partial is true; then each remaining nonempty suffix window is included. Empty input returns an empty list. A short nonempty input yields no full window, or one/more suffix windows according to the step when partial windows are enabled. The outer list and every inner list are fresh mutable snapshots; changing one does not structurally modify another or the input. Element objects are shared. partition returns two fresh mutable lists, including two empty lists for empty input; the data record's component bindings are immutable but its lists are mutable. Invalid sizes/steps are rejected before iterating, and ordinary callback exceptions follow the rules above.

Kalm
use kalm.stdlib.Collections as KalmCollections;
use kalm.stdlib.Time;
use kalm.stdlib.FileOps;

fix windows = KalmCollections.windowed([1, 2, 3, 4], 3); # [[1, 2, 3], [2, 3, 4]]
fix split = KalmCollections.partition([1, 2, 3, 4], fun n => n % 2 == 0);
fix measured = Time.timed(fun () => FileOps.readText(FileOps.path("notes.txt")));
sayLine(measured.elapsed);

9. Core grammar

This grammar is normative. Semicolons or logical newlines terminate simple statements; braces or colon suites delimit blocks, as defined in §2. A semantic modifier check rejects duplicate modifiers and the invalid combinations described in §6. The parser rejects missing statement terminators, unmatched braces, and malformed statements rather than guessing. The precedence productions below resolve the shorthand Expr rule used in statement productions. ??= is a right-associative assignment operator; ?? is right-associative coalescing below logical operators, and ?: is right-associative conditional selection between coalescing and assignment. Longest-match tokenization recognizes ??=, ??, ?., ?[, !!, and contiguous as? before their shorter prefixes. Identifier is a lexical identifier under §2, including contextual words in name positions. IntegerLiteral, FloatLiteral, CharLiteral, TextLiteral, and InterpolatedText are the lexical forms defined there. Comments, including attached KalmDoc, are retained separately from syntax tokens. Newlines following declaration annotations are treated as annotation separation, not as a completed declaration. END below is a zero-width lookahead for }, DEDENT, or EOF: statement termination must not consume the enclosing delimiter. Continued physical newlines inside expression delimiters are not emitted as logical NEWLINE tokens.

ebnf
File              = Separators [ SpaceDecl Separators ] { UseDecl Separators }
                    { Declaration Separators } EOF ;
ScriptFile        = Separators { ScriptItem Separators } EOF ;
ScriptItem        = UseDecl | ScriptDeclaration | Statement ;
ScriptDeclaration = { AnnotationUse } [ Visibility ] [ "legacy" ]
                    ( TypeDecl | FunctionDecl | AliasDecl | ConstantDecl
                    | AugmentDecl | ExternalDecl | AnnotationDecl ) ;
SpaceDecl         = "space" QualifiedName Terminator ;
UseDecl           = "use" QualifiedName [ "as" Identifier | "." "*" ] Terminator ;
Declaration       = { AnnotationUse } [ Visibility ] [ "legacy" ]
                    ( TypeDecl | FunctionDecl | AliasDecl | ConstantDecl
                    | AugmentDecl | ExternalDecl | AnnotationDecl | TestDecl | HookDecl ) ;
AnnotationUse     = "@" QualifiedName [ "(" [ AnnotationArguments ] ")" ] ;
AnnotationArguments = AnnotationArgument { "," AnnotationArgument } [ "," ] ;
AnnotationArgument  = [ Identifier "=" ] AnnotationValue ;
AnnotationValue     = ConstantExpr | Type "." "class" | "{" [ AnnotationValues ] "}" | NestedAnnotation ;
AnnotationValues    = AnnotationValue { "," AnnotationValue } [ "," ] ;
NestedAnnotation    = "@" QualifiedName [ "(" [ AnnotationArguments ] ")" ] ;
Visibility        = "pub" | "internal" | "private" | "protected" ;
TypeDecl          = ClassDecl | ContractDecl | DataDecl | ChoiceDecl | SingletonDecl ;
TypeModifier      = "base" | "closed" | "fix" | "extendable" ;
ClassDecl         = { TypeModifier } "class" Identifier [ TypeParams ] [ InheritsClause ] [ ImplementsClause ] MemberBlock ;
InheritsClause    = "inherits" Type ;
ImplementsClause  = "implements" TypeList ;
ContractDecl      = "contract" Identifier [ TypeParams ] [ "inherits" TypeList ] ContractBlock ;
DataDecl          = "data" Identifier [ TypeParams ] "(" [ Params ] ")" [ GenerateClause ] Terminator ;
ChoiceDecl        = "choice" Identifier ChoiceBlock ;
ChoiceBlock       = "{" Separators { ChoiceVariant Separators } "}" | ":" DeclarationSuite(ChoiceVariant) ;
ChoiceVariant     = Identifier Terminator ;
SingletonDecl     = "singleton" Identifier MemberBlock ;
MemberBlock       = "{" Separators { Member Separators } "}" | ":" DeclarationSuite(Member) ;
Member            = { AnnotationUse } [ Visibility ] [ "legacy" ]
                    ( Field | Constructor | FunctionDecl | NeedsFunction
                    | Accessor | ForwardDecl | TypeDecl ) ;
ContractBlock     = "{" Separators { ContractMember Separators } "}" | ":" DeclarationSuite(ContractMember) ;
ContractMember    = { AnnotationUse } ( FunctionSignature | AccessorSignature ) ;
FunctionHead      = [ "async" ] "fun" Identifier [ TypeParams ] "(" [ Params ] ")"
                    [ "->" ResultType ] [ GivenClause ] ;
FunctionSignature = FunctionHead Terminator ;
NeedsFunction     = "needs" FunctionSignature ;
Constructor       = "init" "(" [ DefaultParams ] ")" Block ;
FunctionDecl      = [ "override" ] [ "async" ] [ "extendable" | "fix" ] "fun" Identifier [ TypeParams ]
                    "(" [ DefaultParams ] ")" [ "->" ResultType ] [ GivenClause ] FunctionBody ;
LocalFunction     = { AnnotationUse } [ "async" ] "fun" Identifier [ TypeParams ] "(" [ DefaultParams ] ")"
                    [ "->" ResultType ] [ GivenClause ] FunctionBody ;
FunctionBody      = "=" Expr Terminator | Block ;
AliasDecl         = "alias" Identifier [ TypeParams ] "=" Type Terminator ;
ConstantDecl      = "constant" Identifier ":" Type "=" ConstantExpr Terminator ;
Field             = [ "lazy" ] [ "late" ] ( "fix" | "var" ) FieldDeclarator
                    { "," FieldDeclarator } Terminator ;
FieldDeclarator   = Identifier ":" Type [ "=" Expr ] ;
Accessor          = "read" Identifier ":" Type ( "=" Expr Terminator | Block )
                    | "write" Identifier "(" Param [ "," ] ")" Block ;
AccessorSignature = "read" Identifier ":" Type Terminator
                    | "write" Identifier "(" Param [ "," ] ")" Terminator ;
ForwardDecl       = "forward" Type "to" Identifier Terminator ;
GenerateClause    = "generate" Identifier { "," Identifier } ;
GivenClause       = "given" TypeConstraint { "," TypeConstraint } ;
TypeConstraint    = TypeParam ":" Type ;
TypeList          = Type { "," Type } ;
Params            = Param { "," Param } [ "," ] ;
Param             = { AnnotationUse } Identifier ":" Type ;
DefaultParams     = DefaultParam { "," DefaultParam } [ "," ] ;
DefaultParam      = Param [ "=" Expr ] ;
TypeParams        = "<" TypeParam { "," TypeParam } [ "," ] ">" ;
TypeParam         = { AnnotationUse } Identifier ;
Type              = { AnnotationUse } ( PrimitiveType | NamedType [ "?" ] ) ;
ResultType        = { AnnotationUse } "void" | Type ;
PrimitiveType     = "boolean" | "byte" | "short" | "int" | "long" | "float" | "double" | "char" ;
NamedType         = QualifiedName [ "<" Type { "," Type } [ "," ] ">" ]
                    | "Unit" | "Bool" | "Byte" | "Short" | "Int" | "Long"
                    | "Float" | "Double" | "Char" | "Text" | "Any" | "Task" "<" Type [ "," ] ">"
                    | "Array" "<" Type [ "," ] ">" | "BoolArray" | "ByteArray" | "ShortArray"
                    | "IntArray" | "LongArray" | "FloatArray" | "DoubleArray" | "CharArray"
                    | "List" "<" Type [ "," ] ">" | "Map" "<" Type "," Type [ "," ] ">" ;
AugmentDecl       = [ "bridge" ] "augment" Type AugmentBlock ;
AugmentBlock      = "{" Separators { AugmentFunction Separators } "}" | ":" DeclarationSuite(AugmentFunction) ;
AugmentFunction   = [ Visibility ] [ "legacy" ] FunctionDecl ;
ExternalDecl      = "external" "fun" Identifier [ TypeParams ] "(" [ Params ] ")"
                    [ "->" ResultType ] [ GivenClause ] "=" QualifiedName Terminator ;
AnnotationDecl    = "annotation" Identifier AnnotationBlock ;
AnnotationBlock   = "{" Separators { AnnotationMember Separators } "}" | ":" DeclarationSuite(AnnotationMember) ;
AnnotationMember  = TargetDecl | AnnotationElement ;
TargetDecl        = "target" TargetKind { "," TargetKind } Terminator ;
TargetKind        = "type" | "function" | "field" | "property" | "parameter"
                    | "constructor" | "localVariable" | "annotationType" | "typeUse"
                    | "typeParameter" | "recordComponent" ;
AnnotationElement = Identifier ":" Type [ "=" AnnotationValue ] Terminator ;
TestDecl          = "test" TextLiteral Block ;
HookDecl          = ( "before" | "after" ) Block ;
Block             = BraceBlock | ":" Suite ;
BraceBlock        = "{" Separators { Statement Separators } "}" ;
Suite             = SimpleSuite | NEWLINE INDENT Separators Statement Separators
                    { Statement Separators } DEDENT ;
SimpleSuite       = EmptySeparators SimpleStatement { EmptySeparators SimpleStatement } EmptySeparators ;
DeclarationSuite(Element) = EmptySeparators Element { EmptySeparators Element } EmptySeparators
                    | NEWLINE INDENT Separators Element Separators { Element Separators } DEDENT ;
SimpleStatement   = Binding | LocalFunction | ReturnStmt | YieldStmt | RaiseStmt | CheckStmt | StopStmt | NextStmt | SuperConstructor
                    | Expr Terminator ;
BlockEnd          = "}" | DEDENT ;
Terminator        = ";" | NEWLINE | END ;
Separators        = { ";" | NEWLINE } ;
EmptySeparators   = { ";" } ;
Statement         = Binding | IfStmt | WhileStmt | ForStmt | MatchStmt | ReturnStmt | YieldStmt | RaiseStmt
                    | TryStmt | WithStmt | DeferStmt | GuardStmt | CheckStmt | StopStmt | NextStmt
                    | LocalFunction | SuperConstructor | Block | Expr Terminator ;
Binding           = { AnnotationUse } ( "fix" | "var" )
                    ( Declarator { "," Declarator } | BindingPattern "=" Expr ) Terminator ;
Declarator        = Identifier [ ":" Type ] "=" Expr ;
BindingPattern    = "[" BindingSlot { "," BindingSlot } [ "," ] "]" ;
BindingSlot       = Identifier [ ":" Type ] ;
IfStmt            = "if" Condition Block { Separators ElseIfHead Condition Block }
                    [ Separators "else" Block ] ;
ElseIfHead        = "elif" | "else" "if" ;
Condition         = Expr | "(" Expr ")" ;
WhileStmt         = "while" Condition Block ;
ForStmt           = "for" ( "(" Identifier "in" Expr ")" | Identifier "in" Expr ) Block ;
MatchStmt         = MatchExpr ;
MatchExpr         = "match" Expr MatchBlock ;
MatchBlock        = "{" Separators { CaseArm Separators } "}" | ":" DeclarationSuite(CaseArm) ;
CaseArm           = "case" Pattern "=>" ( Expr Terminator | Block ) ;
Pattern           = Type | QualifiedName | "_" | Literal ;
ReturnStmt        = "return" [ Expr ] Terminator ;
YieldStmt         = "yield" Expr Terminator ;
RaiseStmt         = "raise" Expr Terminator ;
TryStmt           = "try" Block Separators ( HandleClause { Separators HandleClause }
                    [ Separators "finally" Block ] | "finally" Block ) ;
HandleClause      = "handle" "(" Identifier ":" Type ")" Block ;
WithStmt          = "with" Resource { "," Resource } Block ;
Resource          = Identifier "=" Expr ;
DeferStmt         = "defer" Block ;
GuardStmt         = "guard" Expr Block ;
CheckStmt         = ( "expect" | "require" | "ensure" ) Expr [ "," Expr ] Terminator ;
StopStmt          = "stop" Terminator ;
NextStmt          = "next" Terminator ;
SuperConstructor  = "super" "(" [ Arguments ] ")" Terminator ;
SuperCall         = "super" "." Identifier Call ;
TaskExpr          = "task" Block ;
Lambda            = "fun" LambdaParams "=>" Expr | "fun" LambdaParams Block ;
LambdaParams      = LambdaParam { "," LambdaParam } | "(" [ LambdaParam { "," LambdaParam } [ "," ] ] ")" ;
LambdaParam       = { AnnotationUse } Identifier [ ":" Type ] ;
Expr              = Assignment ;
Assignment        = Conditional [ AssignmentOp Assignment ] ;
Conditional       = Coalesce [ "?" ConditionalBranch ":" ConditionalBranch ] ;
ConditionalBranch = Expr | BraceBlock ;
Coalesce          = LogicalOr [ "??" Coalesce ] ;
AssignmentOp      = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "??=" ;
LogicalOr         = LogicalAnd { ( "or" | "||" ) LogicalAnd } ;
LogicalAnd        = Equality { ( "and" | "&&" ) Equality } ;
Equality          = Relational [ ( "==" | "!=" ) Relational ] ;
Relational        = Additive [ ( "<" | "<=" | ">" | ">=" ) Additive | ( "is" | "as" | "as?" ) Type ] ;
Additive          = Multiplicative { ( "+" | "-" ) Multiplicative } ;
Multiplicative    = Unary { ( "*" | "/" | "%" ) Unary } ;
Unary             = ( "not" | "!" | "+" | "-" | "await" ) Unary | Postfix ;
Postfix           = Primary { Call | MemberAccess | SafeMember | SafeIndex | Index | "!!" } ;
Call              = [ TypeArgs ] "(" [ Arguments ] ")" ;
MemberAccess      = "." Identifier ;
SafeMember        = "?." Identifier ;
SafeIndex         = "?[" Expr "]" ;
Index             = "[" Expr "]" ;
Arguments         = Expr { "," Expr } [ "," ] ;
Primary           = Literal | Identifier | "self" | SuperCall | "(" Expr ")" | List | Map | Lambda | TaskExpr | MatchExpr ;
List              = "[" [ Arguments ] "]" ;
Map               = "{" [ MapEntry { "," MapEntry } [ "," ] ] "}" ;
MapEntry          = Expr ":" Expr ;
Literal           = IntegerLiteral | FloatLiteral | CharLiteral | TextLiteral | InterpolatedText
                    | "true" | "false" | "null" ;
ConstantExpr      = Expr ;
TypeArgs          = "<" Type { "," Type } [ "," ] ">" ;
QualifiedName     = Identifier { "." Identifier } ;

Calls on a name resolving to a type construct it; other calls invoke a function or method. Generic type arguments before constructor parentheses support Java calls such as ArrayList<Text>(). match patterns match enum constants, closed-hierarchy types, literals, or _. Braced blocks are valid only in declarations, control flow, resource/task/guard blocks, tests, lambdas, conditional branches, and standalone block statements. BraceBlock takes precedence over Expr for an unparenthesized brace starting a conditional branch; parenthesize a map literal there. Braces in expression position otherwise denote map literals. Bracket binding destructuring is defined separately in §4; destructuring match patterns remain unsupported. fix has context-dependent but related meanings: immutable binding, non-extendable class, or non-overridable member. A value introduced by fix cannot be reassigned. fun introduces both named functions and lambdas: declarations have a name and parenthesized parameters, while lambdas use => or a brace/colon body. Colon lambdas require parenthesized parameters. Expression parsing follows the precedence table in §4.

Semantic checks restrict defaults to concrete non-override declarations, require defaulted suffixes, check explicit field types, enforce the type/nullability restrictions in §3, and enforce matching/exhaustiveness/yield rules in §5. ResultType admits void only as a result annotation; void cannot fall back to QualifiedName in an ordinary type position. ConstantExpr deliberately shares expression syntax: semantic checking permits only Java-compatible compile-time constant expressions (§6), including eligible value conditionals, and rejects calls, assignment, collections, null, no-result expressions, safe casts, assertions, and block branches. Annotation values additionally admit their explicitly listed enum, class-literal, array, and nested-annotation forms (§7). SuperConstructor and SuperCall are restricted semantically to §6's parent-call contexts; completed parent-call forms take precedence over contextual identifier calls. LocalFunction requires the named declaration shape fun name(...), not a lambda. An expression-bodied local function is a simple declaration for an inline colon suite; a block-bodied local function requires a multiline suite or enclosing braces. Declaration annotations apply to local functions as to other declarations. Modifiers forbidden on local functions are errors. PrimitiveType takes precedence over QualifiedName in type positions: it cannot become a nullable named type through the latter production. Pattern names resolve to constants or types; nullable type patterns are invalid (null has its own literal pattern). The parser applies §2 contextual-keyword lookahead before choosing operator/primary alternatives: a call-shaped not(...)/await(...) is a call, while not value/await task is prefix syntax. A complete control header is preferred to a call-shaped identifier. The standalone MatchStmt interpretation wins over Expr Terminator for an unparenthesized statement match; other expression contexts require value exhaustiveness. A whole conditional expression statement selects execution context under §4, including through parentheses. Condition, argument, initializer, return, yield, assignment-operand, and other value positions select value context. Conditional branch operands are full expressions; their paired separators are resolved recursively, giving right association and allowing branch assignments. A ?/: conditional pair is distinct from nullable type ?, safe-index ?[, map entry :, and suite :. Only the immediate branch-leading brace selects BraceBlock; a map nested inside an expression remains a map. !! is postfix and contiguous; ! !value remains two prefix negations. SimpleSuite stops at its own logical newline; compound elements in a declaration suite require the multiline form defined in §2. Documentation cannot inject executable tokens or alter indentation.

10. Diagnostics

A diagnostic reports a stable code, severity, UTF-16 source range, concise message, and optional related locations. Codes use KALM-1xxx for syntax errors, KALM-2xxx for type and name errors, KALM-3xxx for Java interoperability errors, KALM-4xxx for documentation warnings, and KALM-9xxx for compiler errors. Syntax, type, and interoperability errors prevent compilation. Missing required bodies/initializers, missing conditional branches, malformed comma lists, and malformed patterns are syntax errors; nullable primitives, incompatible returns/defaults, missing branch yields, value-body fallthrough (including nullable results), invalid void positions, invalid safe-cast/assertion operands, non-exhaustive value matches, and illegal inheritance/parent calls are type errors; erased Java signature collisions are interoperability errors. Diagnostics must point to the offending construct and include the expected type, missing coverage, or conflicting declaration where applicable.

KalmDoc code Warning
KALM-4001 Orphaned documentation group or missing declaration target.
KALM-4002 Tag not valid for the attached declaration, nonexistent parameter, or missing inherited target.
KALM-4003 Unresolved/ambiguous symbol reference or a symbol without a Java documentation target.
KALM-4004 Malformed tag syntax or a duplicated singleton tag (@return, @since, or @deprecated).
KALM-4005 Unknown tag; preserve it for the configured doclet.

Documentation warnings do not prevent language compilation. A documentation tool may offer a strict mode that fails documentation generation on these warnings; it must not silently change their meaning or discard source descriptions.

11. Kalm Script and the shell

A UTF-8 .kalms file contains script items: use imports, named/type declarations, bindings, and executable statements in source order. It has no space header and no required entry point; declaring main does not invoke it. Tests and before/after hooks are rejected in script mode. Types/functions can use the same Kalm syntax and Java APIs as application source, subject to the script host's available dependencies. Imports may occur between snippets and remain available to later items. Names must be defined before use, including references needed to validate a newly declared function/type; recursion to the currently defined function is permitted. Duplicate declarations in a file are errors; interactive replacement is a separate session feature below.

Statements and initializers run once, sequentially. A declaration makes its symbol available without invoking its function body. Script bindings are shared by subsequent script items; fix still forbids assignment. A top-level return is invalid outside a function/lambda/task; yield requires a value-match arm or conditional block branch, which may itself occur in a script initializer. stop/next require a loop. await remains restricted to async fun/task, so script mode does not silently allow synchronous top-level await. Scripts have no implicit Java application facade API intended for import by other files. Use .kalm for a reusable project module.

Kalm Script
use java.time.LocalDate;

fix today = LocalDate.now();
var [a: int, b: int] = [5, 7];
fun greeting(name: Text = "Mira") -> Text:
    return @"Hello, $name, on $today"

sayLine(greeting());;;
sayLine(a + b);

Host interface and dependencies

The baseline CLI requires a full JDK 25 or newer and bundles Kalm runtime/stdlib. Its modes are:

sh
kalm shell                         # Persistent interactive session.
kalm shell -e 'sayLine("Hello")'   # One inline input.
kalm shell -f experiment.kalms     # One UTF-8 script file.

-e/--eval and -f/--file accept one input each and cannot be combined. Portable file-mode scripts use .kalms; .kalm is application source. A compatibility host may accept a .kalm file only with an explicit warning that it is being evaluated as a script and remains subject to script restrictions; other extensions are rejected. The baseline host supplies JDK and bundled Kalm libraries only. It does not read Maven/Gradle project metadata, discover neighboring sources, download dependencies, or accept an external --classpath. A richer future host may explicitly supply dependencies, but that is not part of the baseline 1.2.0 CLI contract. Scripts execute with the launching process's working directory and ordinary Java access permissions; file paths do not implicitly resolve relative to the script file.

Session state, results, and failures

Variables, object identities, imports, functions, and types persist across successful interactive submissions. Earlier statements and initializers must never be replayed to compile a later item. A bare value expression displays the same format as text and is bound to a fresh immutable result name such as res1; a no-result expression creates no result binding. File/inline modes also display bare value expressions in encounter order. Result names must avoid existing names; evaluating a literal null displays null with a nullable Any? result type. Explicit sayLine does not create an additional result. Whole conditional expression statements follow §4's execution rule and create no result binding or automatic display, even when a selected call returns a value. Bind the conditional to a name to request a value, then evaluate that name to display it. A value conditional inside a binding initializer still requires compatible branch results.

An interactive declaration may replace an existing definition under the same name; replacement is not assignment to a fix binding. Preflight type checking rejects replacements that invalidate existing definitions before executing the replacement initializer. Method bodies may be replaced while objects remain live, but type layout changes (fields or member signatures) are rejected while reference bindings to that type exist. Reset or a new type name allows such changes. The host must distinguish an import/definition replacement from creating an illegal source overload.

Complete input runs immediately. Unfinished expressions and brace bodies receive a continuation prompt; an interactive multiline colon suite is completed by a blank line. Commands are /help, /exit, /reset, /vars, /list, and /cancel: reset clears session definitions/values, and cancel discards the unfinished submission. /vars shows current bindings; /list shows retained submissions. The baseline provides portable line input; completion and persistent history are not required. Evaluated code receives EOF on standard input, separating the host's command input from program input. Piped host input runs without prompts.

File, inline, and piped execution stop at the first syntax/type/runtime failure; earlier successfully executed effects remain. An interactive error leaves the session available for correction. Runtime exceptions can leave partial object, file, or console effects even if the failed item creates no usable result. There is no transaction or side-effect rollback guarantee. Cancellation is best effort and follows Java task interruption where applicable.

Baseline CLI exit statuses are 0 for success, 1 for source/type/interop/runtime/test failure, 2 for invalid host configuration or arguments, and 3 for an internal compiler failure. Warnings do not fail execution. Diagnostics use §10's source ranges/codes and support --diagnostic-format human or --diagnostic-format json. Application builds remain responsible for project classpaths, module paths, entry points, and test execution.

12. Migration from final 1.1.0

This draft is a complete extension of the final 1.1.0 document, not a reduced replacement. Unchanged capabilities retain their descriptions above: both block styles, Java facades/entry points, null-safe operations, checked conversions, lambdas, exception handling, resources/defer, tasks/guards, records/enums/aliases, generics/bounds, augmentation/bridges, forwarding, property accessors, lazy/late fields, annotations, visibility, Java integration, tests, and the original prelude. The following changes intentionally supersede corresponding 1.1.0 rules:

1.1.0 rule/spelling 1.2.0 rule and migration
Capitalized Bool, Int, etc. could emit primitives Capitalized forms emit wrappers. Use lowercase primitives to preserve primitive signatures, storage, and Java ABI; retain capitalized forms for generic/reference values. Recompile dependents after descriptor changes.
Nullable primitives were written with ? on capitalized primitive names Capitalized names are now wrappers; Int? remains the nullable wrapper spelling. Lowercase int? is rejected.
Numeric literals were described as capitalized types Literal inference is primitive; list/map generic storage boxes elements. Arithmetic follows Java promotion, including mixed numeric widths.
null could target Any Use Any?; Any is consistently non-null.
impl Replace with implements; impl is no longer an implementation-clause keyword.
choose / branch when Replace with match / case; old spellings are no longer match syntax. They may be ordinary identifiers.
Ordinary classes and methods were final by default Add fix to preserve a final class/method contract. Ordinary eligible declarations are open by default; extendable remains an explicit open marker.
An unmarked direct sealed child was implicitly final Add fix, closed, extendable, or base to state its inheritance contract explicitly.
Block functions without result arrows were Unit Omitted block results now use preferred spelling void; explicit Unit remains equivalent. No return, bare return, and literal return null complete without a value.
Nullable result functions required explicit values on every path Retained: nullable results require explicit compatible values, including explicit null, on every normally completing path. Earlier 1.2 draft implicit-null completion is withdrawn.
Public results always required annotations Public block functions may omit the arrow for no-result intent; public value-producing functions retain explicit result annotations.
No default arguments Trailing defaults now evaluate per invocation for omitted arguments; explicit null does not trigger a default. Generated overloads are part of the Java API.
One binding per declaration; no destructuring Comma declarations and flat bracket bindings are added. Ordinary bracket expressions still create lists.
Reserved-word list globally excluded names Contextual recognition permits keyword-named declarations and calls; literals stay reserved. not(...)/await(...) now mean calls: use !(...) for grouped negation and await taskValue/await client.fetch() to await a result.
elif only Both elif and else if are accepted.
Logical precedence table grouped and and or together Conjunction precedes disjunction, matching the old grammar and both symbolic aliases. Parenthesize if different grouping was intended.
Repeated semicolons were unspecified Empty separators are explicitly accepted; incomplete declarations and missing bodies remain errors.
Match expressions had underspecified block results Exhaustive value matches use expression arms or yield; partial statement matches have explicit no-match behavior.
Documentation preserved only “where practical” KalmDoc defines attachment, standard tags, diagnostics, and required semantic Javadoc conversion by documentation-capable generators.
Source rules covered .kalm only Kalm Script and baseline shell/session behavior are now specified separately, sharing core syntax/types.
Unit was described only as a result type despite tasks using generic results No-result task/completion-stage arguments use Unit as the specified Java Void specialization; ordinary Unit values remain invalid.
No conditional operator Add value and execution forms of ?:, including braced branches; value blocks use yield.
No safe cast or non-null assertion Add reference-safe as? and nullable-reference postfix !!; checked numeric conversions remain separate.
No explicit parent-call syntax Add first-statement super(...) construction and direct super.method(...) dispatch.
void and super could be custom names Rename types/aliases named void; complete parent-call forms now take precedence over ordinary calls on a contextual name super. Other permitted function/member name positions remain contextual.
Delimited lists disallowed trailing commas Permit one trailing comma on nonempty delimited lists; unparenthesized declarations retain existing rules.
Indexing and local declarations were incompletely specified Define indexed writes, safe no-result calls, local named functions, and branch refinements consistently with the grammar.

The renamed spellings are replacements, not deprecated syntax aliases. Existing final/draft documents remain immutable historical editions. A 1.2.0 implementation must identify its supported language/library version; compiling against this draft with an older toolchain does not establish conformance. No automatic rewrite or compiler feature delivery is implied by publishing this document.

13. Conformance scenarios

These scenarios are acceptance requirements for future 1.2.0 compiler/library/doc implementations. They are not claims that the current compiler passes them. All source fragments below require their stated enclosing context.

Area Positive scenarios Required rejection/failure scenarios
Primitive/wrapper mapping Verify all eight pairs, primitive literal inference, boxed generics, primitive arrays, widening, and Java overload selection. var n: Int = 5; fix p: int = n; boxes/unboxes. Reject int?, List<int>, unboxing Int? without refinement, and null to Any. A Java null crossing a non-null boundary raises NullPointerException.
Arithmetic/equality 1 + 2L has long type; two independently boxed equal Int values compare equal. Checked toByte() succeeds for 127. Checked toByte() fails for 128; reject numeric use of Bool. Validate wrapper-class equality and floating NaN/signed zero against Java rules.
Independent bindings In a function, var a = 5, b: int = a + 2; initializes in order; typed fields each retain their own type. Reject missing initializer on locals, missing type on a field, forward references, and duplicate names.
Bracket bindings Mixed literal types infer per slot; list/array source runs once and each index is read once; fix names cannot be assigned. Literal arity/type mismatch fails compilation; dynamic arity mismatch raises IllegalArgumentException. Failed extraction/conversion initializes no destination names.
Separators Accept test();;;, ;; in a body, and extra separators between declarations and branch clauses in both block styles. Reject var a = ;;, if ready;, and a colon suite containing only empty separators.
Contextual words Declare/call and(), test(), and a function/member named match; ordinary test() is valid in scripts. not(...) resolves a callable. Reject a literal word as a declaration name, malformed compound headers, and unresolved not(...); recognize real test declarations only in application/test mode.
Operators/branches Equivalent side effects/results for both operator spellings; conjunction precedes disjunction; elif and else if work in braces and colon suites. Nullable Bool? conditions require refinement/coalescing; unchosen short-circuit operands must not run.
Results Verify omitted/explicit void, compatible -> Unit, bare return, literal no-result return null, and no return. Nullable bodies explicitly return values/null. Reject nullable/non-null value fallthrough or bare return, incompatible returns, storing no-result expressions, and void parameters/aliases/generics including Task<void>.
Conditional values Test assignment, argument, expression-body and return contexts; numeric promotion, nullable common types, nested right association, ?? precedence, block yields, cleanup, and enclosing returns. Reject nullable conditions, missing branches, missing yields, incompatible expected results, and no-result value branches. Unchosen branches/conditions must not be evaluated again.
Conditional execution Test no-result calls, discarded value calls, mixed calls, empty blocks, nested execution branches, and multiline braces within colon suites; no script result binding/display. Reject yield in execution branches and colon branch blocks. Parenthesized branch maps remain values; bare branch braces always select blocks.
Null helpers/refinement Safe casts return the same reference or null; assertions evaluate once, retain reference type, and allow later unboxing. Check stable refinements in both conditional branches and short-circuit operands. A null nullable-reference assertion raises NullPointerException; reject non-null/primitive/no-result assertions, non-reifiable/nullable/primitive safe-cast targets, and smart casts through mutable/overridable access paths.
Parent calls Verify superclass construction before subclass field initializers/body, implicit accessible super(), direct parent dispatch, default evaluation without override reentry, and checked exception handling. Reject absent accessible parent constructors, repeated/late/nested super construction, premature instance use, abstract/static/inaccessible parent methods, and unsupported parent-call contexts.
Trailing commas Accept one final comma on nonempty parameter/argument/generic/component/binding/literal/annotation lists, including parenthesized lambdas; evaluation/arity are unchanged. Reject comma-only or doubled-comma lists, missing elements, and trailing commas on unparenthesized declarations/resources/bare lambda parameters.
Locals/indexed writes Test local recursion and effectively-final capture; mutate list/array/map contents through fix references, assignment results, ??= for absent map keys, and receiver/index/right-side evaluation order. Reject forward local references, capture of reassigned locals, local visibility/override modifiers, text/safe-index/read-only writes, numeric map compound writes, and illegal assignment conversions.
Defaults Compare omitted calls, explicit null, and fully supplied calls; defaults run once in order and can use earlier parameters. Verify Java omission overloads and virtual dispatch. Reject required-after-default, forward/self parameter references, override redefinition, abstract/external defaults, and erased-signature collisions.
Matching Evaluate subject once; first matching arm wins; exhaustive choice/type/nullable values produce results; partial statement matches do nothing when unmatched. Block results use yield. Reject missing value coverage, missing yield on a completing arm path, incompatible patterns/results, misplaced yield, and duplicate/unreachable arms.
Inheritance Unmarked ordinary class/method can be extended/overridden; fix preserves finality; verify nested sealed permits and explicit child modifiers. Reject inheritance/override of final declarations, unmarked sealed children, illegal modifier combinations, and mismatched inherited signatures.
Tasks Primitive async bodies expose boxed results; -> void/-> Unit produce Task<Unit>/Java Task<Void>; await accepts completion stages. Value task inference retains explicit nullable returns. Reject value-returning tasks with bare return/fallthrough even for nullable targets, ordinary Unit storage, Task<void>, and await in guards/top-level scripts; verify interruption/cancellation/failure wrapping.
KalmDoc Preserve multiline descriptions/tags; resolve aliases, array/wrapper references, facade methods, getters, and defaults. Render the §7 example with the standard JDK doclet. Emit documented warnings for orphan groups, invalid/duplicate tags, missing parameters, ambiguous references, and unknown tags. Literal comment closers cannot terminate generated Java comments.
Script host Execute items once in order; share definitions, display values, avoid replay, and never auto-invoke main. Interactive replacement/reset retain documented semantics. Reject package/test headers, forward references, conflicting -e/-f, and unsupported dependencies. File mode stops at its first failure; prior effects remain.
Everyday library Exercise empty collections, null parsing results, explicit nulls, UTF-16 length, literal text helpers, ordered callbacks, and descending/overflow-boundary ranges. Reject zero steps, invalid clamp bounds/NaN bounds, map length/null-key errors, and invalid separators; verify short-circuit callback counts.
Broader library Verify UTF-8 round trips, EOF, resource closure, UTC versus host zone, monotonic timing, ordered concurrent results, partial windows, and partition stability. Verify missing-file wrapping, no implicit parent creation, invalid window sizes/concurrency/timeouts, timeout races, cancellation propagation, and retained side effects on failures.

Specification maintenance must also retain every original 1.1.0 section and review unchanged features against their original examples. Validate front matter, document links, balanced code fences, grammar references, and package exports; adding a draft must not advance the latest final edition.

References