ref: 594223c2959cc116ccc2782ebf7930677b053843
parent: 093716ff5e2ffe837793ba7c9239c64e22789ec0
author: Ori Bernstein <ori@eigenstate.org>
date: Sun Jul 30 14:34:52 EDT 2017
Add hook into frontend for sizeof() folding. Before, code like: const f = { var buf: byte[sizeof(int)] } would crash us, because `sizeof` would not get folded. A slightly subtle point: muse doens't install a hook here, but since it's already handling processed usefiles, the array sizes should already be prefolded for its viewing pleasure.
--- a/6/main.c
+++ b/6/main.c
@@ -202,6 +202,7 @@
optinit(&ctx, "cd:?hSo:I:9G:O:", argv, argc);
asmsyntax = Defaultasm;
+ sizefn = size;
while (!optdone(&ctx)) {
switch (optnext(&ctx)) {
case 'O':
--- a/parse/fold.c
+++ b/parse/fold.c
@@ -13,6 +13,8 @@
#include "util.h"
#include "parse.h"
+size_t (*sizefn)(Node *n);
+
static int
getintlit(Node *n, vlong *v)
{
@@ -249,6 +251,10 @@
break;
case Ocast:
r = foldcast(n);
+ break;
+ case Osize:
+ if (sizefn)
+ r = val(n->loc, sizefn(n->expr.args[0]), exprtype(n));
break;
default:
break;
--- a/parse/infer.c
+++ b/parse/infer.c
@@ -2031,6 +2031,9 @@
t->fixed = 1;
if (t->type == Tyarray) {
typesub(t->asize, noerr);
+ t->asize = fold(t->asize, 1);
+ if (exprop(t->asize) != Olit)
+ fatal(t->asize, "nonconstant array size near %s\n", ctxstr(t->asize));
} else if (t->type == Tystruct) {
inaggr++;
for (i = 0; i < t->nmemb; i++)
--- a/parse/parse.h
+++ b/parse/parse.h
@@ -573,5 +573,6 @@
extern char **incpaths;
extern size_t nincpaths;
extern char *localincpath;
+extern size_t (*sizefn)(Node *n);
void yyerror(const char *s);