From 97b99ab8425359b954ba019a636090a105cd24c7 Mon Sep 17 00:00:00 2001 From: alex-eg Date: Sun, 18 Oct 2026 22:02:55 +0300 Subject: [PATCH] decay an array into a wildcard standing alone An array as a value is a pointer to its first element; _ took the array type, and declared a copy that C cannot initialize from it. --- infer.scm | 2 ++ semen.scm | 10 +++++++++- tests/codegen.scm | 12 ++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/infer.scm b/infer.scm index 3b295d5..8e4d024 100644 --- a/infer.scm +++ b/infer.scm @@ -34,9 +34,11 @@ (export ;; The IR + tvar? prim-type? prim-name ptr-type? array-type? array-elt + resolve underlying c-primitive? decay diff --git a/semen.scm b/semen.scm index 13878ea..b0d06d4 100644 --- a/semen.scm +++ b/semen.scm @@ -882,7 +882,15 @@ (sex-error form "cannot infer the type of" (second form))) ;; `(closure ((int)) int)' is spelled `(struct ƛint_int)' ;; everywhere past this point, and is what `parse-type' knows - (unify declared (parse-type (resolve-closure-types type)) form))))) + (let ((given (parse-type (resolve-closure-types type)))) + ;; an array as a value is a pointer to its first element, which + ;; is what a `_' standing alone takes; `[_ 3]' asks for an array + (unify declared + (if (and (tvar? (resolve declared)) + (array-type? (underlying given))) + (decay given) + given) + form)))))) ;;; `#(0 1 4 9)', as against the compound literal `#(T : ...)' (define (brace-initializer? form) diff --git a/tests/codegen.scm b/tests/codegen.scm index d8853c4..172a27a 100644 --- a/tests/codegen.scm +++ b/tests/codegen.scm @@ -687,6 +687,18 @@ "int * p = a + 1")) (test-assert "while a length left to work out is not one" (reports? (in-fn "(var t [_ _] #(1 2))") "cannot infer")) + ;; an array as a value is a pointer to its first element, where `_' + ;; declared a copy, which C cannot initialize from it + (test-assert "an array decays into `_'" + (emits? (in-fn "(var s [char 6]) (var t _ s)") "char * t = s")) + (test-assert "a row of one too" + (emits? (in-fn "(var m [int 2 3]) (var r _ [m 1])") "int * r = m[1]")) + (test-assert "and a field" + (emits? "(struct h ((xs [int 4]))) (fn f ((v (struct h))) void (var p _ (. v xs)))" + "int * p = v.xs")) + (test-assert "while a function is the pointer it already is" + (emits? "(fn g ((n int)) int (return n)) (fn f () void (var p _ g))" + "int (*p)(int) = g")) ;; a variable had nowhere to keep a qualifier written on it, and ;; what it was solved to came out without (test-assert "a qualified wildcard keeps its qualifier"