prim.c 1.66 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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void __sub(Thunk* target)
{
	Thunk* arg1 = stack[stack_top - 2];
	Thunk* arg2 = stack[stack_top - 1];
	
	eval(arg1);
	eval(arg2);
	
	updateI(target, readI(arg1) - readI(arg2));
}

void __gt(Thunk* target)
{
	Thunk* arg1 = stack[stack_top - 2];
	Thunk* arg2 = stack[stack_top - 1];
	
	eval(arg1);
	eval(arg2);
	
	updateB(target, readI(arg1) > readI(arg2));
}

void __lt(Thunk* target)
{
	Thunk* arg1 = stack[stack_top - 2];
	Thunk* arg2 = stack[stack_top - 1];
	
	eval(arg1);
	eval(arg2);
	
	updateB(target, readI(arg1) < readI(arg2));
}

53
PrimEntry* add_prim(int arity, int strictness, char* name, void (*exec)(Thunk*))
54
55
56
57
{
	int nameLength = strlen(name);
	
	// before the PrimEntry there are "arity" number of SliceEntries
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
58
	SliceEntry* entry_base = (SliceEntry*) alloc_desc(sizeof(SliceEntry) * arity + sizeof(PrimEntry) + nameLength + 1);
59
		
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
60
	PrimEntry* entry = (PrimEntry*) (entry_base + arity);
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
61
62
	entry->base.type = FT_PRIM;
	entry->base.arity = arity;
63
64
65
66
67
68
69
70
	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
71
	if(arity>0) gen_slices(entry_base, (Desc*) entry, arity);
72
	
Laszlo Domoszlai's avatar
Laszlo Domoszlai committed
73
	add_desc(entry->name, (Desc*) entry);
74
75
76
77
78
}

void init_prim()
{
	add_prim(2, 3, "add", &__add);
79
80
81
	add_prim(2, 3, "sub", &__sub);
	add_prim(2, 3, "gt", &__gt);
	add_prim(2, 3, "lt", &__lt);
82
}