-
Notifications
You must be signed in to change notification settings - Fork 2
/
barebones-macro.c
85 lines (74 loc) · 2.8 KB
/
barebones-macro.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CONCAT_(a, b) a##b
#define CONCAT(a, b) CONCAT_(a, b)
/* The `Show` typeclass allows types to be turned into their string representation */
typedef struct
{
char* (*const show)(void* self);
} ShowTC;
typedef struct
{
void* self;
ShowTC const* tc;
} Show;
#define impl_show(T, Name, show_f) \
static inline char* CONCAT(show_f, __)(void* self) \
{ \
char* (*const show_)(T* self) = (show_f); \
(void)show_; \
return show_f(self); \
} \
Show Name(T* x) \
{ \
static ShowTC const tc = { .show = (CONCAT(show_f, __)) }; \
return (Show){ .tc = &tc, .self = x }; \
}
/* Polymorphic printing function */
void print(Show showable)
{
char* const s = showable.tc->show(showable.self);
puts(s);
free(s);
}
/* A very holy enum */
typedef enum
{
holy,
hand,
grenade
} Antioch;
static inline char* strdup_(char const* x)
{
char* const s = malloc((strlen(x) + 1) * sizeof(*s));
strcpy(s, x);
return s;
}
/* The `show` function implementation for `Antioch*` */
static char* antioch_show(Antioch* x)
{
/*
Note: The `show` function of a `Show` typeclass is expected to return a malloc'ed value
The users of a generic `Show` are expected to `free` the returned pointer from the function `show`.
*/
switch (*x)
{
case holy:
return strdup_("holy");
case hand:
return strdup_("hand");
case grenade:
return strdup_("grenade");
default:
return strdup_("breakfast cereal");
}
}
/* Make function to build a generic `Show` out of a concrete type- `Antioch` */
impl_show(Antioch, prep_antioch_show, antioch_show)
int main(void)
{
Show const antsh = prep_antioch_show(&(Antioch){ hand });
print(antsh);
return 0;
}