From 0f5312a8acd242fa01be5fdfffbf22e20e0a6920 Mon Sep 17 00:00:00 2001 From: "Michael D. Lowis" Date: Mon, 28 Dec 2015 22:28:06 -0500 Subject: [PATCH] First attempt at generating code for if statements. horribly broken. --- source/anf.c | 12 ++++-------- source/codegen.c | 22 +++++++++++++++++++--- spec/anf_spec.rb | 9 +++++++++ 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/source/anf.c b/source/anf.c index 2f3e8c5..3cc1f76 100644 --- a/source/anf.c +++ b/source/anf.c @@ -19,14 +19,10 @@ static bool isatomic(AST* tree) static bool isconst(AST* tree) { bool ret = isatomic(tree); - if (!ret) { - if (tree->type == AST_FNAPP) { - ret = isatomic(fnapp_fn(tree)); - for (int i = 0; i < vec_size(fnapp_args(tree)); i++) { - ret = ret && isatomic(vec_at(fnapp_args(tree), i)); - } - } else if (tree->type == AST_IF) { - ret = isatomic(ifexpr_cond(tree)); + if (!ret && tree->type == AST_FNAPP) { + ret = isatomic(fnapp_fn(tree)); + for (int i = 0; i < vec_size(fnapp_args(tree)); i++) { + ret = ret && isatomic(vec_at(fnapp_args(tree), i)); } } return ret; diff --git a/source/codegen.c b/source/codegen.c index 9969850..32b6f0d 100644 --- a/source/codegen.c +++ b/source/codegen.c @@ -48,6 +48,16 @@ void codegen(FILE* file, AST* tree) break; case AST_IF: + fprintf(file," if ("); + codegen(file, ifexpr_cond(tree)); + fprintf(file,")\n"); + codegen(file, ifexpr_then(tree)); + if (ifexpr_else(tree)) { + fprintf(file,"\n else\n"); + codegen(file, ifexpr_else(tree)); + } else { + fprintf(file," {return nil;}"); + } break; case AST_FUNC: @@ -75,12 +85,18 @@ void codegen(FILE* file, AST* tree) break; case AST_LET: - fprintf(file,"{val "); + fprintf(file," {val "); codegen(file, let_var(tree)); fprintf(file," = "); codegen(file, let_val(tree)); - fprintf(file,";"); - codegen(file, let_body(tree)); + fprintf(file,";\n"); + if (let_body(tree)->type != AST_LET && let_body(tree)->type != AST_IF) { + fprintf(file," return "); + codegen(file, let_body(tree)); + fprintf(file,";"); + } else { + codegen(file, let_body(tree)); + } fprintf(file,"}"); break; diff --git a/spec/anf_spec.rb b/spec/anf_spec.rb index a22ee6d..52fce54 100644 --- a/spec/anf_spec.rb +++ b/spec/anf_spec.rb @@ -132,5 +132,14 @@ describe "sclpl a-normal form" do "$:0"]]] ]) end + + it "should normalize a literal with a complex expression" do + expect(anf('fn() if 1 2 else 3;;')).to eq([ + ["fn", [], + ["let", ["$:1", ["T_ID:bar"]], + ["let", ["$:0", ["T_ID:foo", "$:1"]], + "$:0"]]] + ]) + end end end -- 2.52.0