commit bd67b4f2a919b5e538d0e230279e75ad0e39213f
parent f9cdc46db899fe46d161837535601c242f1fb8a7
Author: m21c <ho*******@gmail.com>
Date: Mon, 22 Jun 2026 21:29:30 +0200
codegen: add forward declarations
Diffstat:
1 file changed, 29 insertions(+), 3 deletions(-)
diff --git a/compiler.c b/compiler.c
@@ -6071,12 +6071,41 @@ cginit(CodeGen *cg, Env *toplevel, FILE *out)
}
static void
+cgtype(CodeGen *cg, Type *type, Decl *decl);
+
+static void
+cgforward(Source *source, Node *ast, CodeGen *cg)
+{
+ Decl *decl;
+ assert(ast->kind == ADECL);
+
+ decl = ast->u.declref;
+ if (decl->kind == DFUNCTION) {
+ cgtype(cg, ast->type, decl);
+
+ } else if (decl->kind == DVAR) {
+ /* @todo check storage class before using extern */
+ cgprintf(cg, "extern ");
+ cgtype(cg, ast->type, decl);
+
+ /* @todo implement variable forward declaration */
+ } else {
+ assert(!"never reach here");
+ }
+}
+
+static void
cgtoplevel(Source *source, Node *ast, CodeGen *cg)
{
if (source->haspendingenv) {
assert(source->pendingcount < 512);
source->pendingnodes[source->pendingcount++] = ast;
source->haspendingenv = false;
+
+ /* @todo forwad declarations of nested function, etc.
+ * may also be needed */
+ cgforward(source, ast, cg);
+ cgprintf(cg, ";\n");
} else {
codegen(cg, ast);
if (ast->kind != ADECL || ast->u.declref->kind != DFUNCTION)
@@ -6191,9 +6220,6 @@ cgbasetype(CodeGen *cg, Type *type)
#endif
static void
-cgtype(CodeGen *cg, Type *type, Decl *decl);
-
-static void
cgnamedparams(CodeGen *cg, Decl *decl)
{
Decl *param, *head = NULL;