1
0
forked from alex-eg/sex
Files
sex/tools/module-deps.scm
alex-eg 397766822d read the module graph off the import forms
Each module's prerequisite line restated its import form, so adding a
module or an import meant editing the Makefile to match, and a missed
line only showed when an object came out of order.
2026-10-19 21:48:51 +03:00

93 lines
3.2 KiB
Scheme

;;; The compiler's modules and which of them each one imports, as make
;;; reads them: a module is a NAME.scm in the current directory that
;;; the program reaches through import forms.
;;;
;;; csi -s tools/module-deps.scm main.scm > modules.mk
;;;
;;; prints
;;;
;;; MODULES = fmt-c-writer infer reader ...
;;; infer.o: types.o utils.o
;;; ...
(import scheme
(chicken base)
(chicken condition)
(chicken file)
(chicken io)
(chicken process-context)
(chicken sort))
;;; As csc reads them, given -K prefix
(keyword-style #:prefix)
;;; (only sex-macros cat) -> sex-macros
(define (spec-name spec)
(if (and (pair? spec) (memq (car spec) '(only except prefix rename)))
(spec-name (cadr spec))
spec))
(define (module-file name)
(and (symbol? name)
(let ((file (string-append (symbol->string name) ".scm")))
(and (file-exists? file) file))))
;;; The import forms at toplevel, and inside a (module NAME EXPORTS ...)
(define (imported forms)
(let walk ((forms forms) (acc '()))
(if (null? forms)
acc
(let ((form (car forms)))
(walk (cdr forms)
(cond ((not (pair? form)) acc)
((eq? (car form) 'import)
(append (map spec-name (cdr form)) acc))
((eq? (car form) 'module)
(walk (cdddr form) acc))
(else acc)))))))
;;; FILE's forms, or the end of the scan, naming the file that has none
(define (forms-of file)
(handle-exceptions exn
(begin
(display (string-append "module-deps: " file ": "
((condition-property-accessor 'exn 'message "") exn)
"\n")
(current-error-port))
(exit 1))
(call-with-input-file file read-list)))
(define (local-imports file)
(let loop ((names (imported (forms-of file)))
(acc '()))
(cond ((null? names) (sort acc symbol<?))
((or (memq (car names) acc) (not (module-file (car names))))
(loop (cdr names) acc))
(else (loop (cdr names) (cons (car names) acc))))))
(define (symbol<? a b)
(string<? (symbol->string a) (symbol->string b)))
;;; Each module reached from FILE, with the modules it imports
(define (module-graph file)
(let loop ((pending (local-imports file)) (graph '()))
(cond ((null? pending) (sort graph (lambda (a b) (symbol<? (car a) (car b)))))
((assq (car pending) graph) (loop (cdr pending) graph))
(else
(let ((deps (local-imports (module-file (car pending)))))
(loop (append (cdr pending) deps)
(cons (cons (car pending) deps) graph)))))))
(let ((graph (module-graph (car (command-line-arguments)))))
(display "MODULES =")
(for-each (lambda (node) (display " ") (display (car node))) graph)
(newline)
(for-each (lambda (node)
(unless (null? (cdr node))
(display (car node))
(display ".o:")
(for-each (lambda (dep) (display " ") (display dep) (display ".o"))
(cdr node))
(newline)))
graph))