| 1 | (* Ending the program: exit, atExit and stop; and trace, the calls under |
| 2 | way. The compiler's checks, and the faults the run time catches, end |
| 3 | in stop. *) |
| 4 | module Rt; |
| 5 | import Sys; |
| 6 | |
| 7 | const Full*: ERROR = "too many procedures to run at exit"; |
| 8 | |
| 9 | var |
| 10 | procs: [32]proc; (* the procedures to run at exit, the last on top *) |
| 11 | count: INT; |
| 12 | |
| 13 | (* p run when the program ends by exit *) |
| 14 | proc atExit*(p: proc): ERROR; |
| 15 | begin |
| 16 | if count = LEN(procs) then return Full; end; |
| 17 | procs[count] := p; |
| 18 | INC(count); |
| 19 | return nil; |
| 20 | end; |
| 21 | |
| 22 | (* The end: C's buffers flushed, then the process. *) |
| 23 | proc quit(status: INT); |
| 24 | code |
| 25 | (exit-now status); |
| 26 | end; |
| 27 | |
| 28 | (* The atExit procedures, the last first, each taken off the list before |
| 29 | it runs, so that it runs once even if it stops or calls exit itself; |
| 30 | then the end. *) |
| 31 | proc exit*(status: INT); |
| 32 | var p: proc; |
| 33 | begin |
| 34 | while count > 0 do |
| 35 | DEC(count); |
| 36 | p := procs[count]; |
| 37 | p; |
| 38 | end; |
| 39 | quit(status); |
| 40 | end; |
| 41 | |
| 42 | (* the calls under way, on standard error *) |
| 43 | proc trace*; |
| 44 | code |
| 45 | (trace-calls); |
| 46 | end; |
| 47 | |
| 48 | (* msg, and a line feed, on standard error, then exit with status 2 *) |
| 49 | proc stop*(msg: []U8); |
| 50 | begin |
| 51 | _ := Sys.write(Sys.stderr, msg); |
| 52 | _ := Sys.write(Sys.stderr, "\n"); |
| 53 | trace; |
| 54 | exit(2); |
| 55 | end; |
| 56 | |
| 57 | end Rt. |