summaryrefslogtreecommitdiff
path: root/lit.c
blob: 09528a22834b3198b1400020736deffc428329f9 (plain) (blame)
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
#include "lit.h"
#include "fn.h"
#include "lex.h"
#include "parse.h"
#include "prv.h"
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void lit_free(struct lit *l)
{
    free(l->name);
}

static char *gen(struct ast *ast, struct fn *fn)
{
    static const char fmt[] = "__str_%zu";
    int n = snprintf(NULL, 0, fmt, ast->litcnt);
    char *ret = NULL;
    size_t sz;

    if (n < 0)
    {
        fprintf(stderr, "%s: snprintf(3) failed\n", __func__);
        goto failure;
    }
    else if (!(ret = malloc((sz = n + 1))))
    {
        perror("malloc(3)");
        goto failure;
    }

    n = snprintf(ret, sz, fmt, ast->litcnt);

    if (n < 0 || n >= sz)
    {
        fprintf(stderr, "%s: snprintf(3) failed with %d\n", __func__, n);
        goto failure;
    }

    ast->litcnt++;
    return ret;

failure:
    free(ret);
    return NULL;
}

static const struct lit *find(const struct tk *tk, const struct ast *ast)
{
    for (const struct lit *l = ast->lits; l; l = l->next)
        if (!strcmp(l->tk->s, tk->s))
            return l;

    return NULL;
}

int lit_cgen(const struct lit *l)
{
    printf("data $%s = { b \"%s\", b 0 }\n", l->name, l->tk->s);
    return 0;
}

const struct lit *lit_push(const struct tk *tk, struct prv *p)
{
    char *name = NULL;
    struct fn *fn = fn_cur(p);
    struct ast *ast = p->ast;
    const struct lit *prev = find(tk, ast);
    struct lit *l;

    if (prev)
        return prev;
    else if (!(name = gen(ast, fn)))
        goto failure;
    else if (!(l = malloc(sizeof *l)))
    {
        perror("malloc(3)");
        goto failure;
    }

    *l = (struct lit)
    {
        .name = name,
        .fn = fn,
        .tk = tk
    };

    if (!ast->lits)
        ast->lits = l;
    else if (ast->lastlit)
        ast->lastlit->next = l;

    ast->lastlit = l;
    fprintf(stderr, "adding literal \"%s\"\n", name);
    return l;

failure:
    free(name);
    return NULL;
}