Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.43.0

0.43.0 / src / std / ownership / module.lucb

#==============================================================================================
#
#   ownership - Intrusive ownership shared by Base and Luce
#
#   DESCRIPTION:
#       Intrusive ownership shared by Base libraries and compiled Luce programs. Base callers
#       retain and release explicitly; Luce inserts those operations. One header and trace
#       protocol cover native/managed cycles on the owning thread. Runtime allocations use the
#       system heap; an explicit allocator can be supplied to reserve when its lifetime is
#       guaranteed by the native owner.
#
#==============================================================================================

import c
import io
import memory
import core

# mark: Objects ================================================================================

let black: u8 = 0
let gray: u8 = 1
let white: u8 = 2
let purple: u8 = 3
let color_mask: u8 = 3
let buffered: u8 = 4
let dead: u8 = 8
let collecting: u8 = 16
## A literal's text: never counted, never released, never alive at the end.
pub let immortal: u8 = 32
## An object whose `init` failed, while `abandon` releases its fields: a release of it is
## bookkeeping only and the collector never walks into it.
let abandoning: u8 = 64
## Placed in the collector's disposal order (cycles.lucb, `order_disposal`).
let ordered: u8 = 128

## The ownership header every managed object carries, before its fields.
pub struct Object:
    ## The strong reference count; the object is finalized when it reaches zero.
    pub var strong: u32
    ## The number of weak references watching the object.
    pub var weak: u32
    ## The collector's color and state bits (§the cycle collector).
    pub var flags: u8
    ## The object's class description.
    pub var info: Info*
    ## Allocation identity never repeats, even when an allocator reuses an address.
    pub var generation: u64
    ## The owning context the object belongs to.
    pub var context: u64
    ## The size of the object's allocation in bytes.
    pub var allocation_size: usize
    ## The allocator that made the object, when one was supplied explicitly.
    pub var allocator: memory.Allocator?

## What the collector and the destructor need to know about a class.
pub struct Info:
    ## The class name, for diagnostics and the collector.
    pub var name: str
    ## The object's size in bytes, its fields included.
    pub var size: usize
    ## `deinit`, when the class declares one.
    pub var finish: (func(Object*) -> unit)?
    ## Releases the fields in reverse declaration order, tolerating unassigned ones.
    pub var drop: func(Object*) -> unit
    ## Visits every strong reference the object holds, fields in declaration order.
    pub var trace: func(Object*, func(Object*, void*) -> unit, void*) -> unit
    ## An interface adapter preserves the identity of its concrete owner.
    pub var identity: (func(Object*) -> u64)? = none
    ## No object of this type can be part of a reference cycle (text, a list of numbers, a
    ## class whose fields are all such): the collector never takes one as a candidate nor
    ## walks into one, so large acyclic data costs it nothing.
    pub var acyclic: bool = false
    ## `finish` disposes native state that other objects' finishes may still reach (a
    ## native object's close): in a garbage cycle it runs after every `deinit`, and before
    ## the finishes of the objects this one refers to, as releasing them in turn would.
    pub var disposes: bool = false

## Objects alive: allocated and not yet destroyed.
local var live: usize = 0

## Allocated objects not yet finalized on the calling runtime thread.
pub func live_count() -> usize:
    return live

## Where the thread's program is: `file:line:column` of the Luce statement running, set by
## the compiled code before each statement and restored when a function returns; what a
## trap names (§12.4).
pub local var site: str

## The caller's site again, deferred by every function the compiler writes.
pub func restore_site(saved: str):
    site = saved

## Stop the program with `trap: file:line:column: message` on standard error and status 1.
pub func stop(message: str) -> never:
    core.trap_located(site, message)

## A library trap on behalf of the value language: stops at its running statement when one is
## set, so the trap names the Luce line rather than the library's; returns otherwise, for the
## caller's own `trap` to name its statement.
pub func stop_at_site(message: str):
    if site.length > 0:
        core.trap_located(site, message)

func color_of(o: Object*) -> u8:
    return o.flags & color_mask

func set_color(o: Object*, color: u8):
    o.flags = (o.flags & ~color_mask) | color

func has(o: Object*, flag: u8) -> bool:
    return (o.flags & flag) != 0

var next_context: @u64 = 1
var next_generation: @u64 = 1
local var thread_context: u64 = 0
local var runtime_depth: u32 = 0

## A unique runtime identity for this thread, independent of recycled OS thread IDs.
pub func context_id() -> u64:
    if thread_context == 0:
        thread_context = next_context.add(1, .relaxed)
        if thread_context == 0:
            stop("runtime context identity exhausted")
    return thread_context

## Application runtime entry is separate from ordinary manual Base ownership.
## Generated callbacks require entry; native worker adapters establish it internally.
pub func enter():
    _ = context_id()
    runtime_depth += 1

## Trap when no owning context has been entered.
pub func require_context():
    if runtime_depth == 0:
        stop("a managed callback needs a runtime entry on this thread")

## Trap when `o` is touched from a thread other than its owner.
pub func check_thread(o: Object*):
    if not has(o, immortal) and o.context != context_id():
        stop("an object belongs to another runtime thread")

## Trap when `o` has already been finalized.
pub func check_alive(o: Object*):
    check_thread(o)
    if has(o, dead) or o.strong == 0:
        stop("an object has already been destroyed")

## Reserve unpublished storage. The caller supplies a stable descriptor before
## publishing the object and abandons the storage if native initialization fails.
pub func reserve(info: Info*, size: usize, allocator: memory.Allocator? = none) -> Object*!:
    if size < memory.size_of(Object):
        stop("an object allocation is smaller than its header")
    let selected = allocator else memory.heap
    let block = selected.allocate(size, 16) else error(memory.exhausted, "memory.exhausted")
    memory.set(block, 0)
    let o = (Object*)block.data
    o.strong = 1
    o.info = info
    o.context = context_id()
    o.generation = next_generation.add(1, .relaxed)
    if o.generation == 0:
        stop("object allocation identity exhausted")
    o.allocation_size = block.length
    o.allocator = selected
    live += 1
    return o

## Allocate an object of class `info` and its header.
pub func allocate(info: Info*) -> Object*:
    return allocate_sized(info, info.size)

## Runtime wrapper/text allocation retains Luce's trap-on-exhaustion policy.
pub func allocate_sized(info: Info*, size: usize) -> Object*:
    return reserve(info, size) catch failure:
        trap("out of memory")

## Add a strong reference to `o` and return it.
pub func retain(o: Object*) -> Object*:
    check_alive(o)
    if has(o, immortal):
        return o
    o.strong += 1
    set_color(o, black)
    return o

## Drop a strong reference to `o`, finalizing it when the count reaches zero. The value
## language's release: it stores before it releases, so the collector may run here.
pub func release(o: Object*):
    release_from(o, true)

## `release` for a handle native code holds (`interop`): never runs the collector, which
## could trace a field the caller has released but not yet overwritten (`possible_root`).
pub func release_held(o: Object*):
    release_from(o, false)

func release_from(o: Object*, may_collect: bool):
    check_thread(o)
    if has(o, immortal):
        return
    if has(o, collecting) or has(o, abandoning):
        # a white object's field, released while the collector drops it, or a reference
        # back to an object `abandon` is dropping: the count is bookkeeping only, the
        # collector or `abandon` frees the object
        if o.strong > 0:
            o.strong -= 1
        return
    check_alive(o)
    o.strong -= 1
    if o.strong == 0:
        destroy(o)
    elif not o.info.acyclic:
        possible_root(o, may_collect)

## `deinit`, then the fields, then the storage unless a weak reference keeps the shell.
func destroy(o: Object*):
    set_color(o, black)
    if let f = o.info.finish:
        o.strong = 1
        f(o)
        if o.strong != 1:
            trap("`deinit` published `self`")
        o.strong = 0
    o.info.drop(o)
    live -= 1
    o.flags |= dead
    if not has(o, buffered):
        release_shell(o)

## The storage goes when nothing, strong or weak or the candidate buffer, refers to it.
func release_shell(o: Object*):
    if o.weak == 0 and has(o, dead) and not has(o, buffered):
        let allocator = o.allocator else stop("an object has no allocation owner")
        let block = u8[]((u8*)o, o.allocation_size)
        free(block) in allocator

## Free unpublished storage without invoking the successful object's cleanup.
## The native initializer owns cleanup of its partially acquired resources.
pub func discard_unpublished(o: Object*):
    check_alive(o)
    if o.strong != 1 or o.weak != 0 or has(o, buffered):
        stop("an incomplete object was published")
    live -= 1
    o.strong = 0
    o.flags |= dead
    release_shell(o)

## An `init` that failed: the fields assigned so far go, no `deinit` runs. Like `destroy`,
## the object leaves the collector's candidates first, so a collection the drop sets off
## never walks fields already released. What the fields held that refers back to the
## object, a closure over `self` or a child holding its parent, lets go of it in the drop;
## a reference still held after that was published by the failed `init`, which stops the
## program rather than leave it pointing at freed storage. The trap names the `init`'s own
## failure, `cause` raised at `cause_at`, which the publication would otherwise hide.
pub func abandon(o: Object*, cause: str, cause_at: str):
    check_alive(o)
    set_color(o, black)
    o.flags |= abandoning
    o.info.drop(o)
    o.flags &= ~abandoning
    if o.strong != 1:
        core.trap_located_after(site, "a failed `init` published `self`", cause, cause_at)
    live -= 1
    o.strong = 0
    o.flags |= dead
    if not has(o, buffered):
        release_shell(o)

## The allocation identity, or the concrete owner's identity through an adapter.
pub func identity(object: Object*) -> u64:
    check_alive(object)
    if let resolve = object.info.identity:
        return resolve(object)
    return object.generation