prim.c 1.05 KB
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
{
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
11
12
13
14
15
16
17
	Thunk* arg1 = stack[stack_top - 2];
	Thunk* arg2 = stack[stack_top - 1];
	
	eval(arg1);
	eval(arg2);
	
	updateI(target, readI(arg1) + readI(arg2));
18
19
}

20
PrimEntry* add_prim(int arity, int strictness, char* name, void (*exec)(Thunk*))
21
22
23
24
{
	int nameLength = strlen(name);
	
	// before the PrimEntry there are "arity" number of SliceEntries
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
25
	SliceEntry* entry_base = (SliceEntry*) alloc_desc(sizeof(SliceEntry) * arity + sizeof(PrimEntry) + nameLength + 1);
26
		
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
27
	PrimEntry* entry = (PrimEntry*) (entry_base + arity);
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
28
29
	entry->base.type = FT_PRIM;
	entry->base.arity = arity;
30
31
32
33
34
35
36
37
	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
38
	if(arity>0) gen_slices(entry_base, (Desc*) entry, arity);
39
	
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
40
	add_desc(entry->name, (Desc*) entry);
41
42
43
44
45
46
}

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