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

Commit abbed7d

Browse files
committed
Interpreter added
1 parent 8b73e4a commit abbed7d

15 files changed

Lines changed: 444 additions & 13 deletions

File tree

‎CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ add_library(fe STATIC
1717

1818
add_library(intp STATIC
1919
${CMAKE_SOURCE_DIR}/src/intp/types.cpp
20+
${CMAKE_SOURCE_DIR}/src/intp/interpreter.cpp
2021
)
2122

2223
add_executable(lambda_discipline ${CMAKE_SOURCE_DIR}/src/main.cpp)

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,6 @@ cmake ..
77
make
88
```
99

10-
> TODO: Add build instructions for Windows as well.
10+
> TODO: Add build instructions for Windows as well.
11+
12+
> TODO: Add small script to print all TODOs and there Loc.

‎examples/ifthen.lbd‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
true: Bool = \x: Any. \y: Any. x
2+
false: Bool = \x: Any. \y: Any. y
3+
4+
ifthen: Any = \condition: Bool -> Any -> Any -> Any.
5+
\then_clause: Any. \else_clause: Any.
6+
(condition then_clause else_clause)
7+
8+
(print (ifthen true "True" "False"))
9+
(print (ifthen false "True" "False"))

‎examples/pair.lbd‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
pair: Any = \x: Any. \y: Any. \fn: Any. (fn x y)
2+
3+
first: Any = \x: Any. \y: Any. x
4+
second: Any = \x: Any. \y: Any. y
5+
6+
p1: Any = (pair 1.0 2.0)
7+
8+
(print (p1 first))
9+
(print (p1 second))

‎examples/shapes.lbd‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
-- Define Pi as constant
2+
pi: Float = 3.14
3+
4+
-- Define function to calculate square
5+
square: Float -> Float = \x: Float. (mul x x)
6+
7+
-- Define function to calculate area of circle
8+
area_of_circle: Float -> Float = \r: Float.
9+
(mul pi (square r))
10+
11+
-- Define function to calculate volume of cylinder
12+
volume_of_cylinder: Float -> Float -> Float = \r: Float.
13+
\h: Float. (mul (area_of_circle r) h)
14+
15+
-- Calculate the volume of a cylinder
16+
(print "Volume of cylinder is: ")
17+
(print (volume_of_cylinder 5.0 10.0))

‎examples/std.lbd‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,7 @@ first: Any = \x: Any. \y: Any. x
1313
second: Any = \x: Any. \y: Any. y
1414

1515
-- misc
16+
-- TODO: Add support for ifzero and cmp
17+
-- TODO: Add support for `use`
1618
float_eq: Float -> Float -> Bool = \x: Float. \y: Float.
17-
(ifzero (cmp x y) true false)
19+
(ifzero (cmp x y) true false)

‎include/lbd/fe/ast.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#pragma once
22

3-
#include <iostream>
43
#include <lbd/fe/loc.h>
54
#include <lbd/intp/types.h>
65
#include <string>
@@ -36,6 +35,8 @@ namespace fe::ast {
3635
intp::types::Type arg_type;
3736
std::unique_ptr<Expression> expr;
3837
loc::Loc loc;
38+
/// Maybe, this is redundant
39+
/// TODO: Remove after checking
3940
intp::types::CompoundType lmd_expr_type; // Lambda Expression Type
4041

4142
void print(std::ostream &os, size_t indent) const;

‎include/lbd/intp/interpreter.h‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#pragma once
2+
3+
#include <functional>
4+
#include <optional>
5+
#include <string>
6+
#include <lbd/fe/ast.h>
7+
#include <lbd/fe/parser.h>
8+
9+
namespace intp::interp {
10+
struct NativeFunction;
11+
struct Thunk;
12+
struct Env;
13+
14+
/// Runtime representation of Lambda Expression
15+
struct Closure {
16+
std::string param;
17+
const fe::ast::Expression *body; /// Non-owning, read-only AST pointer
18+
std::shared_ptr<Env> env; /// Environment at the time of Lambda Expression creation
19+
20+
friend std::ostream &operator<<(std::ostream &os, const Closure &closure);
21+
};
22+
23+
using Value = std::variant<double, std::string, Closure, NativeFunction>;
24+
25+
struct NativeFunction {
26+
using Impl = std::function<Value(
27+
const std::vector<std::shared_ptr<Thunk> > &, const std::shared_ptr<Env> &)>;
28+
29+
std::size_t arity;
30+
Impl impl;
31+
32+
friend std::ostream &operator<<(std::ostream &os, const NativeFunction &native_fn);
33+
};
34+
35+
/// Pretty print a runtime value for REPL/diagnostics
36+
std::ostream &operator<<(std::ostream &os, const Value &value);
37+
38+
/// Lazy Thunk (call-by-need)
39+
struct Thunk : std::enable_shared_from_this<Thunk> {
40+
mutable std::optional<Value> cached;
41+
const fe::ast::Expression *expr = nullptr; /// Non-owning, read-only AST pointer
42+
std::shared_ptr<Env> env; /// Environment for evaluating Expression
43+
44+
Thunk() = default;
45+
46+
Thunk(const fe::ast::Expression *expr, std::shared_ptr<Env> env);
47+
48+
/// Force computation on Thunk and return a const reference to Value
49+
const Value &force() const; /// Marked const as cached is mutable
50+
51+
/// Sets Thunk's fields after construction
52+
/// Allows for recursive reference
53+
void set(const fe::ast::Expression *expr_, std::shared_ptr<Env> env_);
54+
};
55+
56+
struct Env : std::enable_shared_from_this<Env> {
57+
std::unordered_map<std::string, std::shared_ptr<Thunk> > table;
58+
std::shared_ptr<Env> parent;
59+
60+
explicit Env(std::shared_ptr<Env> parent = nullptr);
61+
62+
std::shared_ptr<Thunk> lookup(const std::string &name) const;
63+
64+
void bind(const std::string &name, std::shared_ptr<Thunk> thunk);
65+
};
66+
67+
Value eval_expr(const fe::ast::Expression &expr, std::shared_ptr<Env> env);
68+
69+
Value apply_fn_apl(Value fn_value, const std::vector<std::shared_ptr<Thunk> > &args,
70+
const std::shared_ptr<Env> &call_site_env);
71+
72+
/// Program Driver
73+
struct Result {
74+
std::shared_ptr<Env> global_env;
75+
};
76+
77+
Result interpret(const fe::ast::Program &program);
78+
79+
/// Add builtins Native Functions into Environment
80+
void install_builtins(const std::shared_ptr<Env> &env);
81+
}

‎include/lbd/string_escape.h‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#pragma once
2+
#include <string>
3+
4+
inline std::string escape(const std::string& str) {
5+
std::string result;
6+
result.reserve(str.size());
7+
for (const char c : str) {
8+
switch (c) {
9+
case '\n': result += "\\n"; break;
10+
case '\t': result += "\\t"; break;
11+
case '\r': result += "\\r"; break;
12+
case '\\': result += "\\\\"; break;
13+
case '"': result += "\\\""; break;
14+
case '\'': result += "\\\'"; break;
15+
default:
16+
// Printable ASCII characters
17+
if (c >= 32 && c <= 126) {
18+
result.push_back(c);
19+
} else {
20+
// Non-printable: use hex escape
21+
char buf[5];
22+
snprintf(buf, sizeof(buf), "\\x%02X", static_cast<unsigned char>(c));
23+
result += buf;
24+
}
25+
}
26+
}
27+
return result;
28+
}
29+
30+
inline std::string unescape_string(const std::string &str) {
31+
std::string result;
32+
result.reserve(str.size());
33+
for (size_t i = 0; i < str.size(); ++i) {
34+
if (str[i] == '\\' && i + 1 < str.size()) {
35+
switch (str[i + 1]) {
36+
case 'n': result.push_back('\n');
37+
break;
38+
case 't': result.push_back('\t');
39+
break;
40+
case 'r': result.push_back('\r');
41+
break;
42+
case '\\': result.push_back('\\');
43+
break;
44+
case '"': result.push_back('"');
45+
break;
46+
default:
47+
result.push_back(str[i + 1]); // Unknown escape: take character
48+
}
49+
++i; // Skip the escaped char
50+
} else {
51+
result.push_back(str[i]);
52+
}
53+
}
54+
return result;
55+
}

‎src/fe/ast.cpp‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#include <lbd/error.h>
22
#include <lbd/fe/ast.h>
33

4+
#include "lbd/string_escape.h"
5+
46
namespace fe::ast {
57
static void print_indent(std::ostream &os, const size_t indent) {
68
for (size_t i = 0; i < indent; ++i) {
@@ -12,8 +14,8 @@ namespace fe::ast {
1214
return os << node.value;
1315
}
1416

15-
std::ostream &operator<<(std::ostream &os, const StringAstNode &node) {
16-
return os << "\"" << node.value << "\"";
17+
std::ostream &operator<<(std::ostream &os, const StringAstNode &node) {\
18+
return os << "\"" << escape(node.value) << "\"";
1719
}
1820

1921
std::ostream &operator<<(std::ostream &os, const FloatAstNode &node) {
@@ -63,14 +65,15 @@ namespace fe::ast {
6365
void Expression::print(std::ostream &os, size_t indent) const {
6466
std::visit([&]<typename T0>(T0 &&arg) {
6567
using T = std::decay_t<T0>;
66-
if constexpr (std::is_same_v<T, IdenAstNode> || std::is_same_v<T, StringAstNode> || std::is_same_v<T,
67-
FloatAstNode>) {
68+
if constexpr (std::is_same_v<T, IdenAstNode>
69+
|| std::is_same_v<T, StringAstNode>
70+
|| std::is_same_v<T, FloatAstNode>) {
6871
print_indent(os, indent);
6972
os << arg;
7073
} else if constexpr (std::is_same_v<T, LambdaExpression> || std::is_same_v<T, FunctionApplication>) {
7174
arg.print(os, indent);
7275
} else {
73-
STATIC_ASSERT_UNREACHABLE_T(T, "Unhandled Type!");
76+
STATIC_ASSERT_UNREACHABLE_T(T, "unhandled expression");
7477
}
7578
}, value);
7679
}

0 commit comments

Comments
 (0)