refuse a macro defined after a call to it

The call was compiled as a function's, and the macro went unused there
without a word.
This commit is contained in:
2026-10-19 14:48:43 +03:00
parent c02b5ab1a8
commit c6a15e0ba2
2 changed files with 30 additions and 1 deletions

View File

@@ -32,8 +32,22 @@
;;; in auxiliary structures and functions.
(define (process raw-sex-forms)
(reset-declarations!)
(set! +called-as-functions+ (make-hash-table))
(process-rec raw-sex-forms (list)))
;;; The first call of each name compiled as a function's, so that a macro
;;; of that name defined after it is told of rather than going unused
;;; there without a word
(define +called-as-functions+ (make-hash-table))
(define (check-not-called-before form name)
(let ((call (hash-table-ref/default +called-as-functions+ name #f)))
(when call
(sex-error form "a macro defined after a call to it, which is a function's"
name
(string-append "called at " (form-file call) ":"
(number->string (form-line call)))))))
(define (process-rec forms acc)
(cond
((null? forms) (reverse acc))
@@ -126,7 +140,11 @@
(process-imports (get-modules-public-forms sex-form) acc))
((or ('defmacro . rest)
('pub 'defmacro . rest)) (defmacro rest) acc)
('pub 'defmacro . rest))
(when (and (pair? rest) (pair? (car rest)))
(check-not-called-before sex-form (caar rest)))
(defmacro rest)
acc)
((or ('typedef new-type target)
('pub 'typedef new-type target))
@@ -733,6 +751,9 @@
,receiver
,@(walk-operands form (cdr form) env))))))
(else
(when (and (symbol? (car form)) (form-source form)
(not (hash-table-exists? +called-as-functions+ (car form))))
(hash-table-set! +called-as-functions+ (car form) form))
(convert-arguments (copy-form-source! form (walk-operands form form env))
env))))))))

View File

@@ -335,6 +335,14 @@
"macro takes at least this many arguments many 1"))
(test-assert "while it may take any more"
(emits? "(defmacro (many x . more) x) (fn f () int (return (many 1 2 3)))" "return 1;"))
;; a call before the macro is defined is a function call, and the
;; macro defined after it went unused there without a word
(test-assert "a macro defined after a call to it is refused"
(reports? "(fn f () int (return (later 1)))\n(defmacro (later x) x)"
"codegen.sex:2: a macro defined after a call to it"))
(test-assert "naming where the call is"
(reports? "(fn f () int\n (return (later 1)))\n(defmacro (later x) x)"
"/codegen.sex:2\""))
(test-assert "an error in a macro's body names the call"
(reports? "(defmacro (boom x) (error \"no good\" x))\n(fn f () int (return (boom 1)))"
"codegen.sex:2: expanding boom: no good")))