Newer
Older
Tardis / lang / object.c
// SPDX-License-Identifier: MIT
// Copyright (c) 2024 John Watts and the LuminaSensum contributors

#include "object.h"
#include "error.h"
#include "vm.h"
#include <stdatomic.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

struct object {
	struct object_class *class_data;
	atomic_int ref_count;
	char priv_data[];
};

Object object_none(void) { return (Object)NULL; }

Object object_create(VmState state, struct object_class *class, int priv_size) {
	(void)state;
	vm_abort_if(state, priv_size < 1, "object_create: priv_size too small");
	size_t size = sizeof(struct object) + priv_size;
	struct object *obj = calloc(size, 1);
	vm_abort_if(state, obj == NULL,
		"object_create: not enough memory for an objects");
	obj->class_data = class;
	obj->ref_count = 1;
	return (Object)obj;
}

char *object_priv(VmState state, Object object, struct object_class *class) {
	(void)state;
	vm_abort_if(
		state, object == object_none(), "object_priv: no priv on none");
	struct object *obj = (struct object *)object;
	vm_abort_if(state, obj->class_data != class,
		"object_priv: incompatible class");
	return obj->priv_data;
}

void object_hold(VmState state, Object obj) {
	(void)state;
	if (obj == object_none())
		return;
	atomic_fetch_add_explicit(&obj->ref_count, 1, memory_order_relaxed);
}

void object_drop(VmState state, Object *objptr) {
	if (*objptr == object_none())
		return;
	Object obj = *objptr;
	atomic_int count = atomic_fetch_sub_explicit(
		&obj->ref_count, 1, memory_order_relaxed);
	if (count == 1) {
		// We were the last user of the object, clean it up
		obj->class_data->cleanup(state, obj);
		free(obj);
	}
	*objptr = object_none();
}

void dispatch_default(VmState state, Object obj, const char *name) {
	struct object_call *call = obj->class_data->calls;
	while (call->name != NULL) {
		if (strcmp(call->name, name) == 0) {
			call->handler(state, obj, call->priv);
			return;
		}
		++call;
	}
	vm_abort_msg(state, "dispatch_default: no call found to dispatch");
}

void dispatch_call(VmState state, Object obj, const char *name) {
	if (obj == object_none())
		vm_abort_msg(state, "dispatch_call: cannot dispatch on none");
	object_caller caller = (obj->class_data->caller);
	if (!caller)
		caller = dispatch_default;
	caller(state, obj, name);
}