Skip to content

Instantly share code, notes, and snippets.

@lerno
Created November 6, 2018 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lerno/1a26da6a8242c4b79acf84d0b1c91bff to your computer and use it in GitHub Desktop.
Save lerno/1a26da6a8242c4b79acf84d0b1c91bff to your computer and use it in GitHub Desktop.
Macro proposal II
// Switch
macro char * @foo(&x) {
$switch (@typeof(x)) {
$case int: return "int";
$case float: return "float";
$default: return "???";
}
}
char *x = @foo(10); // char *x = "int";
char *y = @foo(1.1); // char *y = "float";
// If-else
macro char* @foo2($x) {
$if ($x > 10) {
return "too_big";
} $else {
return "ok";
}
}
char *x = @foo2(5); // char *x = "ok";
char *y = @foo2(20); // char *y = "too_big";
// For
macro float @foo3($x) {
float $f = 0;
$for (int $i = 0; $i < $x; $i++) {
$f += ($i + 1) * ($i + 1);
}
return $f;
}
float x = @foo3(3); // float x = 14.0
// Generating structures (aka poor man's templates)
// ` ` makes pure text insert
macro @hash_define($type) {
$struct_name = $type + "Hash";
typedef struct {
$type value;
int hash;
} `$struct_name`;
$struct_name_map = $struct_name + "Map";
typedef struct {
`$struct_name` *entries;
size_t size;
} `$struct_name_map`;
`$struct_name_map`* `$struct_name_map + "_create()"` {
`$struct_name_map` *new = malloc(@sizeof(`$struct_name_map`));
new->size = 0;
new->entries = NULL;
return new;
}
}
@hash_define(Foo); // =>
typedef struct {
Foo value;
int hash;
} FooHash;
typedef struct {
FooHash *entries;
size_t size;
} FooHashMap;
FooHashMap *FooHashMap_create() {
FooHashMap *new = malloc(@sizeof(Foo));
new->size = 0;
new->entries = NULL;
return new;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment