aboutsummaryrefslogtreecommitdiff
path: root/src/analyzer.c
blob: eaf0ab2b6102cd2d21103b770d6cdbe4daa67a7e (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
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
#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <gmp.h>

#include "alloc.h"
#include "analyzer.h"
#include "common.h"
#include "errors.h"
#include "parser.h"
#include "strview.h"
#include "types.h"

/* A hashmap mapping symbol names to their indicies in the AST */
typedef struct symtab {
	struct symtab *child[4];
	struct strview key;
	idx_t_ val;
} symtab;

/* A dynamic array of scopes */
struct scopes {
	struct scope *buf;
	size_t len, cap;
};

/* Analyzer context; keeps track of the state of static analysis */
struct azctx {
	/* An arena allocator */
	arena *a;

	/* The return type of the function being analyzed */
	struct type fnret;

	/* The name of the symbol being declared.  This is necessary to allow
	   for ‘X :: X’ to be treated as shadowing and not a circular
	   definition */
	struct strview decl;

	/* The index of the current scope in the scopes array */
	idx_t_ si;

	/* If we need to check for return statements.  Only true for the
	   outer body-block of a function that returns a value. */
	bool chkrets;
};

struct cfctx {
	arena *a;
	struct strview decl;
	idx_t_ si;
};

static void analyzeast(struct scope *, struct type *, struct ast,
                       struct lexemes, arena *)
	__attribute__((nonnull));
static void constfold(mpq_t *, struct scope *, struct type *, struct ast,
                      struct lexemes, arena *)
	__attribute__((nonnull));

/* Perform a pass over the entire AST and return an array of symbol
   tables, one for each scope in the program */
static struct scope *gensymtabs(struct ast, struct lexemes, arena *)
	__attribute__((returns_nonnull, nonnull));

/* Find all the unordered symbols in the scope delimited by the inclusive
   indicies BEG and END in the AST, and accumulate them into a symbol
   table appended to the symbol table list.  UP is the index of the
   previous scopes symbol table in the symbol table list. */
static void find_unordered_syms(struct scopes *, struct ast, struct lexemes,
                                idx_t_ up, idx_t_ beg, idx_t_ end, arena *)
	__attribute__((nonnull));

typedef idx_t_ analyzer(struct azctx, struct scope *, struct type *, struct ast,
                        struct lexemes, idx_t_)
	__attribute__((nonnull));

static analyzer analyzeblk, analyzedecl, analyzeexpr, analyzefn, analyzestmt;

static const struct type *typegrab(struct ast, struct lexemes, idx_t_)
	__attribute__((returns_nonnull));
static bool typecompat(struct type, struct type);
static bool returns(struct ast, idx_t_);

/* Index the symbol table M with the key SV, returning a pointer to the
   value.  If no entry exists and A is non-null, a pointer to a newly
   allocated (and zeroed) value is returned, NULL otherwise. */
static idx_t_ *symtab_insert(symtab **m, struct strview sv, arena *a)
	__attribute__((nonnull(1)));

/* Defined in primitives.gperf */
const struct type *typelookup(const uchar *, size_t)
	__attribute__((nonnull));

void
analyzeprog(struct ast ast, struct lexemes toks, arena *a, struct type **types,
            struct scope **scps, mpq_t **folds)
{
	*types = bufalloc(NULL, ast.len, sizeof(**types));
	memset(*types, 0, ast.len * sizeof(**types));

	*scps = gensymtabs(ast, toks, a);
	analyzeast(*scps, *types, ast, toks, a);

	*folds = bufalloc(NULL, ast.len, sizeof(**folds));
	constfold(*folds, *scps, *types, ast, toks, a);
}

struct scope *
gensymtabs(struct ast ast, struct lexemes toks, arena *a)
{
	struct scopes scps = {.cap = 32};
	scps.buf = bufalloc(NULL, scps.cap, sizeof(*scps.buf));
	find_unordered_syms(&scps, ast, toks, 0, 0, ast.len - 1, a);
	return scps.buf;
}

void
find_unordered_syms(struct scopes *scps, struct ast ast, struct lexemes toks,
                    idx_t_ up, idx_t_ beg, idx_t_ end, arena *a)
{
	if (scps->len == scps->cap) {
		scps->cap *= 2;
		scps->buf = bufalloc(scps->buf, scps->cap, sizeof(*scps->buf));
	}

	struct scope *scp = scps->buf + scps->len++;
	*scp = (struct scope){
		.i = beg,
		.up = up,
		.map = NULL,
	};

	for (idx_t_ i = beg; likely(i <= end); i++) {
		bool globl_var = ast.kinds[i] <= _AST_DECLS_END && beg == 0;
		bool const_var = (ast.kinds[i] | 1) == ASTPCDECL;

		if (globl_var || const_var) {
			struct strview sv = toks.strs[ast.lexemes[i]];
			idx_t_ *p = symtab_insert(&scp->map, sv, a);
			if (*p != 0) {
				err("analyzer: Symbol ‘%.*s’ declared multiple times",
				    SV_PRI_ARGS(sv));
			}
			*p = i;
		} else if (ast.kinds[i] == ASTBLK) {
			struct pair p = ast.kids[i];
			find_unordered_syms(scps, ast, toks, beg, p.lhs, p.rhs, a);
			i = p.rhs;
		}
	}
}

const struct type *
typegrab(struct ast ast, struct lexemes toks, idx_t_ i)
{
	struct strview sv = toks.strs[ast.lexemes[i]];
	const struct type *tp = typelookup(sv.p, sv.len);
	if (tp == NULL)
		err("analyzer: Unknown type ‘%.*s’", (int)sv.len, sv.p);
	return tp;
}

void
analyzeast(struct scope *scps, struct type *types, struct ast ast,
           struct lexemes toks, arena *a)
{
	struct azctx ctx = {.a = a};
	for (idx_t_ i = 0; likely(i < ast.len); i = fwdnode(ast, i)) {
		assert(ast.kinds[i] <= _AST_DECLS_END);
		analyzedecl(ctx, scps, types, ast, toks, i);
	}
}

idx_t_
analyzedecl(struct azctx ctx, struct scope *scps, struct type *types,
            struct ast ast, struct lexemes toks, idx_t_ i)
{
	struct strview sv = toks.strs[ast.lexemes[i]];
	if (ctx.si > 0 && (ast.kinds[i] | 1) == ASTPDECL) {
		idx_t_ *ip = symtab_insert(&scps[ctx.si].map, sv, ctx.a);
		if (*ip == 0)
			*ip = i;
		else {
			err("analyzer: Variable ‘%.*s’ declared multiple times",
				SV_PRI_ARGS(sv));
		}
	}

	types[i].kind = TYPE_CHECKING;

	struct pair p = ast.kids[i];
	struct type ltype, rtype;
	ltype.kind = TYPE_UNSET;

	assert(p.lhs != AST_EMPTY || p.rhs != AST_EMPTY);

	idx_t_ ni;

	if (p.lhs != AST_EMPTY)
		ltype = *typegrab(ast, toks, p.lhs);
	if (p.rhs != AST_EMPTY) {
		ctx.decl = sv;
		ni = analyzeexpr(ctx, scps, types, ast, toks, p.rhs);
		rtype = types[p.rhs];
	} else
		ni = fwdnode(ast, i);

	if (ltype.kind == TYPE_UNSET)
		ltype = rtype;
	else if (!typecompat(ltype, rtype))
		err("analyzer: Type mismatch");

	types[i] = ltype;
	return ni;
}

idx_t_
analyzestmt(struct azctx ctx, struct scope *scps, struct type *types,
            struct ast ast, struct lexemes toks, idx_t_ i)
{
	switch (ast.kinds[i]) {
	case ASTDECL:
	case ASTCDECL:
		return analyzedecl(ctx, scps, types, ast, toks, i);
	case ASTRET: {
		idx_t_ expr = ast.kids[i].rhs;
		if (expr == AST_EMPTY) {
			if (ctx.fnret.kind != TYPE_UNSET)
				err("analyzer: Missing return value");
			return i + 1;
		} else if (ctx.fnret.kind == TYPE_UNSET)
			err("analyzer: Function has no return value");

		idx_t_ ni = analyzeexpr(ctx, scps, types, ast, toks, ast.kids[i].rhs);
		if (!typecompat(ctx.fnret, types[ast.kids[i].rhs]))
			err("analyzer: Return type mismatch");
		return ni;
	}
	default:
		__builtin_unreachable();
	}
}

idx_t_
analyzeexpr(struct azctx ctx, struct scope *scps, struct type *types,
            struct ast ast, struct lexemes toks, idx_t_ i)
{
	switch (ast.kinds[i]) {
	case ASTNUMLIT:
		types[i].kind = TYPE_NUM;
		types[i].size = 0;
		types[i].issigned = true;
		return i + 1;
	case ASTIDENT: {
		struct strview sv = toks.strs[ast.lexemes[i]];

		/* Variable shadowing */
		if (strview_eq(sv, ctx.decl) && ctx.si > 0)
			ctx.si--;

		for (idx_t_ lvl = ctx.si;;) {
			struct scope scp = scps[lvl];
			idx_t_ *ip = symtab_insert(&scp.map, sv, NULL);

			if (ip == NULL) {
				if (lvl == 0)
					break;
				lvl = scp.up;
			} else {
				switch (types[*ip].kind) {
				case TYPE_UNSET:
					ctx.si = lvl;
					analyzedecl(ctx, scps, types, ast, toks, *ip);
					break;
				case TYPE_CHECKING:
					err("analyzer: Circular definition of ‘%.*s’", SV_PRI_ARGS(sv));
				}

				types[i] = types[*ip];
				return i + 1;
			}
		}

		err("analyzer: Unknown symbol ‘%.*s’", SV_PRI_ARGS(sv));
	}
	case ASTFN:
		return analyzefn(ctx, scps, types, ast, toks, i);
	default:
		__builtin_unreachable();
	}
}

idx_t_
analyzefn(struct azctx ctx, struct scope *scps, struct type *types,
          struct ast ast, struct lexemes toks, idx_t_ i)
{
	struct type t = {.kind = TYPE_FN};
	struct pair p = ast.kids[i];

	idx_t_ proto = p.lhs;
	if (ast.kids[proto].rhs != AST_EMPTY) {
		t.ret = typegrab(ast, toks, ast.kids[proto].rhs);
		ctx.fnret = *t.ret;
		ctx.chkrets = true;
	} else
		ctx.fnret.kind = TYPE_UNSET;
	types[i] = t;
	return analyzeblk(ctx, scps, types, ast, toks, p.rhs);
}

idx_t_
analyzeblk(struct azctx ctx, struct scope *scps, struct type *types,
           struct ast ast, struct lexemes toks, idx_t_ i)
{
	struct pair p = ast.kids[i];

	while (scps[ctx.si].i != p.lhs)
		ctx.si++;

	bool chkrets = ctx.chkrets, hasret = false;
	ctx.chkrets = false;

	for (i = p.lhs; i <= p.rhs;) {
		if (chkrets && returns(ast, i))
			hasret = true;
		i = analyzestmt(ctx, scps, types, ast, toks, i);
	}
	if (chkrets && !hasret)
		err("analyzer: Function doesn’t return on all paths");

	return i;
}

static idx_t_
constfolddecl(struct cfctx ctx, mpq_t *folds, struct scope *scps,
              struct type *types, struct ast ast, struct lexemes toks, idx_t_ i);
static idx_t_
constfoldexpr(struct cfctx ctx, mpq_t *folds, struct scope *scps,
              struct type *types, struct ast ast, struct lexemes toks, idx_t_ i);

idx_t_
constfoldstmt(struct cfctx ctx, mpq_t *folds, struct scope *scps,
              struct type *types, struct ast ast, struct lexemes toks, idx_t_ i)
{
	switch (ast.kinds[i]) {
	case ASTDECL:
	case ASTCDECL:
	case ASTPCDECL:
	case ASTPDECL:
		return constfolddecl(ctx, folds, scps, types, ast, toks, i);
	case ASTRET:
		return constfoldexpr(ctx, folds, scps, types, ast, toks,
		                     ast.kids[i].rhs);
	default:
		__builtin_unreachable();
	}
}

idx_t_
constfoldblk(struct cfctx ctx, mpq_t *folds, struct scope *scps,
             struct type *types, struct ast ast, struct lexemes toks, idx_t_ i)
{
	struct pair p = ast.kids[i];
	while (scps[ctx.si].i != p.lhs)
		ctx.si++;
	for (i = p.lhs; i <= p.rhs;
	     i = constfoldstmt(ctx, folds, scps, types, ast, toks, i))
		;

	return i;
}

idx_t_
constfoldexpr(struct cfctx ctx, mpq_t *folds, struct scope *scps,
              struct type *types, struct ast ast, struct lexemes toks, idx_t_ i)
{
	/* Check if this expression has already been constant folded.  This
	   works because when an mpq_t is initialized via mpq_init(), it is
	   set to 0/1 meaning that the denominator pointer can’t be NULL. */
	if ((*folds[i])._mp_den._mp_d != NULL)
		return fwdnode(ast, i);

	switch (ast.kinds[i]) {
	case ASTNUMLIT: {
		mpq_init(folds[i]);

		/* TODO: Temporary allocator */
		struct strview sv = toks.strs[ast.lexemes[i]];
		char *buf = bufalloc(NULL, sv.len + 1, 1);
		size_t len = 0;

		for (size_t i = 0; i < sv.len; i++) {
			if (isdigit(sv.p[i]))
				buf[len++] = sv.p[i];
		}
		buf[len] = 0;

		(void)mpq_set_str(folds[i], buf, 10);

		free(buf);
		return fwdnode(ast, i);
	}
	case ASTIDENT: {
		struct strview sv = toks.strs[ast.lexemes[i]];

		/* Variable shadowing */
		if (strview_eq(sv, ctx.decl) && ctx.si > 0)
			ctx.si--;

		for (idx_t_ lvl = ctx.si;;) {
			struct scope scp = scps[lvl];
			idx_t_ *ip = symtab_insert(&scp.map, sv, NULL);

			if (ip == NULL) {
				assert(lvl != 0);
				lvl = scp.up;
			} else {
				switch (ast.kinds[*ip]) {
				case ASTDECL:
				case ASTPDECL:
					break;
				case ASTCDECL:
				case ASTPCDECL: {
					*folds[i] = *folds[*ip];
					if ((*folds[i])._mp_den._mp_d == NULL) {
						ctx.si = lvl;
						(void)constfolddecl(ctx, folds, scps, types, ast, toks,
						                    *ip);
						*folds[i] = *folds[*ip];
						assert((*folds[i])._mp_den._mp_d != NULL);
					}
					break;
				}
				default:
					__builtin_unreachable();
				}

				return fwdnode(ast, i);
			}
		}
	}
	case ASTFN:
		return constfoldblk(ctx, folds, scps, types, ast, toks,
		                    ast.kids[i].rhs);
	default:
		__builtin_unreachable();
	}
}

idx_t_
constfolddecl(struct cfctx ctx, mpq_t *folds, struct scope *scps,
              struct type *types, struct ast ast, struct lexemes toks, idx_t_ i)
{
	if (ast.kids[i].rhs == AST_EMPTY)
		return fwdnode(ast, i);
	ctx.decl = toks.strs[ast.lexemes[i]];
	return constfoldexpr(ctx, folds, scps, types, ast, toks, ast.kids[i].rhs);
}

void
constfold(mpq_t *folds, struct scope *scps, struct type *types, struct ast ast,
          struct lexemes toks, arena *a)
{
	struct cfctx ctx = {.a = a};
	for (idx_t_ i = 0; likely(i < ast.len);) {
		assert(ast.kinds[i] <= _AST_DECLS_END);
		i = constfolddecl(ctx, folds, scps, types, ast, toks, i);
	}
}

bool
returns(struct ast ast, idx_t_ i)
{
	switch (ast.kinds[i]) {
	case ASTDECL:
	case ASTPDECL:
	case ASTCDECL:
	case ASTPCDECL:
		return false;
	case ASTRET:
		return true;
	}
	__builtin_unreachable();
}

bool
typecompat(struct type lhs, struct type rhs)
{
	/* Function types are compatible if they have the same parameter- and
	   return types */
	if (lhs.kind == TYPE_FN && rhs.kind == TYPE_FN)
		return lhs.paramcnt == rhs.paramcnt && lhs.ret == rhs.ret;
	if (lhs.kind == TYPE_FN || rhs.kind == TYPE_FN)
		return false;

	/* At this point we only have numeric types left */

	/* Untyped numeric types are compatible with all numeric types */
	if (lhs.size == 0 || rhs.size == 0)
		return true;

	/* Two typed numeric types are only compatible if they have the same size
	   and sign and are either both integral or both floats */
	return lhs.issigned == rhs.issigned && lhs.isfloat == rhs.isfloat
	    && lhs.size == rhs.size;
}

idx_t_ *
symtab_insert(symtab **m, struct strview k, arena *a)
{
	for (uint64_t h = strview_hash(k); *m; h <<= 2) {
		if (strview_eq(k, (*m)->key))
			return &(*m)->val;
		m = &(*m)->child[h >> 62];
	}
	if (a == NULL)
		return NULL;
	*m = arena_new(a, symtab, 1);
	(*m)->key = k;
	return &(*m)->val;
}