From a61882bdd2bc3abd52fe63e0f8e5253fde91ec4e Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:18:52 +0100 Subject: [PATCH] sbcl: one interface to a module's files, report 2026-10.23, README Each other file of a module is read for its declarations and must export what the one taken does (section 3). Math's bits, fromBits and mul. Frames pushed by moving *sp*, not binding it, so a deep recursion doesn't fill SBCL's binding stack. A generic main module and a constant index out of an array are errors. README: how it works, and this implementation's choices (appendix A). --- diff --git a/sbcl/README.md b/sbcl/README.md new file mode 100644 index 0000000..d04b43f --- /dev/null +++ b/sbcl/README.md @@ -0,0 +1,132 @@ +# raz in SBCL + +A second compiler for raz, written in Common Lisp for SBCL from the +report alone: `doc/raz.md`, the language, and `doc/raz-lib.md`, the +library. It shares no code with the compiler in `src/`, and its library, +`lib/` here, is written afresh from volume 2. It follows report +2026-10.23 and passes the conformance suite, `conform/`: 301 of 301. + + make # ./raz, from src/*.lisp (needs sbcl) + make check # conform/, run from the directory above + ./raz [-I dir]... [-o exe] [-S] file.raz + +`-S` also writes the Lisp it made to `exe.lisp`. With `RAZ_DEBUG` set +in the environment, a mistake of the compiler's own comes with a +backtrace. + +## How it works + +The compiler reads each module once, front to back, checking it and +turning it into Lisp as it goes. Each procedure becomes a `DEFUN`. At +the end the compiler compiles them with SBCL into its own image and +saves the image, program and all, as the executable, which starts at +`START` in `src/rt.lisp`. + +| File | What | +|---|---| +| `src/package.lisp` | the packages: `RAZ`, and `RAZP` for the program's procedures | +| `src/scan.lisp` | the scanner: UTF-8 checked, then tokens | +| `src/types.lisp` | types, their layout, and sameness (5.10) | +| `src/rt.lisp` | the run time the compiled code calls | +| `src/comp.lisp` | what the rest share: modules, names, items, frames, the data block | +| `src/expr.lisp` | expressions, conversions, built-ins and calls | +| `src/stmt.lisp` | statements | +| `src/decl.lisp` | declarations, procedures, modules and generic instances | +| `src/driver.lisp` | the command line, and the executable | + +**Memory.** Every raz variable lives at an address, as `ADR` needs. +The module variables, string literals, constant arrays and records, +and the errors' messages lie in one block, the data, mapped at +`200000000000H`, so that the compiler knows each of their addresses. +A procedure's parameters, variables and temporaries lie in its frame, +on a raz stack of 256 MB that each thread maps for itself; a frame is +zeroed as the procedure starts. + +**Values.** In Lisp an integer, a pointer, an `ERROR` or a set is an +integer, kept within its type's range; a `BOOL` is `T` or `NIL`; a +real a `DOUBLE-FLOAT` or `SINGLE-FLOAT`. An array, a record, a variant +or a slice is handled by its address. An `ERROR` is the address of a +slice of its message, so `MSG` reads it there. A procedure value is an +index into a table of the program's procedures; one given to C becomes +a C function made by SBCL, so C can call it back, from its own threads +too. + +**Results.** A procedure returns its results as Lisp's multiple values; +for each record, array, variant or slice among them the caller passes +the address of a place to put it. + +**Deferred statements** are copied, by the compiler, to each place +their statement list can be left: its end, and each `return`, `try` +and `break` that leaves it. Nothing about them is kept as the program +runs, and a stop, `Rt.exit` or `Sys.exit` runs none of them, as 7.7 +wants. + +## This implementation's choices (appendix A) + +- **The target** is `linux-sbcl`: Linux, on the machine SBCL runs on. + A module's files are looked for as `Name.linux-sbcl.raz`, + `Name.linux.raz`, `Name.sbcl.raz` and `Name.raz`. An address, and + so `INT`, is 8 bytes; reals are there; bytes are little-endian. +- **Separate compilation**: none. Every module of a program is + compiled together, and no object file is written. +- **Atomics**: `CAS` is the machine's, through SBCL; `XCHG` and `XADD` + loop on it. +- **The calling convention** is SBCL's for raz procedures, and C's + (System V) where raz meets C, for `extern` procedures and callbacks. +- **Code procedures.** The target's machine is SBCL, so its assembly + language is Lisp: each instruction, up to its `;`, is a Lisp form, + read in the package `RAZ`, which sees the parameters by their names + in capitals, and the value of the last is the result. A code + procedure returns no record, array or slice. The library uses them + for the few things only the run time can do (`Rt`'s end, `Math`, + threads, signals). x86 code procedures aren't this target's. +- **`SYSCALL`** goes through the C library's `syscall()`, with + x86-64's numbers. A program that makes the system calls SBCL itself + relies on (signals' handlers, `clone`) is on its own. +- **`Out`'s buffer**, `Sys.outSize`, is 4 KB. +- **The executable** is an SBCL image, about 36 MB, which starts in a + few milliseconds. It carries the names of the procedures, which a + stop and `Rt.trace` print, but no line numbers for a debugger. +- **Failures.** A failed check, a division by zero and a `nil` + procedure are checked by the compiled code; a `nil` pointer or a bad + address is caught by SBCL; a stack overflow by either: past the raz + stack, or past SBCL's own (256 MB). Each prints where it was, as far + as it can tell, and the calls under way, without their variables, + then runs `Rt.atExit`'s procedures and ends with status 2. SBCL may + also say on standard error that it used a stack's guard page. +- **Messages.** One error is reported, as `file:line:col: what`, and + the compiler stops with status 1. It gives no warnings, and takes + `-Werror` and does nothing with it. +- **Every program uses C**, in that SBCL's run time is a C program. A + module that says `link static` still must not be in a program with + an `extern` or a `link` of a library, which the compiler reports. + +## The library + +`lib/` has every module of volume 2: the core (`Rt`, `Out`, `Mem`, +`Arena`, `Lock`, `Str`, `Buf`, and `Sys`) and the rest (`Heap`, `Fmt`, +`List`, `Map`, `Sort`, `Math`, `Files`, `Opt`, `Thread`, `C`, +`Bytes`), in raz, over `SYSCALL` and a few code procedures. + +- `Sys` makes Linux's system calls; `spawn` forks and runs the + program; `catch` has SBCL's run time handle the signals and write + each to a pipe, the fd it gives. +- `Thread` runs each thread as one of SBCL's, on a raz stack of its + own; `Mutex` is a futex. +- `Heap` keeps eight free lists, of blocks of 16 to 2048 bytes, and + gives a bigger block, or one aligned to more than 16 bytes, pages of + its own. It refuses a negative size, and an alignment that isn't a + power of 2 up to a page. +- `Bytes`: volume 2 names its procedures but not their parameters. + Here they are `index(s, b)`, `last(s, b)` and `count(s, b)` for a + byte `b: U8`, and `find(s, sub)`, each an `INT`, -1 for none. + +## Beyond conform/ + +Of the reference compiler's own tests, `test/run` and `examples/`, all +pass whose expected output this target can give: the rest are x86 +code procedures (`Asm`, `Atomic`, `Edge`, `Results`, `Simd`, `Single`, +`Cpu`) and a module only for `linux-x86_64` (`Target`). Of +`test/err`, it rejects every program the report makes an error; the +others are that compiler's own limits, its warnings under `-Werror` +and its assembler. diff --git a/sbcl/build.lisp b/sbcl/build.lisp index 51aa99c..174f8ec 100644 --- a/sbcl/build.lisp +++ b/sbcl/build.lisp @@ -15,7 +15,11 @@ (let ((src (format nil "src/~a.lisp" f)) (fasl (format nil "build/~a.fasl" f))) (ensure-directories-exist fasl) - (load (compile-file src :output-file (merge-pathnames fasl)))))))) + (multiple-value-bind (out warnings failure) (compile-file src :output-file (merge-pathnames fasl)) + (declare (ignore warnings)) + ;; an error or a full warning in the compiler stops the build + (when failure (format t "~a doesn't compile~%" src) (sb-ext:exit :code 1)) + (load out))))))) (sb-ext:save-lisp-and-die "raz" :executable t :toplevel (intern "MAIN" :raz) :save-runtime-options t) diff --git a/sbcl/lib/Math.raz b/sbcl/lib/Math.raz index 8783ff0..917d0a8 100644 --- a/sbcl/lib/Math.raz +++ b/sbcl/lib/Math.raz @@ -90,4 +90,31 @@ (c-call "atan2" double-float double-float y double-float x); end; +(* the bits of x, as IEEE 754 lays them out *) +proc bits*(x: F64): U64; +begin + return ^U64(ADR(x))^; +end; + +(* the F64 whose bits are u *) +proc fromBits*(u: U64): F64; +begin + return ^F64(ADR(u))^; +end; + +(* a times b: the low 64 bits of the product, and the high *) +proc mul*(a, b: U64): (U64, U64); +var al, ah, bl, bh, lo, mid1, mid2, hi, carry: U64; +begin + (* by halves of 32 bits, as on paper *) + al := a & 0FFFFFFFFH; ah := a shr 32; + bl := b & 0FFFFFFFFH; bh := b shr 32; + lo := al * bl; + mid1 := ah * bl; + mid2 := al * bh; + hi := ah * bh; + carry := ((lo shr 32) + (mid1 & 0FFFFFFFFH) + (mid2 & 0FFFFFFFFH)) shr 32; + return a * b, hi + (mid1 shr 32) + (mid2 shr 32) + carry; +end; + end Math. diff --git a/sbcl/src/decl.lisp b/sbcl/src/decl.lisp index 5b2db2b..2492b16 100644 --- a/sbcl/src/decl.lisp +++ b/sbcl/src/decl.lisp @@ -121,7 +121,7 @@ :exported *type-exported* :module *module*))) (defun variant-type () - (let ((cases '()) (ty (make-ty :kind :variant))) + (let ((cases '()) (toks '())) (loop until (accept :end) do (let* ((tk (tok)) (name (ident)) (fields '())) (when (accept :|(|) @@ -130,10 +130,11 @@ (when (find name cases :key #'vcase-name :test #'string=) (fail-tok tk "the case ~a is declared twice" name)) (setf cases (append cases (list (make-vcase :name name :index (length cases) :fields fields)))) - (push tk (ty-names ty))) + (push tk toks)) (expect :|;|)) + ;; the cases are named in the scope around the type (5.6) (let ((v (make-variant-type cases *module*))) - (loop for c in cases for tk in (reverse (ty-names ty)) + (loop for c in cases for tk in (reverse toks) do (declare-member (vcase-name c) :case v c tk)) v))) @@ -305,6 +306,7 @@ (cond ((accept :forward) (when (eq obj old) (fail-tok tk "~a is declared forward twice" name)) (setf (obj-forward obj) t)) + (*interface-only* (skip-body) (setf (obj-defined obj) t)) ((eq (kind) :code) (next-tok) (code-procedure obj)) (t (procedure-body obj) (setf (obj-defined obj) t))) @@ -314,6 +316,19 @@ (next-tok)) (expect :|;|)))) +(defun skip-body () + "Reads past a procedure's body unchecked, for a file read only for its +interface: its local declarations and statements, or its code." + (if (accept :code) + (expect :end) + (let ((depth 0)) + (loop (let ((k (kind))) + (next-tok) + (case k + ((:begin :if :while :for :match :record :variant) (incf depth)) + (:end (when (= (decf depth) 0) (return))) + (:eof (fail-here "the procedure never ends")))))))) + (defun procedure-body (obj) "Compiles a procedure's declarations and statements into a DEFUN." (let* ((sig (obj-sig obj)) @@ -342,12 +357,18 @@ (reverse stores) body (zeros-form (sig-results sig))))))) (defun procedure-defun (sym params dests stores body end) + ;; The frame is pushed by moving *SP*, and popped by moving it back as + ;; the procedure returns, by RETURN-FROM or by its end. (Binding *SP* + ;; with LET would be simpler, but each binding takes room on SBCL's + ;; binding stack, which a deep recursion soon fills.) `(defun ,sym (,@params ,@dests) - (let* ((fp *sp*) (*sp* (+ fp ,(proc-size *proc*)))) + (let ((fp *sp*)) (declare (ignorable fp)) (enter fp ,(proc-size *proc*)) + (setf *sp* (+ fp ,(proc-size *proc*))) ,@stores - (block ,(proc-block *proc*) ,@body ,end)))) + (multiple-value-prog1 (block ,(proc-block *proc*) ,@body ,end) + (setf *sp* fp))))) (defun code-procedure (obj) "A code procedure (section 8). This implementation's target is SBCL's @@ -406,6 +427,7 @@ ;;; Modules (section 3). (defvar *search-dirs* '() "Where modules are looked for, in order.") +(defvar *interface-only* nil "Whether the module being read is another target's file, read for its interface.") (defvar *target-names* '("linux-sbcl" "linux" "sbcl")) (defun find-module-file (name tk) @@ -434,7 +456,7 @@ (setf (gethash name *modules*) m) (if (and (eq (tok-kind (aref toks 2)) :|(|)) (read-generic-header m) - (read-module m)))) + (progn (read-module m) (check-other-files m))))) ((eq (module-state m) :compiling) (fail-tok tk "the module ~a imports itself" name))) m)) @@ -495,6 +517,7 @@ (next-tok) (expect :|;|) (setf (module-check-off m) t)) (declarations) + (when *interface-only* (return-from read-module m)) (when (eq (kind) :begin) (next-tok) (let* ((sym (lisp-name "(body)")) @@ -601,3 +624,85 @@ (fail-tok tk "~a's signature isn't the parameter ~a's" (obj-name actual) name)) (setf (gethash name (scope-table *scope*)) actual))))) (expect :|)|))) + +;;; One interface to a module's files (section 3): each file of the +;;; module beside the one taken, Name.*.raz and Name.raz, is read for its +;;; declarations alone, and must export what the one taken does. + +(defun other-files (m) + (let* ((file (module-file m)) (dir (directory-namestring file))) + (remove-if (lambda (f) (equal (namestring f) file)) + (append (directory (format nil "~a~a.*.raz" dir (module-name m))) + (directory (format nil "~a~a.raz" dir (module-name m))))))) + +(defun check-other-files (m) + (loop for f in (other-files m) for i from 1 + do (let* ((file (namestring f)) + (other (make-module :name (module-name m) :file file + :toks (let ((*file* file)) (scan (read-bytes file))) + :lisp-name (format nil "~a{~d}" (module-name m) i)))) + (let ((*interface-only* t)) (read-module other)) + (compare-interfaces m other)))) + +(defun iface-type-p (a b) + "Whether types A and B, of two files of one module, are built alike, a +name in one standing for the same name in the other." + (cond ((eq a b) t) + ((or (ty-name a) (ty-name b)) + (and (ty-name a) (ty-name b) (string= (ty-name a) (ty-name b)) + (eq (ty-kind a) (ty-kind b)))) + ((not (eq (ty-kind a) (ty-kind b))) nil) + (t (case (ty-kind a) + (:ptr (and (eq (ty-vol a) (ty-vol b)) (iface-type-p (ptr-base a) (ptr-base b)))) + (:array (and (= (ty-len a) (ty-len b)) (iface-type-p (ty-elem a) (ty-elem b)))) + (:slice (iface-type-p (ty-elem a) (ty-elem b))) + (:set (iface-type-p (ty-enum a) (ty-enum b))) + (:proc (iface-sig-p (ty-sig a) (ty-sig b))) + (t (iface-shape-p a b)))))) + +(defun iface-fields-p (as bs) + "The exported fields of two records, or the fields of two cases, alike." + (and (= (length as) (length bs)) + (every (lambda (f g) (and (string= (field-name f) (field-name g)) + (iface-type-p (field-type f) (field-type g)))) + as bs))) + +(defun iface-shape-p (a b) + "What a record, variant or enumeration shows another module, alike: +its exported fields, its cases, its names." + (ecase (ty-kind a) + (:record (iface-fields-p (remove-if-not #'field-exported (ty-fields a)) + (remove-if-not #'field-exported (ty-fields b)))) + (:variant (and (= (length (ty-cases a)) (length (ty-cases b))) + (every (lambda (c d) (and (string= (vcase-name c) (vcase-name d)) + (iface-fields-p (vcase-fields c) (vcase-fields d)))) + (ty-cases a) (ty-cases b)))) + (:enum (equal (ty-names a) (ty-names b))) + ((:int :bool :real :error) t))) + +(defun iface-sig-p (a b) + (and (= (length (sig-params a)) (length (sig-params b))) + (= (length (sig-results a)) (length (sig-results b))) + (eq (sig-varargs a) (sig-varargs b)) + (every (lambda (p q) (and (eq (third p) (third q)) (iface-type-p (second p) (second q)))) + (sig-params a) (sig-params b)) + (every #'iface-type-p (sig-results a) (sig-results b)))) + +(defun compare-interfaces (m other) + (flet ((differ (name file) + (error 'raz-error :text (format nil "~a: ~a isn't exported as in ~a" file name (module-file m))))) + (maphash (lambda (name o) + (let ((p (gethash name (module-exports other)))) + (unless (and p (eq (obj-kind o) (obj-kind p)) + (ecase (obj-kind o) + ((:const :var :case) (iface-type-p (obj-type o) (obj-type p))) + (:type (and (eq (ty-kind (obj-type o)) (ty-kind (obj-type p))) + (if (member (ty-kind (obj-type o)) '(:record :variant :enum)) + (iface-shape-p (obj-type o) (obj-type p)) + (iface-type-p (obj-type o) (obj-type p))))) + (:proc (iface-sig-p (obj-sig o) (obj-sig p))))) + (differ name (module-file other))))) + (module-exports m)) + (maphash (lambda (name p) (declare (ignore p)) + (unless (gethash name (module-exports m)) (differ name (module-file other)))) + (module-exports other)))) diff --git a/sbcl/src/driver.lisp b/sbcl/src/driver.lisp index babf4f4..69fc09c 100644 --- a/sbcl/src/driver.lisp +++ b/sbcl/src/driver.lisp @@ -11,7 +11,7 @@ (in-package :raz) -(defparameter *version* "raz-sbcl 0.1.0, report 2026-10.22") +(defparameter *version* "raz-sbcl 0.1.0, report 2026-10.23") (defun body-order (roots) "The modules whose bodies run, in order (section 3): each after those @@ -78,6 +78,9 @@ (let* ((none (make-tok :eof nil 1 1)) (main (progn (load-module "Rt" none) (load-module name none (namestring path)))) (modules (all-modules))) + (when (module-generic main) + (error 'raz-error :text (format nil "~a: ~a is generic: it is compiled where a module imports it" + file name))) (when (and (some #'module-static modules) (some #'module-uses-c modules)) (error 'raz-error :text (format nil "~a: the program uses C (~{~a~^, ~}), which ~{~a~^, ~} doesn't allow by link static" diff --git a/sbcl/src/expr.lisp b/sbcl/src/expr.lisp index f04b26b..45b512c 100644 --- a/sbcl/src/expr.lisp +++ b/sbcl/src/expr.lisp @@ -343,7 +343,6 @@ ((untyped-p x) (takes x b) b) ((untyped-p y) (takes y a) a) ((same-type-p a b) a) - ((and (is a :literal) nil)) (t (fail-tok tk "~a and ~a don't mix" (type-name a) (type-name b))))))) (defun typed-const (item ty) @@ -654,6 +653,9 @@ (+ (ld :u64 ,base) (* ,(if check `(check-index ,lo (ld :i64 (+ ,base 8)) ,(where tk)) lo) ,size)))) + ((and (integerp lo) (not (< -1 lo len-form))) + ;; a constant index out of an array would stop the program + (fail-tok tk "index ~d is out of range for a length of ~d" lo len-form)) (t `(+ ,base-form (* ,(if check `(check-index ,lo ,len-form ,(where tk)) lo) ,size)))) :ro (if (is ty :array) (item-ro item) nil) :vol (and (is ty :array) (item-vol item)) diff --git a/sbcl/src/rt.lisp b/sbcl/src/rt.lisp index bcc00ae..bf70eab 100644 --- a/sbcl/src/rt.lisp +++ b/sbcl/src/rt.lisp @@ -271,16 +271,18 @@ (write-bytes 2 (sb-ext:string-to-octets (format nil " in ~a~%" name))))) (defmacro catching-faults (&body body) - "BODY, where a bad address or an exhausted stack stops the program." - `(let ((where nil)) + "BODY, where a bad address or an exhausted stack stops the program, +from the bottom of the raz stack, where there is room to stop." + `(let ((where nil) (base *sp*)) (handler-case (handler-bind ((sb-sys:memory-fault-error (lambda (c) (declare (ignore c)) (setf where (first (raz-frames)))))) ,@body) (sb-sys:memory-fault-error (c) + (setf *sp* base) (stop (format nil "in ~a: a nil pointer or a bad address (0x~(~x~))" where (fault-address c)))) - ((or storage-condition stack-overflow) () (stop "a stack overflow"))))) + ((or storage-condition stack-overflow) () (setf *sp* base) (stop "a stack overflow"))))) (defun fault-address (c) (let ((a (ignore-errors (slot-value c 'sb-kernel::address))))