summaryrefslogtreecommitdiff
path: root/val.h
blob: 3cf32518ba18c99a6d1ec493235dd66c36049e72 (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
70
71
72
73
74
75
#ifndef _val_h
#define _val_h

#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>


typedef struct _val Val;
typedef struct _obj Obj;


typedef enum {
	TY_NIL,
	TY_NUM,
	TY_BOOL,
	TY_OBJ,
} ValTy;

typedef struct _val {
	ValTy ty;
	union {
		double d;
		bool b;
		Obj *o;
	} as;
} Val;
void print_val(Val v);
void println_val(Val v);
const char *typename_str(Val v);


typedef enum {
	OTY_STRING,
} ObjTy;

typedef struct _obj {
	ObjTy oty;
} Obj;

typedef struct {
	Obj obj;
	size_t len;
	uint32_t hash;
	char *b;
} ObjString;

ObjString *objstring_copy(char *src, size_t len);
ObjString *objstring_take(char *src, size_t len);


#define IS_NIL(x) (x.ty == NIL)
#define IS_NUM(x) (x.ty == TY_NUM)
#define IS_BOOL(x) (x.ty == TY_BOOL)
#define IS_OBJ(x) (x.ty == TY_OBJ)

#define IS_STRING(x) (is_obj_ty((x), OTY_STRING))

#define AS_NUM(x) (x.as.d)
#define AS_BOOL(x) (x.as.b)
#define AS_OBJ(x) (x.as.o)

#define AS_STRING(x) ((ObjString*)AS_OBJ(x))
#define AS_CSTRING(x) (AS_STRING(x)->b)

#define VAL_NIL ((Val){.ty=TY_NIL})
#define VAL_NUM(x) ((Val){.ty=TY_NUM, .as.d=(x) })
#define VAL_BOOL(x) ((Val){.ty=TY_BOOL, .as.b=(x) })
#define VAL_OBJ(x) ((Val){.ty=TY_OBJ, .as.o=(Obj*)(x) })

static inline bool is_obj_ty(Val v, ObjTy t) {
	return IS_OBJ(v) && (AS_OBJ(v)->oty == t);
}

#endif