-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.c
111 lines (94 loc) · 2.28 KB
/
map.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdlib.h>
#include <string.h>
#include "lisp.h"
#define HASHSZ 101
static unsigned hash(Value *v)
{
unsigned h = 0;
int i;
if (v->type == TNumber)
return (int)v->number%HASHSZ;
if (v->type != TString && v->type != TSymbol)
return 0;
for (i = 0; i < v->string->len; i++)
h = string(v, i) + 31 * h;
return h%HASHSZ;
}
int cmp(Value *a, Value *b)
{
if (a->type == TNumber && b->type == TNumber) {
double c = a->number - b->number;
return c < 0? -1 : c > 0? 1 : 0;
}
if ((a->type != TString && a->type != TSymbol) &&
(b->type != TSymbol && b->type != TSymbol))
return 0;
if (a->string->len != b->string->len)
return a->string->len - b->string->len;
return strncmp(a->string->d, b->string->d, a->string->len);
}
Value *mapget(Value *map, Value *key)
{
int i;
unsigned h = hash(key);
Value *group = &list(map, h);
if (group->type != TList)
set(group, make(TList));
/* i += 2 because it's a list of key-val pairs */
for (i = 0; i < group->list->len; i += 2)
if (cmp(&list(group, i), key) == 0)
return &list(group, i+1);
set(&list(group, i), *key);
return &list(group, i+1); /* new undefined nil value */
}
void setvar(Value *map, char *key, Value v)
{
int len = strlen(key);
Value k = nil;
set(&k, make(TSymbol));
string(&k, len-1);
strncpy(k.symbol->d, key, len);
set(mapget(map, &k), v);
delete(&k);
}
/* interfaces for map and list usage inside the language */
Value eval_map_literal(Value *ctx, Value *args)
{
Value m = nil;
int i;
set(&m, make(TList));
for (i = 1; i < args->list->len; i += 2)
set(mapget(&m, &list(args, i)), eval(ctx, &list(args, i+1)));
unmark(&m);
return m;
}
Value eval_map_get(Value *ctx, Value *args)
{
Value m = nil, k = nil, v = make(TWeak);
set(&m, eval(ctx, &list(args, 1)));
set(&k, eval(ctx, &list(args, 2)));
v.weak = mapget(&m, &k);
delete(&m);
delete(&k);
return v;
}
Value eval_list_literal(Value *ctx, Value *args)
{
Value l = nil;
int i;
set(&l, make(TList));
for (i = 1; i < args->list->len; i++)
set(&list(&l, i-1), eval(ctx, &list(args, i)));
unmark(&l);
return l;
}
Value eval_list_get(Value *ctx, Value *args)
{
Value l = nil, i = nil, v = make(TWeak);
set(&l, eval(ctx, &list(args, 1)));
set(&i, eval(ctx, &list(args, 2)));
v.weak = &list(&l, i.number);
delete(&l);
delete(&i);
return v;
}