From 3dd6b03ff5dc54ad38627e468dd4eb93dddf470f Mon Sep 17 00:00:00 2001 From: Leo Tenenbaum Date: Fri, 8 May 2020 23:57:39 -0400 Subject: allow use of global variables at compile time --- test.toc | 16 ++++++++++++++++ types.c | 22 +++++++++++++++++++++- types.h | 8 ++++++-- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/test.toc b/test.toc index c90b3ce..f989ecf 100644 --- a/test.toc +++ b/test.toc @@ -1,6 +1,22 @@ +/* + #include "std/io.toc", io; + + main ::= fn() { io.file_writes(&io.std_out, "hello!\n"); io.file_flush(&io.std_out); } + +*/ + + +#include "tests/std/io.toc", io; +a, b := 5; +main ::= fn() { + a = 6; + io.puti(a); + io.puti(b); +} +main(); diff --git a/types.c b/types.c index b6a3f5c..789d95f 100644 --- a/types.c +++ b/types.c @@ -3417,6 +3417,9 @@ static Status types_decl(Typer *tr, Declaration *d) { goto ret; } } + + size_t n_idents; n_idents = arr_len(d->idents); + if (d->flags & DECL_HAS_EXPR) { if (!types_expr(tr, &d->expr)) { success = false; @@ -3452,11 +3455,28 @@ static Status types_decl(Typer *tr, Declaration *d) { } copy_val(tr->allocr, &d->val, val, dtype); d->flags |= DECL_FOUND_VAL; + if (!(d->flags & DECL_IS_CONST)) { + /* + create a value stack for this declaration so that it can be modified by compile time execution, + but not permanently (i.e. output will still have old value) + */ + + Value *copy = typer_malloc(tr, sizeof *copy); + if (n_idents > 1 && dtype->kind != TYPE_TUPLE) { + /* actually, make n_idents copies of the value, and put them in a tuple. */ + Value *tuple = copy->tuple = typer_malloc(tr, n_idents * sizeof *copy); + for (size_t i = 0; i < n_idents; ++i) { + copy_val(tr->allocr, &tuple[i], val, dtype); + } + } else { + copy_val(tr->allocr, copy, val, dtype); + } + typer_arr_add(tr, d->val_stack, copy); + } } } } - size_t n_idents; n_idents = arr_len(d->idents); if (type_is_compileonly(dtype)) { if (!(d->flags & DECL_IS_CONST)) { diff --git a/types.h b/types.h index 8d68ab7..50983a2 100644 --- a/types.h +++ b/types.h @@ -882,8 +882,12 @@ typedef struct Declaration { }; Value val; /* only for constant decls, non-constant globals, and varargs. */ - /* for eval, for non-constant local decls: */ - /* the pointers to values need to be fixed, which is why this isn't just Value *. */ + /* + for eval, for non-constant local decls + the pointers to values need to be fixed, which is why this isn't just Value *. + no, this can't be a union with val, because of global variables and possibly + other things (varargs maybe?) + */ Value **val_stack; } Declaration; typedef Declaration *DeclarationPtr; -- cgit v1.2.3