From 2790e5db4753df2ab20dd52fbb0d7afb96f3e7d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ibrahim=20Numanagic=CC=81?= Date: Thu, 2 Feb 2023 10:05:44 -0800 Subject: [PATCH] Fix #189 --- codon/parser/visitors/simplify/function.cpp | 14 +++++++++++++- test/parser/simplify_stmt.codon | 11 +++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/codon/parser/visitors/simplify/function.cpp b/codon/parser/visitors/simplify/function.cpp index 1286bf74..f033ae8c 100644 --- a/codon/parser/visitors/simplify/function.cpp +++ b/codon/parser/visitors/simplify/function.cpp @@ -282,8 +282,20 @@ void SimplifyVisitor::visit(FunctionStmt *stmt) { // Expression to be used if function binding is modified by captures or decorators ExprPtr finalExpr = nullptr; // If there are captures, replace `fn` with `fn(cap1=cap1, cap2=cap2, ...)` - if (!captures.empty()) + if (!captures.empty()) { finalExpr = N(N(stmt->name), partialArgs); + // Add updated self reference if case function is recursive! + auto pa = partialArgs; + for (auto &a : pa) { + if (!a.name.empty()) + a.value = N(a.name); + else + a.value = clone(a.value); + } + f->suite = N( + N(N(rootName), N(N(rootName), pa)), + suite); + } // Parse remaining decorators for (auto i = stmt->decorators.size(); i-- > 0;) { diff --git a/test/parser/simplify_stmt.codon b/test/parser/simplify_stmt.codon index faeabbfa..eab1546b 100644 --- a/test/parser/simplify_stmt.codon +++ b/test/parser/simplify_stmt.codon @@ -1232,3 +1232,14 @@ def foo(): foo() #! name 'x' is not defined #! name 'b' is not defined + +#%% capture_recursive,barebones +def f(x: int) -> int: + z = 2 * x + def g(y: int) -> int: + if y == 0: + return 1 + else: + return g(y - 1) * z + return g(4) +print(f(3)) #: 1296