This commit is contained in:
Sebastian Hugentobler 2025-05-28 09:05:18 +02:00
parent 6e02a1a644
commit 463e4abd30
Signed by: shu
SSH key fingerprint: SHA256:ppcx6MlixdNZd5EUM1nkHOKoyQYoJwzuQKXM6J/t66M
13 changed files with 172 additions and 26 deletions

30
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,30 @@
{
"$schema": "https://raw.githubusercontent.com/mfussenegger/dapconfig-schema/master/dapconfig-schema.json",
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Run Lox Interpreter",
"cargo": {
"args": [
"build",
"--package",
"rox",
"--message-format",
"json"
]
},
"program": "${workspaceFolder}/target/debug/rox",
"args": [
"run",
"-s",
"./lox/simple_for.lox"
],
"env": {
"RUST_LOG": "debug"
},
"cwd": "${workspaceFolder}"
}
]
}

6
bf/fibonacci.bf Normal file
View file

@ -0,0 +1,6 @@
>++++++++++>+>+[
[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[
[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>
]<<<
]

1
bf/helloworld.bf Normal file
View file

@ -0,0 +1 @@
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

1
bf/simple_loop.bf Normal file
View file

@ -0,0 +1 @@
++++++[>++++++++<-]>. // prints '0'

14
lox/nested_while.lox Normal file
View file

@ -0,0 +1,14 @@
{
var i = 0;
var j = 0;
while (i < 10) {
print i;
while (j < 100) {
print j;
j = j + 1;
}
i = i + 1;
}
}

8
lox/scope.lox Normal file
View file

@ -0,0 +1,8 @@
var a = "outer";
{
var a = "inner";
print a; // expect: inner
}
print a;

3
lox/simple_for.lox Normal file
View file

@ -0,0 +1,3 @@
for (var i = 0; i < 10; i = i + 1) {
print i;
}

5
lox/simple_while.lox Normal file
View file

@ -0,0 +1,5 @@
var i = 0;
while (i < 10) {
print i;
i = i + 1;
}

View file

@ -99,16 +99,14 @@ impl Environment {
/// Find an environment at a specific lexical distance from the current one. /// Find an environment at a specific lexical distance from the current one.
fn ancestor(&self, distance: usize) -> Result<Environment, EnvironmentError> { fn ancestor(&self, distance: usize) -> Result<Environment, EnvironmentError> {
let mut environment = self.clone(); // println!("{distance}: {self:?}");
if distance == 0 {
for _ in 0..distance { return Ok(self.clone());
let enclosing = match &environment.enclosing {
Some(enc) => enc.borrow().clone(),
None => return Err(EnvironmentError::InvalidDistance),
};
environment = enclosing;
} }
Ok(environment) match &self.enclosing {
Some(enclosing) => enclosing.borrow().ancestor(distance - 1),
None => Err(EnvironmentError::InvalidDistance),
}
} }
} }

View file

@ -52,9 +52,9 @@ pub struct Interpreter {
/// Global environment containing built-in functions and top-level variables /// Global environment containing built-in functions and top-level variables
pub globals: Rc<RefCell<Environment>>, pub globals: Rc<RefCell<Environment>>,
/// Current environment for variable lookups and assignments /// Current environment for variable lookups and assignments
environment: Rc<RefCell<Environment>>, pub environment: Rc<RefCell<Environment>>,
/// Map of expressions to their lexical distance for variable resolution /// Map of expressions to their lexical distance for variable resolution
locals: HashMap<Expression, usize>, pub locals: HashMap<Expression, usize>,
} }
/// Default configuration for the interpreter, with builtin native functions. /// Default configuration for the interpreter, with builtin native functions.
@ -452,11 +452,6 @@ impl Interpreter {
fn assign(&mut self, name: &Token, expression: &Expression) -> Result<Value, InterpreterError> { fn assign(&mut self, name: &Token, expression: &Expression) -> Result<Value, InterpreterError> {
let value = self.evaluate(expression)?; let value = self.evaluate(expression)?;
self.environment
.borrow_mut()
.assign(name, value.clone())
.map_err(InterpreterError::UndefinedVariable)?;
if let Some(distance) = self.locals.get(expression) { if let Some(distance) = self.locals.get(expression) {
self.environment self.environment
.borrow_mut() .borrow_mut()

View file

@ -94,6 +94,9 @@ fn run_rox(input: &str, interpreter: &mut Interpreter) -> Result<(), RoxError> {
debug!("AST:\n{}", crate::ast_printer::print(&ast)); debug!("AST:\n{}", crate::ast_printer::print(&ast));
resolver.resolve(&ast)?; resolver.resolve(&ast)?;
println!("globals: {:?}", interpreter.globals);
println!("environment: {:?}", interpreter.environment);
println!("locals: {:?}", interpreter.locals);
interpreter.run(ast)?; interpreter.run(ast)?;
Ok(()) Ok(())

View file

@ -3,7 +3,7 @@ use ordered_float::OrderedFloat;
use std::{ use std::{
collections::HashMap, collections::HashMap,
fs::File, fs::File,
io::{BufReader, ErrorKind, Read}, io::{stdin, stdout, BufReader, ErrorKind, Read, Seek, SeekFrom, Write},
rc::Rc, rc::Rc,
sync::RwLock, sync::RwLock,
time::{SystemTime, UNIX_EPOCH}, time::{SystemTime, UNIX_EPOCH},
@ -53,7 +53,7 @@ impl Callable for ReadFile {
} }
fn arity(&self) -> usize { fn arity(&self) -> usize {
1 2
} }
fn call( fn call(
@ -61,18 +61,24 @@ impl Callable for ReadFile {
_interpreter: &mut Interpreter, _interpreter: &mut Interpreter,
args: Vec<Value>, args: Vec<Value>,
) -> Result<Value, CallingError> { ) -> Result<Value, CallingError> {
if args.len() != self.arity() { let file_path = args.first().ok_or(CallingError::CallFailed(
return Err(CallingError::ArgumentMismatch(self.arity(), args.len())); "first arg must be file path".into(),
} ))?;
let file_path = args
.first()
.ok_or(CallingError::CallFailed("arg not readable".into()))?;
if let Value::String(file_path) = file_path { if let Value::String(file_path) = file_path {
self.ensure_file_handle(file_path)?; self.ensure_file_handle(file_path)?;
let mut file_handles = FILE_HANDLES.write().unwrap(); let mut file_handles = FILE_HANDLES.write().unwrap();
let reader = file_handles.get_mut(file_path).unwrap(); let reader = file_handles.get_mut(file_path).unwrap();
let mut buffer = [0; 1]; let mut buffer = [0; 1];
let backwards = args.get(1).unwrap_or(&Value::Boolean(false));
if let Value::Boolean(backwards) = backwards {
if *backwards {
reader
.seek(SeekFrom::Current(-2))
.map_err(|e| CallingError::CallFailed(e.to_string()))?;
}
}
let character = match reader.read_exact(&mut buffer) { let character = match reader.read_exact(&mut buffer) {
Ok(_) => { Ok(_) => {
let character = buffer[0] as char; let character = buffer[0] as char;
@ -143,9 +149,81 @@ impl Callable for Out {
} }
} }
struct AsciiOut;
impl Callable for AsciiOut {
fn name(&self) -> String {
"asciiOut".into()
}
fn arity(&self) -> usize {
1
}
fn call(&self, interpreter: &mut Interpreter, args: Vec<Value>) -> Result<Value, CallingError> {
if args.len() != self.arity() {
return Err(CallingError::ArgumentMismatch(self.arity(), args.len()));
}
let value = args
.first()
.ok_or(CallingError::CallFailed("arg not readable".into()))?;
if let Value::Number(value) = value {
let ascii = value.0 as u8 as char;
print!("{ascii}");
Ok(Value::Nil)
} else {
Err(CallingError::CallFailed(
"file_path arg must be a number".into(),
))
}
}
}
struct PromptAscii;
impl Callable for PromptAscii {
fn name(&self) -> String {
"prompt_ascii".into()
}
fn arity(&self) -> usize {
1
}
fn call(
&self,
_interpreter: &mut Interpreter,
args: Vec<Value>,
) -> Result<Value, CallingError> {
if args.len() != self.arity() {
return Err(CallingError::ArgumentMismatch(self.arity(), args.len()));
}
let prompt = args
.first()
.ok_or(CallingError::CallFailed("arg not readable".into()))?;
if let Value::String(prompt) = prompt {
print!("{prompt} ");
stdout().flush();
let mut buffer = [0; 1];
stdin().read_exact(&mut buffer);
todo!()
// Ok(Value::Number(buffer[0] as char))
} else {
Err(CallingError::CallFailed("prompt must be a string".into()))
}
}
}
/// Return all native functions available to the Lox interpreter /// Return all native functions available to the Lox interpreter
pub fn all() -> Vec<(String, Value)> { pub fn all() -> Vec<(String, Value)> {
vec![ vec![
(
"asciiOut".into(),
Value::Callable((Rc::new(AsciiOut {}), CallableType::Function)),
),
( (
"clock".into(), "clock".into(),
Value::Callable((Rc::new(Clock {}), CallableType::Function)), Value::Callable((Rc::new(Clock {}), CallableType::Function)),
@ -158,5 +236,9 @@ pub fn all() -> Vec<(String, Value)> {
"read".into(), "read".into(),
Value::Callable((Rc::new(ReadFile {}), CallableType::Function)), Value::Callable((Rc::new(ReadFile {}), CallableType::Function)),
), ),
(
"prompt".into(),
Value::Callable((Rc::new(PromptAscii {}), CallableType::Function)),
),
] ]
} }

View file

@ -4,7 +4,7 @@ use ordered_float::OrderedFloat;
use crate::{callable::Callable, instance, token::Literal}; use crate::{callable::Callable, instance, token::Literal};
/// Represents the type of a callable value in Lox. /// Represent the type of a callable value in Lox.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub enum CallableType { pub enum CallableType {
/// A regular function or method /// A regular function or method