aboutsummaryrefslogtreecommitdiff
path: root/src/template.c
blob: f73ca1d29517baa2323e35ec23cf3ac3205c07e3 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <assert.h>

#include "vendor/mpc.h"
#include "template.h"

enum unja_object_type {
    OBJ_NULL,
    OBJ_INT,
    OBJ_STRING,
};

struct unja_object {
    enum unja_object_type type;
    int integer;
    char *string;
    char *string_ptr;
};

struct unja_object null_object = { 
    .type = OBJ_NULL,
};

struct buffer {
    int size;
    int cap;
    char *string;
};

struct env {
    struct hashmap *templates;
};

struct template {
    char *name;
    mpc_ast_t *ast;
    struct hashmap *blocks;
    char *parent;
};

/* ensure buffer has room for a string sized l, grows buffer capacity if needed */
static void
buffer_reserve(struct buffer *buf, size_t l)
{
    int req_size = buf->size + l;
    if (req_size >= buf->cap) {
        while (req_size >= buf->cap) {
            buf->cap *= 2;
        }
        
        buf->string = realloc(buf->string, buf->cap);
        if (!buf->string) {
            errx(EXIT_FAILURE, "out of memory");
        }
    }
}

static void
buffer_cat(struct buffer *buf, const char *str)
{
    size_t l = strlen(str);
    buffer_reserve(buf, l);
    strcat(buf->string, str);
	buf->size += l;
}

static mpc_parser_t *
parser_init()
{
    static mpc_parser_t *template;
    if (template != NULL) {
        return template;
    }

    mpc_parser_t *spaces = mpc_new("spaces");
    mpc_parser_t *symbol = mpc_new("symbol");
    mpc_parser_t *number = mpc_new("number");
    mpc_parser_t *string = mpc_new("string");
    mpc_parser_t *text = mpc_new("text");
    mpc_parser_t *print = mpc_new("print");
    mpc_parser_t *lexp = mpc_new("lexp");
    mpc_parser_t *exp = mpc_new("expression");
    mpc_parser_t *comment = mpc_new("comment");
    mpc_parser_t *statement = mpc_new("statement");
    mpc_parser_t *statement_open = mpc_new("statement_open");
    mpc_parser_t *statement_close = mpc_new("statement_close");
    mpc_parser_t *statement_for = mpc_new("for");
    mpc_parser_t *statement_if = mpc_new("if");
    mpc_parser_t *statement_block = mpc_new("block");
    mpc_parser_t *statement_extends = mpc_new("extends");
    mpc_parser_t *body = mpc_new("body");
    mpc_parser_t *content = mpc_new("content");
    mpc_parser_t *factor = mpc_new("factor");
    mpc_parser_t *term = mpc_new("term");
    mpc_parser_t *filter = mpc_new("filter");

    template = mpc_new("template");
    mpca_lang(MPCA_LANG_WHITESPACE_SENSITIVE,
        " spaces    : / */ ;"
        " symbol    : /[a-zA-Z][a-zA-Z0-9_.]*/ ;"
        " number    : /[0-9]+/ ;"
        " text      : /[^{][^{%#]*/;"
        " string    : '\"' /([^\"])*/ '\"' ;"
        " factor    : <symbol> | <number> | <string> ;"
        " filter    : <spaces> '|' <spaces> <symbol>; "
        " term      :  <factor> (<spaces> ('*' | '/' | '%') <spaces> <factor>)* <filter>?;"
        " lexp      : <term> (<spaces> ('+' | '-') <spaces> <term>)* ;"
        " expression: <lexp> <spaces> '>' <spaces> <lexp> "
        "           | <lexp> <spaces> '<' <spaces> <lexp> "
        "           | <lexp> <spaces> \">=\" <spaces> <lexp> "
        "           | <lexp> <spaces> \"<=\" <spaces> <lexp> "
        "           | <lexp> <spaces> \"!=\" <spaces> <lexp> "
        "           | <lexp> <spaces> \"==\" <spaces> <lexp> "
        "           | \"not\" <spaces> <lexp> "
        "           | <lexp> ;"
        " print     : /{{2}-? */ <expression> / *-?}}/ ;"
        " comment   : \"{#\" /[^#][^#}]*/ \"#}\" ;"
        " statement_open: /{\%-? */;"
        " statement_close: / *-?\%}/;"
        " for       : <statement_open> \"for \" <symbol> \" in \" <symbol> <statement_close> <body> <statement_open> \"endfor\" <statement_close> ;"
        " block     : <statement_open> \"block \" <symbol> <statement_close> <body> <statement_open> \"endblock\" <statement_close>;"
        " extends   : <statement_open> \"extends \" <string> <statement_close>;"
        " if        : <statement_open> \"if \" <expression> <statement_close> <body> (<statement_open> \"else\" <statement_close> <body>)? <statement_open> \"endif\" <statement_close> ;"
        " statement : <for> | <block> | <extends> | <if> ;"
        " content   : <print> | <statement> | <text> | <comment>;"
        " body      : <content>* ;"
        " template  : /^/ <body> /$/ ;",
        spaces,
        filter,
        factor, 
        term,
        symbol, 
        text,
        number,
        string,
        print,
        lexp,
        exp, 
        comment,
        statement_open, 
        statement_close, 
        statement,
        statement_if,
        statement_for, 
        statement_block,
        statement_extends,
        content, 
        body, 
        template);

    return template;
}

static mpc_ast_t *
parse(char *tmpl)
{
    mpc_parser_t *parser = parser_init();
    mpc_result_t r;

    if (!mpc_parse("input", tmpl, parser, &r)) {
        puts(tmpl);
        mpc_err_print(r.error);
        mpc_err_delete(r.error);
        return NULL;
    }

    return r.output;
}

static struct hashmap *
find_blocks_in_ast(mpc_ast_t *node, struct hashmap *map)
{
    if (strstr(node->tag, "content|statement|block")) {
        char *name = node->children[2]->contents;
        hashmap_insert(map, name, node);
    }

    for (int i=0; i < node->children_num; i++) {
        find_blocks_in_ast(node->children[i], map);
    }

    return map;
}

struct env *
env_new(const char *dirname)
{
    /* store current working dir so we can revert to it after reading templates */
    char working_dir[256];
    getcwd(working_dir, 255);

    DIR *dr = opendir(dirname); 
    if (dr == NULL) return NULL;
  
    struct env *env = malloc(sizeof *env);
    if (env == NULL) return NULL;

    env->templates = hashmap_new();
    chdir(dirname);

    struct dirent *de;   
    while ((de = readdir(dr)) != NULL) {
        // skip files starting with a dot
        if (de->d_name[0] == '.') {
            continue;
        }

        // copy template name as closedir free's it otherwise
        char *name = malloc(strlen(de->d_name) + 1);
        strcpy(name, de->d_name);

        char *tmpl = read_file(name);
        #if DEBUG
        printf("Parsing template from file %s: %s\n", name, tmpl);
        #endif
        mpc_ast_t *ast = parse(tmpl);
        free(tmpl);

        struct template *t = malloc(sizeof *t);
        t->ast = ast;
        t->name = name;
        t->blocks = find_blocks_in_ast(ast, hashmap_new());
        t->parent = NULL;

        if (ast->children_num > 1 && ast->children[1]->children_num > 0 && strstr(ast->children[1]->children[0]->tag, "content|statement|extends")) {
            t->parent = ast->children[1]->children[0]->children[2]->children[1]->contents;
        }

        hashmap_insert(env->templates, name, t);
    }
  
    closedir(dr); 
    chdir(working_dir);    
    return env;
}

static void
template_free(const void *k, void *v)
{
    struct template *t = v;
    hashmap_free(t->blocks);
    mpc_ast_delete(t->ast);
    free(t->name);
    free(t);
}

void
env_free(struct env *env)
{
    hashmap_walk(env->templates, template_free);
    hashmap_free(env->templates);
    free(env);
}

char *
read_file(char *filename)
{
    char *input = malloc(BUFSIZ);
    unsigned int size = 0;

    FILE *f = fopen(filename, "r");
    if (!f) {
        errx(EXIT_FAILURE, "could not open \"%s\" for reading", filename);
    }

    unsigned int read = 0;
    while ( (read = fread(input + read, 1, BUFSIZ, f)) > 0) {
        size += read;
        input = realloc(input, size + BUFSIZ);
    }

    fclose(f);

    input[size] = '\0';
    return input;
}

static char *
trim_trailing_whitespace(char *str)
{
    for (int i=strlen(str)-1; i >= 0 && isspace(str[i]); i--) {
        str[i] = '\0';
    }
    return str;
}

static char *
trim_leading_whitespace(char *str)
{
    while (isspace(*str)) {
        str++;
    }

    return str;
}

static struct unja_object *
make_string_object(char *value, char *value2)
{
    struct unja_object *obj = malloc(sizeof *obj);
    obj->type = OBJ_STRING;
    int l = strlen(value) + 1;
    if (value2) {
        l += strlen(value2);
    }

   
    obj->string = malloc(l);
    obj->string_ptr = obj->string;
    strcpy(obj->string, value);
    
    if(value2) {
        strcat(obj->string, value2);
    }
    return obj;
}

static struct unja_object *
make_int_object(int value)
{
    struct unja_object *obj = malloc(sizeof *obj);
    obj->type = OBJ_INT;
    obj->integer = value;
    return obj;
}


static void
eval_object(struct buffer *buf, struct unja_object *obj)
{
    char tmp[64];

    switch (obj->type) {
        case OBJ_NULL: 
            break;
        case OBJ_STRING:
            buffer_cat(buf, obj->string);
            break;
        case OBJ_INT: 
            sprintf(tmp, "%d", obj->integer);
            buffer_cat(buf, tmp);
            break;
    }
}

static int
object_to_int(struct unja_object *obj)
{
     switch (obj->type) {
        case OBJ_NULL: return 0; 
        case OBJ_STRING: return atoi(obj->string);
        case OBJ_INT: return obj->integer;
    }

    return 0;
}

static void
object_free(struct unja_object *obj)
{
    switch(obj->type) {
        case OBJ_NULL: return;
        case OBJ_STRING: 
            free(obj->string_ptr);
        break;
        case OBJ_INT: break;
    }

    free(obj);
}

static int
object_is_truthy(struct unja_object *obj)
{
    switch (obj->type) {
        case OBJ_NULL: return 0; 
        case OBJ_STRING: return strlen(obj->string) > 0 && strcmp(obj->string, "0") != 0;
        case OBJ_INT: return obj->integer > 0;
    }

    return 0;
}

struct context {
    struct hashmap *vars;
    struct hashmap *filters;
    struct env *env;
    struct template *current_template;
};

static struct unja_object *
eval_expression_value(mpc_ast_t* node, struct context *ctx)
{
    if (strstr(node->tag, "symbol|")) {
        /* Return empty string if no vars were passed. Should probably signal error here. */
        if (ctx->vars == NULL) {
           return &null_object;
        }

        char *key = node->contents;
        char *value = hashmap_resolve(ctx->vars, key);

        /* TODO: Handle unexisting symbols (returns NULL currently) */
        if (value == NULL) {
            return &null_object;
        }

        return make_string_object(value, NULL);
    } else if(strstr(node->tag, "number|")) {
        return make_int_object(atoi(node->contents));
    } else if(strstr(node->tag, "string|")) {
        return make_string_object(node->children[1]->contents, NULL);
    }

    return &null_object;
}

static struct unja_object *
eval_string_infix_expression(struct unja_object *left, char *op, struct unja_object *right)
{
    struct unja_object *result;

    if (strcmp(op, "+") == 0) {
        result = make_string_object(left->string, right->string);
    } else if (strcmp(op, "==") == 0) {
        result = make_int_object(strcmp(left->string, right->string) == 0);
    } else if(strcmp(op, "!=") == 0) {
        result = make_int_object(strcmp(left->string, right->string) != 0);
    } else {
        errx(EXIT_FAILURE, "invalid string operator: %s", op);
    }

    object_free(left);
    object_free(right);
    return result;
}

static struct unja_object *
eval_infix_expression(struct unja_object *left, char *op, struct unja_object *right)
{
    /* if operator is + and either left or right node is of type string: concat */
    if (left->type == OBJ_STRING && right->type == OBJ_STRING) {           
        return eval_string_infix_expression(left, op, right);
    } 

    int result;
    switch (op[0]) {
        case '+': result = object_to_int(left) + object_to_int(right); break;
        case '-': result = object_to_int(left) - object_to_int(right); break;
        case '/': result = object_to_int(left) / object_to_int(right); break;
        case '*': result = object_to_int(left) * object_to_int(right); break;
        case '%': result = object_to_int(left) % object_to_int(right); break;
        case '>': 
            if (op[1] == '=') {
                result = object_to_int(left) >= object_to_int(right);    
            } else {
                result = object_to_int(left) > object_to_int(right); 
            }
            break;
        case '<': 
            if (op[1] == '=') {
                result = object_to_int(left) <= object_to_int(right);    
            } else {
                result = object_to_int(left) < object_to_int(right); 
            }
            break;
        case '!': 
            if (op[1] == '=') {
                result = object_to_int(left) != object_to_int(right);    
            } else {
                errx(EXIT_FAILURE, "invalid int operator: %s", op);
            }
            break;
        case '=': 
            if (op[1] == '=') {
                result = object_to_int(left) == object_to_int(right);    
            } else {
                errx(EXIT_FAILURE, "invalid int operator: %s", op);
            }
            break;
    }

    object_free(left);
    object_free(right);
    return make_int_object(result);
}

static struct unja_object *
eval_expression(mpc_ast_t* expr, struct context *ctx)
{

    /* singular term */
    if (expr->children_num == 0 || strstr(expr->tag, "string|")) {
        return eval_expression_value(expr, ctx);
    }

    struct unja_object *result;

    /* singular negated term */
    if (strcmp(expr->children[0]->contents, "not") == 0) {
        result = eval_expression_value(expr->children[2], ctx);
        struct unja_object *negated = make_int_object(!object_to_int(result));
        object_free(result);
        return negated;
    }

    /* otherwise: with operator */
    unsigned int offset = 0; 
    mpc_ast_t *left_node = expr->children[0];
    struct unja_object *left = eval_expression(left_node, ctx);
    result = left;

    while (offset < (expr->children_num - 1)) {
        /* Check if we arrived at a filter (guaranteed to be last in expression list) */
        if (strstr(expr->children[offset+1]->tag, "filter")) {
            char *filter_name = expr->children[offset+1]->children[3]->contents;
            struct unja_object *(*filter_fn)(struct unja_object *) = hashmap_get(ctx->filters, filter_name);
            if (NULL == filter_fn) {
                errx(EXIT_FAILURE, "unknown filter: %s", filter_name);
            }
            result = filter_fn(result);
            break;
        }


        mpc_ast_t *op = expr->children[offset+2];
        mpc_ast_t *right_node = expr->children[offset+4];
        struct unja_object *right = eval_expression(right_node, ctx);
        result = eval_infix_expression(left, op->contents, right);

        left = result;
        offset += 4;
    }

    return result;
   
}

static int 
eval(struct buffer *buf, mpc_ast_t* t, struct context *ctx)
{
    static int trim_whitespace = 0;

    // maybe eat whitespace going backward
    if (t->children_num > 0 && strstr(t->children[0]->contents, "-")) {
        buf->string = trim_trailing_whitespace(buf->string);
    }

    if (strstr(t->tag, "content|text")) {
        char *str = t->contents;
        if (trim_whitespace) {
            str = trim_leading_whitespace(str);
            trim_whitespace = 0;
        }

        buffer_cat(buf, str);
        return 0;
    }

    if (strstr(t->tag, "content|statement|block")) {
        trim_whitespace = strstr(t->children[3]->contents, "-") ? 1 : 0;
        char *block_name = t->children[2]->contents;
        
        // find block in "lowest" template
        struct template *templ = ctx->current_template;
        mpc_ast_t *block = hashmap_get(templ->blocks, block_name);
        while (templ != NULL && block == NULL) {
            templ = hashmap_get(ctx->env->templates, templ->parent);
            block = hashmap_get(templ->blocks, block_name);
        }
        
        if (block) {
            eval(buf, block->children[4], ctx);
        } else {
            /* block not found in any lower template, so just render the one we got */
            eval(buf, t->children[4], ctx);
        }

        if (t->children_num == 8) {
        	trim_whitespace = strstr(t->children[7]->contents, "-") ? 1 : 0;
        }
        return 0;
    }

    // eval print statement
    if (strstr(t->tag, "content|print")) {
        trim_whitespace = strstr(t->children[2]->contents, "-") ? 1 : 0;
        mpc_ast_t *expr = t->children[1];      
        struct unja_object *obj = eval_expression(expr, ctx);  
        eval_object(buf, obj);
        object_free(obj);
        return 0;
    }

    if (strstr(t->tag, "content|statement|for")) {
        char *tmp_key = t->children[2]->contents;
        char *iterator_key = t->children[4]->contents;
        struct vector *list = hashmap_resolve(ctx->vars, iterator_key);

        /* add "loop" variable to context */
        struct hashmap *loop = hashmap_new();
        char index[8], first[2], last[2];
        hashmap_insert(loop, "index", index);
        hashmap_insert(loop, "first", first);
        hashmap_insert(loop, "last", last);
        hashmap_insert(ctx->vars, "loop", loop);

        /* loop over values in vector */
        for (int i=0; i < list->size; i++) {
            /* set loop variable values */
            sprintf(index, "%d", i);
            sprintf(first, "%d", i == 0);
            sprintf(last, "%d", i == (list->size - 1));
            hashmap_insert(ctx->vars, tmp_key, list->values[i]);
            trim_whitespace = strstr(t->children[5]->contents, "-") ? 1 : 0;

            /* evaluate body */
            eval(buf, t->children[6], ctx);
        }

        /* remove "loop" variable from context */
        hashmap_remove(ctx->vars, "loop");
        hashmap_free(loop);

        /* trim trailing whitespace if closing tag has minus sign */
        if (strstr(t->children[7]->contents, "-")) {
            buf->string = trim_trailing_whitespace(buf->string);
        }
        
        trim_whitespace = strstr(t->children[9]->contents, "-") ? 1 : 0;
        return 0;
    }

    if (strstr(t->tag, "content|statement|if")) {
        mpc_ast_t *expr = t->children[2];
        struct unja_object *result = eval_expression(expr, ctx);

        if (object_is_truthy(result)) {
            trim_whitespace = strstr(t->children[3]->contents, "-") ? 1 : 0;

            eval(buf, t->children[4], ctx);

            /* trim trailing whitespace if closing tag has minus sign */
            if (strstr(t->children[5]->contents, "-")) {
                buf->string = trim_trailing_whitespace(buf->string);
            }

            trim_whitespace = strstr(t->children[7]->contents, "-") ? 1 : 0;
        } else {
            if (t->children_num > 8) {
                trim_whitespace = strstr(t->children[7]->contents, "-") ? 1 : 0;
                eval(buf, t->children[8], ctx);

                 /* trim trailing whitespace if closing tag has minus sign */
                if (strstr(t->children[9]->contents, "-")) {
                    buf->string = trim_trailing_whitespace(buf->string);
                }

                trim_whitespace = strstr(t->children[11]->contents, "-") ? 1 : 0;
            }
        }

        object_free(result);
        return 0;
    }

    for (int i=0; i < t->children_num; i++) {
        eval(buf, t->children[i], ctx);
    }

    return 0;
}

static char *
render_ast(mpc_ast_t *ast, struct context *ctx)
{
    #if DEBUG
    printf("AST: \n");
    mpc_ast_print(ast);
    printf("\n");
    #endif

    struct buffer buf;
    buf.size = 0;
    buf.cap = 256;
    buf.string = malloc(buf.cap);
    buf.string[0] = '\0';
    eval(&buf, ast, ctx);
    return buf.string;
}

static struct unja_object *
filter_trim(struct unja_object *obj)
{
    assert(obj->type == OBJ_STRING);
    obj->string = trim_leading_whitespace(obj->string);
    trim_trailing_whitespace(obj->string);
    return obj;
}

static struct unja_object *
filter_lower(struct unja_object *obj)
{
    assert(obj->type == OBJ_STRING);
    int len = strlen(obj->string);
    for (int i=0; i < len; i++) {
        obj->string[i] = tolower(obj->string[i]);
    }
    return obj;
}

static struct unja_object *
filter_wordcount(struct unja_object *obj)
{
    assert(obj->type == OBJ_STRING);
    int len = strlen(obj->string);
    int word_count = 1;
    for (int i=0; i < len; i++) {
        if (isspace(obj->string[i])) {
            word_count++;
        }
    }

    object_free(obj);
    return make_int_object(word_count);
}


static struct unja_object *
filter_length(struct unja_object *obj)
{
    assert(obj->type == OBJ_STRING);
    int len = strlen(obj->string);
    object_free(obj);
    return make_int_object(len);
}

static struct hashmap *
default_filters()
{
    struct hashmap *filters = hashmap_new();
    hashmap_insert(filters, "trim", filter_trim);
    hashmap_insert(filters, "lower", filter_lower);
    hashmap_insert(filters, "wordcount", filter_wordcount);
    hashmap_insert(filters, "length", filter_length);
    return filters;
}

static struct context 
context_new(struct hashmap *vars, struct env *env, struct template *current_tmpl)
{
    struct context ctx;
    ctx.filters = default_filters();
    ctx.vars = vars;
    ctx.env = env;
    ctx.current_template = current_tmpl;    
    return ctx;
}

static void 
context_free(struct context ctx)
{
    hashmap_free(ctx.filters);
}

char *
template_string(char *tmpl, struct hashmap *vars)
{
    #if DEBUG
    printf("Template: %s\n", tmpl);
    #endif
    struct mpc_ast_t *ast = parse(tmpl); 
    struct context ctx = context_new(vars, NULL, NULL);     
    char *output = render_ast(ast, &ctx);
    mpc_ast_delete(ast);
    context_free(ctx);
    return output;
}

char *
template(struct env *env, const char *template_name, struct hashmap *vars)
{
    struct template *t = hashmap_get(env->templates, template_name);
    /* TODO: handle template not found */
    #if DEBUG
    printf("Template name: %s\n", t->name);
    printf("Parent: %s\n", t->parent ? t->parent : "None");
    #endif

    struct context ctx = context_new(vars, env, t); 

    // find root template
    while (t->parent != NULL) {
        char *parent_name = t->parent;
        t = hashmap_get(env->templates, parent_name);

        if (t == NULL) {
            errx(EXIT_FAILURE, "template tried to extend unexisting parent \"%s\"", parent_name);
            break;
        }
    }

   
    char *output = render_ast(t->ast, &ctx);
    context_free(ctx);
    return output;
}