ADD: recursive functions.
parent
12f42a86f6
commit
ea5991732c
|
@ -16,3 +16,16 @@
|
|||
;; inner variable
|
||||
($ (d x) ($ y 3) (+ x y))
|
||||
(assert-eq? 7 (d 4))
|
||||
|
||||
;; recursivity
|
||||
($ (e n)
|
||||
(if (eq? 0 n) 1
|
||||
(* n (e (- n 1)))))
|
||||
|
||||
(assert-eq? 120 (e 5))
|
||||
|
||||
;; self keyword
|
||||
(assert-eq? 720 ((-> (x)
|
||||
(if (eq? x 0)
|
||||
1
|
||||
(* x (self (- x 1))))) 6))
|
||||
|
|
|
@ -94,6 +94,16 @@ namespace grino
|
|||
m_scope.size());
|
||||
}
|
||||
|
||||
std::string name = "self";
|
||||
|
||||
if (!m_decl_context.empty())
|
||||
{
|
||||
name = m_decl_context.back();
|
||||
}
|
||||
|
||||
sym.declare(node->loc(), name, get_local_address(),
|
||||
m_scope.size());
|
||||
|
||||
auto prog = std::make_shared<Program>();
|
||||
auto body = node->child(1).lock();
|
||||
compile(body, *prog, sym);
|
||||
|
@ -128,9 +138,12 @@ namespace grino
|
|||
auto expr = node->child(1).lock();
|
||||
size_t address = get_local_address();
|
||||
|
||||
m_decl_context.push_back(ident);
|
||||
compile(expr, program, sym);
|
||||
m_decl_context.pop_back();
|
||||
|
||||
sym.declare(node->loc(), ident, address, m_scope.size());
|
||||
|
||||
program.push_instr(OPCODE_STORE_LOCAL, address);
|
||||
} break;
|
||||
|
||||
|
|
|
@ -33,6 +33,7 @@ namespace grino
|
|||
std::shared_ptr<StaticFunction>> m_statics;
|
||||
|
||||
std::vector<size_t> m_scope;
|
||||
std::vector<std::string> m_decl_context;
|
||||
|
||||
size_t get_local_address();
|
||||
void enter_scope(bool reset=false);
|
||||
|
|
|
@ -127,7 +127,8 @@ namespace grino
|
|||
args.insert(std::begin(args), program().constant(pop()));
|
||||
}
|
||||
|
||||
size_t ref = program().constant(pop())->as_ref();
|
||||
auto ref_val = program().constant(pop());
|
||||
size_t ref = ref_val->as_ref();
|
||||
auto fun = heap(ref)->as_function();
|
||||
|
||||
if (fun->is_native())
|
||||
|
@ -149,6 +150,8 @@ namespace grino
|
|||
set_local(i, args[i]);
|
||||
}
|
||||
|
||||
set_local(args.size(), ref_val);
|
||||
|
||||
m_pc = 0;
|
||||
}
|
||||
} break;
|
||||
|
|
Loading…
Reference in New Issue