Below is a basic Lisp interpreter written in C. It supports:
- Basic data types: Symbols, numbers, and cons cells (for lists).
- Mark-and-sweep garbage collection: Allocated objects are tracked in a linked list. The GC starts from a set of root objects (e.g., the global environment) and marks reachable objects before sweeping and freeing unmarked ones.
- Lambdas with lexical binding: Lambdas create closures that capture the current environment. When a lambda is applied, it extends the captured environment with new bindings.
This implementation is simplified for clarity and brevity. It includes:
- A parser for S-expressions (basic, handles strings like "(+ 1 2)" or "(lambda (x) (+ x 1))").
- An evaluator that handles core forms:
quote, if, lambda, and function application.
- Basic arithmetic (e.g.,
+ and * as built-in functions).
Limitations:
- It only handles a subset of Lisp (no macros, error handling, or I/O).
- The parser assumes well-formed input and doesn't handle whitespace robustly.
- GC roots are manually managed (e.g., the global environment is a root). In a real system, you'd need to handle stack roots more carefully.
- Memory leaks could occur if GC isn't triggered properly; call
gc() manually in the evaluator loop for testing.
Compile with: gcc -o lisp_interpreter lisp_interpreter.c
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Object types
typedef enum {
TYPE_SYMBOL, // e.g., "x"
TYPE_NUMBER, // e.g., 42
TYPE_CONS, // e.g., a pair (car . cdr)
TYPE_FUNCTION, // A lambda closure
TYPE_NIL // The empty list
} ObjectType;
// Object structure with GC mark bit
typedef struct Object {
ObjectType type;
int marked; // For GC: 0 = unmarked, 1 = marked
union {
char* symbol; // For TYPE_SYMBOL
double number; // For TYPE_NUMBER
struct { // For TYPE_CONS
struct Object* car;
struct Object* cdr;
} cons;
struct { // For TYPE_FUNCTION
struct Object* params; // List of symbols
struct Object* body; // Expression
struct Object* env; // Captured environment
} function;
} data;
struct Object* next; // Linked list for GC
} Object;
// Global heap for GC
Object* heap = NULL; // Linked list of all allocated objects
Object* global_env = NULL; // Global environment (a root for GC)
// Forward declarations
Object* alloc_object(ObjectType type);
void mark(Object* obj);
void gc();
Object* read_from_string(const char* str);
Object* eval(Object* expr, Object* env);
Object* extend_env(Object* vars, Object* vals, Object* parent_env);
// Helper: Create a symbol
Object* make_symbol(const char* name) {
Object* obj = alloc_object(TYPE_SYMBOL);
obj->data.symbol = strdup(name); // Simple string copy
return obj;
}
// Helper: Create a number
Object* make_number(double value) {
Object* obj = alloc_object(TYPE_NUMBER);
obj->data.number = value;
return obj;
}
// Helper: Create a cons cell
Object* make_cons(Object* car, Object* cdr) {
Object* obj = alloc_object(TYPE_CONS);
obj->data.cons.car = car;
obj->data.cons.cdr = cdr;
return obj;
}
// Helper: Create a function (closure)
Object* make_function(Object* params, Object* body, Object* env) {
Object* obj = alloc_object(TYPE_FUNCTION);
obj->data.function.params = params;
obj->data.function.body = body;
obj->data.function.env = env; // Lexical capture
return obj;
}
// Helper: The empty list (NIL)
Object* make_nil() {
return alloc_object(TYPE_NIL); // Special object for NIL
}
// Memory allocation with GC tracking
Object* alloc_object(ObjectType type) {
Object* obj = malloc(sizeof(Object));
if (!obj) {
fprintf(stderr, "Out of memory!\n");
exit(1);
}
obj->type = type;
obj->marked = 0;
obj->next = heap; // Add to front of heap list
heap = obj;
return obj;
}
// Mark-and-sweep GC
void mark(Object* obj) {
if (!obj || obj->marked) return;
obj->marked = 1;
if (obj->type == TYPE_CONS) {
mark(obj->data.cons.car);
mark(obj->data.cons.cdr);
} else if (obj->type == TYPE_FUNCTION) {
mark(obj->data.function.params);
mark(obj->data.function.body);
mark(obj->data.function.env); // Mark captured environment
}
// Add more cases if needed (e.g., environments as lists)
}
void gc() {
// Mark phase: Start from roots (for now, just global_env)
mark(global_env); // In a full interpreter, add more roots
// Sweep phase
Object** prev = &heap;
while (*prev) {
Object* current = *prev;
if (!current->marked) {
*prev = current->next; // Unlink
free(current); // Free memory
} else {
current->marked = 0; // Unmark for next GC
prev = ¤t->next;
}
}
}
// Simple parser for S-expressions
Object* read_from_string(const char* str) {
// This is a very basic parser; it assumes well-formed input.
// It skips whitespace and handles numbers, symbols, and lists.
const char* p = str;
while (*p && isspace(*p)) p++; // Skip whitespace
if (*p == '(') { // List
p++; // Skip '('
Object* list = make_nil(); // Build in reverse
while (*p && *p != ')') {
Object* item = read_from_string(p); // Recursive call
// Advance p (this is simplistic; in reality, track position)
list = make_cons(item, list); // Prepend
while (*p && isspace(*p)) p++;
}
if (*p == ')') p++; // Skip ')'
// Reverse the list
Object* reversed = make_nil();
while (list->type == TYPE_CONS) {
reversed = make_cons(list->data.cons.car, reversed);
list = list->data.cons.cdr;
}
return reversed;
} else if (isdigit(*p) || *p == '-') { // Number
double num = strtod(p, (char**)&p);
return make_number(num);
} else if (isalpha(*p)) { // Symbol
const char* start = p;
while (*p && (isalnum(*p) || *p == '+' || *p == '*')) p++;
int len = p - start;
char* sym = malloc(len + 1);
strncpy(sym, start, len);
sym[len] = '\0';
return make_symbol(sym);
} else if (*p == '\'') { // Quote (simple hack)
p++; // Skip '
Object* quoted = read_from_string(p);
return make_cons(make_symbol("quote"), make_cons(quoted, make_nil()));
}
return make_nil(); // Error case
}
// Evaluator
Object* eval(Object* expr, Object* env) {
if (!expr) return make_nil();
if (expr->type == TYPE_SYMBOL) { // Variable lookup
// Search env (a list of frames, each an alist)
Object* frame = env;
while (frame && frame->type == TYPE_CONS) {
Object* binding = frame->data.cons.car; // Each binding is (symbol . value)
if (binding->type == TYPE_CONS &&
binding->data.cons.car->type == TYPE_SYMBOL &&
strcmp(binding->data.cons.car->data.symbol, expr->data.symbol) == 0) {
return binding->data.cons.cdr; // Return value
}
frame = frame->data.cons.cdr;
}
fprintf(stderr, "Unbound symbol: %s\n", expr->data.symbol);
return make_nil();
} else if (expr->type == TYPE_NUMBER) { // Self-evaluating
return expr;
} else if (expr->type == TYPE_CONS) { // List: special forms or function call
Object* first = expr->data.cons.car;
if (first->type == TYPE_SYMBOL) {
if (strcmp(first->data.symbol, "quote") == 0) {
return expr->data.cons.cdr->data.cons.car; // Quoted expression
} else if (strcmp(first->data.symbol, "if") == 0) {
Object* test = eval(expr->data.cons.cdr->data.cons.car, env);
if (test->type == TYPE_NUMBER && test->data.number != 0) { // Truthy if non-zero
return eval(expr->data.cons.cdr->data.cons.cdr->data.cons.car, env);
} else {
return eval(expr->data.cons.cdr->data.cons.cdr->data.cons.cdr->data.cons.car, env);
}
} else if (strcmp(first->data.symbol, "lambda") == 0) {
Object* params = expr->data.cons.cdr->data.cons.car;
Object* body = expr->data.cons.cdr->data.cons.cdr->data.cons.car;
return make_function(params, body, env); // Capture env
}
}
// Function application
Object* func = eval(first, env); // Evaluate operator
if (func->type == TYPE_FUNCTION) {
Object* args = expr->data.cons.cdr; // Evaluate arguments
Object* evaled_args = make_nil();
Object* arg = args;
while (arg->type == TYPE_CONS) {
evaled_args = make_cons(eval(arg->data.cons.car, env), evaled_args);
arg = arg->data.cons.cdr;
}
// Extend environment
Object* new_env = extend_env(func->data.function.params, evaled_args, func->data.function.env);
return eval(func->data.function.body, new_env); // Evaluate body in new env
}
// Built-ins like +
if (first->type == TYPE_SYMBOL && strcmp(first->data.symbol, "+") == 0) {
double sum = 0;
Object* arg = expr->data.cons.cdr;
while (arg->type == TYPE_CONS) {
Object* evaled = eval(arg->data.cons.car, env);
if (evaled->type == TYPE_NUMBER) sum += evaled->data.number;
arg = arg->data.cons.cdr;
}
return make_number(sum);
}
// Add more built-ins as needed
}
return make_nil();
}
// Extend environment for function call
Object* extend_env(Object* vars, Object* vals, Object* parent_env) {
Object* new_frame = make_nil();
Object* var = vars;
Object* val = vals;
while (var->type == TYPE_CONS && val->type == TYPE_CONS) {
Object* binding = make_cons(var->data.cons.car, eval(val->data.cons.car, parent_env)); // Bind var to value
new_frame = make_cons(binding, new_frame);
var = var->data.cons.cdr;
val = val->data.cons.cdr;
}
return make_cons(new_frame, parent_env); // New frame + parent
}
// Initialize global environment
void init_global_env() {
global_env = make_nil(); // Start empty
// Add built-ins if needed, e.g., bind "+" to a function object
}
int main() {
init_global_env();
const char* input = "(+ 1 2)"; // Example
// const char* input = "((lambda (x) (+ x 1)) 41)"; // Lambda example
Object* expr = read_from_string(input);
gc(); // Run GC before evaluation
Object* result = eval(expr, global_env);
if (result->type == TYPE_NUMBER) {
printf("Result: %f\n", result->data.number);
} else {
printf("Result: (not a number)\n");
}
gc(); // Clean up after
return 0;
}
How to Use:
- Compile and run the program.
- Modify the
input string in main() to test expressions.
- Example inputs:
(+ 1 2): Evaluates to 3.
((lambda (x) (+ x 1)) 41): Evaluates to 42 (lexical binding: x is bound in the closure).
Explanation:
- Object Representation: Uses a tagged union for different types, with pointers for references (e.g., in cons cells and functions).
- GC:
mark() traverses the object graph from roots. gc() then frees unmarked objects. Roots are limited to global_env here.
- Lexical Binding: In
make_function(), the current env is captured. In eval(), function application extends this environment.
- Parser: Rudimentary; it recursively parses lists and atoms but assumes perfect input.
This is a starting point. For a production system, you'd need to expand error handling, add more forms, and improve the parser/GC.