Skip to content
This repository was archived by the owner on Oct 12, 2026. It is now read-only.

Commit 5982925

Browse files
committed
Fixed apply_fn_apl, Example math_demos.lbd works
1 parent 0593bd3 commit 5982925

5 files changed

Lines changed: 106 additions & 175 deletions

File tree

‎examples/math_demos.lbd‎

Lines changed: 5 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,6 @@
1-
-- TODO: Add support for `use`
2-
-- Copied from std.lbd
3-
-- booleans and conditions
4-
true: Bool = \x: Any. \y: Any. x
5-
false: Bool = \x: Any. \y: Any. y
6-
7-
if_then: Any = \condition: Any.
8-
\then_clause: Any. \else_clause: Any.
9-
(condition then_clause else_clause)
10-
11-
-- pairs
12-
pair: Any = \x: Any. \y: Any. \fn: Any. (fn x y)
13-
14-
first: Any = \x: Any. \y: Any. x
15-
second: Any = \x: Any. \y: Any. y
16-
17-
-- misc
18-
float_eq: Float -> Float -> Bool = \x: Float. \y: Float.
19-
(if_zero (cmp x y) true false)
20-
21-
-- fibonacci: Any = \num: Float.
22-
-- (if_then (float_eq 0.0 num) 0.0
23-
-- (if_then (float_eq 1.0 num) 1.0
24-
-- (add (fibonacci (sub num 1.0)) (fibonacci (sub num 2.0)))))
25-
26-
-- fibonacci: Any = \num: Float. num
27-
-- res: Float = \num: Float. (add (fibonacci (sub num 1)) (fibonacci (sub num 2)))
28-
-- (print (res 10))
29-
301
fibonacci: Any = \num: Float.
31-
(if_zero (float_eq 1 num) 1
32-
(add (fibonacci (sub num 1)) (fibonacci (sub num 2))))
33-
(print (fibonacci 1))
2+
(if_zero (cmp 0 num) 0
3+
(if_zero (cmp 1 num) 1
4+
(add (fibonacci (sub num 1.0)) (fibonacci (sub num 2.0)))))
5+
6+
(print (fibonacci 10))

‎examples/std.lbd‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
-- TODO: Support for `use`
2+
13
-- booleans and conditions
24
true: Bool = \x: Any. \y: Any. x
35
false: Bool = \x: Any. \y: Any. y
46

5-
ifthen: Any = \condition: Any.
7+
if_then: Any = \condition: Any.
68
\then_clause: Any. \else_clause: Any.
79
(condition then_clause else_clause)
810

@@ -13,6 +15,5 @@ first: Any = \x: Any. \y: Any. x
1315
second: Any = \x: Any. \y: Any. y
1416

1517
-- misc
16-
-- TODO: Add support for `use`
1718
float_eq: Float -> Float -> Bool = \x: Float. \y: Float.
18-
(ifzero (cmp x y) true false)
19+
(if_zero (cmp x y) true false)

‎include/lbd/intp/interpreter.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ namespace intp::interp {
7171
Value eval_expr(const fe::ast::Expression &expr, std::shared_ptr<Env> env);
7272

7373
Value apply_fn_apl(Value fn_value, const std::vector<std::shared_ptr<Thunk> > &args,
74-
const std::shared_ptr<Env> &call_site_env, const std::optional<fe::loc::Loc> &call_loc = std::nullopt);
74+
const std::shared_ptr<Env> &call_site_env,
75+
const std::optional<fe::loc::Loc> &call_loc = std::nullopt);
7576

7677
/// Program Driver
7778
struct Result {

‎src/intp/buitlins.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ namespace intp::interp {
7878
}
7979
const double num1 = std::get<double>(value1);
8080
const double num2 = std::get<double>(value2);
81-
const int result = (num1 < num2) ? -1 : (num1 > num2 ? 1 : 0);
81+
const int result = (num1 < num2) ? -1 : num1 > num2 ? 1 : 0;
8282
return Value{static_cast<double>(result)};
8383
}
8484
};

‎src/intp/interpreter.cpp‎

Lines changed: 94 additions & 138 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,23 @@
1-
#include <complex>
21
#include <lbd/intp/interpreter.h>
2+
#include <lbd/intp/builtins.h>
33
#include <lbd/error.h>
4-
#include <utility>
5-
6-
#include "lbd/intp/builtins.h"
74

85
namespace intp::interp {
96
std::ostream &operator<<(std::ostream &os, const Closure &closure) {
10-
// TODO: Improve this
117
return os << "<closure " << closure.param << ">";
128
}
139

1410
std::ostream &operator<<(std::ostream &os, const NativeFunction &native_fn) {
15-
// TODO: Improve this
1611
return os << "<native_fn " << native_fn.name << " " << native_fn.arity << ">";
1712
}
1813

1914
std::ostream &operator<<(std::ostream &os, const Value &value) {
2015
std::visit([&]<typename T0>(T0 &&arg) {
2116
using T = std::decay_t<T0>;
22-
if constexpr (std::is_same_v<T, std::string>
23-
|| std::is_same_v<T, double>
24-
|| std::is_same_v<T, Closure>
25-
|| std::is_same_v<T, NativeFunction>) {
17+
if constexpr (std::is_same_v<T, std::string> ||
18+
std::is_same_v<T, double> ||
19+
std::is_same_v<T, Closure> ||
20+
std::is_same_v<T, NativeFunction>) {
2621
os << arg;
2722
} else {
2823
STATIC_ASSERT_UNREACHABLE_T(T, "unhandled runtime value");
@@ -132,154 +127,115 @@ namespace intp::interp {
132127
}, expr.value);
133128
}
134129

135-
//
136-
// Value apply_fn_apl(Value fn_value, const std::vector<std::shared_ptr<Thunk> > &args,
137-
// const std::shared_ptr<Env> &call_site_env, const std::optional<fe::loc::Loc> &call_loc) {
138-
// Value current_fn = std::move(fn_value);
139-
// size_t idx = 0;
140-
// std::cout << "debug: fn: " << current_fn << std::endl;
141-
// while (idx < args.size()) {
142-
// // Apply Argument to Closure (Lambda Expression)
143-
// std::optional<Value> resultant_value = std::nullopt;
144-
// if (std::holds_alternative<Closure>(current_fn)) {
145-
// const auto [param, body, env] = std::get<Closure>(current_fn);
146-
// const auto child_env = std::make_shared<Env>(env);
147-
// child_env->bind(param, args[idx]);
148-
// // Evaluate body in child Environment
149-
// resultant_value = eval_expr(*body, child_env);
150-
// ++idx;
151-
// }
152-
// // Apply Argument to Native Function
153-
// if (std::holds_alternative<NativeFunction>(current_fn)) {
154-
// // Using by reference and not creating a copy of Native Function
155-
// const auto &[arity, name, impl] = std::get<NativeFunction>(current_fn);
156-
// if (args.size() - idx < arity) {
157-
// if (call_loc) {
158-
// std::cerr << *call_loc << ": ";
159-
// }
160-
// std::cerr << "runtime error: native function "
161-
// << name << " expects "
162-
// << arity << " argument(s), found "
163-
// << args.size() - idx
164-
// << std::endl;
165-
// exit(EXIT_FAILURE);
166-
// }
167-
// std::vector<std::shared_ptr<Thunk> > slice;
168-
// slice.reserve(arity);
169-
// for (size_t i = 0; i < arity; ++i) {
170-
// slice.push_back(args[idx + i]);
171-
// }
172-
// resultant_value = impl(slice, call_site_env);
173-
// idx += arity;
174-
// }
175-
// if (resultant_value) {
176-
// if (std::holds_alternative<Closure>(*resultant_value) ||
177-
// std::holds_alternative<NativeFunction>(*resultant_value)) {
178-
// current_fn = std::move(*resultant_value);
179-
// continue;
180-
// }
181-
// }
182-
// if (call_loc) {
183-
// std::cerr << *call_loc << ": ";
184-
// }
185-
// std::cerr << "runtime error: trying to apply non-function value "
186-
// << current_fn
187-
// << std::endl;
188-
// exit(EXIT_FAILURE);
189-
// }
190-
// return current_fn;
191-
// }
192-
193-
Value apply_fn_apl(Value fn_value,
194-
const std::vector<std::shared_ptr<Thunk> > &args,
195-
const std::shared_ptr<Env> &call_site_env,
196-
const std::optional<fe::loc::Loc> &call_loc) {
197-
Value current_fn = std::move(fn_value);
198-
size_t idx = 0;
199-
200-
std::cout << "debug: fn: " << current_fn << std::endl;
130+
static std::shared_ptr<Thunk> value_to_thunk(const Value &v) {
131+
auto t = std::make_shared<Thunk>();
132+
t->cached = v;
133+
return t;
134+
}
201135

202-
while (idx < args.size()) {
203-
std::optional<Value> resultant_value; // value returned by applying one step
136+
static std::ostream &print_loc_prefix(std::ostream &os, const std::optional<fe::loc::Loc> &loc) {
137+
if (loc) {
138+
return os << *loc << ": ";
139+
}
140+
return os;
141+
}
204142

205-
// --- Closure (user lambda) branch ---
143+
Value apply_fn_apl(Value fn_value, const std::vector<std::shared_ptr<Thunk> > &args,
144+
const std::shared_ptr<Env> &call_site_env, const std::optional<fe::loc::Loc> &call_loc) {
145+
// Local mutable copy of the args, for inserting evaluated values as Thunks when needed.
146+
std::vector<std::shared_ptr<Thunk> > work_args = args;
147+
// Frame Stack: Functions to which we are currently applying Arguments.
148+
// Start with the initial Function.
149+
std::vector<Value> frames;
150+
frames.push_back(std::move(fn_value));
151+
size_t idx = 0; // Index of next Thunk to consume from work_args
152+
while (true) {
153+
// If there are no frames left, that's unexpected (shouldn't happen), bail.
154+
if (frames.empty()) {
155+
print_loc_prefix(std::cerr, call_loc)
156+
<< "internal error: no function frame to apply" << std::endl;
157+
std::exit(EXIT_FAILURE);
158+
}
159+
// If we've consumed all available Argument Thunks:
160+
if (idx >= work_args.size()) {
161+
// If top frame is a function, and we have no more args to feed it,
162+
// return that function (partial application) or its value as-is.
163+
// If it's not a function (shouldn't happen), return it as value.
164+
return frames.back();
165+
}
166+
// Work on the top-most frame
167+
Value current_fn = frames.back();
168+
std::optional<Value> resultant_value;
169+
// Closure case: Closure consumes exactly one Argument (its Param)
206170
if (std::holds_alternative<Closure>(current_fn)) {
207171
const auto [param, body, env] = std::get<Closure>(current_fn);
208-
auto child_env = std::make_shared<Env>(env);
209-
child_env->bind(param, args[idx]);
210-
211-
// Evaluate the lambda body in the child env
172+
const auto &arg_thunk = work_args[idx++];
173+
const auto child_env = std::make_shared<Env>(env);
174+
child_env->bind(param, arg_thunk);
212175
resultant_value = eval_expr(*body, child_env);
213-
++idx; // we consumed one argument (the parameter)
214176
}
215-
// --- Native function branch ---
177+
// Native Function case: Consumes its arity-many Argument Thunks
216178
else if (std::holds_alternative<NativeFunction>(current_fn)) {
217-
const auto &nf = std::get<NativeFunction>(current_fn);
218-
const auto &arity = nf.arity;
219-
const auto &name = nf.name;
220-
const auto &impl = nf.impl;
221-
222-
if (args.size() - idx < arity) {
223-
if (call_loc) std::cerr << *call_loc << ": ";
224-
std::cerr << "runtime error: native function "
225-
<< name << " expects " << arity
226-
<< " argument(s), found " << (args.size() - idx)
227-
<< std::endl;
179+
const auto &[arity, name, impl] = std::get<NativeFunction>(current_fn);
180+
if (work_args.size() - idx < arity) {
181+
print_loc_prefix(std::cerr, call_loc)
182+
<< "runtime error: native function " << name
183+
<< " expects " << arity << " argument(s), found "
184+
<< (work_args.size() - idx) << std::endl;
228185
std::exit(EXIT_FAILURE);
229186
}
230-
231-
// collect the next `arity` thunks
232187
std::vector<std::shared_ptr<Thunk> > slice;
233188
slice.reserve(arity);
234-
for (size_t i = 0; i < arity; ++i) slice.push_back(args[idx + i]);
235-
189+
for (size_t i = 0; i < arity; ++i) {
190+
slice.push_back(work_args[idx + i]);
191+
}
236192
resultant_value = impl(slice, call_site_env);
237-
idx += arity; // consumed `arity` args
193+
idx += arity;
194+
} else {
195+
// Top frame is not a Function (Closure, NativeFunction) Value but there are still Arguments left
196+
print_loc_prefix(std::cerr, call_loc)
197+
<< "runtime error: trying to apply non-function value "
198+
<< frames.back() << std::endl;
199+
std::exit(EXIT_FAILURE);
238200
}
239-
// --- Not a function when there are still args left: error ---
240-
else {
241-
if (call_loc) std::cerr << *call_loc << ": ";
242-
std::cerr << "runtime error: trying to apply non-function value "
243-
<< current_fn << std::endl;
201+
if (!resultant_value) {
202+
print_loc_prefix(std::cerr, call_loc)
203+
<< "internal error: application produced no result" << std::endl;
244204
std::exit(EXIT_FAILURE);
245205
}
246-
247-
// If the application produced a value (it always should)
248-
if (resultant_value.has_value()) {
249-
std::cout << "debug: result: " << *resultant_value << std::endl;
250-
251-
// If the returned value is a function, curry: continue applying remaining args.
252-
if (std::holds_alternative<Closure>(*resultant_value) ||
253-
std::holds_alternative<NativeFunction>(*resultant_value)) {
254-
current_fn = std::move(*resultant_value);
255-
continue; // try to apply remaining args to this new function
256-
}
257-
258-
// Otherwise the returned value is a terminal (non-function).
259-
// If we've consumed all arguments for the original call, return it.
260-
if (idx >= args.size()) {
261-
return *resultant_value;
206+
if (std::holds_alternative<Closure>(*resultant_value) ||
207+
std::holds_alternative<NativeFunction>(*resultant_value)) {
208+
// Replace the top Frame with the returned Function (curry)
209+
frames.back() = std::move(*resultant_value);
210+
continue;
211+
}
212+
// Resultant is a concrete Value (different from Function Value i.e. double, string).
213+
// Pop the frame that produced it, and insert this Value as a thunk at the current idx
214+
// so the previous Frame (if any) will consume it.
215+
Value concrete = std::move(*resultant_value);
216+
frames.pop_back();
217+
// If there are no more Frames after popping, then this Value is the final result of the
218+
// whole Function Application, but only valid if there are no further Argument Thunks remaining.
219+
if (frames.empty()) {
220+
if (idx < work_args.size()) {
221+
print_loc_prefix(std::cerr, call_loc)
222+
<< "runtime error: too many arguments applied to non-function value "
223+
<< concrete << std::endl;
224+
std::exit(EXIT_FAILURE);
262225
}
263-
264-
// Otherwise there are still args left but we got a non-function — that's an error.
265-
if (call_loc) std::cerr << *call_loc << ": ";
266-
std::cerr << "runtime error: too many arguments applied to non-function value "
267-
<< *resultant_value << std::endl;
268-
std::exit(EXIT_FAILURE);
226+
// No Thunks remaining then concrete Value is the result
227+
return concrete;
269228
}
270-
271-
// Defensive: we should never reach here, but keep an explicit guard.
272-
if (call_loc) std::cerr << *call_loc << ": ";
273-
std::cerr << "runtime error: internal apply error" << std::endl;
274-
std::exit(EXIT_FAILURE);
229+
// There is a previous Frame; insert the concrete Value as a Thunk at the
230+
// current index so the previous Frame will consume it on the next iteration.
231+
auto inj_th = value_to_thunk(concrete);
232+
work_args.insert(work_args.begin() + static_cast<int>(idx), inj_th);
233+
// Do NOT advance idx: the inserted thunk is at position idx and will be consumed
234+
// by the previous frame on the next iteration.
235+
// Loop will continue with frames.back() being the previous frame.
275236
}
276-
277-
// If we consumed all args and still have a function value (e.g., partial application),
278-
// return the function (curried function).
279-
return current_fn;
280237
}
281238

282-
283239
// Creates placeholder Thunk then set body so recursion can refer to it during lazy evaluation
284240
static void bind_def_ast_node_lazy(const fe::ast::DefAstNode &def_ast_node, const std::shared_ptr<Env> &env) {
285241
const auto thunk = std::make_shared<Thunk>();

0 commit comments

Comments
 (0)