From dcb65c5504e1aa62ec429430c56cd5cd2ae52dd9 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 20:51:05 +0300 Subject: [PATCH 01/20] make each compiler module one file, built once A module was a body plus a (module ...) wrapper naming its exports, and the wrapper came in up to three copies: the root's, a test one that exported everything, and sextest's, each recompiling the same body. csc -module makes a file a module by itself, with export forms in its body, so the wrappers are gone. tests/ and tools/sextest/ link what the root built, finding it on the repository path; the tests see what a module exports, and the names only they need are exported as such. --- Makefile | 43 ++++++++++----------------- fmt-c-writer.module.scm | 3 -- fmt-c-writer.scm | 9 ++++++ infer.module.scm | 45 ----------------------------- infer.scm | 46 +++++++++++++++++++++++++++++ reader.module.scm | 6 ---- reader.scm | 11 +++++++ semen.module.scm | 2 -- semen.scm | 6 +++- sex-macros.module.scm | 9 ------ sex-macros.scm | 10 +++++++ sex-modules.module.scm | 7 ----- sex-modules.scm | 11 +++++++ sexc.module.scm | 1 - sexc.scm | 8 ++++++ tests/Makefile | 44 ++++------------------------ tests/fmt-c-writer.module.scm | 3 -- tests/infer.module.scm | 45 ----------------------------- tests/reader.module.scm | 3 -- tests/semen.module.scm | 2 -- tests/sex-macros.module.scm | 3 -- tests/sex-modules.module.scm | 3 -- tests/sexc.module.scm | 3 -- tests/types.module.scm | 50 -------------------------------- tests/utils.module.scm | 3 -- tools/sextest/Makefile | 19 ++++-------- tools/sextest/reader.module.scm | 6 ---- tools/sextest/utils.module.scm | 21 -------------- types.module.scm | 50 -------------------------------- types.scm | 51 +++++++++++++++++++++++++++++++++ utils.module.scm | 25 ---------------- utils.scm | 25 ++++++++++++++++ 32 files changed, 203 insertions(+), 370 deletions(-) delete mode 100644 fmt-c-writer.module.scm delete mode 100644 infer.module.scm delete mode 100644 reader.module.scm delete mode 100644 semen.module.scm delete mode 100644 sex-macros.module.scm delete mode 100644 sex-modules.module.scm delete mode 100644 sexc.module.scm delete mode 100644 tests/fmt-c-writer.module.scm delete mode 100644 tests/infer.module.scm delete mode 100644 tests/reader.module.scm delete mode 100644 tests/semen.module.scm delete mode 100644 tests/sex-macros.module.scm delete mode 100644 tests/sex-modules.module.scm delete mode 100644 tests/sexc.module.scm delete mode 100644 tests/types.module.scm delete mode 100644 tests/utils.module.scm delete mode 100644 tools/sextest/reader.module.scm delete mode 100644 tools/sextest/utils.module.scm delete mode 100644 types.module.scm delete mode 100644 utils.module.scm diff --git a/Makefile b/Makefile index 08e181e..c6b8fc3 100644 --- a/Makefile +++ b/Makefile @@ -65,42 +65,29 @@ sexc: $(OBJ) main.scm #------------------------------------------------------------------ -utils.o: utils.module.scm utils.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) utils.module.scm -o utils.o -unit utils +# A module is one file that declares its own exports, made a module by +# -module -types.o: types.module.scm types.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) types.module.scm -o types.o -unit types +%.o: %.scm + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -module $* -o $@ -unit $* -infer.o: infer.module.scm infer.scm types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) infer.module.scm -o infer.o -unit infer -link types,utils - -sex-macros.o: sex-macros.module.scm sex-macros.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-macros.module.scm -o sex-macros.o -unit sex-macros - -reader.o: reader.module.scm reader.scm utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils - -sex-modules.o: sex-modules.module.scm sex-modules.scm reader.o types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,types,utils - -semen.o: semen.module.scm semen.scm infer.o sex-macros.o sex-modules.o types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,infer,types,utils +infer.o: types.o utils.o +reader.o: utils.o +sex-modules.o: reader.o types.o utils.o +semen.o: infer.o sex-macros.o sex-modules.o types.o utils.o +fmt-c-writer.o: sex-fmt-c.o types.o utils.o +sexc.o: fmt-c-writer.o infer.o reader.o semen.o sex-macros.o sex-modules.o types.o utils.o +# Vendored, and a (module ...) form of its own sex-fmt-c.o: sex-fmt-c.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-fmt-c.scm -o sex-fmt-c.o -unit sex-fmt-c + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -o $@ -unit sex-fmt-c -fmt-c-writer.o: fmt-c-writer.module.scm fmt-c-writer.scm sex-fmt-c.o types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) fmt-c-writer.module.scm -o fmt-c-writer.o -unit fmt-c-writer -link sex-fmt-c,types,utils - -sexc.o: sexc.module.scm infer.o types.o sexc.scm fmt-c-writer.o sex-macros.o sex-modules.o reader.o semen.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sexc.module.scm -o sexc.o -unit sexc -link fmt-c-writer,sex-macros,sex-modules,reader,semen,infer,types,utils - -# Unit testing -sex-tests: +# Unit testing. Both link the modules built here +sex-tests: $(OBJ) $(MAKE) -C ./tests sex-tests cp ./tests/sex-tests ./ -sextest: +sextest: reader.o utils.o $(MAKE) -C ./tools/sextest sextest cp ./tools/sextest/sextest . diff --git a/fmt-c-writer.module.scm b/fmt-c-writer.module.scm deleted file mode 100644 index 5500894..0000000 --- a/fmt-c-writer.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module fmt-c-writer (emit-c - sex-line-directives) - "fmt-c-writer.scm") diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index c3f6219..5df7346 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -4,6 +4,7 @@ scheme (scheme base) ; make-parameter (chicken base) + (chicken module) (chicken string) (chicken syntax) brev-separate ; fn, flatten @@ -16,6 +17,14 @@ types ; array-bound?, named-arg? utils) +(export + emit-c + sex-line-directives + + ;; for the tests + atom-to-fmt-c unkebabify type-convert-to-c + process-toplevel-form walk-expr walk-type walk-var walk-fn-def walk-struct) + ;;; egg `tree' not ported to CHICKEN 6 yet (define (tree-map f tree) (cond ((null? tree) (list)) diff --git a/infer.module.scm b/infer.module.scm deleted file mode 100644 index dc9c3b3..0000000 --- a/infer.module.scm +++ /dev/null @@ -1,45 +0,0 @@ -(module infer - (;; The IR - tvar? - tvar-id - tvar-classes - tvar-rigid? - fresh-tvar - fresh-rigid-tvar - - prim-type? prim-name prim-quals make-prim - ptr-type? ptr-target ptr-quals make-ptr - array-type? array-elt array-size make-array-type - fn-type? fn-ret fn-args fn-variadic? make-fn-type - agg-type? agg-kind agg-name agg-spelling agg-quals make-agg - alias-type? alias-name alias-expansion alias-quals make-alias - unknown-type? the-unknown-type - - resolve - underlying - c-primitive? - type-quals - free-tvars - decay - - ;; The boundary - parse-type - unparse-type - - ;; Constraints - register-class! - add-instance! - entails? - default-tvar! - default-type-variables! - - ;; Unification - unify - - ;; Type schemes - scheme? scheme-vars scheme-constraints scheme-type - make-scheme - generalize - instantiate - substitute) - "infer.scm") diff --git a/infer.scm b/infer.scm index 0ad6574..f719a03 100644 --- a/infer.scm +++ b/infer.scm @@ -25,12 +25,58 @@ scheme (scheme base) (chicken base) + (chicken module) matchable srfi-1 srfi-69 types utils) +(export + ;; The IR + tvar? + tvar-id + tvar-classes + tvar-rigid? + fresh-tvar + fresh-rigid-tvar + + prim-type? prim-name prim-quals make-prim + ptr-type? ptr-target ptr-quals make-ptr + array-type? array-elt array-size make-array-type + fn-type? fn-ret fn-args fn-variadic? make-fn-type + agg-type? agg-kind agg-name agg-spelling agg-quals make-agg + alias-type? alias-name alias-expansion alias-quals make-alias + unknown-type? the-unknown-type + + resolve + underlying + c-primitive? + type-quals + free-tvars + decay + + ;; The boundary + parse-type + unparse-type + + ;; Constraints + register-class! + add-instance! + entails? + default-tvar! + default-type-variables! + + ;; Unification + unify + + ;; Type schemes + scheme? scheme-vars scheme-constraints scheme-type + make-scheme + generalize + instantiate + substitute) + ;;; --------------------------------------------------------------- ;;; The IR ;;; --------------------------------------------------------------- diff --git a/reader.module.scm b/reader.module.scm deleted file mode 100644 index 0b0d208..0000000 --- a/reader.module.scm +++ /dev/null @@ -1,6 +0,0 @@ -(module reader (read-from-file - read-raw-forms - - current-features - platform-features) - "reader.scm") diff --git a/reader.scm b/reader.scm index 42ec90b..a3c058e 100644 --- a/reader.scm +++ b/reader.scm @@ -16,11 +16,22 @@ scheme (scheme base) ; make-parameter (chicken base) + (chicken module) (chicken pathname) (chicken platform) ; software-version, machine-type (only srfi-1 every any) ; srfi-1 also has an append-reverse utils) +(export + read-from-file + read-raw-forms + + current-features + platform-features + + ;; for the tests + parse-all) + ;;; Sentinels for structural tokens (define close-paren (list '%close-paren)) (define close-bracket (list '%close-bracket)) diff --git a/semen.module.scm b/semen.module.scm deleted file mode 100644 index 7320815..0000000 --- a/semen.module.scm +++ /dev/null @@ -1,2 +0,0 @@ -(module semen () - "semen.scm") diff --git a/semen.scm b/semen.scm index a60efa5..e2be434 100644 --- a/semen.scm +++ b/semen.scm @@ -19,7 +19,11 @@ ) (export/rename (process semen-process)) -(export closure-env-declaration) +(export closure-env-declaration + ;; for the tests + sex-fn? sex-fn-public? sex-fn-name sex-fn-arglist + sex-fn-return-type sex-fn-prototype sex-fn-body + walk-form macro-expand) ;;; for lambda extraction, docstring processing, macro expansion, ;;; injection of module headers, i.e. all things that rearrange code diff --git a/sex-macros.module.scm b/sex-macros.module.scm deleted file mode 100644 index 9837c04..0000000 --- a/sex-macros.module.scm +++ /dev/null @@ -1,9 +0,0 @@ -(module sex-macros - (register-macro - cat - comment - get-macro - macro? - apply-macro - defmacro) - "sex-macros.scm") diff --git a/sex-macros.scm b/sex-macros.scm index 327c180..5517bbd 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -2,9 +2,19 @@ scheme (only fmt fmt) (chicken base) + (chicken module) (chicken plist) (chicken string)) +(export + register-macro + cat + comment + get-macro + macro? + apply-macro + defmacro) + (define (cat-syms s-1 s-2) (fmt #f s-1 s-2)) diff --git a/sex-modules.module.scm b/sex-modules.module.scm deleted file mode 100644 index 82f61e7..0000000 --- a/sex-modules.module.scm +++ /dev/null @@ -1,7 +0,0 @@ -(module sex-modules - (get-modules-public-forms - load-persistent-module-paths - check-public-interface - module-dependencies - read-public-interface) - "sex-modules.scm") diff --git a/sex-modules.scm b/sex-modules.scm index 428e398..8044d76 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -4,6 +4,7 @@ (chicken base) (chicken file) (chicken load) + (chicken module) (chicken pathname) (chicken process-context) (chicken string) @@ -14,6 +15,16 @@ 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 diff --git a/sexc.module.scm b/sexc.module.scm deleted file mode 100644 index d4cc041..0000000 --- a/sexc.module.scm +++ /dev/null @@ -1 +0,0 @@ -(module sexc (main) "sexc.scm") diff --git a/sexc.scm b/sexc.scm index 9708be3..80b4e27 100644 --- a/sexc.scm +++ b/sexc.scm @@ -4,6 +4,7 @@ (chicken base) (chicken condition) ; handle-exceptions (chicken file) + (chicken module) (chicken plist) (chicken pretty-print) (chicken process) @@ -20,6 +21,13 @@ srfi-1 ; list routines utils) +(export + main + + ;; for the tests + args-before-separator args-after-separator + dependency-rule spell-stdout-output) + ;;; Main function facilities (define opts-grammar diff --git a/tests/Makefile b/tests/Makefile index 9a4b6c6..1e9ac31 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -1,53 +1,21 @@ CHICKEN_C = csc CSC_FLAGS += -K prefix -static -MODULE_FLAGS = -emit-all-import-libraries -module-registration -c + +# The compiler's modules are built once, in the root; their import +# libraries and objects are found there through the repository path +ROOT = .. +export CHICKEN_REPOSITORY_PATH := $(abspath $(ROOT)):$(or $(CHICKEN_REPOSITORY_PATH),$(shell chicken-install -repository)) MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc -SEX_OBJ = $(MODULES:%=%.o) TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args module-path types infer TEST_SRCS = $(TESTS:%=%.scm) -sex-tests: run.scm $(TEST_SRCS) $(SEX_OBJ) +sex-tests: run.scm $(TEST_SRCS) $(MODULES:%=$(ROOT)/%.o) $(CHICKEN_C) $(CSC_FLAGS) run.scm -o sex-tests -link sexc -#------------------------------------------------------------------ - -utils.o: utils.module.scm ../utils.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) utils.module.scm -o utils.o -unit utils - -types.o: types.module.scm ../types.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) types.module.scm -o types.o -unit types - -infer.o: infer.module.scm ../infer.scm types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) infer.module.scm -o infer.o -unit infer -link types,utils - -sex-macros.o: sex-macros.module.scm ../sex-macros.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-macros.module.scm -o sex-macros.o -unit sex-macros - -reader.o: reader.module.scm ../reader.scm utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils - -sex-modules.o: sex-modules.module.scm ../sex-modules.scm reader.o types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sex-modules.module.scm -o sex-modules.o -unit sex-modules -link reader,types,utils - -semen.o: semen.module.scm ../semen.scm infer.o sex-macros.o sex-modules.o types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) semen.module.scm -o semen.o -unit semen -link sex-macros,sex-modules,infer,types,utils - -sex-fmt-c.o: ../sex-fmt-c.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) ../sex-fmt-c.scm -o sex-fmt-c.o -unit sex-fmt-c - -fmt-c-writer.o: fmt-c-writer.module.scm ../fmt-c-writer.scm sex-fmt-c.o types.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) fmt-c-writer.module.scm -o fmt-c-writer.o -unit fmt-c-writer -link sex-fmt-c,types,utils - -sexc.o: sexc.module.scm infer.o types.o ../sexc.scm fmt-c-writer.o sex-macros.o sex-modules.o reader.o semen.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) sexc.module.scm -o sexc.o -unit sexc -link fmt-c-writer,sex-macros,sex-modules,reader,semen,infer,types,utils - clean: - rm -f $(SEX_OBJ) - rm -f *.import.scm - rm -f *.link rm -f sex-tests .PHONY: clean diff --git a/tests/fmt-c-writer.module.scm b/tests/fmt-c-writer.module.scm deleted file mode 100644 index 5e8036e..0000000 --- a/tests/fmt-c-writer.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module fmt-c-writer - * - "../fmt-c-writer.scm") diff --git a/tests/infer.module.scm b/tests/infer.module.scm deleted file mode 100644 index 5b55c47..0000000 --- a/tests/infer.module.scm +++ /dev/null @@ -1,45 +0,0 @@ -(module infer - (;; The IR - tvar? - tvar-id - tvar-classes - tvar-rigid? - fresh-tvar - fresh-rigid-tvar - - prim-type? prim-name prim-quals make-prim - ptr-type? ptr-target ptr-quals make-ptr - array-type? array-elt array-size make-array-type - fn-type? fn-ret fn-args fn-variadic? make-fn-type - agg-type? agg-kind agg-name agg-spelling agg-quals make-agg - alias-type? alias-name alias-expansion alias-quals make-alias - unknown-type? the-unknown-type - - resolve - underlying - c-primitive? - type-quals - free-tvars - decay - - ;; The boundary - parse-type - unparse-type - - ;; Constraints - register-class! - add-instance! - entails? - default-tvar! - default-type-variables! - - ;; Unification - unify - - ;; Type schemes - scheme? scheme-vars scheme-constraints scheme-type - make-scheme - generalize - instantiate - substitute) - "../infer.scm") diff --git a/tests/reader.module.scm b/tests/reader.module.scm deleted file mode 100644 index a4bc673..0000000 --- a/tests/reader.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module reader - * - "../reader.scm") diff --git a/tests/semen.module.scm b/tests/semen.module.scm deleted file mode 100644 index 25e8734..0000000 --- a/tests/semen.module.scm +++ /dev/null @@ -1,2 +0,0 @@ -(module semen * - "../semen.scm") diff --git a/tests/sex-macros.module.scm b/tests/sex-macros.module.scm deleted file mode 100644 index 3b1fa16..0000000 --- a/tests/sex-macros.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module sex-macros - * - "../sex-macros.scm") diff --git a/tests/sex-modules.module.scm b/tests/sex-modules.module.scm deleted file mode 100644 index 6994c79..0000000 --- a/tests/sex-modules.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module sex-modules - * - "../sex-modules.scm") diff --git a/tests/sexc.module.scm b/tests/sexc.module.scm deleted file mode 100644 index 320e689..0000000 --- a/tests/sexc.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module sexc - * - "../sexc.scm") diff --git a/tests/types.module.scm b/tests/types.module.scm deleted file mode 100644 index d905dff..0000000 --- a/tests/types.module.scm +++ /dev/null @@ -1,50 +0,0 @@ -(module types - (add-struct - add-union - add-enum - add-typedef - add-define - - type-match - type-pattern-matches? - map-fields - - add-sum! - get-sum - add-constructor! - get-constructor - variant-fields - reset-declarations! - - add-spec! - get-spec - spec-parameter - spec-methods - add-realization! - realizes? - normalize-fields - - add-method! - get-method - qualify-op - ops-key - - add-name-type! - get-name-type - type-of - current-type-of - get-return-type - - get-type-info - get-tag-info - get-fields - get-underlying-type - - type-head? - named-arg? - named-arg-type - arglist-types - strip-pub - array-bound? - array-element-type) - "../types.scm") diff --git a/tests/utils.module.scm b/tests/utils.module.scm deleted file mode 100644 index a8e64b8..0000000 --- a/tests/utils.module.scm +++ /dev/null @@ -1,3 +0,0 @@ -(module utils - * - "../utils.scm") diff --git a/tools/sextest/Makefile b/tools/sextest/Makefile index 96fe0ee..d589d13 100644 --- a/tools/sextest/Makefile +++ b/tools/sextest/Makefile @@ -1,23 +1,16 @@ CHICKEN_C = csc CSC_FLAGS += -K prefix -static -MODULE_FLAGS = -emit-all-import-libraries -module-registration -c - -ROOT = ../.. # sextest reuses sexc's reader (and its utils dependency) instead of -# duplicating the S-expression reader. The module wrappers here include -# the shared sources from the project root. +# duplicating the S-expression reader: both are linked from the root, +# found there through the repository path +ROOT = ../.. +export CHICKEN_REPOSITORY_PATH := $(abspath $(ROOT)):$(or $(CHICKEN_REPOSITORY_PATH),$(shell chicken-install -repository)) -sextest: sextest.scm reader.o utils.o +sextest: sextest.scm $(ROOT)/reader.o $(ROOT)/utils.o $(CHICKEN_C) $(CSC_FLAGS) sextest.scm -o sextest -link reader,utils -utils.o: utils.module.scm $(ROOT)/utils.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) utils.module.scm -o utils.o -unit utils - -reader.o: reader.module.scm $(ROOT)/reader.scm utils.o - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) reader.module.scm -o reader.o -unit reader -link utils - clean: - rm -f *.o *.import.scm *.link sextest + rm -f sextest .PHONY: clean diff --git a/tools/sextest/reader.module.scm b/tools/sextest/reader.module.scm deleted file mode 100644 index d3358e7..0000000 --- a/tools/sextest/reader.module.scm +++ /dev/null @@ -1,6 +0,0 @@ -(module reader (read-from-file - read-raw-forms - - current-features - platform-features) - "../../reader.scm") diff --git a/tools/sextest/utils.module.scm b/tools/sextest/utils.module.scm deleted file mode 100644 index 8f41e2f..0000000 --- a/tools/sextest/utils.module.scm +++ /dev/null @@ -1,21 +0,0 @@ -(module utils - (get-env-var - set-working-directory - to-absolute-pathname - comment-form? - strip-header-comments - list-split - list-join - recons - current-source-file - set-form-source! - form-source - form-file - form-line - copy-form-source! - stamp-form-source! - form-location - sex-error - with-directory - ) - "../../utils.scm") diff --git a/types.module.scm b/types.module.scm deleted file mode 100644 index d4b98e1..0000000 --- a/types.module.scm +++ /dev/null @@ -1,50 +0,0 @@ -(module types - (add-struct - add-union - add-enum - add-typedef - add-define - - type-match - type-pattern-matches? - map-fields - - add-sum! - get-sum - add-constructor! - get-constructor - variant-fields - reset-declarations! - - add-spec! - get-spec - spec-parameter - spec-methods - add-realization! - realizes? - normalize-fields - - add-method! - get-method - qualify-op - ops-key - - add-name-type! - get-name-type - type-of - current-type-of - get-return-type - - get-type-info - get-tag-info - get-fields - get-underlying-type - - type-head? - named-arg? - named-arg-type - arglist-types - strip-pub - array-bound? - array-element-type) - "types.scm") diff --git a/types.scm b/types.scm index 182ddac..2a7080f 100644 --- a/types.scm +++ b/types.scm @@ -12,9 +12,60 @@ scheme (scheme base) (chicken base) + (chicken module) srfi-1 srfi-69) +(export + add-struct + add-union + add-enum + add-typedef + add-define + + type-match + type-pattern-matches? + map-fields + + add-sum! + get-sum + add-constructor! + get-constructor + variant-fields + reset-declarations! + + add-spec! + get-spec + spec-parameter + spec-methods + add-realization! + realizes? + normalize-fields + + add-method! + get-method + qualify-op + ops-key + + add-name-type! + get-name-type + type-of + current-type-of + get-return-type + + get-type-info + get-tag-info + get-fields + get-underlying-type + + type-head? + named-arg? + named-arg-type + arglist-types + strip-pub + array-bound? + array-element-type) + ;;; Two namespaces: `struct point' and a `point' typedef are separate ;;; declarations. Tags -- struct, union and enum alike -- share the ;;; second table between them diff --git a/utils.module.scm b/utils.module.scm deleted file mode 100644 index 5b3463c..0000000 --- a/utils.module.scm +++ /dev/null @@ -1,25 +0,0 @@ -(module utils - (get-env-var - set-working-directory - to-absolute-pathname - comment-form? - strip-header-comments - list-split - list-join - recons - current-source-file - set-form-source! - form-source - form-file - form-line - form-end-line - copy-form-source! - stamp-form-source! - form-location - set-form-type! - form-type - sex-error - sex-warning - with-directory - ) - "utils.scm") diff --git a/utils.scm b/utils.scm index 326b554..eb862b8 100644 --- a/utils.scm +++ b/utils.scm @@ -2,11 +2,36 @@ scheme (scheme base) ; make-parameter (chicken base) + (chicken module) (chicken pathname) (chicken process-context) srfi-1 srfi-69) +(export + get-env-var + set-working-directory + to-absolute-pathname + comment-form? + strip-header-comments + list-split + list-join + recons + current-source-file + set-form-source! + form-source + form-file + form-line + form-end-line + copy-form-source! + stamp-form-source! + form-location + set-form-type! + form-type + sex-error + sex-warning + with-directory) + (define-syntax prog1 (syntax-rules () ((prog1 form . forms) -- 2.52.0 From c65721a070e6549c7aaf7357f06660b91252b441 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 23:20:38 +0300 Subject: [PATCH 02/20] keep the local egg repository in a file of its own The Makefile was mostly about where the eggs live; what sexc is built from is easier to find without it. --- Makefile | 48 +++--------------------------------------------- eggs.mk | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 45 deletions(-) create mode 100644 eggs.mk diff --git a/Makefile b/Makefile index c6b8fc3..9459d25 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,4 @@ CHICKEN_C ?= csc -CHICKEN_INSTALL ?= chicken-install -CHICKEN_STATUS ?= chicken-status CSC_FLAGS += -K prefix -static # What and why: # -emit-all-import-libraries: Emit import-libraries for all defined modules. @@ -37,27 +35,10 @@ MODULE_FLAGS = -emit-all-import-libraries -module-registration -c MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc OBJ = $(MODULES:%=%.o) -DEPSFILE = dependencies.txt -DEPSLOCK = eggs.lock -EGGS_DIR := $(abspath .eggs) - -# Compiler's own repository (types.db, chicken.*), ignoring ambient venv vars. -SYSTEM_CHICKEN_REPO := $(shell env \ - -u CHICKEN_INSTALL_REPOSITORY -u CHICKEN_REPOSITORY_PATH \ - -u CHICKEN_EGG_CACHE -u CHICKEN_INSTALL_PREFIX \ - $(CHICKEN_INSTALL) -repository 2>/dev/null) -CHICKEN_ABI := $(notdir $(SYSTEM_CHICKEN_REPO)) -EGGS_STAMP := $(EGGS_DIR)/.installed-$(CHICKEN_ABI) - -# Try project-local chicken repository first. In case it doesn't exist (packaging for distros), -# system-wide repository will be used. -unexport CHICKEN_INSTALL_REPOSITORY -unexport CHICKEN_EGG_CACHE -unexport CHICKEN_INSTALL_PREFIX -export CHICKEN_REPOSITORY_PATH := $(EGGS_DIR):$(SYSTEM_CHICKEN_REPO) - all: sexc +include eggs.mk + sexc: $(OBJ) main.scm $(CHICKEN_C) $(CSC_FLAGS) main.scm -o sexc-tmp -link sexc # otherwise csc hangs, probably because it tries to compile to sexc.o first @@ -143,26 +124,6 @@ uninstall: rm -f $(SEX_LIB:lib/%=$(DESTDIR)$(sexlibdir)/%) -rmdir $(DESTDIR)$(sexlibdir) -$(EGGS_STAMP) deps-update: export CHICKEN_EGG_CACHE := $(EGGS_DIR)/cache -$(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_REPOSITORY := $(EGGS_DIR) -$(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_PREFIX := $(EGGS_DIR) -$(EGGS_STAMP) deps-update: export CHICKEN_REPOSITORY_PATH := $(EGGS_DIR):$(SYSTEM_CHICKEN_REPO) - -$(EGGS_STAMP): $(DEPSLOCK) - mkdir -p $(CHICKEN_EGG_CACHE) - $(CHICKEN_INSTALL) -force -from-list $(DEPSLOCK) - touch $@ - -deps: $(EGGS_STAMP) - -deps-update: $(DEPSFILE) deps-clean - mkdir -p $(CHICKEN_EGG_CACHE) - $(CHICKEN_INSTALL) -force $$(cat $(DEPSFILE)) - # Local repo only: a system path here would leak distro eggs into the lock. - CHICKEN_REPOSITORY_PATH=$(EGGS_DIR) $(CHICKEN_STATUS) -list | sort > $(DEPSLOCK).tmp - mv $(DEPSLOCK).tmp $(DEPSLOCK) - touch $(EGGS_STAMP) - clean: rm -f $(OBJ) main.o rm -f *.import.scm @@ -172,9 +133,6 @@ clean: $(MAKE) -C ./tests/modules clean $(MAKE) -C ./tools/sextest clean -deps-clean: - rm -rf $(EGGS_DIR) - .PHONY: all check run-tests check-modules check-exit-code \ install install-strip installdirs uninstall \ - deps deps-update deps-clean clean sex-tests sextest + clean sex-tests sextest diff --git a/eggs.mk b/eggs.mk new file mode 100644 index 0000000..ba5bb42 --- /dev/null +++ b/eggs.mk @@ -0,0 +1,52 @@ +# The eggs sexc needs, in a project-local repository when there is one. +# +# make deps install the versions pinned in eggs.lock into .eggs +# make deps-update install the newest of dependencies.txt, and pin them +# +# Without .eggs (packaging for distros) the system repository is used. + +CHICKEN_INSTALL ?= chicken-install +CHICKEN_STATUS ?= chicken-status + +DEPSFILE = dependencies.txt +DEPSLOCK = eggs.lock +EGGS_DIR := $(abspath .eggs) + +# Compiler's own repository (types.db, chicken.*), ignoring ambient venv vars. +SYSTEM_CHICKEN_REPO := $(shell env \ + -u CHICKEN_INSTALL_REPOSITORY -u CHICKEN_REPOSITORY_PATH \ + -u CHICKEN_EGG_CACHE -u CHICKEN_INSTALL_PREFIX \ + $(CHICKEN_INSTALL) -repository 2>/dev/null) +CHICKEN_ABI := $(notdir $(SYSTEM_CHICKEN_REPO)) +EGGS_STAMP := $(EGGS_DIR)/.installed-$(CHICKEN_ABI) + +# The path replaces CHICKEN's own rather than extending it, so the +# system repository has to be on it too +unexport CHICKEN_INSTALL_REPOSITORY +unexport CHICKEN_EGG_CACHE +unexport CHICKEN_INSTALL_PREFIX +export CHICKEN_REPOSITORY_PATH := $(EGGS_DIR):$(SYSTEM_CHICKEN_REPO) + +$(EGGS_STAMP) deps-update: export CHICKEN_EGG_CACHE := $(EGGS_DIR)/cache +$(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_REPOSITORY := $(EGGS_DIR) +$(EGGS_STAMP) deps-update: export CHICKEN_INSTALL_PREFIX := $(EGGS_DIR) + +$(EGGS_STAMP): $(DEPSLOCK) + mkdir -p $(CHICKEN_EGG_CACHE) + $(CHICKEN_INSTALL) -force -from-list $(DEPSLOCK) + touch $@ + +deps: $(EGGS_STAMP) + +deps-update: $(DEPSFILE) deps-clean + mkdir -p $(CHICKEN_EGG_CACHE) + $(CHICKEN_INSTALL) -force $$(cat $(DEPSFILE)) + # Local repo only: a system path here would leak distro eggs into the lock. + CHICKEN_REPOSITORY_PATH=$(EGGS_DIR) $(CHICKEN_STATUS) -list | sort > $(DEPSLOCK).tmp + mv $(DEPSLOCK).tmp $(DEPSLOCK) + touch $(EGGS_STAMP) + +deps-clean: + rm -rf $(EGGS_DIR) + +.PHONY: deps deps-update deps-clean -- 2.52.0 From a504fc14108e6b0c4a1d1b02822140a0f90f6532 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 23:21:20 +0300 Subject: [PATCH 03/20] build the unit tests and sextest from the root Each subdirectory's Makefile repeated the compiler's module list just to link one program, and its result was copied back to the root anyway. --- .gitignore | 7 +++---- Makefile | 21 +++++++++++---------- tests/Makefile | 21 --------------------- tools/sextest/Makefile | 16 ---------------- 4 files changed, 14 insertions(+), 51 deletions(-) delete mode 100644 tests/Makefile delete mode 100644 tools/sextest/Makefile diff --git a/.gitignore b/.gitignore index db46251..7469404 100644 --- a/.gitignore +++ b/.gitignore @@ -5,10 +5,9 @@ *.o *.import.scm *.link -sexc -sex-tests -sextest -tools/sextest/sextest +/sexc +/sex-tests +/sextest # Scrapped design docs, kept for reference /attic diff --git a/Makefile b/Makefile index 9459d25..dfb57ea 100644 --- a/Makefile +++ b/Makefile @@ -63,14 +63,17 @@ sexc.o: fmt-c-writer.o infer.o reader.o semen.o sex-macros.o sex-modules.o types sex-fmt-c.o: sex-fmt-c.scm $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -o $@ -unit sex-fmt-c -# Unit testing. Both link the modules built here -sex-tests: $(OBJ) - $(MAKE) -C ./tests sex-tests - cp ./tests/sex-tests ./ +# Both link the modules built here, whose import libraries they find +# with the root on the repository path. The tests are built in their +# own directory, where their includes would otherwise find the modules' +# namesakes +WITH_ROOT_REPO = CHICKEN_REPOSITORY_PATH=$(CURDIR):$(CHICKEN_REPOSITORY_PATH) -sextest: reader.o utils.o - $(MAKE) -C ./tools/sextest sextest - cp ./tools/sextest/sextest . +sex-tests: $(wildcard tests/*.scm) $(OBJ) + cd tests && $(WITH_ROOT_REPO) $(CHICKEN_C) $(CSC_FLAGS) run.scm -o ../$@ -link sexc + +sextest: tools/sextest/sextest.scm reader.o utils.o + $(CHICKEN_C) $(CSC_FLAGS) $< -o $@ -link reader,utils SEX_TEST_PROGRAMS = c11 \ closure-signatures \ @@ -129,10 +132,8 @@ clean: rm -f *.import.scm rm -f *.link rm -f sexc sex-tests sextest - $(MAKE) -C ./tests clean $(MAKE) -C ./tests/modules clean - $(MAKE) -C ./tools/sextest clean .PHONY: all check run-tests check-modules check-exit-code \ install install-strip installdirs uninstall \ - clean sex-tests sextest + clean diff --git a/tests/Makefile b/tests/Makefile deleted file mode 100644 index 1e9ac31..0000000 --- a/tests/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -CHICKEN_C = csc - -CSC_FLAGS += -K prefix -static - -# The compiler's modules are built once, in the root; their import -# libraries and objects are found there through the repository path -ROOT = .. -export CHICKEN_REPOSITORY_PATH := $(abspath $(ROOT)):$(or $(CHICKEN_REPOSITORY_PATH),$(shell chicken-install -repository)) - -MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc - -TESTS = basic semen reader fmt-c-writer utils line-directives codegen encapsulation args module-path types infer -TEST_SRCS = $(TESTS:%=%.scm) - -sex-tests: run.scm $(TEST_SRCS) $(MODULES:%=$(ROOT)/%.o) - $(CHICKEN_C) $(CSC_FLAGS) run.scm -o sex-tests -link sexc - -clean: - rm -f sex-tests - -.PHONY: clean diff --git a/tools/sextest/Makefile b/tools/sextest/Makefile deleted file mode 100644 index d589d13..0000000 --- a/tools/sextest/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -CHICKEN_C = csc -CSC_FLAGS += -K prefix -static - -# sextest reuses sexc's reader (and its utils dependency) instead of -# duplicating the S-expression reader: both are linked from the root, -# found there through the repository path -ROOT = ../.. -export CHICKEN_REPOSITORY_PATH := $(abspath $(ROOT)):$(or $(CHICKEN_REPOSITORY_PATH),$(shell chicken-install -repository)) - -sextest: sextest.scm $(ROOT)/reader.o $(ROOT)/utils.o - $(CHICKEN_C) $(CSC_FLAGS) sextest.scm -o sextest -link reader,utils - -clean: - rm -f sextest - -.PHONY: clean -- 2.52.0 From 397766822de6a3ac73251e1d31ddd147375b2489 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 23:21:49 +0300 Subject: [PATCH 04/20] 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. --- .gitignore | 2 + Makefile | 37 +++++++++++------ tools/module-deps.scm | 92 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 12 deletions(-) create mode 100644 tools/module-deps.scm diff --git a/.gitignore b/.gitignore index 7469404..53ae956 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ *.o *.import.scm *.link +/modules.mk +/modules.stamp /sexc /sex-tests /sextest diff --git a/Makefile b/Makefile index dfb57ea..431abc5 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,6 @@ CHICKEN_C ?= csc +# beside csc, whatever it is called: chicken-csc comes with chicken-csi +CSI ?= $(patsubst %csc,%csi,$(CHICKEN_C)) CSC_FLAGS += -K prefix -static # What and why: # -emit-all-import-libraries: Emit import-libraries for all defined modules. @@ -31,14 +33,18 @@ SEX_LIB = $(wildcard lib/*.sex) MODULE_FLAGS = -emit-all-import-libraries -module-registration -c -# Order matters, since module check correctness on compilation -MODULES = utils types infer sex-macros reader sex-modules semen sex-fmt-c fmt-c-writer sexc -OBJ = $(MODULES:%=%.o) - all: sexc include eggs.mk +# MODULES, and a line for each naming the modules it imports, read off +# the import forms. Not for clean, which has to work when they cannot +# be read +ifneq ($(MAKECMDGOALS),clean) +include modules.mk +endif +OBJ = $(MODULES:%=%.o) + sexc: $(OBJ) main.scm $(CHICKEN_C) $(CSC_FLAGS) main.scm -o sexc-tmp -link sexc # otherwise csc hangs, probably because it tries to compile to sexc.o first @@ -46,19 +52,26 @@ sexc: $(OBJ) main.scm #------------------------------------------------------------------ +# The scan is redone whenever a source may have changed what it +# imports, or a NAME.scm may have come to be the module an import +# names; but modules.mk is rewritten only when that changed, since make +# starts over each time it is, and a source dated in the future would +# have it start over for good +modules.mk: modules.stamp ; + +modules.stamp: $(filter-out %.import.scm,$(wildcard *.scm)) tools/module-deps.scm + $(CSI) -s tools/module-deps.scm main.scm > modules.mk.tmp \ + || { rm -f modules.mk.tmp; exit 1; } + if cmp -s modules.mk.tmp modules.mk; then rm modules.mk.tmp; \ + else mv modules.mk.tmp modules.mk; fi + touch $@ + # A module is one file that declares its own exports, made a module by # -module %.o: %.scm $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -module $* -o $@ -unit $* -infer.o: types.o utils.o -reader.o: utils.o -sex-modules.o: reader.o types.o utils.o -semen.o: infer.o sex-macros.o sex-modules.o types.o utils.o -fmt-c-writer.o: sex-fmt-c.o types.o utils.o -sexc.o: fmt-c-writer.o infer.o reader.o semen.o sex-macros.o sex-modules.o types.o utils.o - # Vendored, and a (module ...) form of its own sex-fmt-c.o: sex-fmt-c.scm $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -o $@ -unit sex-fmt-c @@ -128,7 +141,7 @@ uninstall: -rmdir $(DESTDIR)$(sexlibdir) clean: - rm -f $(OBJ) main.o + rm -f *.o modules.mk modules.stamp rm -f *.import.scm rm -f *.link rm -f sexc sex-tests sextest diff --git a/tools/module-deps.scm b/tools/module-deps.scm new file mode 100644 index 0000000..046223e --- /dev/null +++ b/tools/module-deps.scm @@ -0,0 +1,92 @@ +;;; 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 symbolstring 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 Date: Wed, 14 Oct 2026 23:22:10 +0300 Subject: [PATCH 05/20] check modules and exit codes with the test egg Written as shell inside make, a check said only that it failed and left the reason to rerunning it by hand; now each says what it expected. --- Makefile | 22 ++++----- tests/exit-code/Makefile | 32 -------------- tests/exit-code/check.scm | 65 +++++++++++++++++++++++++++ tests/modules/Makefile | 56 ----------------------- tests/modules/check.scm | 93 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 167 insertions(+), 101 deletions(-) delete mode 100644 tests/exit-code/Makefile create mode 100644 tests/exit-code/check.scm delete mode 100644 tests/modules/Makefile create mode 100644 tests/modules/check.scm diff --git a/Makefile b/Makefile index 431abc5..ffa51b9 100644 --- a/Makefile +++ b/Makefile @@ -114,16 +114,15 @@ SEX_TEST_PROGRAMS = c11 \ unnamed-params \ wildcards -# Multi-module linking is checked end to end; see tests/modules/Makefile. -check-modules: sexc - @$(MAKE) --no-print-directory -C ./tests/modules check SEXC=../../sexc - -# The failure paths are checked end to end; see tests/exit-code/Makefile. -check-exit-code: sexc - @$(MAKE) --no-print-directory -C ./tests/exit-code check SEXC=../../sexc - check run-tests: sexc sex-tests sextest - ./sex-tests && ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS:%=./tests/sex-programs/%.sex) && $(MAKE) check-modules && $(MAKE) check-exit-code + ./sex-tests + ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS:%=./tests/sex-programs/%.sex) + @$(MAKE) --no-print-directory check-modules + @$(MAKE) --no-print-directory check-exit-code + +# The end-to-end checks, each on its own: run with the eggs on the path +check-modules check-exit-code: check-%: sexc + cd tests/$* && SEXC='$(CURDIR)/sexc' $(CSI) -s check.scm install: all installdirs $(INSTALL_PROGRAM) sexc $(DESTDIR)$(bindir)/sexc @@ -145,8 +144,5 @@ clean: rm -f *.import.scm rm -f *.link rm -f sexc sex-tests sextest - $(MAKE) -C ./tests/modules clean -.PHONY: all check run-tests check-modules check-exit-code \ - install install-strip installdirs uninstall \ - clean +.PHONY: all check run-tests check-modules check-exit-code install install-strip installdirs uninstall clean diff --git a/tests/exit-code/Makefile b/tests/exit-code/Makefile deleted file mode 100644 index 79b8837..0000000 --- a/tests/exit-code/Makefile +++ /dev/null @@ -1,32 +0,0 @@ -# The failure paths. -# -# Each needs a process to show itself, so none fits the unit suite: -# sexc has to fail when cc fails -- exiting 0 after a failed compile -# makes every driver, sextest included, read it as success -- it has to -# clean up its temporary .c when its own emission throws, and it has to -# refuse `-o -' for an executable, which cc would write to a file named -# `-'. -# -# Everything is built inside a scratch directory, so nothing is left -# here to clean up. - -SEXC ?= ../../sexc - -check: - @d=`mktemp -d`; \ - TMPDIR=$$d $(SEXC) nested-pointer.sex -o $$d/out >/dev/null 2>&1; \ - if [ -n "`find $$d -name '*.c'`" ]; then \ - echo "exit code FAILED: the temporary .c survived a failed emission"; \ - rm -rf $$d; exit 1; \ - fi; \ - if $(SEXC) hello.sex -o $$d/out -- -no-such-cc-flag >/dev/null 2>&1; then \ - echo "exit code FAILED: sexc reported success after cc failed"; \ - rm -rf $$d; exit 1; \ - fi; \ - if (cd $$d && $(abspath $(SEXC)) $(CURDIR)/hello.sex -o - >/dev/null 2>&1) || [ -e $$d/- ]; then \ - echo "exit code FAILED: -o - built an executable"; \ - rm -rf $$d; exit 1; \ - fi; \ - rm -rf $$d; echo "exit code ok" - -.PHONY: check diff --git a/tests/exit-code/check.scm b/tests/exit-code/check.scm new file mode 100644 index 0000000..b3b31e4 --- /dev/null +++ b/tests/exit-code/check.scm @@ -0,0 +1,65 @@ +;;; The failure paths. +;;; +;;; Each needs a process to show itself, so none fits the unit suite: +;;; sexc has to fail when cc fails -- exiting 0 after a failed compile +;;; makes every driver, sextest included, read it as success -- it has to +;;; clean up its temporary .c when its own emission throws, and it has to +;;; refuse `-o -' for an executable, which cc would write to a file named +;;; `-'. +;;; +;;; Everything is built inside a scratch directory, so nothing is left +;;; here to clean up. +;;; +;;; make check-exit-code + +(import scheme + (chicken base) + (chicken file) + (chicken pathname) + (chicken process) + (chicken process-context) + (chicken string) + test) + +;;; A path stays good past the change of directory below; a bare name +;;; is looked up on PATH +(define sexc + (let ((path (or (get-environment-variable "SEXC") "../../sexc"))) + (if (or (absolute-pathname? path) (not (substring-index "/" path))) + path + (make-pathname (current-directory) path)))) + +(define scratch (create-temporary-directory)) +(define out (make-pathname scratch "out")) +(set-environment-variable! "TMPDIR" scratch) + +;;; Whether sexc exits 0 when run with ARGS, saying nothing of it +(define (sexc-succeeds? . args) + (zero? (system (string-append (string-intersperse (map qs (cons sexc args))) + " >/dev/null 2>&1")))) + +;;; Every check below expects a failure, which a sexc that cannot run +;;; gives too +(test "sexc compiles a program" #t + (sexc-succeeds? "hello.sex" "-o" out)) + +(test "a failed emission leaves no temporary .c" '() + (begin + (sexc-succeeds? "nested-pointer.sex" "-o" out) + (glob (make-pathname scratch "*.c")))) + +(test "a failed cc fails sexc" #f + (sexc-succeeds? "hello.sex" "-o" out "--" "-no-such-cc-flag")) + +(define hello (make-pathname (current-directory) "hello.sex")) +(change-directory scratch) + +(test "-o - is refused for an executable" #f + (sexc-succeeds? hello "-o" "-")) + +(test "and leaves no file named -" #f + (file-exists? "-")) + +(delete-directory scratch #t) + +(test-exit) diff --git a/tests/modules/Makefile b/tests/modules/Makefile deleted file mode 100644 index d43c2f1..0000000 --- a/tests/modules/Makefile +++ /dev/null @@ -1,56 +0,0 @@ -# Multi-module linking. -# -# Modules are only testable end to end, and nothing else in the suite -# links more than one translation unit. Three things have to hold at -# once: an imported `pub fn' comes out as a prototype with external -# linkage, an imported `pub var' as an extern declaration, and the -# module's object survives being passed after `--'. Get any of them -# wrong and this fails to link -- or, in the `pub var' case, links and -# quietly counts into a private copy. -# -# It also checks what only a second translation unit can check: that an -# imported type reaches the type database, by expanding a macro that -# reads the imported struct's fields; and that a closure type crossing -# the boundary works both ways -- one built in the module and called -# here, one built here and called there, through a code pointer that is -# static in the other object. And that a record can cross as a handle -# 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. 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. -# -# The interface prints as importers get it: the declarations first, then -# the pub forms in the order they were written. -# -# The app's dependency rule names both modules: greet, which it imports, -# and ledger, which only greet does but which decides what the app is -# told of it. - -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\nboard 42\nledger 2\ncolour 123 - -check: - @head="`$(SEXC) --public-interface greet.sex | head -3`"; \ - if [ "$$head" != "`printf '(record cell)\n(record ledger)\n(include stdio.h)'`" ]; then \ - echo "modules FAILED, the interface begins:"; echo "$$head"; exit 1; \ - fi - @$(SEXC) ledger.sex -c -o ledger.o - @$(SEXC) greet.sex -c -o greet.o - @$(SEXC) greet-app.sex -o greet-app --depfile=greet-app.d -- greet.o ledger.o - @if ! head -1 greet-app.d | grep -q '^greet-app: greet-app.sex .*/greet.sex .*/ledger.sex$$'; then \ - echo "modules FAILED, the dependency rule is:"; cat greet-app.d; $(MAKE) clean; exit 1; \ - fi - @if [ "`./greet-app`" = "`printf '$(EXPECTED)\n'`" ]; then \ - echo "modules ok"; \ - else \ - echo "modules FAILED, got:"; ./greet-app; $(MAKE) clean; exit 1; \ - fi - @$(MAKE) --no-print-directory clean - -clean: - @rm -f greet.o ledger.o greet-app greet-app.d - -.PHONY: check clean diff --git a/tests/modules/check.scm b/tests/modules/check.scm new file mode 100644 index 0000000..7f09d72 --- /dev/null +++ b/tests/modules/check.scm @@ -0,0 +1,93 @@ +;;; Multi-module linking. +;;; +;;; Modules are only testable end to end, and nothing else in the suite +;;; links more than one translation unit. Three things have to hold at +;;; once: an imported `pub fn' comes out as a prototype with external +;;; linkage, an imported `pub var' as an extern declaration, and the +;;; module's object survives being passed after `--'. Get any of them +;;; wrong and this fails to link -- or, in the `pub var' case, links and +;;; quietly counts into a private copy. +;;; +;;; It also checks what only a second translation unit can check: that an +;;; imported type reaches the type database, by expanding a macro that +;;; reads the imported struct's fields; and that a closure type crossing +;;; the boundary works both ways -- one built in the module and called +;;; here, one built here and called there, through a code pointer that is +;;; static in the other object. And that a record can cross as a handle +;;; 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. 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. +;;; +;;; The interface prints as importers get it: the declarations first, then +;;; the pub forms in the order they were written. +;;; +;;; The app's dependency rule names both modules: greet, which it imports, +;;; and ledger, which only greet does but which decides what the app is +;;; told of it. +;;; +;;; make check-modules + +(import scheme + (chicken base) + (chicken file) + (chicken io) + (chicken irregex) + (chicken pathname) + (chicken process) + (chicken process-context) + srfi-1 + test) + +(define sexc (or (get-environment-variable "SEXC") "../../sexc")) + +;;; Where the objects and the app go: not beside the sources, where what +;;; an earlier run left would pass for what this one did not build +(define scratch (create-temporary-directory)) +(define (built name) (make-pathname scratch name)) + +;;; The lines PROGRAM prints when run with ARGS, or #f when it fails +(define (output-of program . args) + (let* ((proc (process program args)) + (lines (read-lines (process-output-port proc)))) + (process-wait proc) + (and (process-returned-normally? proc) + (zero? (process-exit-status proc)) + lines))) + +(test "the interface begins with the declarations" + '("(record cell)" "(record ledger)" "(include stdio.h)") + (take (or (output-of sexc "--public-interface" "greet.sex") '()) 3)) + +(test-assert "the app links with both modules" + (and (output-of sexc "ledger.sex" "-c" "-o" (built "ledger.o")) + (output-of sexc "greet.sex" "-c" "-o" (built "greet.o")) + (output-of sexc "greet-app.sex" "-o" (built "greet-app") + (string-append "--depfile=" (built "greet-app.d")) + "--" (built "greet.o") (built "ledger.o")))) + +(test-assert "the dependency rule names both modules" + (irregex-match ".*/greet-app: greet-app\\.sex .*/greet\\.sex .*/ledger\\.sex" + (call-with-input-file (built "greet-app.d") read-line))) + +(test "the app runs through both" + '("hello, world" + "hello, sex" + "2 greetings" + "text times " + "text times " + "mood 1" + "closure 15 21 201" + "vec2 7 7" + "vec2(3 4)" + "tally 2" + "board 42" + "ledger 2" + "colour 123") + (output-of (built "greet-app"))) + +(delete-directory scratch #t) + +(test-exit) -- 2.52.0 From faa9036dccb947f3798ed8596349998fe2ad8b18 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Wed, 14 Oct 2026 23:22:38 +0300 Subject: [PATCH 06/20] take every program in tests/sex-programs as a test A program left out of the hand-kept list was never run, and nothing said so; the one module the tests import moves to lib/ instead. --- Makefile | 30 +++----------------- tests/sex-programs/{ => lib}/list-macros.sex | 0 tests/sex-programs/lists.sex | 2 +- 3 files changed, 5 insertions(+), 27 deletions(-) rename tests/sex-programs/{ => lib}/list-macros.sex (100%) diff --git a/Makefile b/Makefile index ffa51b9..fc585d0 100644 --- a/Makefile +++ b/Makefile @@ -88,35 +88,13 @@ sex-tests: $(wildcard tests/*.scm) $(OBJ) sextest: tools/sextest/sextest.scm reader.o utils.o $(CHICKEN_C) $(CSC_FLAGS) $< -o $@ -link reader,utils -SEX_TEST_PROGRAMS = c11 \ - closure-signatures \ - closures \ - comments \ - compound-literals \ - encapsulation \ - feature-flags \ - features \ - fixpoint \ - hello-world \ - inference \ - lambdas \ - lists \ - operators \ - ops \ - precedence \ - records \ - serialize \ - specs \ - sums \ - threading \ - type-shapes \ - unicode \ - unnamed-params \ - wildcards +# A program directly in tests/sex-programs is a test; lib/ holds what +# they import +SEX_TEST_PROGRAMS = $(wildcard tests/sex-programs/*.sex) check run-tests: sexc sex-tests sextest ./sex-tests - ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS:%=./tests/sex-programs/%.sex) + ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS) @$(MAKE) --no-print-directory check-modules @$(MAKE) --no-print-directory check-exit-code diff --git a/tests/sex-programs/list-macros.sex b/tests/sex-programs/lib/list-macros.sex similarity index 100% rename from tests/sex-programs/list-macros.sex rename to tests/sex-programs/lib/list-macros.sex diff --git a/tests/sex-programs/lists.sex b/tests/sex-programs/lists.sex index e428a88..399555b 100644 --- a/tests/sex-programs/lists.sex +++ b/tests/sex-programs/lists.sex @@ -9,7 +9,7 @@ (include stddef.h) (include stdio.h) -(import list-macros) +(import lib/list-macros) (struct foo ((a-field float) -- 2.52.0 From 67749c8db04f87a88ec25ef02867a8528e3ff421 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Mon, 19 Oct 2026 21:49:43 +0300 Subject: [PATCH 07/20] build the programs the way the modules are built Each program had its own recipe: a hand-written link list, a cd into tests/ to keep its includes off the modules' namesakes, and an output renamed so as not to overwrite sexc.o. Read off their imports and built from an object named after their source, they share one rule. --- Makefile | 57 ++++++++--------- tests/run.scm | 24 ++++---- tools/module-deps.scm | 140 +++++++++++++++++++++++++++++------------- 3 files changed, 134 insertions(+), 87 deletions(-) diff --git a/Makefile b/Makefile index fc585d0..2024b64 100644 --- a/Makefile +++ b/Makefile @@ -37,20 +37,17 @@ all: sexc include eggs.mk -# MODULES, and a line for each naming the modules it imports, read off -# the import forms. Not for clean, which has to work when they cannot -# be read +# Each program, and the source it is built from +PROGRAMS = sexc=main.scm sextest=tools/sextest/sextest.scm sex-tests=tests/run.scm +PROGRAM_NAMES = $(foreach p,$(PROGRAMS),$(firstword $(subst =, ,$(p)))) +PROGRAM_OBJ = $(foreach p,$(PROGRAMS),$(patsubst %.scm,%.o,$(lastword $(subst =, ,$(p))))) + +# MODULES, and a line for each module and program naming what it +# imports, read off the import forms. Not for clean, which has to work +# when they cannot be read ifneq ($(MAKECMDGOALS),clean) include modules.mk endif -OBJ = $(MODULES:%=%.o) - -sexc: $(OBJ) main.scm - $(CHICKEN_C) $(CSC_FLAGS) main.scm -o sexc-tmp -link sexc - # otherwise csc hangs, probably because it tries to compile to sexc.o first - mv sexc-tmp sexc - -#------------------------------------------------------------------ # The scan is redone whenever a source may have changed what it # imports, or a NAME.scm may have come to be the module an import @@ -59,34 +56,28 @@ sexc: $(OBJ) main.scm # have it start over for good modules.mk: modules.stamp ; -modules.stamp: $(filter-out %.import.scm,$(wildcard *.scm)) tools/module-deps.scm - $(CSI) -s tools/module-deps.scm main.scm > modules.mk.tmp \ +modules.stamp: $(SOURCES) $(filter-out %.import.scm,$(wildcard *.scm)) \ + tools/module-deps.scm dependencies.txt Makefile + $(CSI) -s tools/module-deps.scm $(PROGRAMS) > modules.mk.tmp \ || { rm -f modules.mk.tmp; exit 1; } if cmp -s modules.mk.tmp modules.mk; then rm modules.mk.tmp; \ else mv modules.mk.tmp modules.mk; fi touch $@ +#------------------------------------------------------------------ + # A module is one file that declares its own exports, made a module by -# -module - +# -module, except the vendored sex-fmt-c, a (module ...) form of its own %.o: %.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -module $* -o $@ -unit $* + $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< $(if $(filter sex-fmt-c,$*),,-module $*) -o $@ -unit $* -# Vendored, and a (module ...) form of its own -sex-fmt-c.o: sex-fmt-c.scm - $(CHICKEN_C) $(CSC_FLAGS) $(MODULE_FLAGS) $< -o $@ -unit sex-fmt-c +# A program's object is named after its source: csc names its own after +# -o, and sexc.o is the module's +$(PROGRAM_OBJ): %.o: %.scm + $(CHICKEN_C) $(CSC_FLAGS) -c $< -o $@ -# Both link the modules built here, whose import libraries they find -# with the root on the repository path. The tests are built in their -# own directory, where their includes would otherwise find the modules' -# namesakes -WITH_ROOT_REPO = CHICKEN_REPOSITORY_PATH=$(CURDIR):$(CHICKEN_REPOSITORY_PATH) - -sex-tests: $(wildcard tests/*.scm) $(OBJ) - cd tests && $(WITH_ROOT_REPO) $(CHICKEN_C) $(CSC_FLAGS) run.scm -o ../$@ -link sexc - -sextest: tools/sextest/sextest.scm reader.o utils.o - $(CHICKEN_C) $(CSC_FLAGS) $< -o $@ -link reader,utils +$(PROGRAM_NAMES): + $(CHICKEN_C) $(CSC_FLAGS) $< -o $@ # A program directly in tests/sex-programs is a test; lib/ holds what # they import @@ -118,9 +109,9 @@ uninstall: -rmdir $(DESTDIR)$(sexlibdir) clean: - rm -f *.o modules.mk modules.stamp + rm -f *.o $(PROGRAM_OBJ) modules.mk modules.stamp rm -f *.import.scm - rm -f *.link - rm -f sexc sex-tests sextest + rm -f *.link $(PROGRAM_OBJ:.o=.link) + rm -f $(PROGRAM_NAMES) .PHONY: all check run-tests check-modules check-exit-code install install-strip installdirs uninstall clean diff --git a/tests/run.scm b/tests/run.scm index 8464382..0065c04 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -1,18 +1,18 @@ (import test) -(include "basic.scm") -(include "semen.scm") -(include "reader.scm") -(include "fmt-c-writer.scm") -(include "utils.scm") -(include "line-directives.scm") -(include "codegen.scm") -(include "encapsulation.scm") -(include "args.scm") -(include "module-path.scm") -(include "types.scm") -(include "infer.scm") +(include-relative "basic.scm") +(include-relative "semen.scm") +(include-relative "reader.scm") +(include-relative "fmt-c-writer.scm") +(include-relative "utils.scm") +(include-relative "line-directives.scm") +(include-relative "codegen.scm") +(include-relative "encapsulation.scm") +(include-relative "args.scm") +(include-relative "module-path.scm") +(include-relative "types.scm") +(include-relative "infer.scm") ;;; Should be the last in the test suite (test-exit) diff --git a/tools/module-deps.scm b/tools/module-deps.scm index 046223e..100662e 100644 --- a/tools/module-deps.scm +++ b/tools/module-deps.scm @@ -1,22 +1,34 @@ -;;; 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. +;;; The compiler's modules and the programs built from them, as make +;;; reads them: what each one imports, read off its import forms. A +;;; module is a NAME.scm in the current directory; a program is named +;;; with its source. The files either includes with include-relative +;;; count as its own. ;;; -;;; csi -s tools/module-deps.scm main.scm > modules.mk +;;; csi -s tools/module-deps.scm sexc=main.scm > modules.mk ;;; ;;; prints ;;; ;;; MODULES = fmt-c-writer infer reader ... +;;; SOURCES = fmt-c-writer.scm infer.scm ... main.scm ;;; infer.o: types.o utils.o ;;; ... +;;; main.o: sexc.o +;;; sexc: main.o sexc.o +;;; fmt-c-writer.scm: +;;; ... +;;; +;;; and a source deleted since is then one make has nothing to do for, +;;; rather than one it has no rule to make (import scheme (chicken base) (chicken condition) (chicken file) (chicken io) + (chicken pathname) (chicken process-context) - (chicken sort)) + (chicken sort) + (chicken string)) ;;; As csc reads them, given -K prefix (keyword-style #:prefix) @@ -27,25 +39,16 @@ (spec-name (cadr spec)) spec)) +;;; dependencies.txt names the eggs, so a stray test.scm is not the +;;; module the tests import +(define eggs (call-with-input-file "dependencies.txt" read-list)) + (define (module-file name) (and (symbol? name) + (not (memq name eggs)) (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 @@ -57,36 +60,89 @@ (exit 1)) (call-with-input-file file read-list))) -(define (local-imports file) - (let loop ((names (imported (forms-of file))) - (acc '())) +;;; The names FILE imports, and the files it includes; the vendored +;;; sex-fmt-c imports inside its (module name exports ...) form +(define (scan file) + (let loop ((forms (forms-of file)) (names '()) (files '())) + (if (null? forms) + (values names files) + (let ((form (car forms))) + (cond + ((not (pair? form)) (loop (cdr forms) names files)) + ((and (eq? (car form) 'module) (list? form) (>= (length form) 3)) + (loop (append (cdddr form) (cdr forms)) names files)) + ((eq? (car form) 'import) + (loop (cdr forms) (append (map spec-name (cdr form)) names) files)) + ((eq? (car form) 'include-relative) + (let ((included (make-pathname (pathname-directory file) (cadr form)))) + (let-values (((more-names more-files) (scan included))) + (loop (cdr forms) + (append more-names names) + (append (cons included more-files) files))))) + (else (loop (cdr forms) names files))))))) + +(define (symbolstring a) (symbol->string b))) + +;;; The modules among NAMES, once each +(define (local-modules names) + (let loop ((names names) (acc '())) (cond ((null? names) (sort acc symbolstring 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 '())) +;;; Each module reached from ROOTS, as (name imported-modules . included-files) +(define (module-graph roots) + (let loop ((pending roots) (graph '())) (cond ((null? pending) (sort graph (lambda (a b) (symbolstring name) ".o")) names)) + +(define (rule target prerequisites) + (unless (null? prerequisites) + (print target ": " (string-intersperse prerequisites " ")))) + +;;; sexc=main.scm, read off main.scm and the files it includes +(define-record-type program + (make-program binary object modules sources) + program? + (binary program-binary) + (object program-object) + (modules program-modules) + (sources program-sources)) + +(define (read-program spec) + (let* ((parts (string-split spec "=")) + (source (cadr parts))) + (let-values (((names files) (scan source))) + (make-program (car parts) (pathname-replace-extension source "o") + (local-modules names) (cons source files))))) + +;;; Only core here: modules.mk is made before `make deps' installs eggs +(let* ((programs (map read-program (command-line-arguments))) + (graph (module-graph + (local-modules (apply append (map program-modules programs)))))) + (define sources + (append (apply append (map (lambda (node) (cons (module-file (car node)) (cddr node))) + graph)) + (apply append (map program-sources programs)))) + (print "MODULES = " (string-intersperse (map (o symbol->string car) graph) " ")) + (print "SOURCES = " (string-intersperse sources " ")) (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)) + (rule (car (objects (list (car node)))) + (append (cddr node) (objects (cadr node))))) + graph) + (for-each (lambda (p) + (let ((modules (objects (program-modules p)))) + (rule (program-object p) (append (cdr (program-sources p)) modules)) + (rule (program-binary p) (cons (program-object p) modules)))) + programs) + (for-each (lambda (source) (print source ":")) sources)) -- 2.52.0 From 49b463ac7b732042e970866294339ed1599dd03d Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:46:13 +0300 Subject: [PATCH 08/20] keep a root file named after a CHICKEN module out of the graph Only the eggs were told apart from the modules, so a scheme.scm became the scheme every unit imports, a dependency of every object and of itself, and the build went on to link it. --- tools/module-deps.scm | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tools/module-deps.scm b/tools/module-deps.scm index 100662e..d5f3e35 100644 --- a/tools/module-deps.scm +++ b/tools/module-deps.scm @@ -23,6 +23,7 @@ (import scheme (chicken base) (chicken condition) + (chicken eval) (chicken file) (chicken io) (chicken pathname) @@ -43,11 +44,22 @@ ;;; module the tests import (define eggs (call-with-input-file "dependencies.txt" read-list)) +;;; A scheme.scm is not the module every unit imports. Asked from /, +;;; since here a NAME.import.scm built from NAME.scm would answer +(define (chicken-module? name) + (let ((here (current-directory))) + (dynamic-wind + (lambda () (change-directory "/")) + (lambda () (handle-exceptions exn #f (module-environment name) #t)) + (lambda () (change-directory here))))) + (define (module-file name) (and (symbol? name) (not (memq name eggs)) (let ((file (string-append (symbol->string name) ".scm"))) - (and (file-exists? file) file)))) + (and (file-exists? file) + (not (chicken-module? name)) + file)))) ;;; FILE's forms, or the end of the scan, naming the file that has none (define (forms-of file) -- 2.52.0 From 0628d1c212a3fbc19af8b1ef1ef1d506338a6c47 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:46:13 +0300 Subject: [PATCH 09/20] read a file once in an include cycle Two files that include-relative each other sent the scan between them for good, and make sat on the stamp recipe with it. --- tools/module-deps.scm | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/tools/module-deps.scm b/tools/module-deps.scm index d5f3e35..eede5d3 100644 --- a/tools/module-deps.scm +++ b/tools/module-deps.scm @@ -72,9 +72,11 @@ (exit 1)) (call-with-input-file file read-list))) -;;; The names FILE imports, and the files it includes; the vendored -;;; sex-fmt-c imports inside its (module name exports ...) form -(define (scan file) +;;; The names FILE imports, and the files it includes, skipping those +;;; SEEN already, so two files that include each other are read once +;;; each; the vendored sex-fmt-c imports inside its (module name +;;; exports ...) form +(define (scan file #!optional (seen (list file))) (let loop ((forms (forms-of file)) (names '()) (files '())) (if (null? forms) (values names files) @@ -86,11 +88,15 @@ ((eq? (car form) 'import) (loop (cdr forms) (append (map spec-name (cdr form)) names) files)) ((eq? (car form) 'include-relative) - (let ((included (make-pathname (pathname-directory file) (cadr form)))) - (let-values (((more-names more-files) (scan included))) - (loop (cdr forms) - (append more-names names) - (append (cons included more-files) files))))) + (let ((included (make-pathname (pathname-directory file) (cadr form))) + (seen (append files seen))) + (if (member included seen) + (loop (cdr forms) names files) + (let-values (((more-names more-files) + (scan included (cons included seen)))) + (loop (cdr forms) + (append more-names names) + (append (cons included more-files) files)))))) (else (loop (cdr forms) names files))))))) (define (symbol Date: Tue, 20 Oct 2026 11:46:13 +0300 Subject: [PATCH 10/20] redo the scan when modules.mk is missing The stamp, newer than every source, stood for a modules.mk deleted since, so make went on without the rules and called sex-tests up to date after a test source changed. --- Makefile | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 2024b64..cc626ad 100644 --- a/Makefile +++ b/Makefile @@ -53,11 +53,13 @@ endif # imports, or a NAME.scm may have come to be the module an import # names; but modules.mk is rewritten only when that changed, since make # starts over each time it is, and a source dated in the future would -# have it start over for good +# have it start over for good. A stamp without modules.mk stands for +# nothing, and is redone whatever its date modules.mk: modules.stamp ; modules.stamp: $(SOURCES) $(filter-out %.import.scm,$(wildcard *.scm)) \ - tools/module-deps.scm dependencies.txt Makefile + tools/module-deps.scm dependencies.txt Makefile \ + $(if $(wildcard modules.mk),,FORCE) $(CSI) -s tools/module-deps.scm $(PROGRAMS) > modules.mk.tmp \ || { rm -f modules.mk.tmp; exit 1; } if cmp -s modules.mk.tmp modules.mk; then rm modules.mk.tmp; \ @@ -114,4 +116,4 @@ clean: rm -f *.link $(PROGRAM_OBJ:.o=.link) rm -f $(PROGRAM_NAMES) -.PHONY: all check run-tests check-modules check-exit-code install install-strip installdirs uninstall clean +.PHONY: all check run-tests check-modules check-exit-code install install-strip installdirs uninstall clean FORCE -- 2.52.0 From 4758802810f7e4faa1d1eb32f0c3bcd26b7b6f48 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:48:02 +0300 Subject: [PATCH 11/20] read the unit tests' sources from a file, the way sexc does The reader exported parse-all only so the tests could give a source the file name its locations carry; read-from-file gives it one, through the reader's own interface. The pipeline helpers move out of codegen.scm for every suite to use. --- reader.scm | 5 +-- tests/codegen.scm | 68 +---------------------------------- tests/encapsulation.scm | 3 +- tests/line-directives.scm | 25 ++++++------- tests/pipeline.scm | 75 +++++++++++++++++++++++++++++++++++++++ tests/run.scm | 1 + 6 files changed, 89 insertions(+), 88 deletions(-) create mode 100644 tests/pipeline.scm diff --git a/reader.scm b/reader.scm index a3c058e..9831012 100644 --- a/reader.scm +++ b/reader.scm @@ -27,10 +27,7 @@ read-raw-forms current-features - platform-features - - ;; for the tests - parse-all) + platform-features) ;;; Sentinels for structural tokens (define close-paren (list '%close-paren)) diff --git a/tests/codegen.scm b/tests/codegen.scm index d3cd632..2e1f079 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -6,66 +6,7 @@ ;;; the existing suite, because both need an operand shape that no ;;; earlier test program happened to use. -(import (chicken condition) - (chicken port) - (chicken string) - srfi-13 - fmt-c-writer - reader - semen - utils) - -(define (read-source source) - (with-input-from-string source - (lambda () - (parameterize ((current-source-file "codegen.sex")) - (parse-all (current-input-port)))))) - -(define (sex->c source) - "Compile SOURCE, a string of Sex, and return the generated C." - (let ((forms (read-source source))) - (with-output-to-string - (lambda () - (parameterize ((sex-line-directives 'none)) - (emit-c (semen-process forms))))))) - -;;; Warnings are what `warns?' is for; a test that happens to trip one -;;; should not print it -(define (silently thunk) - "THUNK's value, with whatever it wrote to stderr dropped." - (let ((value #f)) - (with-error-output-to-string (lambda () (set! value (thunk)))) - value)) - -(define (emits? source fragment) - (and (string-contains (silently (lambda () (sex->c source))) fragment) #t)) - -(define (failure-message thunk) - "The error THUNK raises as the user sees it -- message plus arguments, -the way CHICKEN prints it -- or #f if it raises none." - (handle-exceptions e - (with-output-to-string - (lambda () - (display ((condition-property-accessor 'exn 'message) e)) - (for-each (lambda (a) (display " ") (write a)) - ((condition-property-accessor 'exn 'arguments) e)))) - (begin (thunk) #f))) - -(define (fails-with? thunk fragment) - (let ((m (failure-message thunk))) - (and m (string-contains m fragment) #t))) - -(define (reports? source fragment) - (fails-with? (lambda () (sex->c source)) fragment)) - -(define (followed-by? source first then) - "Is FIRST in the C compiled from SOURCE, and the next thing past it, -whitespace aside, THEN?" - (let* ((c (silently (lambda () (sex->c source)))) - (at (string-contains c first))) - (and at - (let ((next (string-skip c char-whitespace? (+ at (string-length first))))) - (and next (string-prefix? then (substring c next))))))) +(import srfi-13) (define (in-fn body) (string-append "(fn f ((a int) (b int)) void " body ")")) @@ -80,13 +21,6 @@ whitespace aside, THEN?" " (var p (struct point)) (var pp (* struct point) (& p))" " (var l (struct line)) " body ")")) -(define (warnings source) - "What compiling SOURCE writes to stderr." - (with-error-output-to-string (lambda () (sex->c source)))) - -(define (warns? source fragment) - (and (string-contains (warnings source) fragment) #t)) - (test-group "codegen" ;; A case body shared the switch's scope, so two cases could not diff --git a/tests/encapsulation.scm b/tests/encapsulation.scm index d4d9a67..6dcc47a 100644 --- a/tests/encapsulation.scm +++ b/tests/encapsulation.scm @@ -5,8 +5,7 @@ ;;; is checked here is what the compiler refuses, and that it refuses ;;; it with the name of whatever is wrong. ;;; -;;; `sex->c', `read-source', `fails-with?', `emits?', `reports?' -;;; and `in-fn' come from codegen.scm, which run.scm includes first. +;;; `in-fn' comes from codegen.scm, which run.scm includes first. (import sex-modules) diff --git a/tests/line-directives.scm b/tests/line-directives.scm index 7a82100..b27286e 100644 --- a/tests/line-directives.scm +++ b/tests/line-directives.scm @@ -17,14 +17,13 @@ ;;; get the true source line) and in the C output (to get the line the ;;; directives claim). The two must agree. -(import (chicken port) +(import (chicken pathname) + (chicken port) (chicken string) srfi-1 srfi-13 fmt-c-writer - reader - semen - utils) + semen) ;;; ------------------------------------------------------------------ ;;; Fixture. Line numbers are in the trailing comments; keep them @@ -98,15 +97,9 @@ ;;; Pipeline and #line accounting (define (compile-to-c source) - "Run reader -> semen -> writer on SOURCE, returning the generated C. -parse-all is called directly rather than through read-raw-forms so the -fixture can be given a file name: a location carries one, and the -file is what makes an imported module report itself rather than the unit -that imported it." - (let ((forms (with-input-from-string source - (lambda () - (parameterize ((current-source-file "fixture.sex")) - (parse-all (current-input-port))))))) + "Run reader -> semen -> writer on SOURCE, read from fixture.sex, +returning the generated C." + (let ((forms (read-source source "fixture.sex"))) (with-output-to-string (lambda () (emit-c (semen-process forms)))))) @@ -247,6 +240,8 @@ after that is one more. Lines before the first directive get #f." ;; form was read from. (test-group "file name" (test "every directive names the fixture" - (list "\"fixture.sex\"") + (list "fixture.sex") (delete-duplicates - (filter values (map directive-file (split-lines c-out))))))) + (map (lambda (quoted) + (pathname-strip-directory (string-trim-both quoted #\"))) + (filter values (map directive-file (split-lines c-out)))))))) diff --git a/tests/pipeline.scm b/tests/pipeline.scm new file mode 100644 index 0000000..253f511 --- /dev/null +++ b/tests/pipeline.scm @@ -0,0 +1,75 @@ +;;; Sex source in, C or the error it raises out, the way sexc runs +;;; the pipeline: reader -> semen -> writer. The suites after this one +;;; check the compiler through these. + +(import (chicken condition) + (chicken file) + (chicken pathname) + (chicken port) + srfi-13 + fmt-c-writer + reader + semen) + +(define (read-source source #!optional (name "codegen.sex")) + "The forms of SOURCE, read from a file NAME, which is what the +locations then name: (read-source \"(f)\") reads (f) from codegen.sex." + (let* ((dir (create-temporary-directory)) + (file (make-pathname dir name))) + (with-output-to-file file (lambda () (display source))) + (let ((forms (read-from-file file))) + (delete-directory dir #t) + forms))) + +(define (sex->c source) + "Compile SOURCE, a string of Sex, and return the generated C." + (let ((forms (read-source source))) + (with-output-to-string + (lambda () + (parameterize ((sex-line-directives 'none)) + (emit-c (semen-process forms))))))) + +;;; Warnings are what `warns?' is for; a test that happens to trip one +;;; should not print it +(define (silently thunk) + "THUNK's value, with whatever it wrote to stderr dropped." + (let ((value #f)) + (with-error-output-to-string (lambda () (set! value (thunk)))) + value)) + +(define (emits? source fragment) + (and (string-contains (silently (lambda () (sex->c source))) fragment) #t)) + +(define (failure-message thunk) + "The error THUNK raises as the user sees it -- message plus arguments, +the way CHICKEN prints it -- or #f if it raises none." + (handle-exceptions e + (with-output-to-string + (lambda () + (display ((condition-property-accessor 'exn 'message) e)) + (for-each (lambda (a) (display " ") (write a)) + ((condition-property-accessor 'exn 'arguments) e)))) + (begin (thunk) #f))) + +(define (fails-with? thunk fragment) + (let ((m (failure-message thunk))) + (and m (string-contains m fragment) #t))) + +(define (reports? source fragment) + (fails-with? (lambda () (sex->c source)) fragment)) + +(define (followed-by? source first then) + "Is FIRST in the C compiled from SOURCE, and the next thing past it, +whitespace aside, THEN?" + (let* ((c (silently (lambda () (sex->c source)))) + (at (string-contains c first))) + (and at + (let ((next (string-skip c char-whitespace? (+ at (string-length first))))) + (and next (string-prefix? then (substring c next))))))) + +(define (warnings source) + "What compiling SOURCE writes to stderr." + (with-error-output-to-string (lambda () (sex->c source)))) + +(define (warns? source fragment) + (and (string-contains (warnings source) fragment) #t)) diff --git a/tests/run.scm b/tests/run.scm index 0065c04..b31b48a 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -1,6 +1,7 @@ (import test) +(include-relative "pipeline.scm") (include-relative "basic.scm") (include-relative "semen.scm") (include-relative "reader.scm") -- 2.52.0 From 6198c51e8876bb68664d714f9c84a1c67c7267b5 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:48:45 +0300 Subject: [PATCH 12/20] look up a module on SEX_MODULE_PATH through an import in its test The test read the search list off get-module-paths, exported for it alone; importing a module from each entry checks what the list is for. --- sex-modules.scm | 5 +---- tests/module-path.scm | 40 ++++++++++++++++++++++++++++------------ 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/sex-modules.scm b/sex-modules.scm index 8044d76..21acc86 100644 --- a/sex-modules.scm +++ b/sex-modules.scm @@ -20,10 +20,7 @@ load-persistent-module-paths check-public-interface module-dependencies - read-public-interface - - ;; for the tests - get-module-paths) + read-public-interface) (define +persistent-module-paths+ (list)) diff --git a/tests/module-path.scm b/tests/module-path.scm index fbce788..e078106 100644 --- a/tests/module-path.scm +++ b/tests/module-path.scm @@ -1,22 +1,38 @@ ;;; Where imports are looked for. SEX_MODULE_PATH is read once, at the ;;; start, from the directory sexc was started in. -(import (chicken pathname) +(import (chicken file) + (chicken pathname) (chicken process-context) + semen sex-modules) +(define (write-module dir name) + (create-directory dir #t) + (with-output-to-file (make-pathname dir name "sex") + (lambda () (display "(pub fn found () int)")))) + (test-group "module path" ;; make-absolute-pathname took `src' for a directory under the root, ;; and an import searched /src/ - (set-environment-variable! "SEX_MODULE_PATH" "src:/abs/lib") - (load-persistent-module-paths) - (test "a relative entry is from the working directory" - (make-absolute-pathname (current-directory) "src") - (second (get-module-paths))) - (test "an absolute one is as written" - "/abs/lib" - (third (get-module-paths))) + (let ((start (current-directory)) + (scratch (create-temporary-directory))) + (write-module (make-pathname scratch "src") "mp-relative") + (write-module (make-pathname scratch "lib") "mp-absolute") + (change-directory scratch) + (set-environment-variable! "SEX_MODULE_PATH" + (string-append "src:" (make-pathname scratch "lib"))) + (load-persistent-module-paths) + (change-directory start) - (set-environment-variable! "SEX_MODULE_PATH" "") - (load-persistent-module-paths) - (unset-environment-variable! "SEX_MODULE_PATH")) + (test "a relative entry is from the working directory" + '((pub fn found () int)) + (semen-process '((import mp-relative)))) + (test "an absolute one is as written" + '((pub fn found () int)) + (semen-process '((import mp-absolute)))) + + (set-environment-variable! "SEX_MODULE_PATH" "") + (load-persistent-module-paths) + (unset-environment-variable! "SEX_MODULE_PATH") + (delete-directory scratch #t))) -- 2.52.0 From ab881e4c311596236fe35ff428d7af8156d5e679 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:49:29 +0300 Subject: [PATCH 13/20] test semen through semen-process alone Its fn accessors, walk-form and macro-expand were exported to be called on hand-built forms, checking what every compiled function and macro already goes through; sex-fn-public? and sex-fn-body had no other caller. --- semen.scm | 14 +------------- tests/semen.scm | 42 ++---------------------------------------- 2 files changed, 3 insertions(+), 53 deletions(-) diff --git a/semen.scm b/semen.scm index e2be434..353bc39 100644 --- a/semen.scm +++ b/semen.scm @@ -19,11 +19,7 @@ ) (export/rename (process semen-process)) -(export closure-env-declaration - ;; for the tests - sex-fn? sex-fn-public? sex-fn-name sex-fn-arglist - sex-fn-return-type sex-fn-prototype sex-fn-body - walk-form macro-expand) +(export closure-env-declaration) ;;; for lambda extraction, docstring processing, macro expansion, ;;; injection of module headers, i.e. all things that rearrange code @@ -1965,9 +1961,6 @@ Returns #f if the form is not a function, returns the form otherwise" ('extern 'fn . _)) form) (else #f))) -(define (sex-fn-public? fn-form) - (eq? (first fn-form) 'pub)) - (define (sex-fn-name fn-form) (assert (sex-fn? fn-form) (fmt #f "Form " fn-form " is not a function")) @@ -1982,8 +1975,3 @@ Returns #f if the form is not a function, returns the form otherwise" (assert (sex-fn? fn-form) (fmt #f "Form " fn-form " is not a function")) (fourth (fn-core fn-form))) - -(define (sex-fn-body fn-form) - (assert (sex-fn? fn-form) - (fmt #f "Form " fn-form " is not a function")) - (drop fn-form (fn-header-length fn-form))) diff --git a/tests/semen.scm b/tests/semen.scm index 3e685ec..0b89554 100644 --- a/tests/semen.scm +++ b/tests/semen.scm @@ -1,35 +1,8 @@ -(import srfi-69 - semen +(import semen types) -(define print-str-fn - '(fn print-str ((s string)) void - (printf "%s" s))) - -(define sum-fn - '(pub fn sum ((a int) (b int)) float - (return (cast (+ a b) float)))) - (test-group "semen" - (test-assert (sex-fn? print-str-fn)) - (test #f (sex-fn-public? print-str-fn)) - (test 'void (sex-fn-return-type print-str-fn)) - (test 'print-str (sex-fn-name print-str-fn)) - (test '((s string)) (sex-fn-arglist print-str-fn)) - (test '(fn print-str ((s string)) void) (sex-fn-prototype print-str-fn)) - (test '((printf "%s" s)) (sex-fn-body print-str-fn)) - - (test-assert (sex-fn? sum-fn)) - (test #t (sex-fn-public? sum-fn)) - (test 'float (sex-fn-return-type sum-fn)) - (test 'sum (sex-fn-name sum-fn)) - (test '((a int) (b int)) (sex-fn-arglist sum-fn)) - (test '(pub fn sum ((a int) (b int)) float) (sex-fn-prototype sum-fn)) - (test '((return (cast (+ a b) float))) (sex-fn-body sum-fn)) - - (test-assert (sex-fn? '(extern fn foo () void))) - (test 'foo (sex-fn-name '(extern fn foo () void))) - (test #f (sex-fn? '(struct point ((x int))))) +;;; Macro expansion (let ((sex-code '((defmacro (sum-var name a b c) @@ -39,17 +12,6 @@ (test '((var v 6)) (semen-process sex-code))) -;;; Macro expansion - - (define (form-identity form env) - form) - - (test 'a (walk-form 'a form-identity (make-hash-table))) - (test '(a b c) (walk-form '(a b c) form-identity (make-hash-table))) - - (test 'a (macro-expand 'a)) - (test '(a b c) (macro-expand '(a b c))) - (let ((sex-code-macro '((defmacro (x10 a) `(* 10 ,a)) -- 2.52.0 From 600b4801deeeffefd30261215ccf50f72dc30acd Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:51:31 +0300 Subject: [PATCH 14/20] check sexc's command line on a sexc process The -- split, the -o - spelling and the dependency rule were exported to be unit tested, as lists and strings sexc might never hand on; a stand-in cc and the depfile show what it does hand on. --- Makefile | 5 +- sexc.scm | 6 +- tests/args.scm | 83 --------------------------- tests/command-line/cc | 4 ++ tests/command-line/check.scm | 108 +++++++++++++++++++++++++++++++++++ tests/command-line/hello.sex | 2 + tests/modules/check.scm | 8 +++ tests/run.scm | 1 - 8 files changed, 126 insertions(+), 91 deletions(-) delete mode 100644 tests/args.scm create mode 100755 tests/command-line/cc create mode 100644 tests/command-line/check.scm create mode 100644 tests/command-line/hello.sex diff --git a/Makefile b/Makefile index cc626ad..06e5cb0 100644 --- a/Makefile +++ b/Makefile @@ -90,9 +90,10 @@ check run-tests: sexc sex-tests sextest ./sextest --sexc=./sexc $(SEX_TEST_PROGRAMS) @$(MAKE) --no-print-directory check-modules @$(MAKE) --no-print-directory check-exit-code + @$(MAKE) --no-print-directory check-command-line # The end-to-end checks, each on its own: run with the eggs on the path -check-modules check-exit-code: check-%: sexc +check-modules check-exit-code check-command-line: check-%: sexc cd tests/$* && SEXC='$(CURDIR)/sexc' $(CSI) -s check.scm install: all installdirs @@ -116,4 +117,4 @@ clean: rm -f *.link $(PROGRAM_OBJ:.o=.link) rm -f $(PROGRAM_NAMES) -.PHONY: all check run-tests check-modules check-exit-code install install-strip installdirs uninstall clean FORCE +.PHONY: all check run-tests check-modules check-exit-code check-command-line install install-strip installdirs uninstall clean FORCE diff --git a/sexc.scm b/sexc.scm index 80b4e27..001da07 100644 --- a/sexc.scm +++ b/sexc.scm @@ -22,11 +22,7 @@ utils) (export - main - - ;; for the tests - args-before-separator args-after-separator - dependency-rule spell-stdout-output) + main) ;;; Main function facilities diff --git a/tests/args.scm b/tests/args.scm deleted file mode 100644 index a757a1b..0000000 --- a/tests/args.scm +++ /dev/null @@ -1,83 +0,0 @@ -;;; Splitting the command line at `--'. -;;; -;;; getopt-long cannot do this: it consumes the separator and merges -;;; everything after it into `@' alongside the input file. So sexc -;;; splits the raw argv first, and only the head is parsed as options. -;;; Everything else reaches the C compiler exactly as written -- -;;; including the words that do not start with a dash, which a previous -;;; leading-dash heuristic used to drop. - -(import sexc) - -(define full '("foo.sex" "-o" "bar" "--" "-framework" "OpenGL" "-Wall")) - -(test-group "argument separator" - - (test "options and input file stay with sexc" - '("foo.sex" "-o" "bar") - (args-before-separator full)) - - (test "the tail reaches the compiler verbatim" - '("-framework" "OpenGL" "-Wall") - (args-after-separator full)) - - ;; The case that motivated this: `OpenGL' has no leading dash and was - ;; silently dropped, leaving `-framework' to swallow whatever flag - ;; came next. - (test "a word without a dash survives" - '("-framework" "OpenGL") - (args-after-separator '("x.sex" "--" "-framework" "OpenGL"))) - - (test "no separator means nothing for the compiler" - '() - (args-after-separator '("foo.sex" "-o" "bar"))) - - (test "no separator leaves every argument with sexc" - '("foo.sex" "-o" "bar") - (args-before-separator '("foo.sex" "-o" "bar"))) - - (test "a trailing separator is allowed" - '() - (args-after-separator '("foo.sex" "--"))) - - (test "a leading separator leaves no input file" - '() - (args-before-separator '("--" "-lm"))) - - ;; Only the first `--' separates; a later one is an ordinary compiler - ;; argument (ld takes several). - (test "only the first separator counts" - '("-Wl,--as-needed" "--" "-lm") - (args-after-separator '("x.sex" "--" "-Wl,--as-needed" "--" "-lm"))) - - (test "an empty command line is handled" - '() - (args-before-separator '())) - - ;; getopt-long reads a lone `-' as an option and refused `-o -', so - ;; it is handed the one spelling it takes a dash in - (test "-o - reaches getopt-long as a value" - '("x.sex" "--output=-" "-C") - (spell-stdout-output '("x.sex" "-o" "-" "-C"))) - (test "and so does --output -" - '("--output=-") - (spell-stdout-output '("--output" "-"))) - (test "any other output is left alone" - '("-o" "out" "-") - (spell-stdout-output '("-o" "out" "-")))) - -;;; --depfile: an import pastes another file's forms into the output, so -;;; the output depends on that file as a C object does on a header -(test-group "dependency rule" - (test "the target, the source and the modules, then a rule per module" - "app.o: app.sex /m/greet.sex /m/ledger.sex\n\n/m/greet.sex:\n\n/m/ledger.sex:\n" - (dependency-rule "app.o" "app.sex" '("/m/greet.sex" "/m/ledger.sex"))) - (test "no modules, no rules of their own" - "app.o: app.sex\n" - (dependency-rule "app.o" "app.sex" '())) - (test "a space is escaped, the way make reads it" - "a\\ b.o: a\\ b.sex\n" - (dependency-rule "a b.o" "a b.sex" '())) - (test "stdin is no file to depend on" - "app.o: /m/greet.sex\n\n/m/greet.sex:\n" - (dependency-rule "app.o" #f '("/m/greet.sex")))) diff --git a/tests/command-line/cc b/tests/command-line/cc new file mode 100755 index 0000000..643e16b --- /dev/null +++ b/tests/command-line/cc @@ -0,0 +1,4 @@ +#!/bin/sh +# Stands in for the C compiler: writes the arguments it was given, one +# to a line, to $CC_ARGUMENTS +printf '%s\n' "$@" > "$CC_ARGUMENTS" diff --git a/tests/command-line/check.scm b/tests/command-line/check.scm new file mode 100644 index 0000000..28276b1 --- /dev/null +++ b/tests/command-line/check.scm @@ -0,0 +1,108 @@ +;;; What sexc makes of its command line. +;;; +;;; Everything after the first `--' is the C compiler's, word for word; +;;; `-o -' is stdout; --depfile writes a make rule. Each shows only in +;;; what a sexc process hands on, so each is checked on one. `cc' here +;;; stands in for the compiler and writes down the arguments it got. +;;; +;;; make check-command-line + +(import scheme + (chicken base) + (chicken file) + (chicken io) + (chicken pathname) + (chicken process) + (chicken process-context) + (chicken string) + srfi-1 + test) + +(define sexc (or (get-environment-variable "SEXC") "../../sexc")) + +(define scratch (create-temporary-directory)) +(define (built name) (make-pathname scratch name)) + +(define cc-arguments-file (built "cc-arguments")) +(set-environment-variable! "CC_ARGUMENTS" cc-arguments-file) +(define cc-option (string-append "--c-compiler=" (make-pathname (current-directory) "cc"))) + +;;; The lines sexc prints when run with ARGS and INPUT on its stdin, or +;;; #f when it fails +(define (output-with-input input . args) + (let ((proc (process sexc args))) + (display input (process-input-port proc)) + (close-output-port (process-input-port proc)) + (let ((lines (read-lines (process-output-port proc)))) + (process-wait proc) + (and (process-returned-normally? proc) + (zero? (process-exit-status proc)) + lines)))) + +(define (output-of . args) + (apply output-with-input "" args)) + +(define (cc-arguments) + (call-with-input-file cc-arguments-file read-lines)) + +;;; ("-o" "a" "/tmp/x.c" "-lm") -> ("-lm") +(define (past-c-file arguments) + (cdr (find-tail (lambda (a) (equal? (pathname-extension a) "c")) arguments))) + +;;; What the compiler got past sexc's own -o and .c file, when sexc +;;; compiles with ARGS +(define (cc-tail . args) + (and (apply output-of cc-option args) + (past-c-file (cc-arguments)))) + +(define hello (string-intersperse (call-with-input-file "hello.sex" read-lines) "\n")) + +(test-group "--" + ;; `OpenGL' has no dash, and was once dropped for it, leaving + ;; -framework to swallow whatever came next + (test "what follows reaches the compiler as written" + '("-framework" "OpenGL" "-Wall") + (cc-tail "hello.sex" "-o" (built "a") "--" "-framework" "OpenGL" "-Wall")) + (test "what precedes stays with sexc" + (list "-o" (built "a")) + (begin (cc-tail "hello.sex" "-o" (built "a") "--" "-lm") + (take (cc-arguments) 2))) + (test "without one the compiler gets nothing more" + '() + (cc-tail "hello.sex" "-o" (built "a"))) + (test "nor after a trailing one" + '() + (cc-tail "hello.sex" "-o" (built "a") "--")) + ;; ld takes a `--' of its own + (test "only the first one separates" + '("-Wl,--as-needed" "--" "-lm") + (cc-tail "hello.sex" "-o" (built "a") "--" "-Wl,--as-needed" "--" "-lm")) + (test "a file after it is the compiler's, and the source is stdin" + '("extra.o") + (and (output-with-input hello cc-option "-o" (built "a") "--" "extra.o") + (past-c-file (cc-arguments))))) + +;;; getopt-long reads a lone `-' as an option, and refused `-o -' +(test-group "-o -" + (test-assert "writes the C to stdout" + (member "int main (void) {" (or (output-of "hello.sex" "-C" "-o" "-") '()))) + (test-assert "and so does --output -" + (member "int main (void) {" (or (output-of "hello.sex" "-C" "--output" "-") '())))) + +;;; The rules for the modules a unit imports are checked in tests/modules +(test-group "--depfile" + (copy-file "hello.sex" (built "a b.sex")) + (test "a space is escaped, the way make reads it" + (list (string-append (built "a\\ b.c") ": " (built "a\\ b.sex"))) + (and (output-of (built "a b.sex") "-C" "-o" (built "a b.c") + (string-append "--depfile=" (built "a b.d"))) + (call-with-input-file (built "a b.d") read-lines))) + (test "stdin is no file to depend on" + (list (string-append (built "hello.c") ":")) + (and (output-with-input hello "-C" "-o" (built "hello.c") + (string-append "--depfile=" (built "hello.d"))) + (call-with-input-file (built "hello.d") read-lines)))) + +(delete-directory scratch #t) + +(test-exit) diff --git a/tests/command-line/hello.sex b/tests/command-line/hello.sex new file mode 100644 index 0000000..28bf140 --- /dev/null +++ b/tests/command-line/hello.sex @@ -0,0 +1,2 @@ +(pub fn main () int + (return 0)) diff --git a/tests/modules/check.scm b/tests/modules/check.scm index 7f09d72..71e68ae 100644 --- a/tests/modules/check.scm +++ b/tests/modules/check.scm @@ -72,6 +72,14 @@ (irregex-match ".*/greet-app: greet-app\\.sex .*/greet\\.sex .*/ledger\\.sex" (call-with-input-file (built "greet-app.d") read-line))) +;;; Each module has a rule of its own, so make takes one deleted since as +;;; out of date rather than as a file it has no rule to make +(test "and gives each a rule of its own" + '("greet.sex:" "ledger.sex:") + (filter-map (lambda (line) + (and (irregex-match ".*\\.sex:" line) (pathname-strip-directory line))) + (call-with-input-file (built "greet-app.d") read-lines))) + (test "the app runs through both" '("hello, world" "hello, sex" diff --git a/tests/run.scm b/tests/run.scm index b31b48a..20e72f8 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -10,7 +10,6 @@ (include-relative "line-directives.scm") (include-relative "codegen.scm") (include-relative "encapsulation.scm") -(include-relative "args.scm") (include-relative "module-path.scm") (include-relative "types.scm") (include-relative "infer.scm") -- 2.52.0 From 13d20a102d1e6661b42435654f32113a42d9560d Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:54:37 +0300 Subject: [PATCH 15/20] keep what follows the star of a pointer to a tagged type fmt-c wrote (const * struct what) as struct what*, and (* * struct what) as struct what*, a pointer short; a pointer to an enum crashed it, the star taken for the enum's values. --- sex-fmt-c.scm | 14 +++++++++++--- tests/codegen.scm | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/sex-fmt-c.scm b/sex-fmt-c.scm index 4be8e0c..6b02d3b 100644 --- a/sex-fmt-c.scm +++ b/sex-fmt-c.scm @@ -664,7 +664,13 @@ "") (if (not (null? body)) (cat body) - "")))))) + "") + (c-type-words o)))))) + + ;; MODIFIED FROM UPSTREAM fmt-c: what follows the first star of a + ;; tagged type, `* const' in (struct what * const), was dropped + (define (c-type-words words) + (fmt-join (lambda (word) (cat " " word)) words "")) (define (c-struct . args) (apply c-struct/aux "struct" args)) (define (c-union . args) (apply c-struct/aux "union" args)) @@ -679,13 +685,15 @@ (if (pair? x) (cat (car x) " = " (c-expr (cadr x))) (dsp x))) (let* ((name (if (null? o) (if (or (symbol? x) (string? x)) x #f) x)) (vals (if name (if (null? o) #f (car o)) x))) - (if vals + ;; MODIFIED FROM UPSTREAM fmt-c: (enum mood * const) is a + ;; pointer, and its star was taken for the list of values + (if (pair? vals) (c-wrap-stmt (cat (c-braced-block (if name (cat "enum " name) (dsp "enum")) (c-in-expr (apply c-begin (map c-enum-one vals)))))) - (c-wrap-stmt (cat "enum " name))))) + (c-wrap-stmt (cat "enum " name (or vals "") (c-type-words (if vals (cdr o) '()))))))) (define (c-attribute . args) (cat "__attribute__ ((" (fmt-join c-expr args ", ") "))")) diff --git a/tests/codegen.scm b/tests/codegen.scm index 2e1f079..eff2537 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -855,6 +855,22 @@ (< (string-contains c "static int λ0_f (int x)") (string-contains c "(*f)(int) = λ0_f"))))) + ;; fmt-c kept the first star after a tag and dropped what followed it, + ;; and took an enum's star for its list of values + (test-group "pointers to tagged types" + (test-assert "a const pointer to a struct stays const" + (emits? "(var q (const * struct what))" "struct what* const q;")) + (test-assert "and one in an array" + (emits? "(var a [const * struct what 4])" "struct what* const a[4];")) + (test-assert "a pointer to a pointer keeps both stars" + (emits? "(var pp (* * struct what))" "struct what* * pp;")) + (test-assert "so does a union's" + (emits? "(var u (const * union val))" "union val* const u;")) + (test-assert "a pointer to an enum is a pointer" + (emits? "(enum mood (glad sad)) (var e (* enum mood))" "enum mood* e;")) + (test-assert "and a const one" + (emits? "(enum mood (glad sad)) (var f (const * enum mood))" "enum mood* const f;"))) + ;; Toplevel forms used to be separated by a blank line unconditionally, ;; which spread a block of adjacent typedefs over twice the lines its ;; author wrote -- 2.52.0 From bf8ba2f9fdaee94540b7fafc45ed161e73e0c5d2 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 11:56:02 +0300 Subject: [PATCH 16/20] test the writer on the C it writes The walk-* tests pinned the forms handed to fmt-c, which were right while the C they became lost a const; spelled as C, they check what fmt-c makes of them too. The cases no source can reach, an atom no form holds and a name the reader takes for a negation, go. --- fmt-c-writer.scm | 6 +- tests/basic.scm | 58 -------- tests/codegen.scm | 10 +- tests/fmt-c-writer.scm | 306 +++++++++++++++++------------------------ tests/run.scm | 1 - 5 files changed, 127 insertions(+), 254 deletions(-) delete mode 100644 tests/basic.scm diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index 5df7346..eb4b9b3 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -19,11 +19,7 @@ (export emit-c - sex-line-directives - - ;; for the tests - atom-to-fmt-c unkebabify type-convert-to-c - process-toplevel-form walk-expr walk-type walk-var walk-fn-def walk-struct) + sex-line-directives) ;;; egg `tree' not ported to CHICKEN 6 yet (define (tree-map f tree) diff --git a/tests/basic.scm b/tests/basic.scm deleted file mode 100644 index f03157d..0000000 --- a/tests/basic.scm +++ /dev/null @@ -1,58 +0,0 @@ -(import fmt-c-writer) - -(test-group "basic" - - ;; unkebabify - (test '- (unkebabify '-)) - (test '-- (unkebabify '--)) - (test '-> (unkebabify '->)) - (test '-= (unkebabify '-=)) - (test 'kebab_case (unkebabify 'kebab-case)) - (test '_what_ (unkebabify '-what-)) - (test 'this->member (unkebabify 'this->member)) - (test '_this_->_member_ (unkebabify '-this-->-member-)) - (test '__->>> (unkebabify '--->>>)) - - ;; A Lisp predicate and mutator, in letters C takes. The operators - ;; spelled with the same characters are not names - (test 'ident_startʔ (unkebabify 'ident-start?)) - (test 'resetꜝ (unkebabify 'reset!)) - (test '! (unkebabify '!)) - (test '!= (unkebabify '!=)) - - ;; Non-ASCII identifiers must survive intact. The `regex' egg's - ;; string-substitute drops one trailing character per multi-byte - ;; character, which renames things silently -- the C still compiles, - ;; just under a different name than was written. - (test 'naïve_count (unkebabify 'naïve-count)) - (test 'aï_b (unkebabify 'aï-b)) - (test 'ïï (unkebabify 'ïï)) - - ;; atom-to-fmt-c - (test '%fun (atom-to-fmt-c 'fn)) - (test '%prototype (atom-to-fmt-c 'prototype)) - (test '%block-begin (atom-to-fmt-c 'do)) - (test '%define (atom-to-fmt-c 'define)) - (test '%pointer (atom-to-fmt-c 'pointer)) - (test '%array (atom-to-fmt-c 'array)) - (test 'vector-ref (atom-to-fmt-c '¤)) - (test '%include (atom-to-fmt-c 'include)) - - ;; C99 onwards, true C spellings for bool - (test 'bool (atom-to-fmt-c 'bool)) - (test 'true (atom-to-fmt-c 'true)) - (test 'false (atom-to-fmt-c 'false)) - - ;; dot-access -> %. member-access directive (kebab-converted operands) - (test '(%. a b) (walk-expr '(dot-access a b))) - (test '(%. a b c) (walk-expr '(dot-access a b c))) - (test '(%. a_b c) (walk-expr '(dot-access a-b c))) - - ;; comment -> %comment directive (rendered as /* ... */) - ;; The reader eats only the `;' that introduced the line, so ";;; Foo" - ;; arrives as ";; Foo"; and c-comment puts nothing between /* */ and - ;; the text. Both are handled on the way out. - (test '(%comment " hi ") (walk-expr '(comment " hi"))) - (test '(%comment " hi ") (process-toplevel-form '(comment " hi"))) - (test '(%comment " Foo ") (walk-expr '(comment ";; Foo"))) - (test '(%comment " Foo ") (walk-expr '(comment ";;; Foo ")))) diff --git a/tests/codegen.scm b/tests/codegen.scm index eff2537..9da8790 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -1,10 +1,6 @@ -;;; Codegen details that are easy to get subtly wrong, and that the -;;; walk-* unit tests cannot see: they check the intermediate form we -;;; hand to fmt-c, not the C that fmt-c renders from it. -;;; -;;; Both cases below were found by writing an OpenGL example, not by -;;; the existing suite, because both need an operand shape that no -;;; earlier test program happened to use. +;;; Codegen details that are easy to get subtly wrong: precedence, +;;; scopes, comments in odd places, and the shapes no earlier test +;;; program happened to use. (import srfi-13) diff --git a/tests/fmt-c-writer.scm b/tests/fmt-c-writer.scm index 152662a..992c5f3 100644 --- a/tests/fmt-c-writer.scm +++ b/tests/fmt-c-writer.scm @@ -1,192 +1,132 @@ -;;; Types -(test-group "fmt-writer" +;;; The C each declaration comes out as: names, types, variables, +;;; initializers, functions and structs. Non-pub ones are static, which +;;; the fragments leave out. - (test - '(const int) - (walk-type '(const int))) +(test-group "fmt-c-writer" - (test - '(%array (const char) 512) - (walk-type '(¤ const char 512))) + (test-group "names" + (test-assert "kebab case is snake case" + (emits? "(var kebab-case int)" "int kebab_case;")) + ;; A Lisp predicate and mutator, in letters C takes + (test-assert "a predicate" + (emits? "(var ident-start? int)" "int ident_startʔ;")) + (test-assert "a mutator" + (emits? "(var reset! int)" "int resetꜝ;")) + ;; The `regex' egg's string-substitute dropped one trailing character + ;; per multi-byte one, and the C still compiled under the new name + (test-assert "a non-ASCII name survives" + (emits? "(var naïve-count int)" "int naïve_count;")) + (test-assert "wherever the dash is" + (emits? "(var aï-b int)" "int aï_b;")) + (test-assert "or with none" + (emits? "(var ïï int)" "int ïï;")) + (test-assert "an arrow inside a name is C's" + (emits? "(fn f () void (= this->member 1))" "this->member = 1;"))) - (test - '(%array (float) 512) - (walk-type '(¤ (float) 512))) + ;; The operators spelled with the characters names are converted from + (test-group "operators" + (test-assert "-=" + (emits? "(fn f ((a int) (b int)) void (-= a b))" "a -= b;")) + (test-assert "!" + (emits? "(fn f ((a int)) void (if (! a) (return)))" "if (!a)")) + (test-assert "!=" + (emits? "(fn f ((a int) (b int)) void (if (!= a b) (return)))" "if (a != b)"))) - (test - '(%array (const char) 512) - (walk-type '(¤ (const char) 512))) + (test-group "toplevel comments" + (test-assert "are C comments" + (emits? ";; hi" "/* hi */")) + (test-assert "without the markers or the padding" + (emits? ";;; Foo " "/* Foo */"))) - (test - '(%array (const char)) - (walk-type '(¤ const char))) + (test-group "types" + (test-assert "an array" + (emits? "(var a [const char 512])" "const char a[512];")) + (test-assert "whose element type is grouped" + (emits? "(var c [(const char) 512])" "const char c[512];")) + (test-assert "an unsized one" + (emits? "(extern var d [const char])" "extern const char d[];")) + (test-assert "a pointer to const" + (emits? "(var p (* const char))" "const char * p;")) + (test-assert "a const pointer to const" + (emits? "(var q (const * const char))" "const char * const q;")) + (test-assert "a function pointer" + (emits? "(var fp (fn ((int) (float) [const * struct what]) void))" + "void (*fp)(int, float, struct what* const []);")) + (test-assert "taking an array" + (emits? "(var fq (fn ((int) [float]) void))" + "void (*fq)(int, float []);")) + (test-assert "an array of them" + (emits? "(extern var fa [(fn ((int) [float]) void)])" + "extern void (*fa[])(int, float []);"))) - (test - '(%array (const char)) - (walk-type '(¤ (const char)))) + (test-group "variables" + (test-assert "a local array" + (emits? "(fn f () void (var a [float 8]))" "float a[8];")) + (test-assert "a pointer, initialized" + (emits? "(fn f () void (var n int) (var b (* int) (& n)))" "int * b = &n;")) + (test-assert "a pointer to const" + (emits? "(fn f () void (var n int) (var c (* const int) (& n)))" + "const int * c = &n;")) + (test-assert "a struct" + (emits? "(fn f () void (var s (struct suc)))" "struct suc s;")) + (test-assert "a pointer to a const struct" + (emits? "(fn f ((s1 (* const struct suc))) void (var t (* const struct suc) s1))" + "const struct suc * t = s1;")) + (test-assert "grouped" + (emits? "(fn f ((s1 (* const struct suc))) void (var u (* (const struct suc)) s1))" + "const struct suc * u = s1;")) + (test-assert "a struct from a call" + (emits? "(fn f () void (var v (struct suc) (hoge piyo)))" + "struct suc v = hoge(piyo);")) + (test-assert "a pointer to one" + (emits? "(fn f () void (var w (* struct suc) (hoge piyo)))" + "struct suc* w = hoge(piyo);"))) - (test - '(%array float 8) - (walk-type '(¤ float 8))) + (test-group "initializers" + (test-assert "a bare one is braces" + (emits? "(fn f () void (var a [int 2] #(1 2)))" "int a[2] = {1, 2};")) + (test-assert "`:' ends the type and makes it a compound literal" + (emits? "(fn f () void (var p (struct point) #(struct point : 3 4)))" + "struct point p = (struct point){3, 4};")) + (test-assert "the type is bare words, as everywhere else" + (emits? "(fn f () void (var s (* const char) #(* const char : 65)))" + "const char * s = (const char *){65};")) + (test-assert "and may be an array type" + (emits? "(fn f () void (var t [int 3] #([int 3] : 10 20 30)))" + "int t[3] = (int [3]){10, 20, 30};")) + (test-assert "`.field value' is a designated initializer, kebab and all" + (emits? "(fn f () void (var n (struct named) #(struct named : .n 7 .first-name \"zoe\")))" + "(struct named){.n = 7, .first_name = \"zoe\"}")) + (test-assert "positional and designated may be mixed" + (emits? "(fn f () void (var m (struct point) #(struct point : 1 .y 5)))" + "(struct point){1, .y = 5}")) + (test-assert "designators work in an untyped initializer too" + (emits? "(fn f () void (var o (struct point) #(.y 5)))" + "struct point o = {.y = 5};"))) - (test - "Pointer to const char" - '(const char *) - (walk-type '(* const char))) + (test-group "functions" + (test-assert "a prototype may leave its parameters nameless" + (emits? "(fn puk ((int) [float 8]) void)" "void puk (int, float [8]);")) + (test-assert "an array parameter" + (emits? "(fn g ((argc int) (argv [const char])) int (return 0))" + "int g (int argc, const char argv[]) {")) + (test-assert "a pointer parameter" + (emits? "(fn quxu ((bar (* struct piq))) int (return 0))" + "int quxu (struct piq * bar) {")) + (test-assert "an array of pointers" + (emits? "(fn quxu ((bar (* struct piq)) (ploop [* struct tt])) int (return 0))" + "int quxu (struct piq * bar, struct tt* ploop[]) {"))) - (test - "Const pointer to const char" - '(const char * const) - (walk-type '(const * const char))) - - (test - '(%fun void (int float (%array (struct what * const)))) - (walk-type '(fn ((int) (float) (¤ (const * struct what))) void))) - - (test - '(%fun void (int (%array float) (%array (struct what * const)))) - (walk-type '(fn ((int) (¤ float) (¤ (const * struct what))) void))) - - (test - '(%array (%fun void (int (%array float) (%array (struct what * const))))) - (walk-type '(¤ (fn ((int) (¤ float) (¤ (const * struct what))) void)))) - - ;; Type convert to C - (test - '(int) - (type-convert-to-c '(int))) - - (test - '(* int) - (type-convert-to-c '(int *))) - - (test - '(* const int) - (type-convert-to-c '(const int *))) - - (test - '(const * const char) - (type-convert-to-c '(const char * const))) - -;;; Variable defs - (test - '(%var (%array float 8) a) - (walk-var '(var a (¤ float 8)))) - - (test - '(%var (int *) a (& n)) - (walk-var '(var a (* int) (& n)))) - - (test - '(%var (const int *) a (& n)) - (walk-var '(var a (* const int) (& n)))) - - (test - '(%var (struct suc) s) - (walk-var '(var s (struct suc)))) - - (test - '(%var (const struct suc *) s s1) - (walk-var '(var s (* const struct suc) s1))) - - (test - '(%var (const struct suc *) s s1) - (walk-var '(var s (* (const struct suc)) s1))) - - (test - '(%var (struct suc) s (hoge piyo)) - (walk-var '(var s (struct suc) (hoge piyo)))) - - (test - '(%var (struct suc *) s (hoge piyo)) - (walk-var '(var s (* struct suc) (hoge piyo)))) - -;;; Initializers and compound literals - (test "a bare initializer is unchanged" - '#(1 2) - (walk-expr '#(1 2))) - - (test "`:' ends the type and makes it a compound literal" - '(%compound (struct point) 3 4) - (walk-expr '#(struct point : 3 4))) - - (test "the type is bare words, as everywhere else" - '(%compound (const char *) 65) - (walk-expr '#(* const char : 65))) - - (test "and may be an array type" - '(%compound (%array int 3) 10 20 30) - (walk-expr '#(¤ int 3 : 10 20 30))) - - (test "a grouped type is unwrapped the way a declaration's is" - '(%compound (%array int 3) 10) - (walk-expr '#((¤ int 3) : 10))) - - (test "`.field value' is a designated initializer, kebab and all" - '(%compound (struct named) (%designate n 7) (%designate first_name "zoe")) - (walk-expr '#(struct named : .n 7 .first-name "zoe"))) - - (test "positional and designated may be mixed" - '(%compound (struct point) 1 (%designate y 5)) - (walk-expr '#(struct point : 1 .y 5))) - - (test "designators work in an untyped initializer too" - '#((%designate y 5)) - (walk-expr '#(.y 5))) - -;;; Fn defs - (test - '(%fun void puk ((int #f) ((%array float 8) #f))) - (walk-fn-def '(fn puk ((int) (¤ float 8)) void))) - - (test - '(%fun int main ((int argc) ((%array (const char)) argv)) - (return 0)) - (walk-fn-def - '(fn main ((argc int) (argv (¤ const char))) int - (return 0)))) - (test - '(%fun int quxu (((struct piq *) bar)) - (return 0)) - (walk-fn-def - '(fn quxu ((bar (* struct piq))) int - (return 0)))) - - (test - '(%fun int quxu (((struct piq *) bar) ((%array (struct tt *)) ploop)) - (return 0)) - (walk-fn-def - '(fn quxu ((bar (* struct piq)) (ploop (¤ * struct tt))) int - (return 0)))) - - ;; Structs - (test - '(struct no_kebab ((int a) (float f))) - (walk-struct '(struct no-kebab ((a int) (f float))))) - - (test - '(struct settings ((u32 x y w h) - ((%array (struct ((float r g b a))) 4) colors))) - (walk-struct - '(struct settings - ((x y w h u32) - (colors [¤ struct ((r g b a float)) 4]))))) - - (test - '(struct settings ((u32 x y w h) - ((%array (struct color ((float r g b a))) 4) colors))) - (walk-struct - '(struct settings - ((x y w h u32) - (colors [¤ struct color ((r g b a float)) 4]))))) - - (test - '(struct mega_kebab ((int a) - ((struct ((int year) (int month) (int day))) dob) - ((%fun bool (int (%array int))) min))) - (walk-struct '(struct mega-kebab - ((a int) - (dob (struct ((year int) - (month int) - (day int)))) - (min (fn ((int) (¤ int)) bool))))))) + (test-group "structs" + (test-assert "names are converted" + (emits? "(struct no-kebab ((a int) (f float)))" + "struct no_kebab {\n int a;\n float f;\n};")) + (test-assert "fields sharing a type share a line, and a field may be a struct" + (emits? "(struct settings ((x y w h u32) (colors [struct ((r g b a float)) 4])))" + "struct settings {\n u32 x, y, w, h;\n struct{\n float r, g, b, a;\n } colors[4];\n};")) + (test-assert "a named one" + (emits? "(struct settings ((x y w h u32) (colors [struct color ((r g b a float)) 4])))" + " struct color{\n float r, g, b, a;\n } colors[4];")) + (test-assert "or a function pointer" + (emits? "(struct mega-kebab ((a int) (min (fn ((int) [int]) bool))))" + " bool (*min)(int, int []);")))) diff --git a/tests/run.scm b/tests/run.scm index 20e72f8..32e3068 100644 --- a/tests/run.scm +++ b/tests/run.scm @@ -2,7 +2,6 @@ test) (include-relative "pipeline.scm") -(include-relative "basic.scm") (include-relative "semen.scm") (include-relative "reader.scm") (include-relative "fmt-c-writer.scm") -- 2.52.0 From bc4f9246c254e742e64172fc20acc36199ea0aa5 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 12:00:17 +0300 Subject: [PATCH 17/20] drop the generics scaffolding from infer, and test what semen uses Schemes, instances, rigid variables and defaulting were built ahead of generics and called by the tests alone, which reached into the IR for them. The suite now goes through what infer exports, the eleven names semen imports; what a wildcard solves is checked from source as well. --- infer.scm | 193 +++++----------------------------------------- tests/codegen.scm | 13 ++++ tests/infer.scm | 190 ++------------------------------------------- 3 files changed, 41 insertions(+), 355 deletions(-) diff --git a/infer.scm b/infer.scm index f719a03..62b71a9 100644 --- a/infer.scm +++ b/infer.scm @@ -1,8 +1,8 @@ ;;; Type inference, layer 0: the type representation and unification. ;;; -;;; Nothing in the compiler calls this unit yet. It is the ground floor -;;; of the pass described in Type-inference.org -- built and tested on -;;; its own before a single form is routed through it. +;;; semen solves the wildcards of a declared type with it -- `(var n _ +;;; (strlen s))', `(var p (* _) (& x))' -- and asks it what an operand +;;; decays or promotes to. ;;; ;;; Two representations meet here. *Surface* types are the forms the ;;; rest of the compiler passes around -- `int', `(* const char)', @@ -34,48 +34,18 @@ (export ;; The IR - tvar? - tvar-id - tvar-classes - tvar-rigid? - fresh-tvar - fresh-rigid-tvar - - prim-type? prim-name prim-quals make-prim - ptr-type? ptr-target ptr-quals make-ptr - array-type? array-elt array-size make-array-type - fn-type? fn-ret fn-args fn-variadic? make-fn-type - agg-type? agg-kind agg-name agg-spelling agg-quals make-agg - alias-type? alias-name alias-expansion alias-quals make-alias - unknown-type? the-unknown-type - - resolve + prim-type? prim-name + ptr-type? + array-type? array-elt underlying c-primitive? - type-quals - free-tvars decay ;; The boundary parse-type unparse-type - ;; Constraints - register-class! - add-instance! - entails? - default-tvar! - default-type-variables! - - ;; Unification - unify - - ;; Type schemes - scheme? scheme-vars scheme-constraints scheme-type - make-scheme - generalize - instantiate - substitute) + unify) ;;; --------------------------------------------------------------- ;;; The IR @@ -161,18 +131,12 @@ (%make-unknown) unknown-type?) -(define the-unknown-type (%make-unknown)) - (define tvar-counter 0) (define (fresh-tvar . classes) (set! tvar-counter (+ tvar-counter 1)) (%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #f)) -(define (fresh-rigid-tvar . classes) - (set! tvar-counter (+ tvar-counter 1)) - (%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #t)) - ;;; Follow a bound variable to what it stands for, compressing the path ;;; on the way out. Every procedure that looks at a type's shape starts ;;; here. @@ -207,16 +171,6 @@ ((fn-type? t) (make-ptr t (list))) (else (resolve type))))) -(define (free-tvars type) - (let collect ((t type) (acc (list))) - (let ((t (resolve t))) - (cond ((tvar? t) (if (memq t acc) acc (cons t acc))) - ((ptr-type? t) (collect (ptr-target t) acc)) - ((array-type? t) (collect (array-elt t) acc)) - ((alias-type? t) (collect (alias-expansion t) acc)) - ((fn-type? t) (fold collect (collect (fn-ret t) acc) (fn-args t))) - (else acc))))) - ;;; --------------------------------------------------------------- ;;; Surface -> IR ;;; --------------------------------------------------------------- @@ -400,49 +354,24 @@ ;;; Constraints ;;; --------------------------------------------------------------- -;;; `(numeric a)' is already a type class, so it is written as one from -;;; the start: one representation, one table, one entailment check. A -;;; trait bound `(ord (struct circle))' is the same shape, discharged -;;; the same way, and reported by the same procedure -- which is the -;;; whole reason to build it this way while there is only one kind of -;;; constraint to build. -;;; -;;; `default' is the type an unresolved constraint falls back to, the -;;; way Haskell defaults `Num a' to Integer. `test' is how the built-in -;;; classes say "every arithmetic type" without enumerating twenty -;;; spellings as instances; a user trait has no test and lives entirely -;;; in the instance table. `strict?' marks a class that must not be -;;; guessed at: static dispatch needs a real instance, so `?' fails it. +;;; `(numeric a)' is a type class: one representation, one table, one +;;; entailment check. `test' is how a class says "every arithmetic +;;; type" without enumerating twenty spellings. (define-record-type - (%make-type-class name default test strict?) + (%make-type-class name test) type-class? (name type-class-name) - (default type-class-default) - (test type-class-test) - (strict? type-class-strict?)) + (test type-class-test)) (define +classes+ (make-hash-table)) -(define +instances+ (make-hash-table)) -(define (register-class! name default test strict?) - (hash-table-set! +classes+ name (%make-type-class name default test strict?))) +(define (register-class! name test) + (hash-table-set! +classes+ name (%make-type-class name test))) (define (get-class name) (or (hash-table-ref/default +classes+ name #f) (error "no such type class" name))) -;;; Instances key on the *resolved* type, so `(impl show for size-t)' -;;; and `(impl show for unsigned long)' collide rather than quietly -;;; coexisting as two instances of one C type. -(define (instance-key type) - (unparse-type (underlying type))) - -(define (add-instance! class-name type) - (hash-table-set! +instances+ (cons class-name (instance-key type)) #t)) - -(define (has-instance? class-name type) - (hash-table-exists? +instances+ (cons class-name (instance-key type)))) - ;;; #t, #f, or 'unknown -- and the third answer is the important one. ;;; A C name we never parsed a declaration for might well be numeric; ;;; saying #f there would reject working programs, and saying #t would @@ -453,10 +382,8 @@ (t (underlying type))) (cond ((tvar? t) 'unknown) - ;; `?' is consistent with every type, but it entails nothing: - ;; there is no instance to select and no name to mangle. - ((unknown-type? t) (if (type-class-strict? cls) #f 'unknown)) - ((has-instance? class-name t) #t) + ;; `?' is consistent with every type, and says nothing of one + ((unknown-type? t) 'unknown) ((type-class-test cls) => (lambda (test) (test t))) (else #f)))) @@ -500,36 +427,10 @@ ((fn-type? t) #t) ; likewise (else (arithmetic-type? t)))) -;;; The built-ins. They are ordinary classes, registered the same way a -;;; trait will be -- that is the point. -(register-class! 'numeric 'int arithmetic-type? #f) -(register-class! 'integral 'int integral-type? #f) -(register-class! 'floating 'double floating-type? #f) -(register-class! 'scalar #f scalar-type? #f) - -;;; A constraint that survives to the end of a function is defaulted: -;;; `(numeric a)' with nothing else known is an `int'. A *strict* -;;; class has no default and no business guessing, so an unresolved one -;;; is an error -- the rule is worth stating while there is only one -;;; kind of constraint to state it about. -(define (default-tvar! v form) - (let ((strict (find (lambda (c) (type-class-strict? (get-class c))) - (tvar-classes v)))) - (cond - (strict (sex-error form "unresolved constraint" (list strict (unparse-type v)))) - ((find (lambda (c) (type-class-default (get-class c))) (tvar-classes v)) - => (lambda (c) - (tvar-ref-set! v (parse-type (type-class-default (get-class c)))) - #t)) - (else #f)))) - -;;; Default every variable still open in TYPE. Returns #t when none is -;;; left unsolved, so a caller can tell "inferred" from "give up and -;;; ask for the type in writing". -(define (default-type-variables! type form) - (fold (lambda (v ok) (and (default-tvar! v form) ok)) - #t - (free-tvars type))) +(register-class! 'numeric arithmetic-type?) +(register-class! 'integral integral-type?) +(register-class! 'floating floating-type?) +(register-class! 'scalar scalar-type?) (define (check-classes classes type form) (for-each @@ -634,57 +535,3 @@ ((fn-type? t) (or (occurs? v (fn-ret t)) (any (lambda (a) (occurs? v a)) (fn-args t)))) (else #f)))) - -;;; --------------------------------------------------------------- -;;; Type schemes -;;; --------------------------------------------------------------- - -;;; Nothing generalizes yet -- every `fn' in Sex carries a written -;;; signature and there is no polymorphism to abstract over. These are -;;; here because they are ten lines on top of unification and because -;;; they are exactly what a `fn' with type parameters needs, and -;;; because a scheme without a constraint list is the wrong shape for -;;; every bounded generic. `(forall vars constraints type)' it is, -;;; from the start. -(define-record-type - (make-scheme vars constraints type) - scheme? - (vars scheme-vars) - (constraints scheme-constraints) - (type scheme-type)) - -;;; Quantify over everything free in TYPE that is not also free in the -;;; environment, carrying each variable's class constraints along as -;;; the scheme's context. -(define (generalize type env-tvars) - (let ((vars (lset-difference eq? (free-tvars type) env-tvars))) - (make-scheme vars - (append-map (lambda (v) - (map (lambda (c) (cons c v)) (tvar-classes v))) - vars) - type))) - -(define (instantiate scheme) - (let ((subst (map (lambda (v) (cons v (fresh-tvar (tvar-classes v)))) - (scheme-vars scheme)))) - (substitute (scheme-type scheme) subst))) - -;;; Structural copy with the variables in SUBST replaced. Copying is -;;; how a generic body must be handled anyway -- `form-type' is keyed -;;; by cons cell, one form one type, so an instantiation gets fresh -;;; cells rather than a second type for the same cell. -(define (substitute type subst) - (let ((t (resolve type))) - (cond - ((tvar? t) (let ((hit (assq t subst))) (if hit (cdr hit) t))) - ((ptr-type? t) (make-ptr (substitute (ptr-target t) subst) (ptr-quals t))) - ((array-type? t) (make-array-type (substitute (array-elt t) subst) - (array-size t))) - ((alias-type? t) (make-alias (alias-name t) - (substitute (alias-expansion t) subst) - (alias-quals t))) - ((fn-type? t) (make-fn-type (substitute (fn-ret t) subst) - (map (lambda (a) (substitute a subst)) - (fn-args t)) - (fn-variadic? t))) - (else t)))) diff --git a/tests/codegen.scm b/tests/codegen.scm index 9da8790..83f21bc 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -564,6 +564,19 @@ "struct p* x = &s")) (test-assert "a wildcard inside an array" (emits? (in-fn "(var t [_ 3] #([int 3] : 1 2 3))") "int t[3]")) + ;; each `_' is its own variable: solving one leaves the rest open + (test-assert "every wildcard in a signature is its own" + (emits? "(fn g ((x int)) char (return 0)) + (fn f () void (var h (fn ((_)) _) g))" + "char (*h)(int) = g")) + (test-assert "and the signature's arity has to match" + (reports? "(fn g ((x int) (y int)) int (return 0)) + (fn f () void (var h (fn ((_)) _) g))" + "type mismatch")) + (test-assert "a typedef answers as itself" + (emits? "(typedef count int) (fn g () count (return 0)) + (fn f () void (var x _ (g)))" + "count x = g()")) ;; a compound literal carries its own type, where a brace ;; initializer has none and takes one from its context (test-assert "a compound literal answers a bare wildcard" diff --git a/tests/infer.scm b/tests/infer.scm index 2d13c64..f41d6c3 100644 --- a/tests/infer.scm +++ b/tests/infer.scm @@ -3,7 +3,7 @@ ;;; Names registered in the type database are prefixed, since the ;;; database is one table shared by every suite in the linked binary. -(import infer types (chicken sort)) +(import infer types) ;;; Parse and print a surface type again. Everything in this suite goes ;;; through this pair, which is deliberate: they are the only thing the @@ -85,23 +85,10 @@ ;; Each _ is its own variable: solving one must not solve the rest. (let ((t (parse-type '(fn ((_)) _)))) - (unify (car (fn-args t)) (parse-type 'int) #f) + (unify t (parse-type '(fn ((int)) _)) #f) (test "one hole at a time" '(fn ((int)) _) (unparse-type t)))) - (test-group "structure" - (test-assert "a pointer is a pointer" (ptr-type? (parse-type '(* char)))) - (test "and knows what it points at" 'char - (unparse-type (ptr-target (parse-type '(* char))))) - (test "quals sit on the level they were written at" '(const) - (ptr-quals (parse-type '(const * char)))) - (test "an unsized array has no size" #f (array-size (parse-type '(¤ int)))) - (test "a sized one does" 16 (array-size (parse-type '(¤ int 16)))) - (test "an aggregate is nominal" 'point (agg-name (parse-type '(struct point)))) - (test-assert "a variadic signature says so" - (fn-variadic? (parse-type '(fn ((* const char) (...)) int)))) - (test-assert "and a plain one does not" - (not (fn-variadic? (parse-type '(fn ((int)) int))))) - + (test-group "decay" ;; decay: the conversion C performs at a call site, an operand of ;; `+', or the left half of a subscript. (test "an array decays to a pointer" '(* int) (unparse-type (decay (parse-type '(¤ int 16))))) @@ -115,7 +102,7 @@ (test-error "and not with another one" (unify (parse-type 'int) (parse-type 'char) #f)) - (let ((a (fresh-tvar))) + (let ((a (parse-type '_))) (unify a (parse-type '(* const char)) #f) (test "a variable takes the shape it is unified with" '(* const char) (unparse-type a))) @@ -125,8 +112,8 @@ (unify p (parse-type '(* int)) #f) (test "a partial type is completed by one step" '(* int) (unparse-type p))) - (let ((a (fresh-tvar)) - (b (fresh-tvar))) + (let ((a (parse-type '_)) + (b (parse-type '_))) (unify a b #f) (unify b (parse-type 'double) #f) (test "two variables joined then solved" 'double (unparse-type a))) @@ -152,168 +139,7 @@ (add-typedef 'i-count '(typedef i-count int)) (test-assert "a typedef unifies with its target" (unify (parse-type 'i-count) (parse-type 'int) #f)) - (let ((a (fresh-tvar))) + (let ((a (parse-type '_))) (unify a (parse-type 'i-count) #f) (test "and keeps its name when it is the one printed" - 'i-count (unparse-type a))) - - (test-group "the unknown type" - (test-assert "? is consistent with anything" - (unify the-unknown-type (parse-type '(struct point)) #f)) - (test-assert "in either order" - (unify (parse-type 'int) the-unknown-type #f)) - ;; ...and binds nothing. Degrading to ? is what keeps an - ;; unparsed C declaration from poisoning everything it touches. - (let ((a (fresh-tvar))) - (unify a the-unknown-type #f) - (test "a variable met with ? stays open" '_ (unparse-type a)))) - - (test-group "occurs check" - ;; Unreachable without recursive types, and the alternative to - ;; having it is not an error but a hang. - (let ((a (fresh-tvar))) - (test-error "a variable may not contain itself" - (unify a (make-ptr a (list)) #f)))) - - (test-group "rigid variables" - (let ((r (fresh-rigid-tvar)) - (a (fresh-tvar))) - (test-error "a type parameter does not unify with a type" - (unify r (parse-type 'int) #f)) - (test-assert "an ordinary variable binds to it instead" - (unify a r #f)) - ;; An unsolved variable resolves to itself. - (test-assert "it is still open" (tvar? (resolve r)))) - ;; ...and the same the other way round: it is which side is free - ;; that decides, not which side was written first. - (let ((r (fresh-rigid-tvar)) - (a (fresh-tvar))) - (test-assert "rigid first binds the free one" (unify r a #f)) - (test-assert "to the parameter itself" (eq? r (resolve a)))) - (let ((r1 (fresh-rigid-tvar)) - (r2 (fresh-rigid-tvar))) - (test-error "two parameters do not unify with each other" - (unify r1 r2 #f))))) - - (test-group "constraints" - (test #t (entails? 'numeric (parse-type 'int))) - (test #t (entails? 'numeric (parse-type '(unsigned long)))) - (test #t (entails? 'integral (parse-type 'char))) - (test #f (entails? 'integral (parse-type 'double))) - (test #t (entails? 'floating (parse-type 'double))) - (test #f (entails? 'floating (parse-type 'int))) - (test #f (entails? 'numeric (parse-type '(* char)))) - (test #t (entails? 'scalar (parse-type '(* char)))) - (test #f (entails? 'numeric (parse-type 'void))) - - (add-enum 'i-mood '(enum i-mood (glad sad))) - (test "an enum is an integer" #t (entails? 'integral (parse-type '(enum i-mood)))) - - ;; The third answer, and the important one. A name from a header - ;; might well be numeric; #f would reject working programs and #t - ;; would invent knowledge. - (test "an unparsed C name is not known either way" - 'unknown (entails? 'numeric (parse-type 'size-t))) - (test "nor is an open variable" 'unknown (entails? 'numeric (fresh-tvar))) - (test "? entails nothing, but says so quietly" - 'unknown (entails? 'numeric the-unknown-type)) - - ;; A typedef is entailed by what it resolves to, so an alias cannot - ;; sneak past a constraint its target would fail. - (add-typedef 'i-len '(typedef i-len int)) - (test "a typedef is judged by its target" #t (entails? 'numeric (parse-type 'i-len))) - - ;; A constrained variable checks its classes at the moment it is - ;; solved, not at the end. - (let ((a (fresh-tvar '(numeric)))) - (test-error "solving to a type that fails the class is an error" - (unify a (parse-type '(* char)) #f))) - (let ((a (fresh-tvar '(numeric)))) - (test-assert "and to one that satisfies it is not" - (unify a (parse-type 'double) #f))) - ;; ...but an unparsed name is not a failure, it is an absence of - ;; knowledge, and must stay silent. - (let ((a (fresh-tvar '(numeric)))) - (test-assert "an unparsed C name does not trip a constraint" - (unify a (parse-type 'GLuint) #f))) - - ;; Joining two variables joins what is known about both. - (let ((a (fresh-tvar '(numeric))) - (b (fresh-tvar '(integral)))) - (unify a b #f) - (test "constraints merge when variables do" - '("integral" "numeric") - (sort (map symbol->string (tvar-classes b)) string Date: Tue, 20 Oct 2026 12:18:52 +0300 Subject: [PATCH 18/20] export only what another module imports set-working-directory is reached only through with-directory's expansion, so it is exported as that macro's helper; form-location, form-type, register-macro and get-macro had no importer. --- sex-macros.scm | 2 -- utils.scm | 5 +---- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/sex-macros.scm b/sex-macros.scm index 5517bbd..54017df 100644 --- a/sex-macros.scm +++ b/sex-macros.scm @@ -7,10 +7,8 @@ (chicken string)) (export - register-macro cat comment - get-macro macro? apply-macro defmacro) diff --git a/utils.scm b/utils.scm index eb862b8..dd53147 100644 --- a/utils.scm +++ b/utils.scm @@ -10,7 +10,6 @@ (export get-env-var - set-working-directory to-absolute-pathname comment-form? strip-header-comments @@ -25,12 +24,10 @@ form-end-line copy-form-source! stamp-form-source! - form-location set-form-type! - form-type sex-error sex-warning - with-directory) + (with-directory set-working-directory)) (define-syntax prog1 (syntax-rules () -- 2.52.0 From d2f36d35c687e79835a51d4c5e4a3f05411eaded Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 12:19:41 +0300 Subject: [PATCH 19/20] delete what nothing calls walk-generic-toplevel and non-empty-list? had no caller left, a type variable's id was never read, and every expression's type was recorded in a table nothing looked up. --- fmt-c-writer.scm | 5 ----- infer.scm | 8 ++------ semen.scm | 9 +-------- utils.scm | 14 -------------- 4 files changed, 3 insertions(+), 33 deletions(-) diff --git a/fmt-c-writer.scm b/fmt-c-writer.scm index eb4b9b3..92ce013 100644 --- a/fmt-c-writer.scm +++ b/fmt-c-writer.scm @@ -215,11 +215,6 @@ forms, and what remains." acc)))))) (else (loop (cdr fs) (cons (car fs) acc)))))) -(define (walk-generic-toplevel form) - (cond ((atom? form) (atom-to-fmt-c form)) - ((list? form) (map walk-generic-toplevel form)) - (else (sex-error form "malformed form" form)))) - (define (walk-expr form) (match form ((? vector?) (walk-initializer (vector->list form))) diff --git a/infer.scm b/infer.scm index 62b71a9..8ed70fc 100644 --- a/infer.scm +++ b/infer.scm @@ -61,9 +61,8 @@ ;;; unused until a `fn' grows type parameters, and five lines now ;;; against an IR change later. (define-record-type - (%make-tvar id ref classes rigid?) + (%make-tvar ref classes rigid?) tvar? - (id tvar-id) (ref tvar-ref tvar-ref-set!) (classes tvar-classes tvar-classes-set!) (rigid? tvar-rigid?)) @@ -131,11 +130,8 @@ (%make-unknown) unknown-type?) -(define tvar-counter 0) - (define (fresh-tvar . classes) - (set! tvar-counter (+ tvar-counter 1)) - (%make-tvar tvar-counter #f (if (null? classes) (list) (car classes)) #f)) + (%make-tvar #f (if (null? classes) (list) (car classes)) #f)) ;;; Follow a bound variable to what it stands for, compressing the path ;;; on the way out. Every procedure that looks at a type's shape starts diff --git a/semen.scm b/semen.scm index 353bc39..429f623 100644 --- a/semen.scm +++ b/semen.scm @@ -1181,16 +1181,12 @@ ;;; member access. ;;; The type of an expression as a surface type, or #f when nothing -;;; here can say. Every form it visits is recorded in `form-type', so -;;; asking once types the whole subtree. +;;; here can say. ;;; ;;; 42 -> int (. p x) -> that field's type ;;; "hi" -> (* const char) (& p) -> (* (struct point)) ;;; (area 3 4) -> what `area' returns (define (expression-type expr env) - (set-form-type! expr (compute-expression-type expr env))) - -(define (compute-expression-type expr env) (cond ((and (number? expr) (exact? expr)) 'int) ((number? expr) 'double) @@ -1948,9 +1944,6 @@ form)) ;;; Utils -(define (non-empty-list? form) - (and (list? form) - (not (null? form)))) (define (sex-fn? form) "The `form` must be toplevel. diff --git a/utils.scm b/utils.scm index dd53147..7ea0123 100644 --- a/utils.scm +++ b/utils.scm @@ -24,7 +24,6 @@ form-end-line copy-form-source! stamp-form-source! - set-form-type! sex-error sex-warning (with-directory set-working-directory)) @@ -126,19 +125,6 @@ ;;; The file `parse-all' is currently reading. Bound by the reader (define current-source-file (make-parameter "")) -;;; What type a form has, once something has worked it out. Keyed by -;;; cons cell like the sources above, so one form has one type: a body -;;; typed at two instantiations has to be copied before the second. -(define +form-types+ (make-hash-table eq?)) - -(define (set-form-type! form type) - (when (pair? form) - (hash-table-set! +form-types+ form type)) - type) - -(define (form-type form) - (hash-table-ref/default +form-types+ form #f)) - (define (set-form-source! form file line #!optional (end-line line)) (hash-table-set! +form-sources+ form (list file line end-line))) -- 2.52.0 From 635cc48aa368c20561f1307092edd4c59f6011a8 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Tue, 20 Oct 2026 12:20:40 +0300 Subject: [PATCH 20/20] drop what infer had for types nothing builds No source makes an unknown type, a rigid variable or a variable with a class to satisfy, so the branches unify, bind-tvar! and entails? kept for them never ran, and the classes registered for them were never asked. --- infer.scm | 132 ++++-------------------------------------------------- 1 file changed, 9 insertions(+), 123 deletions(-) diff --git a/infer.scm b/infer.scm index 8ed70fc..8063d7e 100644 --- a/infer.scm +++ b/infer.scm @@ -28,7 +28,6 @@ (chicken module) matchable srfi-1 - srfi-69 types utils) @@ -54,25 +53,16 @@ ;;; A type variable is a mutable cell. `ref' is #f while unsolved and ;;; the type it stands for once bound -- union-find, with the path ;;; compression done in `resolve'. -;;; -;;; `classes' is the list of type classes the variable must satisfy -;;; (`numeric', and one day `ord'); see "constraints" below. `rigid?' -;;; marks a variable that must not unify with anything but itself -- -;;; unused until a `fn' grows type parameters, and five lines now -;;; against an IR change later. (define-record-type - (%make-tvar ref classes rigid?) + (%make-tvar ref) tvar? - (ref tvar-ref tvar-ref-set!) - (classes tvar-classes tvar-classes-set!) - (rigid? tvar-rigid?)) + (ref tvar-ref tvar-ref-set!)) ;;; A primitive or otherwise nominal type. `name' is the list of words ;;; making it up, so `int', `(unsigned int)' and `(long long)' are all ;;; one node, and so is a name we have never parsed a declaration for ;;; (`size-t', `GLuint'). The two cases are told apart by -;;; `c-primitive?', which is what keeps a constraint over an unparsed C -;;; typedef from being an error. +;;; `c-primitive?'. (define-record-type (make-prim name quals) prim-type? @@ -122,16 +112,8 @@ (expansion alias-expansion) (quals alias-quals)) -;;; `?'. Sex has full C interop, so `printf', `SDL-CreateWindow' and -;;; `size-t' arrive from headers nobody parsed. Rather than reject -;;; every real program, the lattice gets a top element: `?' is -;;; consistent with every type and constrains nothing. -(define-record-type - (%make-unknown) - unknown-type?) - -(define (fresh-tvar . classes) - (%make-tvar #f (if (null? classes) (list) (car classes)) #f)) +(define (fresh-tvar) + (%make-tvar #f)) ;;; Follow a bound variable to what it stands for, compressing the path ;;; on the way out. Every procedure that looks at a type's shape starts @@ -307,7 +289,6 @@ (let ((t (resolve type))) (cond ((tvar? t) '_) - ((unknown-type? t) '?) ((alias-type? t) (qualify (alias-quals t) (list (alias-name t)))) ((prim-type? t) (qualify (prim-quals t) (prim-name t))) ((agg-type? t) (qualify (agg-quals t) (agg-spelling t))) @@ -347,42 +328,9 @@ (else surface))) ;;; --------------------------------------------------------------- -;;; Constraints +;;; C's own types ;;; --------------------------------------------------------------- -;;; `(numeric a)' is a type class: one representation, one table, one -;;; entailment check. `test' is how a class says "every arithmetic -;;; type" without enumerating twenty spellings. -(define-record-type - (%make-type-class name test) - type-class? - (name type-class-name) - (test type-class-test)) - -(define +classes+ (make-hash-table)) - -(define (register-class! name test) - (hash-table-set! +classes+ name (%make-type-class name test))) - -(define (get-class name) - (or (hash-table-ref/default +classes+ name #f) - (error "no such type class" name))) - -;;; #t, #f, or 'unknown -- and the third answer is the important one. -;;; A C name we never parsed a declaration for might well be numeric; -;;; saying #f there would reject working programs, and saying #t would -;;; invent knowledge. 'unknown means "do not constrain, do not -;;; complain". -(define (entails? class-name type) - (let ((cls (get-class class-name)) - (t (underlying type))) - (cond - ((tvar? t) 'unknown) - ;; `?' is consistent with every type, and says nothing of one - ((unknown-type? t) 'unknown) - ((type-class-test cls) => (lambda (test) (test t))) - (else #f)))) - (define +integer-words+ '(char short int long signed unsigned bool _Bool)) (define +float-words+ '(float double)) (define +known-words+ (append '(void) +integer-words+ +float-words+)) @@ -393,71 +341,18 @@ (and (prim-type? t) (every (lambda (word) (memq word +known-words+)) (prim-name t)))) -(define (void-type? t) - (and (prim-type? t) (equal? (prim-name t) '(void)))) - -(define (arithmetic-type? t) - (cond ((and (agg-type? t) (eq? (agg-kind t) 'enum)) #t) ; an enum is an integer - ((not (prim-type? t)) #f) - ((not (c-primitive? t)) 'unknown) - ((void-type? t) #f) - (else #t))) - -(define (integral-type? t) - (cond ((and (agg-type? t) (eq? (agg-kind t) 'enum)) #t) - ((not (prim-type? t)) #f) - ((not (c-primitive? t)) 'unknown) - ((void-type? t) #f) - ((any (lambda (word) (memq word +float-words+)) (prim-name t)) #f) - (else #t))) - -(define (floating-type? t) - (cond ((not (prim-type? t)) #f) - ((not (c-primitive? t)) 'unknown) - (else (and (any (lambda (word) (memq word +float-words+)) (prim-name t)) - #t)))) - -(define (scalar-type? t) - (cond ((ptr-type? t) #t) - ((array-type? t) #t) ; decays to one - ((fn-type? t) #t) ; likewise - (else (arithmetic-type? t)))) - -(register-class! 'numeric arithmetic-type?) -(register-class! 'integral integral-type?) -(register-class! 'floating floating-type?) -(register-class! 'scalar scalar-type?) - -(define (check-classes classes type form) - (for-each - (lambda (c) - (when (eq? #f (entails? c type)) - (sex-error form "type does not satisfy a constraint" - (list c (unparse-type type))))) - classes)) - ;;; --------------------------------------------------------------- ;;; Unification ;;; --------------------------------------------------------------- -;;; Consistency in the gradual-typing sense rather than equality: `?' -;;; succeeds against anything and binds nothing, which is what keeps -;;; the pass from rejecting every program that includes a C header. -;;; ;;; FORM is carried only so a failure can say where it was written. (define (unify t1 t2 form) (let ((a (resolve t1)) (b (resolve t2))) (cond ((eq? a b) #t) - ((unknown-type? a) #t) - ((unknown-type? b) #t) - ;; Whichever side is free takes the binding: `(unify a r)' and - ;; `(unify r a)' both leave `a' bound to `r'. Two rigid and - ;; distinct is the mismatch `eq?' above let through. - ((and (tvar? a) (not (tvar-rigid? a))) (bind-tvar! a b form)) - ((and (tvar? b) (not (tvar-rigid? b))) (bind-tvar! b a form)) - ((or (tvar? a) (tvar? b)) (type-mismatch a b form)) + ((tvar? a) (bind-tvar! a b form)) + ((tvar? b) (bind-tvar! b a form)) ;; A typedef unifies as what it stands for. Its name survives in ;; whichever side is printed later, since neither side is rebuilt. ((alias-type? a) (unify (alias-expansion a) b form)) @@ -511,16 +406,7 @@ ;; Without recursive types this cannot trigger. It is four lines, ;; and the alternative to having it is a hang. ((occurs? v t) (sex-error form "recursive type" (unparse-type v))) - ;; A rigid variable is a type *parameter*: inside a generic body it - ;; stands for one specific unknown type and must not be solved. - ((tvar-rigid? v) (type-mismatch v t form)) - (else - (when (tvar? t) - (tvar-classes-set! t (lset-union eq? (tvar-classes t) (tvar-classes v)))) - (tvar-ref-set! v t) - (unless (tvar? t) - (check-classes (tvar-classes v) t form)) - #t))) + (else (tvar-ref-set! v t) #t))) (define (occurs? v type) (let ((t (resolve type))) -- 2.52.0