Files
sex/sex-modules.scm
alex-eg 30cabc009a read every trailing array bound as a dimension
[m 1 2] lost its second index, and [int 2 3] came out int 2 x[3]. Each
index now subscripts what the one before it gave, and [int 2 3] declares
what it indexes, int[2][3]. An inline struct's fields, once more than
one bound was looked for, were taken for one; their shape tells them apart.
2026-10-19 21:52:43 +03:00

400 lines
16 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 file)
(chicken load)
(chicken module)
(chicken pathname)
(chicken process-context)
(chicken string)
matchable
reader
srfi-1
types
utils)
(export
get-modules-public-forms
load-persistent-module-paths
check-public-interface
module-dependencies
read-public-interface
;; for the tests
get-module-paths)
(define +persistent-module-paths+ (list))
;;; for guarding against multiple imports (sort of mandatory #pragma
;;; once)
(define +imported-modules+ (list))
(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 module-path +imported-modules+)
(list)
(begin
(set! +imported-modules+ (cons 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 ((raw-forms (read-module 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
(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)
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))
(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))))
(('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 pub-form? 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 (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))
(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 (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))))))
;;; A realization leaves with the methods written in it, reduced to
;;; prototypes. Its defaults do not travel: the importer synthesizes
;;; its own static copies from the spec, which is why a default is
;;; static even when the realization is pub.
(define (realize-public-interface form)
(let ((core (cdr form)))
(copy-form-source!
form
`(pub realize ,(second core)
;; pub goes back on at the realize, not on its methods
,@(map (lambda (m) (cdr (public-fn-interface (cons 'pub m))))
(remove comment-form? (cddr core)))))))
;;; 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 'spec '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 'realize . _)
(cons (realize-public-interface form) 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 ":"))))))