From b717aa808dcaa9b050e0e1515bac813f2837a55a Mon Sep 17 00:00:00 2001 From: alex-eg Date: Fri, 9 Oct 2026 17:43:09 +0300 Subject: [PATCH] check what a module's importers can see of its types An importer is given the pub forms and nothing else, so a pub form naming a private type, or one from an import without pub, compiled in its module and failed in every importer with `unknown type name'. The pub forms are checked as the module itself is compiled. A record, struct, union or sum behind a pointer needs only declaring, so its bodyless declaration goes out ahead of them -- the opaque handle that (pub record T) already gave by hand. Held by value it needs its body, and a typedef or an enum has no declaration short of its definition: those are errors at the pub form, saying what would do instead. A name Sex has no declaration for is left to C. An importer may now be handed a declaration after the definition it declares, so a bodyless aggregate no longer replaces known fields. Fixes #57, #58. --- semen.scm | 4 +- sex-modules.module.scm | 1 + sex-modules.scm | 196 +++++++++++++++++++++++++++++++++++- sexc.scm | 22 ++-- tests/encapsulation.scm | 67 +++++++++++- tests/modules/Makefile | 11 +- tests/modules/greet-app.sex | 5 + tests/modules/greet.sex | 26 +++++ tests/modules/ledger.sex | 8 ++ 9 files changed, 323 insertions(+), 17 deletions(-) create mode 100644 tests/modules/ledger.sex diff --git a/semen.scm b/semen.scm index fc583cd..9597806 100644 --- a/semen.scm +++ b/semen.scm @@ -1880,7 +1880,9 @@ (name (and (pair? (cdr f)) (symbol? (cadr f)) (cadr f)))) ;; An anonymous aggregate has a field list where the name would be, ;; and nothing can refer to it by name anyway - (when name + ;; ...and a bodyless one adds nothing to what is known: an importer + ;; may be handed a declaration after the definition it declares + (when (and name (not (and (null? (cddr f)) (get-tag-info name)))) (case (car f) ((struct) (add-struct name form)) ((union) (add-union name form)) diff --git a/sex-modules.module.scm b/sex-modules.module.scm index 7b56569..eec7ab7 100644 --- a/sex-modules.module.scm +++ b/sex-modules.module.scm @@ -1,5 +1,6 @@ (module sex-modules (get-modules-public-forms load-persistent-module-paths + check-public-interface read-public-interface) "sex-modules.scm") diff --git a/sex-modules.scm b/sex-modules.scm index a613cb3..52391b4 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -82,13 +82,203 @@ ;; pub fns are reduced to prototypes, other pub forms are just pasted. ;; Declaration order is kept: a module that declares a type and then a ;; pub fn taking it has to paste them that way round, or the prototype - ;; names a type C has not seen. + ;; names a type C has not seen. The declarations of the types its + ;; importers see only behind a pointer go first. (let ((raw-forms (read-from-file module-path))) + (append (check-public-interface raw-forms) + (interface-forms raw-forms)))) + +(define (interface-forms raw-forms) + (reverse (fold process-public-interface-form (list) raw-forms))) + +;;; What importers can see of a module's types +;;; +;;; They are given the pub forms and nothing else, so a pub form that +;;; names a type not among them compiled here and failed there: +;;; (pub record shape ((cells (* cell)))) with `cell' private told the +;;; importer `unknown type name cell'. A record behind a pointer needs +;;; only declaring, and its declaration goes out with the pub forms. +;;; Held by value it needs its body; and a typedef or an enum has no +;;; declaration short of its definition. Those are errors here, where +;;; they were written. A name Sex has no declaration for is one only C +;;; knows, and is left to C. + +;;; The bodyless declarations FORMS' importers need, in the order the +;;; pub forms ask for them. An error when a pub form needs more than a +;;; declaration of a type they cannot see. +(define (check-public-interface forms) + (let ((visible (visible-types forms)) + (hidden (hidden-types forms))) (reverse (fold - process-public-interface-form + (lambda (form acc) + (fold (lambda (use acc) (check-type-use form use visible hidden acc)) + acc + (append-map (lambda (type) (type-uses type #f)) + (interface-types form)))) (list) - raw-forms)))) + forms)))) + +;;; USE is (name . behind-a-pointer?) +(define (check-type-use form use visible hidden acc) + (let* ((name (car use)) + (seen (assq name visible)) + (kept (assq name hidden))) + (cond + ((and seen (third seen)) acc) ; pub with its body + ((and seen (cdr use)) acc) ; a pub handle, held by one + (seen + (sex-error form "only a handle of this type is pub, so hold it through a pointer" + name)) + ((not kept) acc) + ((not (memq (second kept) '(record struct union sum))) + (sex-error form (string-append "importers cannot see this " + (symbol->string (second kept)) + ", and C declares one only by defining it; " + (if (fourth kept) + "import its module with pub" + "make it pub")) + name)) + ((not (cdr use)) + (sex-error form (string-append "importers cannot see this type, held by value; " + (if (fourth kept) + "import its module with pub" + "make it pub") + ", or hold it through a pointer") + name)) + ((any (lambda (f) (eq? name (cadr f))) acc) acc) + (else + (cons (copy-form-source! + form + (list (if (memq (second kept) '(record sum)) 'record (second kept)) + name)) + acc))))) + +;;; The type forms a pub form shows its importers +;;; +;;; (pub fn f ((c (* cell)) (n int)) shape) -> ((* cell) int shape) +(define (interface-types form) + (match form + (('pub 'fn . _) + (match (strip-header-comments form 5) + (('pub 'fn name (args ...) ret . _) (signature-types args ret)) + (_ (list)))) + (('pub 'var . _) + (match (strip-header-comments form 4) + (('pub 'var name type . _) (list type)) + (_ (list)))) + (('pub 'typedef name target) (list target)) + (('pub (or 'record 'struct 'union) name . rest) + (field-types (find list? (remove comment-form? rest)))) + (('pub 'sum name (variants ...)) + (append-map (lambda (v) + (if (and (pair? v) (pair? (cdr v))) (field-types (second v)) (list))) + (remove comment-form? variants))) + (('ops type . methods) + (append-map interface-types + (filter (lambda (m) (and (pair? m) (eq? (car m) 'pub))) methods))) + (('pub 'realize spec . methods) + (append-map (lambda (m) (interface-types (cons 'pub m))) + (remove comment-form? methods))) + (_ (list)))) + +(define (field-types fields) + (if (list? fields) (map second (normalize-fields fields)) (list))) + +(define (signature-types args ret) + (cons ret (map arg-type (remove comment-form? args)))) + +;;; (f1 float) -> float, (n unsigned int) -> (unsigned int), (int) -> (int) +(define (arg-type arg) + (cond ((not (named-arg? arg)) arg) + ((null? (cddr arg)) (second arg)) + (else (cdr arg)))) + +;;; Each name TYPE mentions, and whether it is behind a pointer: +;;; +;;; (* const cell) -> ((const . #t) (cell . #t)) +;;; [cell 4] -> ((cell . #f)) +;;; (fn ((cell)) int) -> ((cell . #t) (int . #t)) ; declaring is enough +(define (type-uses type behind?) + (cond + ((symbol? type) (list (cons type behind?))) + ((not (pair? type)) (list)) + (else + (case (car type) + ((*) (append-map (lambda (t) (type-uses t #t)) (cdr type))) + ((ยค) (let ((element (array-element-type type))) + (if element (type-uses element behind?) (list)))) + ((fn closure) + (if (and (pair? (cdr type)) (list? (second type))) + (append-map (lambda (t) (type-uses t #t)) + (signature-types (second type) (last type))) + (list))) + ((struct union enum) + (if (and (pair? (cdr type)) (symbol? (second type))) + (list (cons (second type) behind?)) + (list))) + (else (append-map (lambda (t) (type-uses t behind?)) type)))))) + +;;; The types FORMS declare, as (name kind body?): +;;; +;;; (pub record tally) -> (tally record #f) +;;; (sum colour ((none ()))) -> (colour sum #t) +(define (declared-types forms) + (filter-map + (lambda (form) + (and (pair? form) + (let ((core (if (pub-form? form) (cdr form) form))) + (and (pair? core) (pair? (cdr core)) + (memq (car core) '(record struct union enum sum typedef)) + (symbol? (second core)) + (list (second core) + (car core) + (or (eq? (car core) 'typedef) + (any list? (remove comment-form? (cddr core))))))))) + forms)) + +(define (pub-form? form) (and (pair? form) (eq? (car form) 'pub))) + +;;; Pub here or through a pub import. A type declared pub both bodyless +;;; and whole is whole +(define (visible-types forms) + (let ((all (append (declared-types (filter pub-form? forms)) + (append-map exported-types (imported-modules forms #t))))) + (map (lambda (entry) + (list (first entry) (second entry) + (any third (filter (lambda (e) (eq? (first e) (first entry))) all)))) + all))) + +;;; Declared here without pub, or brought by an import without it, as +;;; (name kind body? imported?) +(define (hidden-types forms) + (append (map (lambda (entry) (append entry (list #f))) + (declared-types (remove pub-form? forms))) + (map (lambda (entry) (append entry (list #t))) + (append-map exported-types (imported-modules forms #f))))) + +;;; The names of the modules FORMS import, with pub or without +(define (imported-modules forms pub?) + (append-map (lambda (form) + (match form + (('pub 'import . modules) (if pub? modules (list))) + (('import . modules) (if pub? (list) modules)) + (_ (list)))) + forms)) + +;;; The types a module gives its importers, its pub imports' included. +;;; Two modules may import each other, so each is read once +(define (exported-types module) + (let read ((modules (list module)) (seen (list)) (acc (list))) + (if (null? modules) + acc + (let ((path (locate-module (symbol->string (car modules))))) + (if (or (not path) (member path seen)) + (read (cdr modules) seen acc) + (let ((forms (interface-forms (read-from-file path)))) + (read (append (cdr modules) (imported-modules forms #f)) + (cons path seen) + (append acc (declared-types forms))))))))) (define (public-fn-interface raw-form) ;; (pub fn name args ret . body) -> prototype, keeping a docstring so diff --git a/sexc.scm b/sexc.scm index 668c092..e1ffb05 100644 --- a/sexc.scm +++ b/sexc.scm @@ -180,11 +180,15 @@ status, which is ours to pass on." (delete-file* c-file) (if normal-exit? status 1))))))) -(define (semantic-process-forms raw-forms input-source) - (if (eq? input-source 'stdin) - (semen-process raw-forms) - (with-directory input-source - (semen-process raw-forms)))) +;;; The unit's own forms are checked for what its importers will need, +;;; the prelude's not: every unit has those +(define (semantic-process-forms unit-forms input-source) + (let ((process (lambda () + (check-public-interface unit-forms) + (semen-process (append prelude unit-forms))))) + (if (eq? input-source 'stdin) + (process) + (with-directory input-source (process))))) (define prelude (append @@ -228,6 +232,10 @@ status, which is ours to pass on." (platform-features)) (cli-features args))) + ;; before the interface too, which asks the modules it imports + ;; what types they export + (load-persistent-module-paths) + (when (get-arg args 'public-interface #f) (assert (not (eq? input 'stdin)) "Error: --public-interface requires file argument") @@ -237,7 +245,6 @@ status, which is ours to pass on." (map pp (reverse (read-public-interface input))))) (return #f)) - (load-persistent-module-paths) ;; The file name in a #line directive now comes from the form's ;; own recorded location, so imported modules report themselves @@ -247,8 +254,7 @@ status, which is ours to pass on." (not (get-arg args 'line-directives #f))) (sex-line-directives 'none)) - (let* ((raw-forms (append prelude (read-raw-forms input))) - (sex-forms (semantic-process-forms raw-forms input))) + (let ((sex-forms (semantic-process-forms (read-raw-forms input) input))) (if (or (get-arg args 'macro-expand #f) (get-arg args 'emit-c #f)) ;; Emit processed and macro-expanded sex code, or emit C code diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index bff1c67..76b4123 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -8,6 +8,22 @@ ;;; `sex->c', `emits?', `reports?' and `in-fn' come from codegen.scm, ;;; which run.scm includes first. +(import sex-modules) + +(define (interface-of source) + "The declarations SOURCE, compiled as a module, hands its importers +ahead of its pub forms." + (check-public-interface + (with-input-from-string source + (lambda () + (parameterize ((current-source-file "codegen.sex")) + (parse-all (current-input-port))))))) + +(define (interface-reports? source fragment) + (let ((m (handle-exceptions e ((condition-property-accessor 'exn 'message) e) + (begin (interface-of source) #f)))) + (and m (string-contains m fragment) #t))) + (define (ops-src . body) (string-append "(record vec2 ((x float) (y float)))" @@ -457,4 +473,53 @@ "switch (t.tag)")) (test-assert "and a scrutinee that is not a sum" (reports? "(fn f () void (var n int 1) (match n ((a ()) (= n 2))))" - "match wants a sum")))) + "match wants a sum"))) + + ;; An importer is given the pub forms and nothing else, so a type one + ;; of them names has to be among them, or C is told no more of it + ;; than a declaration can say + (test-group "what importers can see" + (test "a private record behind a pointer is declared for them" + '((record cell)) + (interface-of "(record cell ((v int))) (pub record shape ((c (* cell))))")) + (test "once" + '((record cell)) + (interface-of "(record cell ((v int))) (pub fn f ((a (* cell)) (b (* cell))) void)")) + (test "a struct as a struct" + '((struct cell)) + (interface-of "(struct cell ((v int))) (pub fn f ((a (* struct cell))) void)")) + (test "a pub one needs nothing" + '() + (interface-of "(pub record cell ((v int))) (pub record shape ((c cell)))")) + (test "nor one only C knows" + '() + (interface-of "(pub fn f ((p (* FILE)) (n size-t)) void)")) + (test "nor a private fn's" + '() + (interface-of "(record cell ((v int))) (fn f ((c cell)) void)")) + (test-assert "held by value it is an error" + (interface-reports? "(record cell ((v int))) (pub record shape ((c cell)))" + "held by value")) + (test-assert "naming the line" + (interface-reports? "(record cell ((v int)))\n(pub record shape ((c cell)))" + "codegen.sex:2:")) + (test-assert "in an array too" + (interface-reports? "(record cell ((v int))) (pub record shape ((cs [cell 4])))" + "held by value")) + (test-assert "returned" + (interface-reports? "(record cell ((v int))) (pub fn f () cell)" "held by value")) + (test-assert "or taken by a pub method" + (interface-reports? "(record cell ((v int))) (ops cell (pub fn get ((self cell)) int))" + "held by value")) + (test-assert "a typedef has no declaration to give, pointer or not" + (interface-reports? "(typedef small int) (pub fn f ((p (* small))) void)" + "this typedef, and C declares one only by defining it")) + (test-assert "nor has an enum" + (interface-reports? "(enum mood (up down)) (pub var m (* enum mood))" + "this enum, and C declares")) + (test-assert "a pub handle is held through a pointer" + (interface-reports? "(pub record h) (record h ((n int))) (pub fn f ((x h)) void)" + "only a handle")) + (test "which is all it takes" + '() + (interface-of "(pub record h) (record h ((n int))) (pub fn f ((x (* h))) void)")))) diff --git a/tests/modules/Makefile b/tests/modules/Makefile index 034cd95..e76f6e9 100644 --- a/tests/modules/Makefile +++ b/tests/modules/Makefile @@ -17,15 +17,18 @@ # alone, its fields left behind and its methods still found. # # The public forms carry comments in their headers, which the reduction -# to a prototype and to an extern both have to look past. +# to a prototype and to an extern both have to look past. And a type the +# app cannot see -- private to greet, or from a module greet imports +# without `pub' -- crosses behind a pointer, declared and no more. SEXC ?= ../../sexc -EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\ncolour 123 +EXPECTED = hello, world\nhello, sex\n2 greetings\ntext times \ntext times \nmood 1\nclosure 15 21 201\nvec2 7 7\nvec2(3 4)\ntally 2\nboard 42\nledger 2\ncolour 123 check: + @$(SEXC) ledger.sex -c -o ledger.o @$(SEXC) greet.sex -c -o greet.o - @$(SEXC) greet-app.sex -o greet-app -- greet.o + @$(SEXC) greet-app.sex -o greet-app -- greet.o ledger.o @if [ "`./greet-app`" = "`printf '$(EXPECTED)\n'`" ]; then \ echo "modules ok"; \ else \ @@ -34,6 +37,6 @@ check: @$(MAKE) --no-print-directory clean clean: - @rm -f greet.o greet-app + @rm -f greet.o ledger.o greet-app .PHONY: check clean diff --git a/tests/modules/greet-app.sex b/tests/modules/greet-app.sex index 7675207..0836313 100644 --- a/tests/modules/greet-app.sex +++ b/tests/modules/greet-app.sex @@ -47,6 +47,11 @@ (printf "tally %d\n" (.count t)) (.drop t) + ;; neither cell nor ledger is visible here, only declared + (var b board (make-board)) + (printf "board %d\n" (board-total (& b))) + (printf "ledger %d\n" (ledger-total (greet-ledger))) + (var c colour (colour/rgb 1 2 3)) (match c ((rgb (r g b)) (printf "colour %d%d%d\n" r g b)) diff --git a/tests/modules/greet.sex b/tests/modules/greet.sex index 3da58b3..575636e 100644 --- a/tests/modules/greet.sex +++ b/tests/modules/greet.sex @@ -8,6 +8,8 @@ (pub include stdio.h) (include stdlib.h) +(import ledger) + (pub var greet-count ;; a comment in the header of a public form is ;; not part of it: what the importer is given has ;; to be `extern int greet-count', not a form @@ -30,12 +32,36 @@ (lambda (name field-type) `(printf "%s " ,(symbol->string name)))))) +(var greetings ledger #(ledger : 0)) + (pub fn greet ;; ...and here the prototype would lose its return type ((name (* const char))) void "Print a greeting for NAME." (++ greet-count) + (ledger-add (& greetings) 1) (printf "hello, %s\n" name)) +;;; Types the importer cannot see, crossing behind a pointer. `cell' is +;;; private and `ledger' was imported without `pub', and the importer +;;; is handed a declaration of each and nothing else. +(record cell ((v int))) + +(var the-cell cell #(cell : 40)) + +(pub record board ((first (* cell)) (size int))) + +(pub fn make-board () board + (return #(board : (& the-cell) 2))) + +(pub fn board-total ((b (* const board))) int + (return (+ (. b first v) (. b size)))) + +(pub fn greet-ledger () (* ledger) + (return (& greetings))) + +(pub fn ledger-total ((l (* const ledger))) int + (return (. l total))) + ;;; A closure type crossing the boundary. Both units generate the ;;; struct for this signature independently, so they have to agree on ;;; its tag and its layout, or the value is passed wrong and nothing diff --git a/tests/modules/ledger.sex b/tests/modules/ledger.sex new file mode 100644 index 0000000..14cbea7 --- /dev/null +++ b/tests/modules/ledger.sex @@ -0,0 +1,8 @@ +;;; A module greet.sex imports without `pub'. greet-app.sex never +;;; imports it, yet holds a (* ledger) that greet hands out: what greet +;;; exports has to declare the type for it. + +(pub record ledger ((total int))) + +(pub fn ledger-add ((l (* ledger)) (n int)) void + (+= (. l total) n))