summaryrefslogtreecommitdiff
path: root/val.c
blob: 530737d85719e5736ea991711e47ef42f415d63f (plain)
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
#include <stdio.h>
#include <string.h>
#include "val.h"
#include "mem.h"
#include "ht.h"


ObjString *objstring_copy(char *src, size_t len) {
	char *d = NEW_ARR(char, 1+len);
	memcpy(d, src, len);
	d[len] = '\0';
	ObjString *o = NEW_OBJ(ObjString, OTY_STRING);
	o->len = len;
	o->b = d;
	o->hash = hash(d, len);

	return o;
}

ObjString *objstring_take(char *src, size_t len) { 
	ObjString *o = NEW_OBJ(ObjString, OTY_STRING);
	o->len = len;
	o->b = src;
	o->hash = hash(src, len);

	return o;
}

void print_val(Val v) {
	switch (v.ty) {
	case TY_NIL:
		printf("nil");
		break;
	case TY_NUM:
		printf("%f",AS_NUM(v));
		break;
	case TY_BOOL:
		printf("%s",AS_BOOL(v) ? "true" : "false");
		break;
	case TY_OBJ:
		switch (AS_OBJ(v)->oty) {
		case OTY_STRING:
			printf("%s", AS_CSTRING(v));
			break;
		}
		break;
	}
}


void println_val(Val v) {
	print_val(v);
	putchar('\n');
}


const char *typename_str(Val v) {
	switch(v.ty) {
	case TY_NIL: return "nil";
	case TY_NUM: return "num";
	case TY_BOOL: return "bool";
	case TY_OBJ:
		switch (AS_OBJ(v)->oty) {
		case OTY_STRING: return "String";
		}
		break;
	}
	return "???";
}