1
0
forked from alex-eg/sex

let a method call one written below it

Each method was registered just before its own body was walked, so an
earlier one could not find it. All are registered first now, and one
called above its definition is declared ahead of the bodies, which C
needs as well.

Fixes #44.
This commit is contained in:
2026-10-09 17:37:03 +03:00
parent 9fd40da8b1
commit 19090414b7
3 changed files with 63 additions and 8 deletions

View File

@@ -19,6 +19,13 @@
"(fn f () void (var v vec2 #(vec2 : 1.0 2.0)) (var p (* vec2) (& v)) "
(apply string-append body) ")"))
(define forward-src
(string-append
"(record pb ((n int)))"
"(ops pb"
" (fn twice ((self (* pb))) int (return (* 2 (.len self))))"
" (pub fn len ((self (* pb))) int (return (. self n))))"))
(define (sum-src . body)
(string-append
"(sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ())))"
@@ -79,7 +86,15 @@
" (fn g ((s v)) int (return 2)))")
"method is already defined on"))
(test-assert "pub goes on the methods, not the block"
(reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods")))
(reports? "(record v ((x int)))(pub ops v)" "pub belongs on the methods"))
;; Every method is known before any body is walked, and C is told of
;; one before a body above it calls it -- and only then
(test-assert "a method can call one written below it"
(emits? forward-src "return 2 * pbːlen(self)"))
(test-assert "which is declared ahead of the call"
(emits? forward-src "int pbːlen (pb * self);"))
(test-assert "and nothing else is"
(not (emits? (ops-src "") "vec2ːsum_of (vec2 self);"))))
;; The method sits in the head, so the shape of a form can be read
;; without knowing the receiver's type.

View File

@@ -2,7 +2,8 @@
(input)
(output "5.0 5.0 10.0 14.0 14.0 6.0"
"struct receiver: 14"
"private: 8.0")
"private: 8.0"
"forward call: 28.0")
(return 0)
;;; An ops block is mangled fns plus a registry entry, so a method is
@@ -22,6 +23,10 @@
(record vec2 ((x float) (y float)))
(ops vec2
;; a method may call one written below it
(fn twice-sum ((self vec2)) float
(return (* 2.0 (.sum-of self))))
(pub fn length ((self (* const vec2))) float
"Pointer self, so (.length v) has to take the address."
(return (sqrtf (+ (* (. self x) (. self x))
@@ -55,4 +60,5 @@
(var u vec2 #(vec2 : 8.0 0.0))
(printf "private: %.1f\n" (vec2/sum-of u))
(printf "forward call: %.1f\n" (.twice-sum v))
(return 0))