Files
sex/sex-modules.scm
alex-eg 2c78756e61 remove spec and realize
They were too much surface for a language this small: a nominal
contract layer, per-type default synthesis and a pub interface of their
own. Type introspection and macros are the intended replacement, so the
storage, the forms and the tests that pin them go; the ops method
registry they leaned on stays.

The implementation is kept at tag 0.0.1.
2026-11-11 08:54:29 +03:00

528 lines
22 KiB
Scheme
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(import
scheme
(chicken base)
(chicken condition)
(chicken file)
(chicken load)
(chicken module)
(chicken pathname)
(chicken process-context)
(chicken string)
matchable
reader
sex-macros
srfi-1
types
utils)
(export
get-modules-public-forms
mark-imported!
load-persistent-module-paths
check-public-interface
module-dependencies
read-public-interface)
(define +persistent-module-paths+ (list))
;;; for guarding against multiple imports (sort of mandatory #pragma
;;; once)
(define +imported-modules+ (list))
;;; The unit is one of its own imports from the start: two modules that
;;; import each other with pub hand it its own interface back otherwise,
;;; and its types are defined twice
(define (mark-imported! path)
(set! +imported-modules+ (cons (normalize-pathname path) +imported-modules+)))
(define (get-modules-public-forms import-form)
;; How Sex handles modules:
;; For each module IMPORT-FORM names, construct path, find module by
;; path in module path directories, extract public definitions from
;; the module, paste them in current one in emulation of C include
;; directives.
(append-map (lambda (name) (import-module (symbol->string name) import-form))
(cdr (strip-pub import-form))))
(define (import-module name form)
(let* ((directory (import-directory form))
(module-path (locate-module name directory)))
(unless module-path
(sex-error form "Failed to find module" name (get-module-paths directory)))
(if (member (normalize-pathname module-path) +imported-modules+)
(list)
(begin
(set! +imported-modules+ (cons (normalize-pathname module-path)
+imported-modules+))
(read-public-interface module-path)))))
;;; An import is looked for beside the file it is written in, so a
;;; module's imports are its neighbours wherever the unit importing it
;;; is. One with no file to be beside -- stdin's, a macro's -- is looked
;;; for from the working directory, which is the unit's
(define (import-directory form)
(let ((file (form-file form)))
(or (and file (pathname-directory file)) (current-directory))))
(define (get-module-paths #!optional (directory (current-directory)))
(cons directory
(append +persistent-module-paths+ (standard-library-paths))))
;;; Where the modules shipped with the compiler live. Asked of the
;;; binary rather than baked in when it is built: in a work tree sexc
;;; sits beside lib/, and installed it sits in bindir with the modules
;;; under ../share/sex. Last in the search order, so a module of one's
;;; own wins over one of ours by the same name
(define (standard-library-paths)
(let ((binary (executable-pathname)))
(if binary
(let ((bin (pathname-directory binary)))
(list (make-pathname bin "lib")
(make-pathname (list (pathname-directory bin) "share") "sex")))
(list))))
(define (locate-module name directory)
;; Module locations: relative to DIRECTORY, or in what was in
;; SEX_MODULE_PATH env var at the start of the process (see
;; load-persistent-module-paths function)
(let ((search-paths (get-module-paths directory)))
(let loop ((paths search-paths))
(if (null? paths)
#f
(or (module-exists? name (car paths))
(loop (cdr paths)))))))
(define (module-exists? name module-dir)
;; returns absolute path to module, if it exists
(and (directory-exists? module-dir)
(let ((module-path (make-absolute-pathname module-dir name "sex")))
(and (file-exists? module-path)
(file-readable? module-path)
module-path))))
;;; Every module file read for this unit, with its forms, last read
;;; first: what its output depends on, besides the unit itself. A module
;;; that an import chain and the interface check both reach is read once
(define +modules-read+ (list))
(define (module-dependencies) (reverse (map car +modules-read+)))
(define (read-module path)
(cond ((assoc path +modules-read+) => cdr)
(else (let ((forms (read-from-file path)))
(set! +modules-read+ (cons (cons path forms) +modules-read+))
forms))))
(define (read-public-interface module-path)
;; 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. The declarations of the types its
;; importers see only behind a pointer go first.
(let ((forms (module-forms (read-module module-path))))
(append (check-public-interface forms)
(interface-forms forms))))
;;; A module's forms with its toplevel macro calls expanded, so that the
;;; pub forms a macro writes reach importers as written ones do:
;;; (getter forty-two 42) gives them (pub fn forty-two () int). The
;;; macros are the module's own and those its imports give it, lent for
;;; the expanding and taken back after, so the importer is left with the
;;; pub ones alone. One that reads the type database sees what the
;;; importer knows, which no declaration of the module's is yet; a call
;;; that fails after asking for one -- (field-count box), box being the
;;; module's record -- gives importers nothing, as before, and is the
;;; module's own compile's to check. Any other failure is the importer's
;;; too: (boom) raising "nope" says so wherever it is read
(define +modules-expanded+ (list))
(define (module-forms raw-forms)
(cond ((assq raw-forms +modules-expanded+) => cdr)
(else (let ((forms (expanded raw-forms)))
(set! +modules-expanded+
(cons (cons raw-forms forms) +modules-expanded+))
forms))))
(define (expanded raw-forms)
(let ((lent (list))
(declared (declared-names raw-forms)))
(define (lend! form)
(let ((name (macro-name form)))
(unless (assq name lent)
(set! lent (cons (cons name (macro-definition name)) lent)))
(defmacro (if (pub-form? form) (cddr form) (cdr form)))))
(define (expand form)
(cond ((macro-name form) (lend! form) (list form))
((splice? form) (append-map expand (cdr form)))
((macro? form)
(let ((result (expand-call form declared)))
(cond ((or (not result) (null? result)) (list))
(else (stamp-form-source! result (form-source form))
(expand result)))))
(else (list form))))
(dynamic-wind
void
(lambda ()
(for-each lend! (imported-macro-forms raw-forms))
(append-map expand raw-forms))
(lambda ()
(for-each (lambda (entry) (restore-macro! (car entry) (cdr entry)))
lent)))))
(define (expand-call form declared)
(let ((unknown (list)))
(handle-exceptions exn
(if (any (lambda (name) (memq name declared)) unknown) #f (abort exn))
(parameterize ((unknown-name (lambda (name) (set! unknown (cons name unknown)))))
(apply-macro form)))))
;;; The names FORMS declare, types and all
(define (declared-names forms)
(append (map car (declared-types forms))
(filter-map (lambda (form)
(match form
((or ('pub (or 'fn 'var) (? symbol? name) . _)
((or 'fn 'var) (? symbol? name) . _))
name)
(_ #f)))
forms)))
(define (splice? form)
(and (pair? form) (eq? (car form) '$) (list? form)))
;;; The macros importing FORMS' modules gives: each one's pub macros and
;;; their helpers, and those of the modules it imports with pub
(define (imported-macro-forms forms)
(let next ((paths (append (imported-modules forms #t)
(imported-modules forms #f)))
(seen (list))
(acc (list)))
(cond ((null? paths) (concatenate (reverse acc)))
((member (car paths) seen) (next (cdr paths) seen acc))
(else
(let* ((raw (read-module (car paths)))
(helpers (helper-macros raw)))
(next (append (cdr paths) (imported-modules raw #t))
(cons (car paths) seen)
(cons (filter (lambda (form)
(and (macro-name form)
(or (pub-form? form) (memq form helpers))))
raw)
acc)))))))
(define (macro-name form)
(match form
(('defmacro (name . _) . _) name)
(('pub 'defmacro (name . _) . _) name)
(_ #f)))
(define (interface-forms raw-forms)
(let ((helpers (helper-macros raw-forms)))
(reverse (fold (lambda (form acc)
(if (memq form helpers)
(cons form acc)
(process-public-interface-form form acc)))
(list)
raw-forms))))
;;; The private macros a pub one expands into, and the ones those do:
;;; the importer expands them all, the way a C header that defines a
;;; macro has to define what it uses too
(define (helper-macros raw-forms)
(let* ((private (filter (lambda (form)
(and (macro-name form) (not (pub-form? form))))
raw-forms))
(mentions (lambda (form name)
(let walk ((x (cdr form)))
(or (eq? x name) (and (pair? x) (or (walk (car x)) (walk (cdr x)))))))))
(let grow ((needed (list))
(users (filter (lambda (form) (and (macro-name form) (pub-form? form)))
raw-forms)))
(let ((more (filter (lambda (form)
(and (not (memq form needed))
(any (lambda (user) (mentions user (macro-name form)))
users)))
private)))
(if (null? more)
needed
(grow (append needed more) more))))))
;;; 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
(lambda (form acc)
(check-written-out form)
(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)
forms))))
;;; Importers declare a pub var from its type, not its initializer, so
;;; there is nothing on their side to solve a `_' with
(define (check-written-out form)
(match form
(('pub 'var . _)
(match (strip-header-comments form 4)
(('pub 'var name type . _)
(when (let wildcard? ((t type))
(or (eq? t '_) (and (pair? t) (any wildcard? t))))
(sex-error form "a pub var's type is what importers declare it with; write it out"
name)))
(_ #f)))
(_ #f)))
;;; 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))
(remedy (if (and kept (fourth kept)) "import its module with pub" "make it pub")))
(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; "
remedy)
name))
((not (cdr use))
(sex-error form (string-append "importers cannot see this type, held by value; "
remedy ", 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 'define name . body) body)
(('pub (or 'record 'struct 'union) name . rest)
(field-types (find list? (remove comment-form? rest))))
((or ('pub 'sum name (variants ...))
('pub 'sum name (? string?) (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 pub-form? methods)))
(_ (list))))
(define (field-types fields)
(if (list? fields) (map second (normalize-fields fields)) (list)))
(define (signature-types args ret)
(cons ret (arglist-types (remove comment-form? args))))
;;; 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 . #f) (int . #f))
;;;
;;; A function type takes and returns by value whatever it is held
;;; through: C wants the body to define or call one of its functions.
(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)))
(append (if element (type-uses element behind?) (list))
(if (array-bound? type) (bound-uses (array-bound type)) (list)))))
((fn closure)
(if (and (pair? (cdr type)) (list? (second type)))
(append-map (lambda (t) (type-uses t #f))
(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))))))
;;; [int (* 2 N)] needs N, as a value: there is no declaring it
(define (bound-uses bound)
(cond ((symbol? bound) (list (cons bound #f)))
((pair? bound) (append-map bound-uses (cdr bound)))
(else (list))))
;;; The types and constants FORMS declare, as (name kind body?):
;;;
;;; (pub record tally) -> (tally record #f)
;;; (sum colour ((none ()))) -> (colour sum #t)
;;; (define (sq x) (* x x)) -> (sq define #t)
(define (declared-types forms)
(filter-map
(lambda (form)
(and (pair? form)
(let* ((core (strip-pub form))
(name (and (pair? core) (pair? (cdr core))
(if (and (eq? (car core) 'define)
(pair? (second core)))
(car (second core))
(second core)))))
(and (memq (car core)
'(record struct union enum sum typedef define))
(symbol? name)
(list name
(car core)
(or (memq (car core) '(typedef define spec))
(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: its whole entries come first, for `assq'
(define (visible-types forms)
(let ((all (append (declared-types (filter pub-form? forms))
(append-map exported-types (imported-modules forms #t)))))
(append (filter third all) (remove third 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 files 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? (located form modules) (list)))
(('import . modules) (if pub? (list) (located form modules)))
(_ (list))))
forms))
(define (located form modules)
(let ((directory (import-directory form)))
(filter-map (lambda (name) (locate-module (symbol->string name) directory))
modules)))
;;; 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 path)
(let next ((paths (list path)) (seen (list)) (acc (list)))
(cond ((null? paths) (concatenate (reverse acc)))
((member (car paths) seen) (next (cdr paths) seen acc))
(else
(let ((exports (module-exports (car paths))))
(next (append (cdr paths) (cdr exports))
(cons (car paths) seen)
(cons (car exports) acc)))))))
;;; The types the module at PATH declares to its importers, and the
;;; modules its interface imports; worked out once, though the check of
;;; every module above it on a pub import chain walks there
(define +module-exports+ (list))
(define (module-exports path)
(cond ((assoc path +module-exports+) => cdr)
(else (let* ((forms (interface-forms (module-forms (read-module path))))
(exports (cons (declared-types forms)
(imported-modules forms #f))))
(set! +module-exports+ (cons (cons path exports) +module-exports+))
exports))))
(define (public-fn-interface raw-form)
;; (pub fn name args ret . body) -> prototype, keeping a docstring so
;; the importer can emit it above the declaration
(let ((form (strip-header-comments raw-form 5)))
(match form
(('pub 'fn name args ret)
form)
(('pub 'fn name args ret ('comment . _) . rest)
(public-fn-interface `(pub fn ,name ,args ,ret ,@rest)))
(('pub 'fn name args ret (? string? doc) . _)
`(pub fn ,name ,args ,ret ,doc))
(('pub 'fn name args ret . _)
`(pub fn ,name ,args ,ret)))))
;;; An ops block is not pub itself -- its methods are. The block leaves
;;; as a block, its pub methods reduced to prototypes, so the importer
;;; runs its own `process-ops' over it: prototypes alone would say that
;;; vec2ːlength exists without saying that vec2 has a `length', and
;;; (. v length) needs the second thing.
(define (ops-public-interface form)
(let ((type (and (pair? (cdr form)) (cadr form)))
(methods (filter (lambda (m)
(and (pair? m) (eq? (car m) 'pub)
(pair? (cdr m)) (eq? (cadr m) 'fn)))
(cddr form))))
(and (symbol? type)
(pair? methods)
(copy-form-source! form
`(ops ,type ,@(map public-fn-interface methods))))))
;;; TODO: use semen facilities to analyze modules
(define (process-public-interface-form form acc)
(match form
;; Reduced to a prototype, still `pub', so the importer declares it
;; with external linkage
(('pub 'fn . _)
(cons (copy-form-source! form (public-fn-interface form)) acc))
(('pub 'var . _)
(match-let ((('pub 'var name type . _) (strip-header-comments form 4)))
(cons (copy-form-source! form `(extern var ,name ,type)) acc)))
(('pub (or 'define 'defmacro 'enum 'import 'include 'record 'struct 'sum 'typedef 'union) . _)
(cons (copy-form-source! form (cdr form)) acc))
(('ops . _)
(let ((exported (ops-public-interface form)))
(if exported (cons exported acc) acc)))
(('pub . _)
(sex-error form "pub must be followed by a definition" form))
(_ acc)))
(define (load-persistent-module-paths)
(let ((sex-module-path-env-var
(get-env-var "SEX_MODULE_PATH")))
(when sex-module-path-env-var
(set! +persistent-module-paths+
(map to-absolute-pathname
(string-split sex-module-path-env-var ":"))))))