-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatoms.c
90 lines (72 loc) · 2.17 KB
/
atoms.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
#include "atoms.h"
#include "type.h"
#include "nil.h"
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
static void boolean_writer(void *, Printf);
static void number_writer(void *, Printf);
static void identifier_writer(void *, Printf);
static void string_writer(void *, Printf);
static long last(char *);
void declare_atoms(void) {
boolean_type = declare("Boolean", free, boolean_writer);
number_type = declare("Number", free, number_writer);
identifier_type = declare("Identifier", free, identifier_writer);
string_type = declare("String", free, string_writer);
}
Object *boolean(bool true_or_false) {
bool *cell = (bool *)malloc(sizeof(bool));
*cell = true_or_false;
return wrap(boolean_type, cell);
}
int is_boolean(Object *boolean) {
return is_a(boolean_type, boolean);
}
bool is_true(Object *condition) {
return ! is_false(condition);
}
bool is_false(Object *condition) {
return is_nil(condition) || (is_boolean(condition) && (*(bool *)value(condition) == false));
}
static void boolean_writer(void *boolean, Printf printer) {
printer("%s", *(bool *)boolean == true ? "true" : "false");
}
Object *number(long number) {
long *cell = (long *)malloc(sizeof(long));
*cell = number;
return wrap(number_type, cell);
}
int is_number(Object *object) {
return is_a(number_type, object);
}
static void number_writer(void *number, Printf printer) {
printer("%d", *(long *)number);
}
Object *identifier(char *name) {
return wrap(identifier_type, strdup(name));
}
int is_identifier(Object *object) {
return is_a(identifier_type, object);
}
static void identifier_writer(void *name, Printf printer) {
printer("%s", (char *)name);
}
Object *quoted_string(char *quoted) {
char *string = strdup(quoted + 1);
string[last(string)] = '\0';
return wrap(string_type, string);
}
Object *unquoted_string(char *unquoted) {
return wrap(string_type, unquoted);
}
int is_string(Object *object) {
return is_a(string_type, object);
}
static long last(char *string) {
return strlen(string) - 1;
}
static void string_writer(void *text, Printf printer) {
printer("\"%s\"", (char *)text);
}