From 54b8a8918bb63c98a8f58e823033232243647562 Mon Sep 17 00:00:00 2001 From: zinc Date: Wed, 14 Oct 2026 10:39:47 +0000 Subject: zc: add the defer statement defer expr; and defer { ... } register code that runs when the enclosing block ends: at the end of the block, and at return, break and continue that leave it. the tokens are kept at the defer and compiled again at each exit (block_close, body, kw_return, kw_break, kw_continue), newest first, before the block's variables are released, so the analyzer sees a deferred rt.free(p) as the transfer of p where it runs. names mean what they meant at the defer; values are read when it runs. return, break and continue inside a deferred statement are errors, reported once. works in unchecked code and closures (own base per function context). --- examples/learn/34-defer.out | 4 ++++ examples/learn/34-defer.zc | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 examples/learn/34-defer.out create mode 100644 examples/learn/34-defer.zc (limited to 'examples/learn') diff --git a/examples/learn/34-defer.out b/examples/learn/34-defer.out new file mode 100644 index 0000000..284c915 --- /dev/null +++ b/examples/learn/34-defer.out @@ -0,0 +1,4 @@ +0 1 100 0 0 +1 +4 1 100 0 2 +6 100 7 3 diff --git a/examples/learn/34-defer.zc b/examples/learn/34-defer.zc new file mode 100644 index 0000000..10e46e1 --- /dev/null +++ b/examples/learn/34-defer.zc @@ -0,0 +1,20 @@ +namespace; +include rt; +fn say(n) { rt.put_n(n); rt.put_c(32); return 0; } +int work(int n) { + int* p = rt.new(int); + defer rt.free(p); + defer say(100); + *p = n * 2; + say(*p); + if (n > 2) return *p + 1; + say(1); + return 0; +} +fn main() { + for (let i = 0; i < 4; i++) { + defer { say(i); rt.put_c(10); } + if (i == 1) continue; + say(work(i)); + } +} -- cgit v1.2.3