From 0d7e2bdb0f6e45319960d99d3e331e8c9d508fd4 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:19:46 +0100 Subject: [PATCH] Go on after an error: every error in a run, none twice Each statement and declaration is a recovery point (setjmp): an error jumps back, the scanner rereads the construct and skips to its end, and parsing goes on. Undeclared names become poison where used; errors in constructs that use poison aren't reported, nor a second one at one place. A symbol at a line's start ends a skip and gives up the proc. Lexical errors and a module with errors stop the run. tools/Mutate.raz mutates a symbol of each program; make check fails on a crash, a status > 1 or two errors at one place. --- diff --git a/PLAN.md b/PLAN.md index e543299..7e186ff 100644 --- a/PLAN.md +++ b/PLAN.md @@ -227,12 +227,18 @@ the previous symbol's end. The machinery, *main*; moving each of the 200 `Mark` calls onto the right position, *agent*, one per file. -- [ ] 22. Going on after an error. A poison type that every check - accepts without a word, so one mistake makes one message; a name - not declared is declared as poison where it is first used; after - a syntax error the parser skips to the next `proc` or the end of - the module; code is still generated, then thrown away; at most - 20 errors. A module with errors stops the run after it. *main*. +- [x] 22. Going on after an error. Each statement and declaration is + a recovery point (`setjmp`): an error jumps back to it, the + scanner rereads it from its start and skips to its end, and the + parser carries on with the next; no error site goes on past its + error, so none needs reviewing. A name not declared is declared + with a poison type where it is first used, as are the names of a + declaration with an error, and errors in a construct that uses + poison aren't reported. A symbol at the start of a line ends a + skip: it starts the next declaration, and its procedure is given + up. Code is still generated, then thrown away; at most 20 errors; + an error in the text, or a module with errors, stops the run. + *main*. `tools/Mutate.raz`, which deletes, doubles and swaps symbols in the tests that compile; `make check` runs it with fixed seeds and fails on a crash or two messages at one place. Writing it @@ -245,7 +251,8 @@ first; *main* reviews the wording as a whole. - [ ] 24. Notes and help. Objects remember where they are declared: "declared here", "the first one is here", "the signature is - here". Did you mean: the closest name by edit distance in the + here". The checks on `main` in `raz.pas` point at + it, so that every error has a place (the fuzzer finds them). Did you mean: the closest name by edit distance in the scopes in reach, in a module's exports, among the built-ins (`len` for `LEN`). Slips from other languages: `!=`, `==`, `=` for `:=`, `&&`, `||`, `!`, `elif`, a missing `then` or `do`, a diff --git a/doc/compiler.md b/doc/compiler.md index 98e0226..0bfe9f7 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -8,12 +8,12 @@ | File | Lines | Code | What | |---|---|---|---| -| `src/diag.pas` | 243 | 174 | Messages: positions, source excerpts, colour, counts | -| `src/scan.pas` | 584 | 495 | Symbols, literals, comments, positions | -| `src/sym.pas` | 510 | 424 | Types, objects, scopes, layout | +| `src/diag.pas` | 248 | 177 | Messages: positions, source excerpts, colour, counts | +| `src/scan.pas` | 612 | 509 | Symbols, literals, comments, positions | +| `src/sym.pas` | 526 | 437 | Types, objects, scopes, layout | | `src/x64.pas` | 682 | 548 | Code buffer, chunks, fixups, line notes, instruction encoder | | `src/gen.pas` | 1,468 | 1,281 | Items: loading, storing, copying, frames, calls | -| `src/parse.pas` | 1,851 | 1,720 | Declarations, statements, expressions, built-ins | +| `src/parse.pas` | 2,053 | 1,873 | Declarations, statements, expressions, built-ins, recovery | | `src/link.pas` | 131 | 95 | Tree shaking, layout, patching | | `src/elf.pas` | 425 | 351 | Static and dynamic ELF, symbol table, line numbers | | `src/raz.pas` | 219 | 172 | The command line, the entry points | @@ -144,7 +144,10 @@ and `MissingPos` the place to say a symbol is missing: just after the symbol before, when the current one starts a new line. Errors go through `Mark`, at the current symbol, or `MarkAt`, at a position; each -reports the error (`diag.Error`) and stops. There is no +reports the error (`diag.Error`) and jumps to `recovery`, the parser's +place to go on from (see parse.pas). Errors in the text itself stop the +compiler (`MarkBytes`, `LexError`): past a string left open, the +symbols can't be trusted. There is no recovery: the first error ends the compilation. `SaveScan` and `RestoreScan` keep the scanner's state while an imported module is compiled. @@ -287,7 +290,8 @@ `want` parameter carries the type an expression must have, where it is known, so that `[1, 2, 3]`, `{x: 1}` and `{red}` know what to build. -Then statements: `Statement` dispatches; `IfStatement`, +Then statements: `Statement` makes each one a recovery point (below) +and `OneStatement` dispatches; `IfStatement`, `WhileStatement`, `ForStatement` and `MatchStatement` emit their jumps with `x64.pas`'s labels. `Defer` is worth reading: a deferred statement is compiled where it stands, as a little subroutine of the procedure @@ -295,7 +299,8 @@ way out of its statement list: the end, `return` and `break`. Then declarations: `Declarations` reads `const`, `type`, `var`, `proc` -and `extern`. `ProcDecl` handles forward declarations, code procedures +and `extern`, each one through `Declaration`, a recovery point, which +calls `ConstDecl`, `TypeDecl`, `VarDecl`, `ProcDecl` or `ExternDecl`. `ProcDecl` handles forward declarations, code procedures (`CodeBody`, which just copies the bytes) and bodies (`Body`). `ParseType` and its helpers (`RecordType`, `VariantType`, `Signature`, `EnumType`) build `TType`s. @@ -308,6 +313,22 @@ is compiled once per distinct list of arguments: `ParseArgs` reads them at the import, `Params` binds them to the module's parameters, and `IsModule` decides whether an instance already exists. + +**Recovery.** After an error the parser carries on, so that one run +reports them all. `Guard` notes, at the start of a statement or +declaration, the scanner's state and the parser's; `setjmp` marks the +place, and `MarkAt` jumps back to it after reporting. `Restore` puts +the state back, the construct's first symbol current again, and +`SkipConstruct` reads past it, counting the words that open and close +blocks. A symbol at the start of a line ends the skip: by the usual +layout it starts the next declaration, so the statement gives up its +procedure (`GiveUp`), and `SkipProc` reads to the procedure's +`end Name;`. A name not declared is declared where it is used, with +the type `tPoison` (`Poison`), as are the names of a declaration that +had an error; a construct that uses poison sets `quiet`, and its errors +aren't reported, since they follow from one that was. Nothing breaks +for the half-made code: once there is an error, no executable is +written. The built-in procedures are in `Builtin` (and `New_`, `Atomic`): each parses its own arguments, since `SIZE` takes a type and `INC` a diff --git a/doc/raz.md b/doc/raz.md index c2ca800..64b407d 100644 --- a/doc/raz.md +++ b/doc/raz.md @@ -853,9 +853,11 @@ where they help, notes pointing at other places, such as where a name is declared, and a suggestion, such as a name in reach spelled almost alike. It goes on after an error to find the others, up to 20, and -writes no executable. After an error of syntax it skips to the next -procedure, so that one misplaced symbol brings no false reports after -it. A module with errors stops the compile after it. +writes no executable. After an error it skips the statement or +declaration the error is in and carries on with the next; a name that +isn't declared is reported once, and nothing that follows from it is +reported. An error in the text itself, such as a string left open, +stops the compile, and so does a module with errors, after it. The compiler also warns of what is declared and never used: an import; a constant, type, variable or procedure that isn't exported; a diff --git a/src/diag.pas b/src/diag.pas index fb072bd..b444829 100644 --- a/src/diag.pas +++ b/src/diag.pas @@ -60,6 +60,7 @@ numFiles, cap: longint; colour, colourKnown: boolean; cwd: shortstring; { the working directory and a /, or '' if unknown } + lastError: TPos; { where the last error was } { Paths are shown from the working directory where they are under it, so messages read the same wherever the compiler or its library is. } @@ -189,6 +190,10 @@ procedure Error(const p: TPos; const msg: shortstring); begin + { a second error at one place follows from the first: when a symbol + ends a construct with an error, the one around it may stop there too } + if (errors > 0) and (p.f = lastError.f) and (p.a = lastError.a) then exit; + lastError := p; Show(p, 'error', Red, msg); inc(errors); if errors >= MaxErrors then begin diff --git a/src/parse.pas b/src/parse.pas index 48fe040..f2a0442 100644 --- a/src/parse.pas +++ b/src/parse.pas @@ -52,6 +52,7 @@ checkMode: boolean; { reading a file only for its interface } inTypes: boolean; { in a type section: ^T may name a later type } fwdTypes: array[0..255] of PType; + fwdPos: array[0..255] of TPos; { where each names its type } numFwd: longint; declExported: boolean; { the export mark of the declaration being read } curLoop: PLoop; { the innermost loop, or nil } @@ -64,6 +65,9 @@ inExtern: boolean; { reading an extern's signature: ... allowed } tArgv, tBodySig: PType; nameRt, nameFail, nameEq, nameMain, nameBody, nameStatic: longint; + declaring: array[0..63] of longint; { the names the declaration being read declares } + numDeclaring: longint; + skipped: boolean; { the last statement had an error and was skipped } procedure Expression(var x: TItem; want: PType); forward; function ParseType: PType; forward; @@ -106,7 +110,122 @@ curModule^.last := o; end; end; + +{ Recovery + After an error the parser goes on with the next statement or + declaration, so that one run reports every error. Each statement and + declaration is a recovery point: it notes the state of the scanner + and the parser where it starts, and an error (MarkAt) jumps back to + it. The state is put back, the scanner reads the construct again + from its start, skipping to its end, and the parser carries on after + it. Nothing is generated after an error, so the code half made for + the construct does no harm. A name that isn't declared is declared + where it is used, with type tPoison, and what follows from it is not + reported again; so are the names of a declaration that had an error. + + Skipping counts the words that open and close blocks. A symbol at + the start of a line is taken to start a declaration of the module, + as layout has it: a statement skipped up to one gives up its + procedure, and the procedure is skipped up to its end. } + +type + TRecover = record + jb: jmp_buf; + outer: ^jmp_buf; + scan: TScanState; + scopes, depth, numDefers: longint; + loop: PLoop; + result: PType; + deferring, directDefer, quiet: boolean; + end; + +procedure Guard(var r: TRecover); +begin + r.outer := recovery; + SaveScan(r.scan); + r.scopes := ScopeDepth; r.depth := depth; r.numDefers := numDefers; + r.loop := curLoop; r.result := curResult; + r.deferring := deferring; r.directDefer := directDefer; r.quiet := quiet; + recovery := @r.jb; + quiet := false; +end; + +procedure Unguard(var r: TRecover); +begin + recovery := r.outer; + quiet := r.quiet; +end; + +{ After an error: the state as it was at the start of r's construct, + whose first symbol is again the current one } +procedure Restore(var r: TRecover); +begin + RestoreScan(r.scan); + CutScopes(r.scopes); depth := r.depth; numDefers := r.numDefers; + curLoop := r.loop; curResult := r.result; + deferring := r.deferring; directDefer := r.directDefer; + inTypes := false; declExported := false; inExtern := false; +end; + +{ Gives up the construct r is for, and the one around it } +procedure GiveUp(var r: TRecover); +begin + Unguard(r); + if recovery = nil then Finish; + longjmp(recovery^, 1); +end; + +{ Reads to the end of a statement or declaration, from its first + symbol: up to the ";" that ends it, not read, or to the "end", + "else", "elsif", "until" or "|" of the statement around it. False if + it stopped at a symbol that starts a line, or the end of the file. } +function SkipConstruct: boolean; +var d, p: longint; +begin + d := 0; p := 0; + repeat + case tok of + sIf, sWhile, sFor, sMatch, sRepeat, sRecord, sVariant: inc(d); + sEnd, sUntil: if d = 0 then exit(true) else dec(d); + sElse, sElsif, sBar: if (d = 0) and (p = 0) then exit(true); + sLparen, sLbrak, sLbrace: inc(p); + sRparen, sRbrak, sRbrace: if p > 0 then dec(p); + sSemicolon: if (d = 0) and (p = 0) then exit(true); + sEof: exit(false); + end; + Next; + until AtLineStart; + SkipConstruct := false; +end; + +{ Declares n where it is used, after it was reported as not declared, + or after the declaration of it had an error } +function Poison(n: longint): PObj; +var o: PObj; +begin + o := NewObj(oConst, n, tPoison); + Insert(o, TopScope); + Poison := o; +end; + +procedure WillDeclare(n: longint); +begin + if numDeclaring <= High(declaring) then declaring[numDeclaring] := n; + inc(numDeclaring); +end; + +{ After a declaration had an error: its names are poison, and reading + goes on after it } +procedure SkipDeclaration; +var i: longint; +begin + for i := 0 to numDeclaring - 1 do + if (i <= High(declaring)) and (Find(TopScope, declaring[i]) = nil) then + Poison(declaring[i]); + if SkipConstruct and (tok = sSemicolon) then Next; +end; + function ConstValue(var x: TItem): int64; begin if x.mode <> mConst then MarkAt(x.pos, 'constant expected'); @@ -126,7 +245,12 @@ begin if tok <> sIdent then MarkAt(MissingPos, 'name expected'); o := Lookup(id); - if o = nil then Mark(NameOf(id) + ' isn''t declared'); + if o = nil then begin + Poison(id); + quiet := false; + Mark(NameOf(id) + ' isn''t declared'); + end; + if o^.typ = tPoison then quiet := true; Next; if o^.cls = oModule then begin Expect(sPeriod, '.'); @@ -396,6 +520,7 @@ t^.fwd := id; if numFwd > High(fwdTypes) then Mark('too many forward pointers'); fwdTypes[numFwd] := t; + fwdPos[numFwd] := TokPos; inc(numFwd); Next; end else @@ -1161,7 +1286,7 @@ inc(numDefers); end; -procedure Statement; +procedure OneStatement; var x, y: TItem; called: boolean; m: int64; c: TCall; start: TPos; begin start := TokPos; @@ -1218,11 +1343,30 @@ Jmp(curLoop^.brk); end; sDefer: Defer; + else if AtLineStart then MarkAt(MissingPos, 'end expected') else MarkAt(MissingPos, 'statement expected'); end; ReleaseTemps(m); end; +procedure Statement; +var r: TRecover; m: int64; +begin + m := TempMark; + Guard(r); + if setjmp(r.jb) = 0 then begin + OneStatement; + skipped := false; + end else begin + Restore(r); + { a statement never starts a line: this is the next declaration } + if AtLineStart or not SkipConstruct then GiveUp(r); + ReleaseTemps(m); + skipped := true; + end; + Unguard(r); +end; + procedure Statements; var base: longint; old: boolean; begin @@ -1231,7 +1375,7 @@ directDefer := false; while not (tok in [sEnd, sElse, sElsif, sUntil, sBar, sEof]) do begin Statement; - Expect(sSemicolon, ';'); + if not skipped or (tok = sSemicolon) then Expect(sSemicolon, ';'); end; RunDefers(base); numDefers := base; @@ -1383,6 +1527,7 @@ Next; at := TokPos; IdentDef(n, exp); + WillDeclare(n); at := SpanFrom(at); inExtern := true; t := Signature; @@ -1399,6 +1544,7 @@ if tok <> sVar then MarkAt(MissingPos, 'proc or var expected'); Next; IdentDef(n, exp); + WillDeclare(n); Expect(sColon, ':'); declExported := exp; t := ParseType; @@ -1411,103 +1557,158 @@ Declare(o); end; -procedure Declarations(top: boolean); +procedure ConstDecl(top: boolean); +var n: longint; exp: boolean; x: TItem; o: PObj; t: PType; start: TPos; +begin + IdentDef(n, exp); + WillDeclare(n); + t := nil; + if tok = sColon then begin + Next; + start := TokPos; + t := ParseType; + if t <> tError then MarkAt(SpanFrom(start), 'only an ERROR constant has a type'); + end; + Expect(sEql, '='); + Expression(x, nil); + o := NewObj(oConst, n, x.typ); + o^.exported := exp and top; + if t = tError then begin + o^.typ := tError; + o^.val := ErrorChunk(x, curModule^.sname, n) + 1; + end else if x.mode = mStr then begin o^.val := x.val; o^.chunk := x.chunk end + else o^.val := ConstValue(x); + Declare(o); + Expect(sSemicolon, ';'); +end; + +procedure TypeDecl(top: boolean); +var n: longint; exp: boolean; o: PObj; t: PType; +begin + IdentDef(n, exp); + WillDeclare(n); + Expect(sEql, '='); + declExported := exp and top; + inTypes := true; + t := ParseType; + o := NewObj(oType, n, t); + o^.exported := exp and top; + if t^.obj = nil then t^.obj := o; + Declare(o); + Expect(sSemicolon, ';'); +end; + +procedure VarDecl(top: boolean); var - n, i, k: longint; exp: boolean; x: TItem; o: PObj; t: PType; - names: array[0..63] of longint; exps: array[0..63] of boolean; start: TPos; + i, k: longint; o: PObj; t: PType; + names: array[0..63] of longint; exps: array[0..63] of boolean; +begin + k := 0; + repeat + if k > High(names) then Mark('too many names'); + IdentDef(names[k], exps[k]); + WillDeclare(names[k]); + inc(k); + if tok <> sComma then break; + Next; + until false; + Expect(sColon, ':'); + declExported := top and exps[0]; + t := ParseType; + declExported := false; + for i := 0 to k - 1 do begin + o := NewObj(oVar, names[i], t); + o^.exported := exps[i] and top; + o^.isVar := false; + if top then begin + o^.lev := 0; + o^.chunk := NewChunk(secBss, curModule^.sname, names[i]); + SetBss(o^.chunk, t^.size, t^.align); + end else begin + o^.lev := 1; + o^.val := AllocPerm(t^.size, t^.align); + end; + Declare(o); + end; + Expect(sSemicolon, ';'); +end; + +{ After a procedure had an error: its name is poison if it wasn't + declared, and reading goes on after the "end Name;" that closes it, + or at the next procedure if that is missing } +procedure SkipProc; +var st: TScanState; +begin + Next; + if (tok = sIdent) and (Find(TopScope, id) = nil) then Poison(id); + repeat + repeat Next until AtLineStart or (tok = sEof); + if tok in [sProc, sExtern, sEof] then exit; + if tok = sEnd then begin + SaveScan(st); + Next; + if tok = sIdent then Next; + if tok = sSemicolon then begin Next; exit end; + RestoreScan(st); + exit; + end; + until false; +end; + +{ One declaration, of the kind k, as a recovery point } +procedure Declaration(k: TSym; top: boolean); +var r: TRecover; +begin + Guard(r); + numDeclaring := 0; + if setjmp(r.jb) = 0 then + case k of + sConst: ConstDecl(top); + sType: TypeDecl(top); + sVar: VarDecl(top); + sProc: begin + if not top then Mark('procedures don''t nest'); + ProcDecl; + Expect(sSemicolon, ';'); + end; + sExtern: begin + if not top then Mark('extern only at the top of a module'); + ExternDecl; + Expect(sSemicolon, ';'); + end; + end + else begin + Restore(r); + if k = sProc then SkipProc else SkipDeclaration; + end; + Unguard(r); +end; + +procedure Declarations(top: boolean); +var i: longint; o: PObj; k: TSym; begin repeat - case tok of - sConst: begin + k := tok; + case k of + sConst, sVar: begin Next; - while tok = sIdent do begin - IdentDef(n, exp); - t := nil; - if tok = sColon then begin - Next; - start := TokPos; - t := ParseType; - if t <> tError then MarkAt(SpanFrom(start), 'only an ERROR constant has a type'); - end; - Expect(sEql, '='); - Expression(x, nil); - o := NewObj(oConst, n, x.typ); - o^.exported := exp and top; - if t = tError then begin - o^.typ := tError; - o^.val := ErrorChunk(x, curModule^.sname, n) + 1; - end else if x.mode = mStr then begin o^.val := x.val; o^.chunk := x.chunk end - else o^.val := ConstValue(x); - Declare(o); - Expect(sSemicolon, ';'); - end; + while tok = sIdent do Declaration(k, top); end; sType: begin Next; - inTypes := true; numFwd := 0; - while tok = sIdent do begin - IdentDef(n, exp); - Expect(sEql, '='); - declExported := exp and top; - t := ParseType; - o := NewObj(oType, n, t); - o^.exported := exp and top; - if t^.obj = nil then t^.obj := o; - Declare(o); - Expect(sSemicolon, ';'); - end; + while tok = sIdent do Declaration(sType, top); + inTypes := false; for i := 0 to numFwd - 1 do begin o := Lookup(fwdTypes[i]^.fwd); - if (o = nil) or (o^.cls <> oType) then Mark(NameOf(fwdTypes[i]^.fwd) + ' isn''t declared'); - fwdTypes[i]^.base := o^.typ; + if (o = nil) or (o^.cls <> oType) then begin + Error(fwdPos[i], NameOf(fwdTypes[i]^.fwd) + ' isn''t declared'); + fwdTypes[i]^.base := tPoison; + end else fwdTypes[i]^.base := o^.typ; fwdTypes[i]^.fwd := -1; end; - inTypes := false; - declExported := false; end; - sVar: begin - Next; - while tok = sIdent do begin - k := 0; - repeat - if k > High(names) then Mark('too many names'); - IdentDef(names[k], exps[k]); - inc(k); - if tok <> sComma then break; - Next; - until false; - Expect(sColon, ':'); - declExported := top and exps[0]; - t := ParseType; - declExported := false; - for i := 0 to k - 1 do begin - o := NewObj(oVar, names[i], t); - o^.exported := exps[i] and top; - o^.isVar := false; - if top then begin - o^.lev := 0; - o^.chunk := NewChunk(secBss, curModule^.sname, names[i]); - SetBss(o^.chunk, t^.size, t^.align); - end else begin - o^.lev := 1; - o^.val := AllocPerm(t^.size, t^.align); - end; - Declare(o); - end; - Expect(sSemicolon, ';'); - end; - end; - sProc: begin - if not top then Mark('procedures don''t nest'); - ProcDecl; - Expect(sSemicolon, ';'); - end; - sExtern: begin - if not top then Mark('extern only at the top of a module'); - ExternDecl; - Expect(sSemicolon, ';'); - end; + sProc, sExtern: Declaration(k, top); else exit; end; until false; @@ -1716,9 +1917,10 @@ if tok <> sPeriod then MarkAt(MissingPos, '. expected'); o := m^.first; while o <> nil do begin - if (o^.cls = oProc) and o^.fwd then Mark(NameOf(o^.name) + ' is declared forward but never defined'); + if (o^.cls = oProc) and o^.fwd then Error(TokPos, NameOf(o^.name) + ' is declared forward but never defined'); o := o^.link; end; + if errors > 0 then Finish; { a module with errors stops the compiler after it } CloseScope; m^.done := true; if not checkOnly then begin diff --git a/src/scan.pas b/src/scan.pas index 96463b8..01e07e3 100644 --- a/src/scan.pas +++ b/src/scan.pas @@ -7,7 +7,9 @@ current symbol is, for messages. Depends on: BaseUnix, to read files; diag, to report errors. - Leaves out: recovery from errors. The first error stops the compiler. } + Leaves out: recovery from errors in the text itself, such as a string + not closed: the first such error stops the compiler. The parser goes + on after its own errors, through recovery below. } unit scan; @@ -68,6 +70,15 @@ procedure Next; procedure Mark(const msg: shortstring); procedure MarkAt(const p: TPos; const msg: shortstring); +function AtLineStart: boolean; + +var + { Where the parser goes on after an error: the innermost statement or + declaration being read. nil stops the compiler at the first error. } + recovery: ^jmp_buf; + { The construct being read uses a name already reported as not + declared: its errors follow from that one, and aren't reported. } + quiet: boolean; procedure SaveScan(var st: TScanState); procedure RestoreScan(const st: TScanState); function TokPos: TPos; @@ -219,20 +230,37 @@ MarkAt(TokPos, msg); end; -{ Report at the bytes a to b of the file being read } +{ An error in the parser's construct at p: reported, then the parser + goes on from the recovery point. } +procedure MarkAt(const p: TPos; const msg: shortstring); +begin + if not quiet then Error(p, msg); + if recovery = nil then Finish; + longjmp(recovery^, 1); +end; + +{ An error in the text at bytes a to b of the file being read, which + stops the compiler: past it, the symbols can't be trusted. } procedure MarkBytes(a, b: longint; const msg: shortstring); var p: TPos; begin p.f := cur.f; p.a := a; p.b := b; - MarkAt(p, msg); + Error(p, msg); + Finish; end; -procedure MarkAt(const p: TPos; const msg: shortstring); +procedure LexError(const msg: shortstring); begin - Error(p, msg); - Finish; + MarkBytes(cur.tokPos, cur.pos, msg); end; +{ The current symbol is the first on its line: at the top level of a + module, by the usual layout, so where reading can start again. } +function AtLineStart: boolean; +begin + AtLineStart := cur.tokPos = cur.tokLineStart; +end; + { Files } function Open(const path: shortstring): boolean; @@ -296,13 +324,13 @@ $F4: begin n := 3; cp := 4; hi := $8F end; { up to 10FFFFH } else cur.tokPos := pos; - Mark('bad UTF-8'); + LexError('bad UTF-8'); end; for i := 1 to n do begin b1 := byte(cur.buf[pos + i]); if (b1 < lo) or (b1 > hi) or (pos + i >= cur.len) then begin cur.tokPos := pos; - Mark('bad UTF-8'); + LexError('bad UTF-8'); end; cp := cp shl 6 or (b1 and $3F); lo := $80; hi := $BF; @@ -313,7 +341,7 @@ procedure Put(b: longint); begin - if slen >= MaxStr then Mark('string too long'); + if slen >= MaxStr then LexError('string too long'); sbuf[slen] := b; inc(slen); end; @@ -385,7 +413,7 @@ end else if byte(c) >= $80 then v := Utf8(cur.pos) else if (c < ' ') or (c = #127) then - Mark('unterminated literal') + LexError('unterminated literal') else begin v := ord(c); inc(cur.pos); @@ -431,40 +459,40 @@ if cur.buf[cur.pos] = 'H' then begin v := 0; for i := start to cur.pos - 1 do begin - if v shr 60 <> 0 then Mark('number too big'); + if v shr 60 <> 0 then LexError('number too big'); v := v * 16 + qword(HexVal(cur.buf[i])); end; inc(cur.pos); tok := sInt; ival := int64(v); { 16 digits are the bits of a 64-bit word } end else if (cur.buf[cur.pos] = '.') and (cur.buf[cur.pos + 1] in ['0'..'9']) then begin - if not allDec then Mark('bad number'); + if not allDec then LexError('bad number'); inc(cur.pos); while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos); if cur.buf[cur.pos] = 'E' then begin inc(cur.pos); if cur.buf[cur.pos] in ['+', '-'] then inc(cur.pos); - if not (cur.buf[cur.pos] in ['0'..'9']) then Mark('bad exponent'); + if not (cur.buf[cur.pos] in ['0'..'9']) then LexError('bad exponent'); while cur.buf[cur.pos] in ['0'..'9'] do inc(cur.pos); end; - if cur.pos - start > 255 then Mark('number too long'); + if cur.pos - start > 255 then LexError('number too long'); SetLength(s, cur.pos - start); Move(cur.buf[start], s[1], cur.pos - start); Val(s, rval, code); - if code <> 0 then Mark('bad real'); + if code <> 0 then LexError('bad real'); tok := sReal; end else begin - if not allDec then Mark('hex number needs H'); + if not allDec then LexError('hex number needs H'); v := 0; for i := start to cur.pos - 1 do begin d := ord(cur.buf[i]) - ord('0'); - if v > (qword(high(int64)) - qword(d)) div 10 then Mark('number too big'); + if v > (qword(high(int64)) - qword(d)) div 10 then LexError('number too big'); v := v * 10 + qword(d); end; tok := sInt; ival := int64(v); end; - if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then Mark('bad number'); + if cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '_', '0'..'9'] then LexError('bad number'); end; procedure Next; @@ -492,7 +520,7 @@ start := cur.pos; repeat inc(cur.pos) until not (cur.buf[cur.pos] in ['A'..'Z', 'a'..'z', '0'..'9', '_']); - if cur.pos - start > MaxIdent then Mark('name too long'); + if cur.pos - start > MaxIdent then LexError('name too long'); h := Intern(@cur.buf[start], cur.pos - start); if h < NumWords then tok := TSym(ord(sAnd) + h) else begin tok := sIdent; id := h end; @@ -500,9 +528,9 @@ '0'..'9': Number; '''': begin inc(cur.pos); - if cur.buf[cur.pos] = '''' then Mark('empty character'); + if cur.buf[cur.pos] = '''' then LexError('empty character'); v := LitChar(false); - if cur.buf[cur.pos] <> '''' then Mark('character not closed'); + if cur.buf[cur.pos] <> '''' then LexError('character not closed'); inc(cur.pos); tok := sChar; ival := v; @@ -563,7 +591,7 @@ end; else if byte(c) >= $80 then - Mark('text outside strings, characters and comments must be ASCII'); + LexError('text outside strings, characters and comments must be ASCII'); MarkBytes(cur.pos, cur.pos + 1, 'unexpected character'); end; end; diff --git a/src/sym.pas b/src/sym.pas index 6c26e0a..f6d0106 100644 --- a/src/sym.pas +++ b/src/sym.pas @@ -124,6 +124,7 @@ var tI8, tI16, tI32, tI64, tU8, tU16, tU32, tU64: PType; tBool, tF32, tReal, tRConst, tError, tConst, tNil, tStr, tNone, tPtrU8, tBytes: PType; + tPoison: PType; { of a name reported as not declared } curModule: PModule; function NewType(form: TForm; size, align: int64): PType; @@ -131,6 +132,8 @@ function NewScope: longint; procedure OpenScope(s: longint); procedure CloseScope; +function ScopeDepth: longint; +procedure CutScopes(d: longint); function TopScope: longint; procedure SaveScopes(var d: longint; var saved: array of longint); procedure RestoreScopes(d: longint; const saved: array of longint); @@ -221,8 +224,19 @@ begin depth := d; for i := 0 to depth - 1 do scopes[i] := saved[i]; +end; + +function ScopeDepth: longint; +begin + ScopeDepth := depth; end; +{ Closes the scopes opened since there were d, after an error } +procedure CutScopes(d: longint); +begin + depth := d; +end; + function TopScope: longint; begin TopScope := scopes[depth - 1]; @@ -490,6 +504,8 @@ tPtrU8^.base := tU8; tBytes := NewType(fSlice, 16, 8); tBytes^.base := tU8; + tPoison := NewType(fInt, 8, 8); + tPoison^.signed := true; Enter('true', oConst, tBool, 1); Enter('false', oConst, tBool, 0); Enter('nil', oConst, tNil, 0); diff --git a/test/check.sh b/test/check.sh index 5917e4c..5fd96bd 100755 --- a/test/check.sh +++ b/test/check.sh @@ -122,6 +122,37 @@ echo "FAIL tools/Pretty.raz: $(cat $out/Pretty.cerr)"; fail=$((fail + 1)) fi +# error recovery: tools/Mutate.raz changes one symbol of each program, +# and the compiler must not crash, must exit with status 0 or 1, must +# say "error:" when it exits with 1, and must not report one place twice. +# Reproduce a failure with: build/Mutate FILE SEED > M.raz +fuzz() { # fuzz file seed + f=$1; seed=$2; dir=$(dirname $f) + mkdir -p $out/fuzz; m=$out/fuzz/$(basename $f) + $out/Mutate $f $seed > $m + $raz -I $dir/mods -o $out/mutant $m 2>$out/mutant.err + status=$? + why= + if [ $status -gt 1 ]; then why="exit status $status" + elif grep -q 'internal error' $out/mutant.err; then why="internal error" + elif [ $status = 1 ] && ! grep -q ': error:' $out/mutant.err; then why="status 1 without an error" + elif [ -n "$(grep ': error:' $out/mutant.err | sed 's/: error:.*//' | sort | uniq -d)" ]; then + why="two errors at one place" + fi + if [ -n "$why" ]; then + echo "FAIL fuzz $f seed $seed: $why"; cat $out/mutant.err + fail=$((fail + 1)) + else pass=$((pass + 1)); fi +} +if ./raz -o $out/Mutate tools/Mutate.raz 2>$out/Mutate.cerr; then + for f in examples/*.raz test/run/*.raz; do + $raz -I $(dirname $f)/mods -o $out/mutant $f 2>/dev/null || continue + for seed in ${FUZZ_SEEDS:-1 2 3}; do fuzz $f $seed; done + done +else + echo "FAIL tools/Mutate.raz: $(cat $out/Mutate.cerr)"; fail=$((fail + 1)) +fi + # each library module's main is its test; Sys over C is tested in test/libc for f in lib/*.raz; do [ $f = lib/Sys.raz ] && continue diff --git a/test/err/Recover.err b/test/err/Recover.err new file mode 100644 index 0000000..9fd59b6 --- /dev/null +++ b/test/err/Recover.err @@ -0,0 +1,31 @@ +test/err/Recover.raz:6:27: error: Foo isn't declared + 6 | P = record a: I64; b: Foo; end; + | ^^^ +test/err/Recover.raz:9:8: error: Bar isn't declared + 9 | var g: Bar; + | ^^^ +test/err/Recover.raz:15:10: error: can't use I64 as BOOL + 15 | b := x; + | ^ +test/err/Recover.raz:16:10: error: y isn't declared + 16 | x := y + 1; + | ^ +test/err/Recover.raz:19:14: error: can't combine I64 and BOOL + 19 | x := (x + 2) * b; + | ^^^^^^^^^^^ +test/err/Recover.raz:20:17: error: z isn't declared + 20 | Out.int(z); + | ^ +test/err/Recover.raz:22:12: error: can't combine I64 and BOOL + 22 | return x + true; + | ^^^^^^^^ +test/err/Recover.raz:28:7: error: no field c + 28 | q.c := 1; + | ^ +test/err/Recover.raz:30:18: error: ; expected + 30 | Out.str("hi") + | ^ +test/err/Recover.raz:37:13: error: nope isn't declared + 37 | Out.int(nope(2)); + | ^^^^ +raz: 10 errors diff --git a/test/err/Recover.raz b/test/err/Recover.raz new file mode 100644 index 0000000..456aca7 --- /dev/null +++ b/test/err/Recover.raz @@ -0,0 +1,40 @@ +module Recover; + +import Out; + +type + P = record a: I64; b: Foo; end; + Q = record a: I64; end; + +var g: Bar; + h: I64; + +proc f(x: I64): I64; +var b: BOOL; +begin + b := x; + x := y + 1; + x := y * 2; + if x = 1 then + x := (x + 2) * b; + Out.int(z); + end; + return x + true; +end f; + +proc g2(): Q; +var q: Q; +begin + q.c := 1; + h := g; + Out.str("hi") + return q; +end g2; + +proc main*(); +begin + Out.int(f(1)); + Out.int(nope(2)); +end main; + +end Recover. diff --git a/test/err/Resync.err b/test/err/Resync.err new file mode 100644 index 0000000..5ad280b --- /dev/null +++ b/test/err/Resync.err @@ -0,0 +1,22 @@ +test/err/Resync.raz:10:5: error: ; expected + 10 | end a; + | ^ +test/err/Resync.raz:14:31: error: ; expected + 14 | while x > 0 do x := x - 1 end; + | ^^^ +test/err/Resync.raz:15:10: error: expression expected + 15 | x := ) + 2; + | ^ +test/err/Resync.raz:16:11: error: match needs a variant or an enumeration + 16 | match x + | ^ +test/err/Resync.raz:23:13: error: expression expected + 23 | x := 1 +; + | ^ +test/err/Resync.raz:23:14: error: end expected + 23 | x := 1 +; + | ^ +test/err/Resync.raz:27:10: error: can't use BOOL as I64 + 27 | x := false; + | ^^^^^ +raz: 7 errors diff --git a/test/err/Resync.raz b/test/err/Resync.raz new file mode 100644 index 0000000..1b31efa --- /dev/null +++ b/test/err/Resync.raz @@ -0,0 +1,35 @@ +module Resync; + +import Out; + +proc a(x: I64); +begin + if x = 1 then + x := 2; + Out.int(x); +end a; + +proc b(x: I64); +begin + while x > 0 do x := x - 1 end; + x := ) + 2; + match x + | 1: x := true; + end; +end b; + +proc c(x: I64); +begin + x := 1 +; + +proc d(x: I64); +begin + x := false; +end d; + +proc main*(); +begin + a(1); b(2); c(3); d(4); +end main; + +end Resync. diff --git a/tools/Mutate.raz b/tools/Mutate.raz new file mode 100644 index 0000000..9626ac4 --- /dev/null +++ b/tools/Mutate.raz @@ -0,0 +1,96 @@ +(* Mutate: a raz source with one random change, to try the compiler's + recovery from errors. + + Mutate File.raz seed + prints the file with one symbol deleted, duplicated, swapped with the + next, or replaced by another symbol of the file. The seed picks the + change: the same seed gives the same text. Comments and spacing stay + as they are around the change. *) +module Mutate; +import Out, Rt, Buf, Heap, Scan, Files; + +var + src: []U8; + state: U64; (* the generator: xorshift64 *) + +(* A number from the generator, below n. *) +proc random(n: I64): I64; +begin + state := state xor (state shl 13); + state := state xor (state shr 7); + state := state xor (state shl 17); + return I64(state mod U64(n)); +end; + +(* The seed, as a nonzero state. *) +proc seed(s: []U8); +var i: I64; +begin + state := 88172645463325252; + for i := 0 to LEN(s) - 1 do state := state * 31 + U64(s[i]); end; + if state = 0 then state := 1; end; + for i := 1 to 10 do random(2); end; +end; + +(* The symbols that aren't comments. *) +proc count(): I64; +var sc: Scan.Scanner; n: I64; +begin + Scan.init(ADR(sc), src); + Scan.next(ADR(sc)); + n := 0; + while sc.kind # Scan.eof do + if sc.kind # Scan.comment then INC(n); end; + Scan.next(ADR(sc)); + end; + return n; +end; + +(* Symbol k, counting from 0 and leaving out comments. *) +proc symbol(k: I64): Scan.Scanner; +var sc: Scan.Scanner; +begin + Scan.init(ADR(sc), src); + repeat + Scan.next(ADR(sc)); + if sc.kind # Scan.comment then DEC(k); end; + until k < 0; + return sc; +end; + +proc main*; +var buf: Buf.Buf; n, op, i: I64; a, b, c: Scan.Scanner; +begin + if ARGC() # 3 then Rt.stop("usage: Mutate File.raz seed"); end; + Buf.init(ADR(buf), Heap.heap); + if not Files.read(Files.arg(1), ADR(buf)) then Rt.stop("Mutate: can't read the file"); end; + src := Buf.bytes(ADR(buf)); + seed(Files.arg(2)); + n := count(); + if n < 2 then Out.str(src); return; end; + op := random(4); + i := random(n - 1); + a := symbol(i); + b := symbol(i + 1); + c := symbol(random(n)); + Out.str(src[0..a.start]); + if op = 0 then + Out.str(src[a.stop..b.start]); + elsif op = 1 then + Out.str(Scan.text(ADR(a))); + Out.str(" "); + Out.str(Scan.text(ADR(a))); + Out.str(src[a.stop..b.start]); + elsif op = 2 then + Out.str(Scan.text(ADR(b))); + Out.str(src[a.stop..b.start]); + Out.str(Scan.text(ADR(a))); + b.start := b.stop; (* b has been written, as the first *) + else + Out.str(Scan.text(ADR(c))); + Out.str(src[a.stop..b.start]); + end; + Out.str(src[b.start..LEN(src)]); +end; + +end Mutate.