aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/compiler.h
blob: e892df633cd52c04b451a69bdd8a2166b65e1666 (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

/*
 * Common declarations for the bootstrap compiler.
 *
 * Copyright © 2025 Samuel Lidén Borell <samuel@kodafritt.se>
 *
 * SPDX-License-Identifier: EUPL-1.2+ AND (EUPL-1.2+ OR MIT-0)
 *
 * Note that the "Common Definitions and Macros" section is shared
 * with the rtlincl/rtl.h file and is dual EUPL-1.2+ / MIT-0 licensed.
 */
#ifndef SLUL_COMPILER_H
#define SLUL_COMPILER_H

/* =======================================================================
   |||||||||||||||||||  Common Definitions and Macros  |||||||||||||||||||
   ======================================================================= */
#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
    #define bool int
    #define true 1
    #define false 0
#elif __STDC_VERSION__ < 202311L /* untested */
    #include <stdbool.h>
#endif
#include <stdint.h> /* for uint64_t. Not actually part of C89 */
#include <stdio.h>
#include <stdlib.h>

#define FAIL(s)         do { \
        fprintf(stderr, "failure in bootstrap compiler at %s:%d: %s\n", \
            __FILE__, __LINE__, s); \
        abort(); \
    } while (1)
#define NO_NEG(expr)    do { if ((expr) < 0) FAIL(#expr); } while (0)
#define NO_NULL(expr)   do { if ((expr) == NULL) FAIL(#expr); } while (0)

/* Define unreachable() */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
    /* C23 already has unreachable in stddef.h */
#elif (defined(__GNUC__) && __GNUC__ > 4) || defined(__clang__)
    #define unreachable() __builtin_unreachable()
#else
    #define unreachable() ((void)0)
#endif
/* Define NORETURN */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
    #define NORETURN [[noreturn]]
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
    #define NORETURN _Noreturn
#elif (defined(__GNUC__) && __GNUC__ > 2) || defined(__clang__)
    #define NORETURN __attribute__((__noreturn__))
#else
    #define NORETURN
#endif


/* =======================================================================
   |||||||||||||||||||||||  Basic Data Structures  |||||||||||||||||||||||
   ======================================================================= */

typedef unsigned HashCode;

/**
 * A head of a tree node. This structure is supposed to be followed by
 * node data.
 */
struct TreeNode {
    HashCode hashcode;
    unsigned length     :  8;
    unsigned rankdelta  :  2;
    unsigned is_new     :  1;
    unsigned is_defined :  1;
    unsigned line       : 20;
    struct TreeNode *lower, *higher;
    const char *name;
};
#define TREE_MAXDEPTH      24 /* 16 million entries */
#define TREENODE_LEN_MAX  255
#define TREENODE_LEN_TYPE unsigned char /* to suppress conversion warning */

int treenode_equals(const struct TreeNode *n, const char *s, size_t len);

/**
 * Looks up a node.
 *
 * \return A pointer the to node if it existed, or NULL if not found.
 */
struct TreeNode *tree_search(const struct TreeNode *root,
                             HashCode h, size_t len, const char *name);
struct TreeNode *tree_search_node(const struct TreeNode *root,
                                  const struct TreeNode *n);

/**
 * Looks up or inserts a node. If newnode is NULL, the node is allocated
 * if it does not exist.
 *
 * The is_new field is set to 0 if the node already existed, or
 * 1 if it was just inserted.
 *
 * \return A pointer the to node, or NULL is returned on memory
 *         allocation failure.
 */
struct TreeNode *tree_insert(struct TreeNode **root,
                             HashCode h, const char *name, size_t len,
                             struct TreeNode *newnode, size_t newsize);

struct TreeNode *tree_insert_str(struct TreeNode **root,
                                 const char *name, size_t len,
                                 struct TreeNode *newnode, size_t newsize);

/* =======================================================================
   ||||||||||||||||||||||||  Abstract Syntax Tree  |||||||||||||||||||||||
   ======================================================================= */

struct Stmt;
struct Expr;

struct SourceLocation {
    const char *filename;
    int line;
};

struct Ident {
    struct TreeNode node;
    struct SourceLocation srcloc;
    unsigned is_defined : 1;
};
#define ident_equals(ident) (treenode_equals((ident)->node))

struct Type {
    struct Ident ident;
    struct Type *outer;

    struct TreeNode *funcs;
    struct Func *funcs_list;
    struct TreeNode *inner_types;
    struct Type *inner_types_list;
    /* TODO flags, fields, ... */

    struct Type *next;
};

struct TypeRefNumeric {
    /** Range of target type */
    uint64_t tmin, tmax;
    /** Range of source type */
    uint64_t smin, smax;
    unsigned tmin_neg : 1;
    unsigned tmax_neg : 1;
    unsigned smin_neg : 1;
    unsigned smax_neg : 1;
};

enum TypeRefKind {
    TR_UNKNOWN,
    TR_BOOL,
    TR_INT,
    TR_STRING,
    TR_CLASS
};

struct TypeRef {
    enum TypeRefKind kind;
    unsigned quals;
    union {
        struct TypeRefNumeric *num;
        struct Type *class_;
    } u;
};

struct ExprInteger {
    /* Negative numbers are created with the unary minus operator */
    uint64_t num;
};

extern struct ExprString *string_constants;
extern unsigned next_string_const_id;

struct ExprString {
    struct ExprString *next;
    size_t len;
    unsigned id;
    char *s;
};

struct ExprIdent {
    size_t namelen;
    union {
        /* if namelen != 0 */
        const char *name;
        /* if namelen == 0 */
        /* TODO bound identifier */
    } u;
};

struct CallArg {
    struct CallArg *next;
    struct Expr *expr;
};

struct ExprCall {
    struct ExprIdent ident;
    struct CallArg *args;
    struct CallArg **nextptr;
};

struct ExprBinary {
    int left_id;
    /* the right_id is:  expr->id - 1 */
};

enum ExprGroupKind {
    GK_GROUPING_PAREN,
    GK_ARRAY_LITERAL
};

enum ExprKind {
    E_GROUP_TEMP,
    E_SEQPOINT,
    /* Terminals - Scalar constants */
    E_NONE,
    E_FALSE,
    E_TRUE,
    E_INTEGER,
    E_STRING,
    /* Terminals - Identifiers */
    E_IDENT,
    E_MEMBER,
    /* Terminals - Multi-argument */
    E_ARRAY,
    E_CALL,
    /* Unary operators */
    E_NEGATE,
    E_BOOL_NOT,
    /* Binary operators */
    E_ADD,
    E_SUB,
    E_MUL,
    E_DIV,
    E_MOD,
    E_EQUAL,
    E_NOT_EQUAL,
    E_LESS,
    E_GREATER,
    E_LESS_EQUAL,
    E_GREATER_EQUAL,
    E_BOOL_AND,
    E_BOOL_OR,
    E_ASSIGN,
    E_ASSIGN_FINAL
};
#define NUM_EXPRKINDS (E_ASSIGN_FINAL+1)

struct Expr {
    enum ExprKind kind;
    int id;
    union {
        struct ExprInteger  intval;
        struct ExprString  *strval;
        struct ExprBinary   binary;
        struct ExprIdent    ident;
        struct ExprCall    *call;
        enum ExprGroupKind  grouptemp;
        struct Expr *seqpoint_end;
        /* TODO identifier exprs */
        /* TODO member exprs */
        /* TODO array exprs */
        /* TODO cal exprs */
    } u;
    struct TypeRef *typeref;
    struct Expr *rpnnext;
};

struct Var {
    struct Ident ident;
    struct TypeRef *typeref;
    unsigned is_funcparam : 1;
    unsigned is_initially_final : 1;
    struct Expr *initval;
    struct Var *next;
};

struct LoopInfo {
    struct Expr *cond;
    struct Stmt *body;
    struct Stmt *loopempty;
    struct Stmt *loopend;
};

struct StmtFor {
    struct LoopInfo loop;
    struct Var *var;
};

/** "else if". Only appears inside StmtIf */
struct StmtElif {
    struct Expr *cond;
    struct Stmt *body;
    struct StmtElif *next;
};

struct StmtIf {
    struct Expr *cond;
    struct Stmt *true_;
    struct StmtElif *elifs;
    struct Stmt *false_;
};

struct StmtBreak {
    struct Stmt *loop;
};

struct Case {
    struct Case *next;
    struct Expr *value;
    struct Stmt *block;
};

struct StmtSwitch {
    struct Expr *cond;
    struct Case *cases;
    struct Stmt *default_;
};

enum StmtType {
    S_ASSERT,
    S_BREAK,
    S_CONTINUE,
    S_EXPR,
    S_FOR,
    S_IF,
    S_RETURN_NOVALUE,
    S_RETURN_VALUE,
    S_SWITCH,
    S_VARDECL,
    S_WHILE
};

struct Stmt {
    struct Stmt *next;
    enum StmtType kind;
    int line;
    int id;
    union {
        struct Expr       *expr;
        struct Var        *var;
        struct LoopInfo    loop;
        struct StmtBreak   break_;
        struct StmtFor     for_;
        struct StmtIf      if_;
        struct StmtSwitch  switch_;
    } u;
};

struct Section {
    struct Ident ident;
    struct Stmt *code;
    struct Section *next;
};

#define FUNCPARAMS_MAX 255
struct Func {
    struct Ident ident;
    struct Type *class_;
    struct Var *params;
    struct Var *returns;
    struct Var *vardecls;

    struct TreeNode *vars;
    struct Stmt *code;
    struct Section *section_first;
    struct TreeNode *section_by_name;

    unsigned is_noreturn : 1;
    size_t num_params, num_returns;

    struct Func *next;
};

struct Module {
    struct TreeNode *types;
    struct TreeNode *funcs;
    struct Type *types_list;
    struct Func *funcs_list;
    struct Module *next;
};

void module_start(void);
struct Type *map_named_type(const char *name, size_t len);
void type_start(const char *name, size_t len);
void type_end(void);
struct Func *map_named_func(const char *name, size_t len);
void func_start(const char *name, size_t len);
void func_end(void);

/* =======================================================================
   |||||||||||||||||||||||||||  Module State  ||||||||||||||||||||||||||||
   ======================================================================= */
#define MAX_SOURCES 256
extern int num_sources;
extern char *(sources[MAX_SOURCES]);

extern char *current_filename;
extern int current_line;

extern struct Module *module, *modules;
extern struct Type *current_type;
extern struct Func *current_func;


/* =======================================================================
   |||||||||||||||||||||  Internal Parser Functions  |||||||||||||||||||||
   ======================================================================= */

enum VarType {
    VAR_DECL_ONLY,
    VAR_ALLOW_INITVAL /* TODO might not a VAR_ALLOW_CONST_INITVAL also */
};

void parse_func_body(void);
struct Expr *parse_expr(void);
struct Var *parse_var(struct TreeNode **root, enum VarType vartype,
                      struct Var **list_out);
/** Reports an error in the source code */
NORETURN void error(const char *s);

/* =======================================================================
   ||||||||||||||||||||||  Main Parsing Functions  |||||||||||||||||||||||
   ======================================================================= */

/** Parses a source index file */
void parse_source_index(FILE *f);
/** Parses the code in a source file.
    basename is the filename without the path */
void parse_file(FILE *f, const char *basename);

/* =======================================================================
   |||||||||||||||||||||||||  C Code Generation  |||||||||||||||||||||||||
   ======================================================================= */
void emit_c_code(const char *filename);

/* =======================================================================
   |||||||||||||||||||||||||  Utility Functions  |||||||||||||||||||||||||
   ======================================================================= */

#define SOURCELINE_MAX 512
enum ReadSourceMode {
    KEEP_COMMENTS,
    STRIP_COMMENTS
};

/** Reads a line from a file, optionall skipping any comments */
bool read_source_line(FILE *f, char line[SOURCELINE_MAX], size_t *len_out,
                      enum ReadSourceMode mode);
/** Replace all occurrences of given character in a string */
void memreplace(char *s, char from, char to, size_t len);
/** Duplicates memory with a null-terminator at the end (len excludes it) */
char *memzdup(const char *s, size_t len);
/** Checks that a filename is "safe" (on modern systems) */
void check_filename(const char *s);
/** Returns the last component (i.e. the name of the file) in a file path */
const char *path_basename(const char *path);
/** Very fast but stupid hash function. Used to avoid string comparison
    in AVL trees */
HashCode hash_str(const char *s, size_t len);

#endif