From 27bc4da4fda40c728a031fbb3b66330c341579f0 Mon Sep 17 00:00:00 2001 From: nub31 Date: Sun, 26 Oct 2025 20:04:57 +0100 Subject: [PATCH] ... --- compiler/NubLang/Generation/Generator.cs | 11 +++++++---- examples/playgroud/main.nub | 4 ++-- runtime/ref.c | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/compiler/NubLang/Generation/Generator.cs b/compiler/NubLang/Generation/Generator.cs index d773102..4c5aa97 100644 --- a/compiler/NubLang/Generation/Generator.cs +++ b/compiler/NubLang/Generation/Generator.cs @@ -196,6 +196,7 @@ public class Generator if (assignmentNode.Target.Type is NubRefType) { _writer.WriteLine($"rc_retain({value});"); + Scope.Defer(() => _writer.WriteLine($"rc_release({value});")); _writer.WriteLine($"rc_release({target});"); } @@ -322,11 +323,14 @@ public class Generator if (variableDeclarationNode.Assignment != null) { var value = EmitExpression(variableDeclarationNode.Assignment); - _writer.WriteLine($"{CType.Create(variableDeclarationNode.Type, variableDeclarationNode.NameToken.Value)} = {value};"); + if (variableDeclarationNode.Type is NubRefType) { - _writer.WriteLine($"rc_retain({variableDeclarationNode.NameToken.Value});"); + _writer.WriteLine($"rc_retain({value});"); + Scope.Defer(() => _writer.WriteLine($"rc_release({value});")); } + + _writer.WriteLine($"{CType.Create(variableDeclarationNode.Type, variableDeclarationNode.NameToken.Value)} = {value};"); } else { @@ -544,6 +548,7 @@ public class Generator var tmp = NewTmp(); _writer.WriteLine($"{CType.Create(type)} {tmp} = ({CType.Create(type)})rc_alloc(sizeof({CType.Create(structType)}), NULL);"); + Scope.Defer(() => _writer.WriteLine($"rc_release({tmp});")); var initValues = new List(); foreach (var initializer in refStructInitializerNode.Initializers) @@ -558,8 +563,6 @@ public class Generator _writer.WriteLine($"*{tmp} = ({CType.Create(structType)}){{{initString}}};"); - Scope.Defer(() => _writer.WriteLine($"rc_release({tmp});")); - return tmp; } diff --git a/examples/playgroud/main.nub b/examples/playgroud/main.nub index 2325235..44658a3 100644 --- a/examples/playgroud/main.nub +++ b/examples/playgroud/main.nub @@ -15,10 +15,10 @@ extern "main" func main(argc: i64, argv: [?]^i8): i64 name = "test" } - puts(x^.name) - test(x) + let y = x + return 0 } diff --git a/runtime/ref.c b/runtime/ref.c index 93a674c..17ab78b 100644 --- a/runtime/ref.c +++ b/runtime/ref.c @@ -12,7 +12,7 @@ void *rc_alloc(size_t size, void (*destructor)(void *self)) exit(69); } - header->ref_count = 0; + header->ref_count = 1; header->destructor = destructor; return (void *)(header + 1); @@ -29,7 +29,7 @@ void rc_release(void *obj) { ref_header *header = ((ref_header *)obj) - 1; printf("rc_release\n"); - if (--header->ref_count <= 0) + if (--header->ref_count == 0) { if (header->destructor) {