aboutsummaryrefslogtreecommitdiff
path: root/src/preprocess.c
blob: 3a0c0bc5445665f0f5972b0f3209799e12032ad7 (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
#include <assert.h>
#include <math.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include <log.h>
#include <preprocess.h>

static void preprocess_erase(struct ctx *ctx, size_t start)
{
	assert(ctx->data[start] == '#');

	for (size_t i = start; i < ctx->size; i++) {
		char cur = ctx->data[i];
		if (cur == '\n' || cur == '\0')
			break;

		ctx->data[i] = ' '; // Spaces get skipped by tokenizer anyways
	}
}

void preprocess(struct ctx *ctx)
{
	ctx->size = ctx->location.size;
	ctx->data = malloc(ctx->size);
	memcpy(ctx->data, ctx->location.data, ctx->size);

	for (size_t i = 0; i < ctx->location.size; i++) {
		const char cur = ctx->location.data[i];

		ctx->location.column++;

		if (cur == '\n') {
			ctx->location.line++;
			ctx->location.column = 0;
			continue;
		} else if (cur == '\0') {
			break;
		} else if (cur == '#' && ctx->location.column == 1) {
			if (strncmp(ctx->location.data + i + 1, "inc ",
				    fmin(4, ctx->location.size - i)) == 0) {
				// TODO: Add include features
			} else if (*(ctx->location.data + i + 1) == '#') {
				// Comment
			} else {
				errln(&ctx->location, "Invalid preprocessing directive");
			}
			preprocess_erase(ctx, i);
		}
	}

	context_rewind(ctx);
}