prim.c 1020 Bytes
Newer Older
1
2
3
4
5

#include <string.h>

#include "prim.h"
#include "desc.h"
6
#include "thunk.h"
7
8
#include "mem.h"

9
void __add(Thunk* target)
10
{
11
	return updateI(target, readI(eval(stack[stack_top - 2])) + readI(eval(stack[stack_top - 1])));
12
13
}

14
PrimEntry* add_prim(int arity, int strictness, char* name, void (*exec)(Thunk*))
15
16
17
18
{
	int nameLength = strlen(name);
	
	// before the PrimEntry there are "arity" number of SliceEntries
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
19
	SliceEntry* entry_base = (SliceEntry*) alloc_desc(sizeof(SliceEntry) * arity + sizeof(PrimEntry) + nameLength + 1);
20
		
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
21
	PrimEntry* entry = (PrimEntry*) (entry_base + arity);
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
22
23
	entry->base.type = FT_PRIM;
	entry->base.arity = arity;
24
25
26
27
28
29
30
31
	entry->strictness = strictness;
	entry->exec = exec;
	
	// TODO: should it be copied at all?
	memcpy(entry->name, name, nameLength);
	entry->name[nameLength] = '\0';
	
	// generate slices. avoid function call if arity is zero
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
32
	if(arity>0) gen_slices(entry_base, (Desc*) entry, arity);
33
	
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
34
	add_desc(entry->name, (Desc*) entry);
35
36
37
38
39
40
}

void init_prim()
{
	add_prim(2, 3, "add", &__add);
}