From 7916b9fd3aada0225b54cdb9961eec720c2d57f2 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:01:30 +0100 Subject: [PATCH] try: return an error that is not nil from the procedure it stands in Report 2026-10.20, section 7.8: try c calls c, whose last result is an ERROR, and if that is not nil the procedure returns it, with zeros for its other results, after the deferred statements; else it is the call's other results. A statement, an operand, or the right of a multiple assignment. try is a reserved word. The seed: sTry in scan, TryCall in parse, TryAlign and TryReturn in gen, which make no entry on the stack of values, so try can stand in the middle of an expression. conform/ has Try and twelve errors; test/err has the dropped values. The tutorial's Errors and the tour's Layers use it. The keyword lists of tools, self/, vim, emacs, the site and raz(7) know try. --- diff --git a/CLAUDE.md b/CLAUDE.md index d45d05e..bab40b5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,7 +102,8 @@ defect, and the library grows only by what breaks no program written for it. A wish for more, the owner's or yours, goes on the list in `PLAN.md`, for a later thaw; it isn't built. v0.6.0 was such a thaw, -by the owner's word: report 2026-10.12; the compiler follows 2026-10.19, +by the owner's word: report 2026-10.12; the compiler follows 2026-10.20, whose `try` returns an error that isn't +nil from the procedure it stands in (10.20, the owner's word), and 2026-10.19, whose `Sys` writes without waiting, for rat's pastes (10.13), and whose blank, `_ := f(x)`, drops a result that is otherwise warned of (10.14), and whose `Math` has `pow`, the logarithms to 2 and 10, diff --git a/PLAN.md b/PLAN.md index fb94ee4..3997953 100644 --- a/PLAN.md +++ b/PLAN.md @@ -17,6 +17,10 @@ compiler lives in `self/`, one raz module to a seed unit, the same names, and has its own targets; nothing in `src/` or `lib/` changes. +The language gained `try` (report 2026-10.20) for this: the parser's +errors will return an `ERROR` that `try` passes up, and `self/Jump.raz`, +which the scanner's `fail` uses now, goes when step 4 lands. + Each unit is ported in the seed's order (leaves first) and tested on its own against the seed's, on the same inputs, since no program can link both. The language and the library are frozen: a gap found goes diff --git a/conform/err/TryConversion.raz b/conform/err/TryConversion.raz new file mode 100644 index 0000000..cefcc18 --- /dev/null +++ b/conform/err/TryConversion.raz @@ -0,0 +1,8 @@ +module TryConversion; +var n: INT; +proc g: ERROR; +begin + n := try INT(n); + return nil; +end; +end TryConversion. diff --git a/conform/err/TryCount.raz b/conform/err/TryCount.raz new file mode 100644 index 0000000..d4a8338 --- /dev/null +++ b/conform/err/TryCount.raz @@ -0,0 +1,12 @@ +module TryCount; +proc f: (INT, ERROR); +begin + return 1, nil; +end; +proc g: ERROR; +var a, b: INT; +begin + a, b := try f(); + return nil; +end; +end TryCount. diff --git a/conform/err/TryDeferred.raz b/conform/err/TryDeferred.raz new file mode 100644 index 0000000..1a225db --- /dev/null +++ b/conform/err/TryDeferred.raz @@ -0,0 +1,11 @@ +module TryDeferred; +proc f: ERROR; +begin + return nil; +end; +proc g: ERROR; +begin + defer try f(); + return nil; +end; +end TryDeferred. diff --git a/conform/err/TryInBody.raz b/conform/err/TryInBody.raz new file mode 100644 index 0000000..7594779 --- /dev/null +++ b/conform/err/TryInBody.raz @@ -0,0 +1,8 @@ +module TryInBody; +proc f: ERROR; +begin + return nil; +end; +begin + try f(); +end TryInBody. diff --git a/conform/err/TryInMain.raz b/conform/err/TryInMain.raz new file mode 100644 index 0000000..9934e0f --- /dev/null +++ b/conform/err/TryInMain.raz @@ -0,0 +1,10 @@ +module TryInMain; +proc f: ERROR; +begin + return nil; +end; +proc main*; +begin + try f(); +end; +end TryInMain. diff --git a/conform/err/TryNeedsArguments.raz b/conform/err/TryNeedsArguments.raz new file mode 100644 index 0000000..22448a6 --- /dev/null +++ b/conform/err/TryNeedsArguments.raz @@ -0,0 +1,11 @@ +module TryNeedsArguments; +proc f(n: INT): ERROR; +begin + return nil; +end; +proc g: ERROR; +begin + try f; + return nil; +end; +end TryNeedsArguments. diff --git a/conform/err/TryNoValue.raz b/conform/err/TryNoValue.raz new file mode 100644 index 0000000..1349e10 --- /dev/null +++ b/conform/err/TryNoValue.raz @@ -0,0 +1,12 @@ +module TryNoValue; +proc f: ERROR; +begin + return nil; +end; +proc g: ERROR; +var n: INT; +begin + n := try f(); + return nil; +end; +end TryNoValue. diff --git a/conform/err/TryNotACall.raz b/conform/err/TryNotACall.raz new file mode 100644 index 0000000..1ca83b9 --- /dev/null +++ b/conform/err/TryNotACall.raz @@ -0,0 +1,8 @@ +module TryNotACall; +var n: INT; +proc g: ERROR; +begin + try n; + return nil; +end; +end TryNotACall. diff --git a/conform/err/TryNotError.raz b/conform/err/TryNotError.raz new file mode 100644 index 0000000..772c774 --- /dev/null +++ b/conform/err/TryNotError.raz @@ -0,0 +1,11 @@ +module TryNotError; +proc f: INT; +begin + return 1; +end; +proc g: ERROR; +begin + try f; + return nil; +end; +end TryNotError. diff --git a/conform/err/TryReturnsNothing.raz b/conform/err/TryReturnsNothing.raz new file mode 100644 index 0000000..89c7b3c --- /dev/null +++ b/conform/err/TryReturnsNothing.raz @@ -0,0 +1,10 @@ +module TryReturnsNothing; +proc f; +begin +end; +proc g: ERROR; +begin + try f(); + return nil; +end; +end TryReturnsNothing. diff --git a/conform/err/TrySeveralValues.raz b/conform/err/TrySeveralValues.raz new file mode 100644 index 0000000..a44de78 --- /dev/null +++ b/conform/err/TrySeveralValues.raz @@ -0,0 +1,12 @@ +module TrySeveralValues; +proc f: (INT, INT, ERROR); +begin + return 1, 2, nil; +end; +proc g: ERROR; +var n: INT; +begin + n := try f(); + return nil; +end; +end TrySeveralValues. diff --git a/conform/err/TryWrongResults.raz b/conform/err/TryWrongResults.raz new file mode 100644 index 0000000..b234cf3 --- /dev/null +++ b/conform/err/TryWrongResults.raz @@ -0,0 +1,11 @@ +module TryWrongResults; +proc f: ERROR; +begin + return nil; +end; +proc g: (INT, BOOL); +begin + try f(); + return 1, true; +end; +end TryWrongResults. diff --git a/conform/run/Try.expect b/conform/run/Try.expect new file mode 100644 index 0000000..387d7c3 --- /dev/null +++ b/conform/run/Try.expect @@ -0,0 +1,23 @@ +one 4: 0 ok, log 92 +one -1: 0 bad, log 0 +one 0: 0 worse, log 0 +two 8: 13 ok, log 0 +two 0: 0 worse, log 0 +many 3: 9 ok, log 0 +15 +many -2: 0 bad, log 0 +0 +whole 4: 49 ok, log 0 +whole -4: 0 bad, log 0 +deferred 6: 103 ok, log 21 +deferred 0: 0 worse, log 21 +among 4 6: 123 ok, log 3 +among 4 0: 0 worse, log 3 +among 0 6: 0 worse, log 3 +shortcut 3: 0 bad, log 0 +shortcut 0: 0 ok, log 0 +through 3: 0 ok, log 0 +through -3: 0 bad, log 0 +loop 5 3: 12 ok, log 0 +loop 2 3: 0 ok, log 0 +loop 5 -2: 0 bad, log 0 diff --git a/conform/run/Try.raz b/conform/run/Try.raz new file mode 100644 index 0000000..d032ca8 --- /dev/null +++ b/conform/run/Try.raz @@ -0,0 +1,178 @@ +module Try; +(* try: an error that isn't nil is returned, with zeros for the other + results; else the call's other results are the value. Every shape of + results, in expressions, among arguments, past deferred statements. *) +import Out; + +const + Bad*: ERROR = "bad"; + Worse*: ERROR = "worse"; + +type Pair = record a, b: I64; end; + +var + log: INT; (* the deferred statements run, as digits *) + handler: proc(n: INT): ERROR; + +(* fails when n is negative *) +proc check(n: INT): ERROR; +begin + if n < 0 then return Bad; end; + return nil; +end; + +(* two words: a value, and Worse when n is zero *) +proc half(n: INT): (INT, ERROR); +begin + if n = 0 then return 7, Worse; end; + return n div 2, nil; +end; + +(* several results, in a temporary *) +proc three(n: INT): (I64, I64, ERROR); +begin + if n < 0 then return 5, 6, Bad; end; + return I64(n), I64(n * 2), nil; +end; + +proc real(n: INT): (F64, ERROR); +begin + if n < 0 then return 1.5, Bad; end; + return F64(n) / 2.0, nil; +end; + +proc pair(n: INT): (Pair, ERROR); +begin + if n < 0 then return {a: 1, b: 2}, Bad; end; + return {a: I64(n), b: I64(n + 1)}, nil; +end; + +proc add(a, b, c: INT): INT; +begin + return a * 100 + b * 10 + c; +end; + +proc yes(n: INT): (BOOL, ERROR); +begin + if n < 0 then return true, Bad; end; + return n > 5, nil; +end; + +proc setup: ERROR; +begin + log := log * 10 + 9; + return nil; +end; + +(* the enclosing procedure ends in a lone ERROR *) +proc one(n: INT): ERROR; +var h: INT; +begin + try check(n); + h := try half(n); + try setup; + log := log * 10 + h; + return nil; +end; + +(* in two words *) +proc two(n: INT): (INT, ERROR); +begin + return 1 + try half(n) * 3, nil; +end; + +(* behind a pointer *) +proc many(n: INT): (I64, F64, ERROR); +var a, b: I64; r: F64; +begin + a, b := try three(n); + r := try real(n); + return a + b, r, nil; +end; + +(* a record result, so the results of the caller are behind a pointer *) +proc whole(n: INT): (Pair, I64, ERROR); +var p: Pair; +begin + p := try pair(n); + return p, p.a + p.b, nil; +end; + +(* deferred statements run on the way out, the error unchanged *) +proc deferred(n: INT): (INT, ERROR); +begin + defer log := log * 10 + 1; + defer log := log * 10 + 2; + return try half(n) + 100, nil; +end; + +(* among the arguments of another call, with a value pushed already *) +proc among(n, m: INT): (INT, ERROR); +begin + defer log := log * 10 + 3; + return add(1, try half(n), try half(m)), nil; +end; + +(* only when its operand is evaluated *) +proc shortcut(n: INT): (BOOL, ERROR); +begin + return (n > 0) and try yes(n - 1 - 100), nil; +end; + +proc through(n: INT): ERROR; +begin + handler := check; + try handler(n); + return nil; +end; + +proc loop(n, off: INT): (INT, ERROR); +var i, sum: INT; +begin + for i := 1 to n do + if try yes(i + off) then sum := sum + try half(i * 2); end; + end; + return sum, nil; +end; + +proc flag(b: BOOL): INT; +begin + if b then return 1; end; + return 0; +end; + +proc show(what: []U8; v: INT; e: ERROR); +begin + Out.str(what); Out.str(": "); Out.int(v); + if e = nil then Out.str(" ok"); else Out.str(" "); Out.str(MSG(e)); end; + Out.str(", log "); Out.int(log); Out.ln; + log := 0; +end; + +proc main*; +var v: INT; e: ERROR; a: I64; f: F64; p: Pair; b: BOOL; +begin + e := one(4); show("one 4", 0, e); + e := one(-1); show("one -1", 0, e); + e := one(0); show("one 0", 0, e); + v, e := two(8); show("two 8", v, e); + v, e := two(0); show("two 0", v, e); + a, f, e := many(3); show("many 3", INT(a), e); Out.int(INT(f * 10.0)); Out.ln; + a, f, e := many(-2); show("many -2", INT(a), e); Out.int(INT(f * 10.0)); Out.ln; + p, a, e := whole(4); show("whole 4", INT(p.a * 10 + a), e); + p, a, e := whole(-4); show("whole -4", INT(p.a * 10 + a), e); + v, e := deferred(6); show("deferred 6", v, e); + v, e := deferred(0); show("deferred 0", v, e); + v, e := among(4, 6); show("among 4 6", v, e); + v, e := among(4, 0); show("among 4 0", v, e); + v, e := among(0, 6); show("among 0 6", v, e); + b, e := shortcut(3); show("shortcut 3", flag(b), e); + b, e := shortcut(0); show("shortcut 0", flag(b), e); + e := through(3); show("through 3", 0, e); + e := through(-3); show("through -3", 0, e); + v, e := loop(5, 3); show("loop 5 3", v, e); + v, e := loop(2, 3); show("loop 2 3", v, e); + v, e := loop(5, -2); show("loop 5 -2", v, e); +end; + +end Try. diff --git a/conform/run/Try.reals b/conform/run/Try.reals new file mode 100644 index 0000000..e69de29 diff --git a/doc/compiler.md b/doc/compiler.md index 55cd8ce..a820852 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1026,6 +1026,31 @@ the end, `return` and `break`. A `return`'s result waits in the frame meanwhile, so that gen's stack is empty when they run. +`try` (report 7.8) is `TryCall`, for the statement, an operand +(`Factor`) and the right of a multiple assignment (`MultiAssign`). It +reads the call as `Designator` does, takes the error, the last of its +results, out of the way into a slot of the frame, and leaves in `x` +the results that are left: none, one value, or a tuple of the others, +`WithoutLast`. Then, in the code before and after, this: + +``` + load [slot]; jz ok ; JumpIf(ok, false) + and rsp, -16 ; TryAlign, if a deferred statement is in force + call deferred... ; RunDefers(0), as for a return + mov rax/rdx or the results ; TryReturn(slot): zeros, and the error last + jmp exit +ok: ... +``` + +Unlike `return`, which is a statement and finds gen's stack empty, +`try` can stand in the middle of an expression, with values waiting +on gen's stack and quadwords pushed for another call's arguments. The +out-of-line code therefore makes no entry on the stack: `TryReturn` +loads registers and jumps, and `TryAlign` makes the machine's stack +even for the deferred statements, which expect it so. The code that +follows is the code for an error that is nil, with the stack as it +was, so no model needs resetting. + Then declarations: `Declarations` reads `const`, `type`, `var`, `proc` and `extern`, each one through `Declaration`, a recovery point, which calls `ConstDecl`, `TypeDecl`, `VarDecl`, `ProcDecl` or `ExternDecl`. `ProcDecl` handles forward declarations, code procedures diff --git a/doc/raz-tutorial.7 b/doc/raz-tutorial.7 index f91e90c..c2b5a14 100644 --- a/doc/raz-tutorial.7 +++ b/doc/raz-tutorial.7 @@ -513,6 +513,16 @@ return INT(n), nil; end; +(* the sum of the numbers in words: the first error ends it *) +proc total(words: [][]U8): (INT, ERROR); +var i, sum: INT; +begin + for i := 0 to LEN(words) - 1 do + sum := sum + try number(words[i]); + end; + return sum, nil; +end; + proc main*; var words: [3][]U8; i, n: INT; err: ERROR; begin @@ -525,6 +535,10 @@ end; Out.ln; end; + n, err := total(["1", "2", "3"]); + Out.int(n); Out.ln; + n, err := total(words); + if err # nil then Out.str(MSG(err)); Out.ln; end; end; end Errors. @@ -533,6 +547,8 @@ 42 empty not a number up to 1000 +6 +nothing to read .Ed .Pp A procedure that can fail returns an @@ -550,6 +566,30 @@ An exported one, as .Cm Empty is here, lets the callers tell it from the others. +.Pp +A caller that can't deal with an error passes it on to its own caller +with +.Cm try , +as +.Cm total +does: if the call returned an error that isn't +.Cm nil , +the procedure +.Cm try +stands in returns that error, with zero for its other results, and +otherwise +.Cm try +is the call's other results, here a number. +.Cm try +is a +.Cm return , +written where the call is: it has no handler, keeps no state and +unwinds nothing, so every place a procedure can leave is in its text. +The procedure it stands in must itself end in an +.Cm ERROR , +so +.Cm main , +which returns none, tests each error and deals with it. raz has no exceptions. .Sh 9. DEFER .Bd -literal -offset indent diff --git a/doc/raz.7 b/doc/raz.7 index c73a77e..3563ba2 100644 --- a/doc/raz.7 +++ b/doc/raz.7 @@ -63,8 +63,8 @@ .Bd -literal -offset indent and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of -or packed proc record repeat return set shl shr then to type -until var variant VOLATILE while xor +or packed proc record repeat return set shl shr then to try +type until var variant VOLATILE while xor .Ed .Pp The basic types, diff --git a/doc/raz.md b/doc/raz.md index faef334..2a54ffd 100644 --- a/doc/raz.md +++ b/doc/raz.md @@ -9,12 +9,13 @@ This report defines the language. It is short on purpose. Whatever it doesn't allow, raz doesn't have. -This is version 2026-10.19 of the report; section 12 says what each +This is version 2026-10.20 of the report; section 12 says what each version changed. 2026-10.11 and 2026-10.12 are a thaw the owner chose, for a language anyone can build again. They break programs written for 2026-10.10 and before: for 2026-10.9, say, the report of compiler 0.5.0, the last release before them; and 2026-10.12 breaks code -procedures written for 2026-10.11. +procedures written for 2026-10.11. 2026-10.20 is a third, for `try` +(section 7.8); it breaks a program that has a name `try`. The language is frozen, softly, from this version on: it changes only to mend a defect, and its library grows only by what breaks no program @@ -59,8 +60,8 @@ ``` and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record -repeat return set shl shr then to type until var variant VOLATILE while -xor +repeat return set shl shr then to try type until var variant VOLATILE +while xor ``` `static`, in `link static;` (section 3), isn't one. @@ -499,6 +500,10 @@ const NotFound*: ERROR = "not found"; ``` +An `ERROR` is how a procedure says it failed: by convention the last +of its results, and `nil` when nothing failed. A caller that can't +deal with a failure itself passes it on with `try` (section 7.8). + `ERROR` is a basic type as big as an address. A value of it is made only by a constant declared as above, and each such declaration makes an error different from every other, whatever its message: two modules that @@ -588,15 +593,16 @@ | "not" Factor | "~" Factor | "[" [ Expr { "," Expr } ] "]" | "{" [ Element { "," Element } ] "}" - | "^" [ "VOLATILE" ] Type "(" Expr ")" . + | "^" [ "VOLATILE" ] Type "(" Expr ")" + | "try" Designator . Element = Expr | ident ":" Expr . Designator = QualIdent { Selector } . Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]" | "(" [ Expr { "," Expr } ] ")" . ``` -The operators bind in the order of the grammar: `not` and `~` most -tightly, then the multiplying operators, then the adding ones, then +The operators bind in the order of the grammar: `not`, `~` and `try` +(section 7.8) most tightly, then the multiplying operators, then the adding ones, then the relations, then `and`, then `or`. So `a + b * c = d` is `(a + (b * c)) = d`, `x & 0FH = 0` is `(x & 0FH) = 0`, and `i < n and a[i] # 0 or done` is `((i < n) and (a[i] # 0)) or done`. A @@ -607,7 +613,7 @@ A pointer to a record isn't the record: its fields are `p^.f`, never `p.f`, and the elements of a pointer to an array are `p^[i]`. A -statement starts with a name, so `^T(x)^ := v` isn't one. +statement starts with a name or `try`, so `^T(x)^ := v` isn't one. ### 6.1 Integers @@ -819,7 +825,8 @@ | "match" Expr "of" { "|" Arm } "end" | "return" [ Expr { "," Expr } ] | "break" - | "defer" Statement . + | "defer" Statement + | "try" Designator . Arm = ( ident [ "(" ident { "," ident } ")" ] | Label { "," Label } | "else" ) ":" Statements . Label = Expr [ ".." Expr ] . @@ -983,10 +990,105 @@ ``` `return e;` evaluates `e` before the deferred statements run. A -deferred statement can't contain `return`, `break` or `defer` that -would leave it. A failed check, `Rt.exit` and `Sys.exit` end the +deferred statement can't contain `return`, `break`, `defer` or `try` +that would leave it. A failed check, `Rt.exit` and `Sys.exit` end the program without running the deferred statements still pending. + +### 7.8 Try + +A procedure that can fail returns an `ERROR` as its last result +(section 5.8), `nil` when it didn't. A caller that can't deal with the +failure passes it on to its own caller, which `try` does in a word: +``` +proc total(words: [][]U8): (INT, ERROR); +var i, sum: INT; +begin + for i := 0 to LEN(words) - 1 do + sum := sum + try number(words[i]); + end; + return sum, nil; +end; +``` + +`try c`, where `c` is a call (below) of a procedure whose last result +is an `ERROR`, makes the call and looks at that error. If it is `nil`, +the program goes on, and `try c` is what `c` returned without the +error. If it isn't, the procedure `try` stands in returns at once, as +`return` does (section 7.3): its last result is that error, and every +other result is zero, as a variable of its type starts (section 4). +Nothing more of the statement `try` stands in is done; in the example, +`sum` isn't assigned. So + +``` +x := try f(a); +``` + +is, with `e` a variable the program can't name, and `0` standing for +a zero of each of the procedure's other results: + +``` +x, e := f(a); +if e # nil then return 0, e; end; +``` + +The error is the one `c` returned, and compares with `=` as it did +there. `try` has no handler and keeps no state: it is a `return`, +written where the call is, so that every place a procedure can leave is +in its text. A program that means to deal with an error tests it, as +section 5.8 shows. + +**What `try` is applied to.** `c` is a designator that ends in a call: +`f(x)`, `Mod.f(x)`, `p^.next(x)`, or a call through a variable of +procedure type. Where the procedure has no parameters its parentheses +may be left out, as in a statement (section 7.1), and `try` calls it: +`try setup;`. A conversion, a built-in procedure (section 6.8) and the +case of a variant are written like calls and aren't procedures'; `try` +can't be applied to them. + +**What `try c` is.** `c`'s results but the last. + +- With none, `try c` isn't a value and stands only as a statement: + `try flush;`. +- With one, it is a value of that type, an operand wherever `c` + would be: `n := try number(s);`, `sum + try number(s)`, + `if try ready(fd) then`. Like `not`, it applies to the factor after + it: `try f(x) + 1` is `(try f(x)) + 1`. +- With several, it stands only on the right of a multiple assignment, + as `c` itself would, with a target for each: `a, b := try f(x);`. + +As a statement, `try c;` drops the values of `c` that it has, and a +dropped value is warned of as a call that drops a result is (section +10); `_ := try c;` and `a, _ := try c;` say it is meant (section 7.1). +The error is never dropped: `try` is the way of passing it on. + +**Where `try` may stand.** Every use of `try` is an error unless: + +- the procedure it stands in has an `ERROR` as its last result. A + module's body, and a procedure with no results, such as `proc + main*;`, have none: there an error is dealt with where it is found, + by a test; +- the last result of the procedure `c` calls is an `ERROR`; +- it is not inside a deferred statement, which `try` would leave + (section 7.7). + +A generic module is checked in each instance (section 3), so a +procedure of an instance whose last result, by its type arguments, is +no `ERROR` and uses `try` is an error in that instance. + +**Order.** The arguments of `c` are evaluated from left to right, then +`c` is called, and then its error is looked at (section 7.5). The +designators on the left of an assignment are evaluated before its +right side as always, so in `a[i()] := try g()`, `i` is called, then +`g`; if `g` fails, nothing is assigned. A `try` in the right operand +of `and` or `or` is reached only when that operand is evaluated +(section 6.2). + +**Deferred statements.** When `try` returns, the statements deferred +in the procedure and not yet run are run, the last first, as for a +`return` (section 7.7), after the error and the zero results have been +chosen; no deferred statement can change them. + ## 8. Procedures ``` @@ -1016,7 +1118,9 @@ that returns several values can only stand on the right of a multiple assignment, alone as a statement, or alone after `return` in a procedure whose results are of the same types, in the same order, -which then returns them as they are: `return divmod(n, 2);`. +which then returns them as they are: `return divmod(n, 2);`. A +procedure that can fail has an `ERROR` as its last result (section +5.8), which `try` passes on (section 7.8). ``` module Divide; @@ -1933,6 +2037,10 @@ - **2026-10.18.** A code procedure takes and returns slices (section 8). - **2026-10.19.** The library gains `Bytes` (section 11). +- **2026-10.20.** `try`: a call of a procedure whose last result is an + `ERROR`, which makes the procedure it stands in return that error + when it isn't `nil` (sections 2, 5.8, 6, 7.8 and appendix B). `try` + becomes a reserved word, which breaks a program with a name `try`. ## Appendix A. What an implementation chooses @@ -2057,7 +2165,8 @@ | "not" Factor | "~" Factor | "[" [ Expr { "," Expr } ] "]" | "{" [ Element { "," Element } ] "}" - | "^" [ "VOLATILE" ] Type "(" Expr ")" . + | "^" [ "VOLATILE" ] Type "(" Expr ")" + | "try" Designator . Element = Expr | ident ":" Expr . Designator = QualIdent { Selector } . Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]" @@ -2075,7 +2184,8 @@ | "match" Expr "of" { "|" Arm } "end" | "return" [ Expr { "," Expr } ] | "break" - | "defer" Statement . + | "defer" Statement + | "try" Designator . Arm = ( ident [ "(" ident { "," ident } ")" ] | Label { "," Label } | "else" ) ":" Statements . Label = Expr [ ".." Expr ] . diff --git a/editor/emacs/raz-mode.el b/editor/emacs/raz-mode.el index e264480..2df17d8 100644 --- a/editor/emacs/raz-mode.el +++ b/editor/emacs/raz-mode.el @@ -24,8 +24,8 @@ '("and" "begin" "break" "by" "code" "const" "defer" "div" "do" "else" "elsif" "end" "extern" "for" "forward" "if" "import" "in" "link" "match" "mod" "module" "not" "of" "or" "packed" "proc" "record" - "repeat" "return" "set" "shl" "shr" "then" "to" "type" "until" "var" - "variant" "VOLATILE" "while" "xor")) + "repeat" "return" "set" "shl" "shr" "then" "to" "try" "type" "until" + "var" "variant" "VOLATILE" "while" "xor")) (defconst raz-types '("I8" "I16" "I32" "I64" "INT" "UINT" "U8" "U16" "U32" "U64" "BOOL" "F32" "F64" "ERROR")) diff --git a/editor/vim/syntax/raz.vim b/editor/vim/syntax/raz.vim index 925e712..cc39dda 100644 --- a/editor/vim/syntax/raz.vim +++ b/editor/vim/syntax/raz.vim @@ -10,8 +10,8 @@ syntax keyword razKeyword and begin break by code const defer div do else syntax keyword razKeyword elsif end extern for forward if import in link syntax keyword razKeyword match mod module not of or packed proc record -syntax keyword razKeyword repeat return set shl shr then to type until var -syntax keyword razKeyword variant VOLATILE while xor +syntax keyword razKeyword repeat return set shl shr then to try type until +syntax keyword razKeyword var variant VOLATILE while xor syntax keyword razType I8 I16 I32 I64 INT UINT U8 U16 U32 U64 BOOL F32 F64 ERROR syntax keyword razBuiltin SIZE ADR LEN NEW MSG SYSCALL FENCE CAS XCHG XADD syntax keyword razBuiltin ARGC ARGV INC DEC diff --git a/self/Scan.raz b/self/Scan.raz index 4ddc262..ba4c449 100644 --- a/self/Scan.raz +++ b/self/Scan.raz @@ -26,7 +26,7 @@ sAnd, sBegin, sBreak, sBy, sCode, sConst, sDefer, sDiv, sDo, sElse, sElsif, sEnd, sExtern, sFor, sForward, sIf, sImport, sIn, sLink, sMatch, sMod, sModule, sNot, sOf, sOr, sPacked, sProc, sRecord, - sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sType, sUntil, sVar, + sRepeat, sReturn, sSet, sShl, sShr, sThen, sTo, sTry, sType, sUntil, sVar, sVariant, sVolatile, sWhile, sXor, sEof); @@ -47,14 +47,15 @@ const MaxIdent* = 63; MaxStr* = 65536; - NumWords = 42; + NumWords = 43; NumOps = 28; words: [NumWords][]U8 = [ "and", "begin", "break", "by", "code", "const", "defer", "div", "do", "else", "elsif", "end", "extern", "for", "forward", "if", "import", "in", "link", "match", "mod", "module", "not", "of", "or", "packed", "proc", "record", "repeat", "return", "set", "shl", "shr", "then", - "to", "type", "until", "var", "variant", "VOLATILE", "while", "xor"]; + "to", "try", "type", "until", "var", "variant", "VOLATILE", "while", + "xor"]; (* sPlus to sBlank *) ops: [NumOps][]U8 = [ "+", "-", "*", "/", "=", "#", "<", "<=", ">", ">=", diff --git a/self/test/genlex.py b/self/test/genlex.py index 5aa49e6..f2607ea 100644 --- a/self/test/genlex.py +++ b/self/test/genlex.py @@ -22,7 +22,7 @@ "tab": "\t\tx := @;\n", "multi": "x := \"\u00e9\u00e9\u00e9\" + @;\n", "ident64": "x" * 64 + ";\n", "ident63": "x" * 63 + ";\n", "bigstr": "x := \"" + "a" * 70000 + "\";\n", "empty": "", "nonl": "x := y", "ops": "+ - * / = # < <= > >= := : ; , . .. ... ( ) [ ] { } ^ & ~ | _ __ _a\n", - "words": "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to type until var variant VOLATILE while xor Volatile\n", + "words": "and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc record repeat return set shl shr then to try type until var variant VOLATILE while xor Volatile\n", } for k, v in cases.items(): open(f"{d}/{k}.raz", "wb").write(v.encode("utf-8", "surrogateescape") if isinstance(v, str) else v) diff --git a/site/build.py b/site/build.py index af605bf..75c6240 100644 --- a/site/build.py +++ b/site/build.py @@ -48,7 +48,7 @@ KEYWORDS = set("""and begin break by code const defer div do else elsif end extern for forward if import in link match mod module not of or packed proc -record repeat return set shl shr then to type until var variant VOLATILE +record repeat return set shl shr then to try type until var variant VOLATILE while xor""".split()) PREDECLARED = set("""INT UINT I8 I16 I32 I64 U8 U16 U32 U64 F32 F64 BOOL ERROR true false nil LEN ADR NEW SIZE INC DEC MSG XADD CAS XCHG""".split()) diff --git a/site/content/tour/10-errors.txt b/site/content/tour/10-errors.txt index 03c288d..31294ad 100644 --- a/site/content/tour/10-errors.txt +++ b/site/content/tour/10-errors.txt @@ -53,7 +53,14 @@ ## Passing errors up -When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. There is no hidden unwinding: the `return` is right there. +When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. Written out, that is a test and a `return` after each call: + +```raz +x, err := value(a); +if err # nil then return 0, err; end; +``` + +`try` says the same in a word. `x := try value(a)` calls `value` and, if the error it returned isn't `nil`, returns that error from the procedure it stands in, with zero for that procedure's other results; otherwise it is `value`'s number. There is no hidden unwinding and no handler: `try` is a `return`, written where the call is, and a procedure that uses it must end in an `ERROR` itself, so its signature says it can fail. `main` returns none, so it tests its errors and deals with them. ```raz Layers run module Layers; @@ -71,15 +78,10 @@ return INT(n), nil; end; -(* the sum of the values of two lines *) +(* the sum of the values of two lines: the first error ends it *) proc sum(a, b: []U8): (INT, ERROR); -var x, y: INT; err: ERROR; begin - x, err := value(a); - if err # nil then return 0, err; end; (* passed up *) - y, err := value(b); - if err # nil then return 0, err; end; - return x + y, nil; + return try value(a) + try value(b), nil; end; proc main*; diff --git a/site/public/advanced/static.html b/site/public/advanced/static.html index c568cb9..c4325cf 100644 --- a/site/public/advanced/static.html +++ b/site/public/advanced/static.html @@ -65,7 +65,7 @@ $ ldd Bare not a dynamic executable $ ls -l Bare | awk '{print $5, "bytes"}' -26176 bytes +26184 bytes
It is statically linked: no interpreter, no shared libraries, no libc. ldd says so.
strace lists every system call a program makes. This is the whole of it:
$ raz Lean.raz
$ raz Heavy.raz
$ ls -l Lean Heavy | awk '{print $9, $5}'
-Heavy 28384
-Lean 28376
+Heavy 28392
+Lean 28384
The sizes differ by a few bytes, not by the hundreds of kilobytes that the table and the procedure would take: they are not in the executable at all. You can link in a library module without worrying what else it offers.
-s leaves out what is there for finding faults: the symbols and line numbers, the places a failure is told by, and the profiler. It is for the final build of a size-conscious program; the default keeps them so that gdb and failure messages work.
$ raz -s -o Lean-stripped Lean.raz
$ ls -l Lean Lean-stripped | awk '{print $9, $5}'
-Lean 28376
+Lean 28384
Lean-stripped 6720
$ ./Lean-stripped
same program
diff --git a/site/public/spec.html b/site/public/spec.html
index eb5d4f2..c460eaf 100644
--- a/site/public/spec.html
+++ b/site/public/spec.html
@@ -36,7 +36,7 @@
raz is a small systems language, first made for x86-64 Linux. A raz program can lay a record over a device’s registers, read and write a device’s memory exactly as written, take part in lock-free algorithms, make system calls and call C libraries. It has no garbage collector and no hidden run time: what the program does is what its text says.
This report defines the language. It is short on purpose. Whatever it doesn’t allow, raz doesn’t have.
-This is version 2026-10.19 of the report; section 12 says what each version changed. 2026-10.11 and 2026-10.12 are a thaw the owner chose, for a language anyone can build again. They break programs written for 2026-10.10 and before: for 2026-10.9, say, the report of compiler 0.5.0, the last release before them; and 2026-10.12 breaks code procedures written for 2026-10.11.
+This is version 2026-10.20 of the report; section 12 says what each version changed. 2026-10.11 and 2026-10.12 are a thaw the owner chose, for a language anyone can build again. They break programs written for 2026-10.10 and before: for 2026-10.9, say, the report of compiler 0.5.0, the last release before them; and 2026-10.12 breaks code procedures written for 2026-10.11. 2026-10.20 is a third, for try (section 7.8); it breaks a program that has a name try.
The language is frozen, softly, from this version on: it changes only to mend a defect, and its library grows only by what breaks no program written for it. What anyone wishes it had waits on a list, for a later thaw.
module Hello;
@@ -55,8 +55,8 @@
Reserved words are lowercase, except VOLATILE:
and begin break by code const defer div do else elsif end extern for
forward if import in link match mod module not of or packed proc record
-repeat return set shl shr then to type until var variant VOLATILE while
-xor
+repeat return set shl shr then to try type until var variant VOLATILE
+while xor
static, in link static; (section 3), isn’t one.
Predeclared names are the basic types (section 5.1), ERROR, true, false, nil and the built-in procedures (section 6.8). They belong to a scope around every module, so a module or a procedure may declare the same name for something else, which hides them there.
Numbers. 123 is decimal. 0FFH is hexadecimal: it starts with a digit, its digits are 0 to 9 and A to F, and it ends in H, all in capitals. 1.5 and 2.0E-3 are reals; a real always has a digit on both sides of its point, and its exponent, if it has one, is E, a sign if wanted, and digits. A decimal number above the largest I64, or a hexadecimal one above the largest U64, is an error.
set of E, for an enumeration E of at most 64 names, holds any choice of E’s names: bit i stands for the name at position i. It takes the smallest of 1, 2, 4 and 8 bytes that has a bit for each name, so a set can stand for a C flags word.
const NotFound*: ERROR = "not found";
+An ERROR is how a procedure says it failed: by convention the last of its results, and nil when nothing failed. A caller that can’t deal with a failure itself passes it on with try (section 7.8).
ERROR is a basic type as big as an address. A value of it is made only by a constant declared as above, and each such declaration makes an error different from every other, whatever its message: two modules that both declare "not found" have two different errors. A generic module makes its errors once per instance. nil is no error.
Errors compare with = and # only, by which declaration made them, never by their message. MSG(e) is the message, a []U8; MSG(nil) is "".
proc find*(key: I64): (^Node, ERROR);
@@ -266,14 +267,15 @@
| "not" Factor | "~" Factor
| "[" [ Expr { "," Expr } ] "]"
| "{" [ Element { "," Element } ] "}"
- | "^" [ "VOLATILE" ] Type "(" Expr ")" .
+ | "^" [ "VOLATILE" ] Type "(" Expr ")"
+ | "try" Designator .
Element = Expr | ident ":" Expr .
Designator = QualIdent { Selector } .
Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
| "(" [ Expr { "," Expr } ] ")" .
-The operators bind in the order of the grammar: not and ~ most tightly, then the multiplying operators, then the adding ones, then the relations, then and, then or. So a + b * c = d is (a + (b * c)) = d, x & 0FH = 0 is (x & 0FH) = 0, and i < n and a[i] # 0 or done is ((i < n) and (a[i] # 0)) or done. A unary minus applies to the first term: -a * b is -(a * b).
The operators bind in the order of the grammar: not, ~ and try (section 7.8) most tightly, then the multiplying operators, then the adding ones, then the relations, then and, then or. So a + b * c = d is (a + (b * c)) = d, x & 0FH = 0 is (x & 0FH) = 0, and i < n and a[i] # 0 or done is ((i < n) and (a[i] # 0)) or done. A unary minus applies to the first term: -a * b is -(a * b).
and, or and not are for BOOLs only; &, |, xor and ~ are for integers only.
A pointer to a record isn’t the record: its fields are p^.f, never p.f, and the elements of a pointer to an array are p^[i]. A statement starts with a name, so ^T(x)^ := v isn’t one.
A pointer to a record isn’t the record: its fields are p^.f, never p.f, and the elements of a pointer to an array are p^[i]. A statement starts with a name or try, so ^T(x)^ := v isn’t one.
Both operands of + - * div mod & | xor, and of a relation, have the same integer type, or one is an untyped constant that takes the other’s type, which it must fit. So do v and k in INC(v, k) and DEC(v, k). The result has that type and wraps around at its width: in U8, 200 + 100 is 44. A unary minus wraps too: for x of an unsigned type, -x is 0 - x. Two integer types are never mixed, whatever their sizes: with i: I64, i < LEN(s) is an error, and i should be an INT.
Where the report asks for an integer and names no type, as an index, a slice’s bound, a shift’s count, a pointer’s offset i in p + i, or a conversion’s operand, any integer type will do, and its value is taken. On a target whose INT is narrower, a pointer’s offset is cut to an INT.
return e; evaluates e before the deferred statements run. A deferred statement can’t contain return, break or defer that would leave it. A failed check, Rt.exit and Sys.exit end the program without running the deferred statements still pending.
return e; evaluates e before the deferred statements run. A deferred statement can’t contain return, break, defer or try that would leave it. A failed check, Rt.exit and Sys.exit end the program without running the deferred statements still pending.
A procedure that can fail returns an ERROR as its last result (section 5.8), nil when it didn’t. A caller that can’t deal with the failure passes it on to its own caller, which try does in a word:
proc total(words: [][]U8): (INT, ERROR);
+var i, sum: INT;
+begin
+ for i := 0 to LEN(words) - 1 do
+ sum := sum + try number(words[i]);
+ end;
+ return sum, nil;
+end;
+try c, where c is a call (below) of a procedure whose last result is an ERROR, makes the call and looks at that error. If it is nil, the program goes on, and try c is what c returned without the error. If it isn’t, the procedure try stands in returns at once, as return does (section 7.3): its last result is that error, and every other result is zero, as a variable of its type starts (section 4). Nothing more of the statement try stands in is done; in the example, sum isn’t assigned. So
x := try f(a);
+is, with e a variable the program can’t name, and 0 standing for a zero of each of the procedure’s other results:
x, e := f(a);
+if e # nil then return 0, e; end;
+The error is the one c returned, and compares with = as it did there. try has no handler and keeps no state: it is a return, written where the call is, so that every place a procedure can leave is in its text. A program that means to deal with an error tests it, as section 5.8 shows.
What try is applied to. c is a designator that ends in a call: f(x), Mod.f(x), p^.next(x), or a call through a variable of procedure type. Where the procedure has no parameters its parentheses may be left out, as in a statement (section 7.1), and try calls it: try setup;. A conversion, a built-in procedure (section 6.8) and the case of a variant are written like calls and aren’t procedures’; try can’t be applied to them.
What try c is. c’s results but the last.
try c isn’t a value and stands only as a statement: try flush;.c would be: n := try number(s);, sum + try number(s), if try ready(fd) then. Like not, it applies to the factor after it: try f(x) + 1 is (try f(x)) + 1.c itself would, with a target for each: a, b := try f(x);.As a statement, try c; drops the values of c that it has, and a dropped value is warned of as a call that drops a result is (section 10); _ := try c; and a, _ := try c; say it is meant (section 7.1). The error is never dropped: try is the way of passing it on.
Where try may stand. Every use of try is an error unless:
ERROR as its last result. A module’s body, and a procedure with no results, such as proc main*;, have none: there an error is dealt with where it is found, by a test;c calls is an ERROR;try would leave (section 7.7).A generic module is checked in each instance (section 3), so a procedure of an instance whose last result, by its type arguments, is no ERROR and uses try is an error in that instance.
Order. The arguments of c are evaluated from left to right, then c is called, and then its error is looked at (section 7.5). The designators on the left of an assignment are evaluated before its right side as always, so in a[i()] := try g(), i is called, then g; if g fails, nothing is assigned. A try in the right operand of and or or is reached only when that operand is evaluated (section 6.2).
Deferred statements. When try returns, the statements deferred in the procedure and not yet run are run, the last first, as for a return (section 7.7), after the error and the zero results have been chosen; no deferred statement can change them.
ProcDeclaration = "proc" IdentDef Signature ";"
( "forward" | { LocalDeclaration } "begin" Statements "end" [ ident ]
@@ -548,7 +584,7 @@
Results = Type | "(" Type { "," Type } ")" .
A procedure without parameters may leave out the parentheses, both where it is declared (proc main*;) and where it is called (Out.ln). Used without parentheses in an expression, a procedure is a procedure value, not a call.
Parameters. A value parameter is a copy: the procedure may change it, and the caller’s variable stays as it was. A var parameter is the caller’s variable itself; its argument must be a variable of exactly the parameter’s type.
Results. A procedure returns nothing, one value, or several. A call that returns several values can only stand on the right of a multiple assignment, alone as a statement, or alone after return in a procedure whose results are of the same types, in the same order, which then returns them as they are: return divmod(n, 2);.
Results. A procedure returns nothing, one value, or several. A call that returns several values can only stand on the right of a multiple assignment, alone as a statement, or alone after return in a procedure whose results are of the same types, in the same order, which then returns them as they are: return divmod(n, 2);. A procedure that can fail has an ERROR as its last result (section 5.8), which try passes on (section 7.8).
module Divide;
import Out;
@@ -1059,6 +1095,7 @@
2026-10.17. COPY copies the elements of one array or slice to another as a block (section 6.8).
2026-10.18. A code procedure takes and returns slices (section 8).
2026-10.19. The library gains Bytes (section 11).
+2026-10.20. try: a call of a procedure whose last result is an ERROR, which makes the procedure it stands in return that error when it isn’t nil (sections 2, 5.8, 6, 7.8 and appendix B). try becomes a reserved word, which breaks a program with a name try.
Appendix A. What an implementation chooses
Everything in this report binds every implementation of raz, except what follows, which each chooses for itself and documents. This compiler’s choices are in doc/compiler.md, under “This compiler’s choices”. The programs in conform/ are how an implementation shows that it follows this report: it passes them all, its reals aside where its target has none; conform/check.sh runs them.
@@ -1133,7 +1170,8 @@
| "not" Factor | "~" Factor
| "[" [ Expr { "," Expr } ] "]"
| "{" [ Element { "," Element } ] "}"
- | "^" [ "VOLATILE" ] Type "(" Expr ")" .
+ | "^" [ "VOLATILE" ] Type "(" Expr ")"
+ | "try" Designator .
Element = Expr | ident ":" Expr .
Designator = QualIdent { Selector } .
Selector = "." ident | "^" | "[" Expr [ ".." Expr ] "]"
@@ -1151,7 +1189,8 @@
| "match" Expr "of" { "|" Arm } "end"
| "return" [ Expr { "," Expr } ]
| "break"
- | "defer" Statement .
+ | "defer" Statement
+ | "try" Designator .
Arm = ( ident [ "(" ident { "," ident } ")" ]
| Label { "," Label } | "else" ) ":" Statements .
Label = Expr [ ".." Expr ] .
diff --git a/site/public/tour/errors.html b/site/public/tour/errors.html
index 98a30ba..5d5209a 100644
--- a/site/public/tour/errors.html
+++ b/site/public/tour/errors.html
@@ -56,6 +56,16 @@
return INT(n), nil;
end;
+(* the sum of the numbers in words: the first error ends it *)
+proc total(words: [][]U8): (INT, ERROR);
+var i, sum: INT;
+begin
+ for i := 0 to LEN(words) - 1 do
+ sum := sum + try number(words[i]);
+ end;
+ return sum, nil;
+end;
+
proc main*;
var words: [3][]U8; i, n: INT; err: ERROR;
begin
@@ -68,12 +78,18 @@
end;
Out.ln;
end;
+ n, err := total(["1", "2", "3"]);
+ Out.int(n); Out.ln;
+ n, err := total(words);
+ if err # nil then Out.str(MSG(err)); Out.ln; end;
end;
end Errors.
42
empty
not a number up to 1000
+6
+nothing to read
A procedure that can fail returns an ERROR beside its result, and nil when it didn't. Each ERROR constant is an error of its own, compared with = by which declaration made it, never by its message; MSG(err) is the message. An exported one, as Empty is here, lets the callers tell it from the others. raz has no exceptions, so every failure is visible in the signature and handled where the call is written.
When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. There is no hidden unwinding: the return is right there.
When a procedure can't do anything useful with an error, it returns it, so the first caller that can decide gets it. Written out, that is a test and a return after each call:
``raz x, err := value(a); if err # nil then return 0, err; end; ``
try says the same in a word. x := try value(a) calls value and, if the error it returned isn't nil, returns that error from the procedure it stands in, with zero for that procedure's other results; otherwise it is value's number. There is no hidden unwinding and no handler: try is a return, written where the call is, and a procedure that uses it must end in an ERROR itself, so its signature says it can fail. main returns none, so it tests its errors and deals with them.
module Layers;
import Out, Str;
@@ -137,15 +155,10 @@
return INT(n), nil;
end;
-(* the sum of the values of two lines *)
+(* the sum of the values of two lines: the first error ends it *)
proc sum(a, b: []U8): (INT, ERROR);
-var x, y: INT; err: ERROR;
begin
- x, err := value(a);
- if err # nil then return 0, err; end; (* passed up *)
- y, err := value(b);
- if err # nil then return 0, err; end;
- return x + y, nil;
+ return try value(a) + try value(b), nil;
end;
proc main*;
diff --git a/site/public/tour/hello.html b/site/public/tour/hello.html
index 1870137..6c85aac 100644
--- a/site/public/tour/hello.html
+++ b/site/public/tour/hello.html
@@ -70,7 +70,7 @@
$ raz run Quiet.raz
hello, again
$ ls -l Quiet | awk '{print $5, "bytes"}'
-28384 bytes
+28392 bytes
The program is a static executable with no run time besides the code it uses, so it is a few kilobytes, and runs without any library installed.
Out can writeOut is the library's buffered output. It writes strings, single characters, numbers in decimal or hexadecimal, and a line feed. A string is written as it is, with \n for a line feed, \t for a tab, \" and \\.