interp.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. use crate::ast::*;
  2. use rand::Rng;
  3. use std::cell::RefCell;
  4. use std::collections::HashMap;
  5. use std::fmt;
  6. use std::rc::Rc;
  7. macro_rules! bail {
  8. ($fmt:expr) => { return Err(Error { message: format!($fmt), }) };
  9. ($fmt:expr, $($e:expr),*) => { return Err(Error { message: format!($fmt, $($e),*), }) }
  10. }
  11. #[derive(Debug, Clone)]
  12. pub enum Value {
  13. Lit(Literal),
  14. Tup(Vec<Thunk>),
  15. Builtin(&'static BuiltinFunc),
  16. Closure(Closure),
  17. Nil,
  18. }
  19. impl Value {
  20. fn as_num(&self) -> Result<i64, Error> {
  21. match self {
  22. Value::Lit(Literal::Num(n)) => Ok(*n),
  23. _ => self.with_str(|s| bail!("Expected number, got {}", s)),
  24. }
  25. }
  26. fn as_str(&self) -> Result<&str, Error> {
  27. match self {
  28. Value::Lit(Literal::Str(s)) => Ok(s),
  29. _ => self.with_str(|s| bail!("Expected string, got {}", s)),
  30. }
  31. }
  32. fn with_str<U>(&self, f: impl FnOnce(&str) -> U) -> U {
  33. match self {
  34. Value::Nil => f(""),
  35. Value::Lit(Literal::Str(s)) => f(s),
  36. Value::Lit(Literal::Atom(s)) => f(&format!("{:?}", s)),
  37. Value::Lit(Literal::Num(n)) => f(&format!("{}", n)),
  38. Value::Tup(values) => {
  39. let mut buf = String::new();
  40. buf.push('<');
  41. for (i, val) in values.iter().enumerate() {
  42. if i > 0 {
  43. buf.push_str(", ");
  44. }
  45. match val {
  46. Thunk::Value(v) => buf.push_str(&v.to_string()),
  47. Thunk::Expr(..) => buf.push_str("#<unevaluated>"),
  48. Thunk::Builtin(func) =>
  49. buf.push_str(&format!("#<builtin {}>", func.name)),
  50. }
  51. }
  52. buf.push('>');
  53. f(&buf)
  54. }
  55. Value::Builtin(func) => f(&format!("#<builtin {}>", func.name)),
  56. Value::Closure(_) => f(&format!("#<lambda ...>")),
  57. }
  58. }
  59. }
  60. impl fmt::Display for Value {
  61. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  62. self.with_str(|s| write!(f, "{}", s))
  63. }
  64. }
  65. pub struct BuiltinFunc {
  66. name: &'static str,
  67. callback: &'static dyn Fn(&State, ExprRef, &Env) -> Result<Value, Error>,
  68. }
  69. #[derive(Debug)]
  70. pub struct Error {
  71. message: String,
  72. }
  73. impl From<lalrpop_util::ParseError<usize, crate::lexer::Token<'_>, crate::lexer::LexerError>>
  74. for Error
  75. {
  76. fn from(
  77. err: lalrpop_util::ParseError<usize, crate::lexer::Token<'_>, crate::lexer::LexerError>,
  78. ) -> Error {
  79. Error {
  80. message: format!("{:?}", err),
  81. }
  82. }
  83. }
  84. impl fmt::Display for Error {
  85. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  86. write!(fmt, "{}", self.message)
  87. }
  88. }
  89. impl std::error::Error for Error {}
  90. const BUILTINS: &[BuiltinFunc] = &[
  91. BuiltinFunc {
  92. name: "rep",
  93. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  94. let (rep, expr) = {
  95. let ast = state.ast.borrow();
  96. let args = match &ast[expr] {
  97. Expr::Tup(tup) => tup,
  98. _ => bail!("`rep`: expected tuple"),
  99. };
  100. if args.len() != 2 {
  101. bail!("`rep`: expected two arguments, got {}", args.len())
  102. }
  103. (args[0], args[1])
  104. };
  105. let mut buf = String::new();
  106. let num = state.eval(rep, env)?.as_num()?;
  107. for _ in 0..num {
  108. buf.push_str(&state.eval(expr, env)?.as_str()?.to_string());
  109. }
  110. Ok(Value::Lit(Literal::Str(buf)))
  111. },
  112. },
  113. BuiltinFunc {
  114. name: "length",
  115. callback: &|state: &State, expr: ExprRef, _env: &Env| -> Result<Value, Error> {
  116. let ast = state.ast.borrow();
  117. let args = match &ast[expr] {
  118. Expr::Tup(tup) => tup,
  119. _ => bail!("`length`: expected tuple"),
  120. };
  121. Ok(Value::Lit(Literal::Num(args.len() as i64)))
  122. },
  123. },
  124. BuiltinFunc {
  125. name: "to-upper",
  126. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  127. let s = state.eval(expr, env)?;
  128. Ok(Value::Lit(Literal::Str(s.as_str()?.to_uppercase())))
  129. },
  130. },
  131. BuiltinFunc {
  132. name: "to-lower",
  133. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  134. let s = state.eval(expr, env)?;
  135. Ok(Value::Lit(Literal::Str(s.as_str()?.to_lowercase())))
  136. },
  137. },
  138. ];
  139. impl fmt::Debug for BuiltinFunc {
  140. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  141. writeln!(fmt, "BuiltinFunc {{ name: {:?}, ... }}", self.name)
  142. }
  143. }
  144. #[derive(Debug, Clone)]
  145. pub enum Thunk {
  146. Expr(ExprRef, Env),
  147. Value(Value),
  148. Builtin(&'static BuiltinFunc),
  149. }
  150. type Env = Option<Rc<Scope>>;
  151. #[derive(Debug)]
  152. pub struct Scope {
  153. vars: HashMap<Name, Thunk>,
  154. parent: Env,
  155. }
  156. #[derive(Debug, Clone)]
  157. pub struct Closure {
  158. func: ExprRef,
  159. scope: Env,
  160. }
  161. pub struct State {
  162. ast: RefCell<ASTArena>,
  163. root_scope: RefCell<HashMap<Name, Thunk>>,
  164. rand: RefCell<rand::rngs::ThreadRng>,
  165. parser: crate::grammar::StmtsParser,
  166. }
  167. impl Default for State {
  168. fn default() -> State {
  169. Self::new()
  170. }
  171. }
  172. impl State {
  173. pub fn new() -> State {
  174. let s = State {
  175. root_scope: RefCell::new(HashMap::new()),
  176. rand: RefCell::new(rand::thread_rng()),
  177. parser: crate::grammar::StmtsParser::new(),
  178. ast: RefCell::new(ASTArena::new()),
  179. };
  180. for builtin in BUILTINS {
  181. let sym = s.ast.borrow_mut().add_string(builtin.name);
  182. s.root_scope
  183. .borrow_mut()
  184. .insert(sym, Thunk::Builtin(builtin));
  185. }
  186. s
  187. }
  188. fn lookup(&self, env: &Env, name: Name) -> Result<Thunk, Error> {
  189. if let Some(env) = env {
  190. if let Some(ne) = env.vars.get(&name) {
  191. Ok(ne.clone())
  192. } else {
  193. self.lookup(&env.parent, name)
  194. }
  195. } else {
  196. match self.root_scope.borrow().get(&name) {
  197. None => bail!("no such thing: {:?}", name),
  198. Some(ne) => Ok(ne.clone()),
  199. }
  200. }
  201. }
  202. pub fn run(&self, src: &str) -> Result<(), Error> {
  203. let lexed = crate::lexer::tokens(src);
  204. let stmts = self.parser.parse(&mut self.ast.borrow_mut(), lexed)?;
  205. for stmt in stmts {
  206. self.execute(&stmt)?;
  207. }
  208. Ok(())
  209. }
  210. pub fn run_repl(&self, src: &str) -> Result<(), Error> {
  211. let lexed = crate::lexer::tokens(src);
  212. let stmts = {
  213. let mut ast = self.ast.borrow_mut();
  214. self.parser.parse(&mut ast, lexed)
  215. };
  216. let stmts = match stmts {
  217. Ok(stmts) => stmts,
  218. Err(err) => {
  219. let with_puts = format!("puts {}", src);
  220. let lexed = crate::lexer::tokens(&with_puts);
  221. if let Ok(stmts) = self.parser.parse(&mut self.ast.borrow_mut(), lexed) {
  222. stmts
  223. } else {
  224. return Err(err.into());
  225. }
  226. }
  227. };
  228. for stmt in stmts {
  229. self.execute(&stmt)?;
  230. }
  231. Ok(())
  232. }
  233. pub fn autocomplete(&self, fragment: &str, at_beginning: bool) -> Vec<String> {
  234. let mut possibilities = Vec::new();
  235. for name in self.root_scope.borrow().keys() {
  236. if self.ast.borrow()[*name].starts_with(fragment) {
  237. possibilities.push(self.ast.borrow()[*name].to_string());
  238. }
  239. }
  240. if at_beginning && "puts".starts_with(fragment) {
  241. possibilities.push("puts ".to_owned());
  242. }
  243. possibilities
  244. }
  245. pub fn execute(&self, stmt: &Stmt) -> Result<(), Error> {
  246. match stmt {
  247. Stmt::Puts(expr) => {
  248. let val = self.eval(*expr, &None)?;
  249. println!("{}", val.to_string());
  250. }
  251. Stmt::Fix(name) => {
  252. let (expr, env) = match self.lookup(&None, *name)? {
  253. Thunk::Expr(e, env) => (e, env),
  254. // if it's not an expr, then our work here is done
  255. _ => return Ok(()),
  256. };
  257. let val = self.eval(expr, &env)?;
  258. self.root_scope.borrow_mut().insert(*name, Thunk::Value(val));
  259. }
  260. Stmt::Assn(fixed, name, expr) => {
  261. if *fixed {
  262. let val = self.eval(*expr, &None)?;
  263. self.root_scope.borrow_mut().insert(*name, Thunk::Value(val));
  264. } else {
  265. self.root_scope
  266. .borrow_mut()
  267. .insert(*name, Thunk::Expr(*expr, None));
  268. }
  269. }
  270. Stmt::LitAssn(fixed, name, strs) => {
  271. if *fixed {
  272. let choice = &strs[self.rand.borrow_mut().gen_range(0..strs.len())];
  273. self.root_scope.borrow_mut().insert(
  274. *name,
  275. Thunk::Value(Value::Lit(Literal::Str(choice.clone()))),
  276. );
  277. return Ok(());
  278. }
  279. let choices = strs
  280. .iter()
  281. .map(|s| Choice {
  282. weight: None,
  283. value: self
  284. .ast
  285. .borrow_mut()
  286. .add_expr(Expr::Lit(Literal::Str(s.clone()))),
  287. })
  288. .collect();
  289. let choices = self.ast.borrow_mut().add_expr(Expr::Chc(choices));
  290. self.root_scope
  291. .borrow_mut()
  292. .insert(*name, Thunk::Expr(choices, None));
  293. }
  294. }
  295. Ok(())
  296. }
  297. fn eval(&self, expr_ref: ExprRef, env: &Env) -> Result<Value, Error> {
  298. let expr = &self.ast.borrow()[expr_ref];
  299. match expr {
  300. Expr::Lit(l) => Ok(Value::Lit(l.clone())),
  301. Expr::Nil => Ok(Value::Nil),
  302. Expr::Var(v) => {
  303. let (e, env) = match self.lookup(env, *v)? {
  304. Thunk::Expr(e, env) => (e, env),
  305. Thunk::Value(v) => return Ok(v.clone()),
  306. Thunk::Builtin(b) => return Ok(Value::Builtin(b)),
  307. };
  308. self.eval(e, &env)
  309. }
  310. Expr::Cat(cat) => {
  311. if cat.len() == 1 {
  312. self.eval(cat[0], env)
  313. } else {
  314. let mut buf = String::new();
  315. for expr in cat {
  316. let val = self.eval(*expr, env)?;
  317. buf.push_str(&val.to_string());
  318. }
  319. Ok(Value::Lit(Literal::Str(buf)))
  320. }
  321. }
  322. Expr::Chc(choices) => {
  323. if choices.len() == 1 {
  324. self.eval(choices[0].value, env)
  325. } else {
  326. self.choose(&choices, env)
  327. }
  328. }
  329. Expr::Tup(values) => Ok(Value::Tup(
  330. values
  331. .iter()
  332. .map(|v| Thunk::Expr(*v, env.clone()))
  333. .collect::<Vec<Thunk>>()
  334. )),
  335. Expr::Range(from, to) => {
  336. let from = self.eval(*from, env)?.as_num()?;
  337. let to = self.eval(*to, env)?.as_num()?;
  338. Ok(Value::Lit(Literal::Num(
  339. self.rand.borrow_mut().gen_range(from..=to),
  340. )))
  341. }
  342. Expr::Fun(_) => {
  343. Ok(Value::Closure(Closure {
  344. func: expr_ref,
  345. scope: env.clone(),
  346. }))
  347. }
  348. Expr::Ap(func, val) => {
  349. let closure = match self.eval(*func, env)? {
  350. Value::Closure(c) => c,
  351. Value::Builtin(builtin) => return (builtin.callback)(self, *val, env),
  352. _ => bail!("Bad function: {:?}", func),
  353. };
  354. let ast = self.ast.borrow();
  355. let cases = match &ast[closure.func] {
  356. Expr::Fun(cases) => cases,
  357. _ => bail!("INVARIANT FAILED"),
  358. };
  359. if cases.len() != 1 {
  360. bail!("UNIMPLEMENTED: more than one case");
  361. }
  362. let case = cases.first().unwrap();
  363. let var = if let Pat::Var(v) = case.pat {
  364. v
  365. } else {
  366. bail!("UNIMPLEMENTED: patterns");
  367. };
  368. let mut new_scope = HashMap::new();
  369. new_scope.insert(var, Thunk::Expr(*val, env.clone()));
  370. let new_scope = Rc::new(Scope {
  371. vars: new_scope,
  372. parent: closure.scope,
  373. });
  374. self.eval(case.expr, &Some(new_scope))
  375. }
  376. _ => bail!("unimplemented: {:?}", expr),
  377. }
  378. }
  379. fn choose(&self, choices: &[Choice], env: &Env) -> Result<Value, Error> {
  380. let max = choices.iter().map(Choice::weight).sum();
  381. let mut choice = self.rand.borrow_mut().gen_range(0..max);
  382. for ch in choices {
  383. if choice < ch.weight() {
  384. return self.eval(ch.value, env);
  385. }
  386. choice -= ch.weight();
  387. }
  388. bail!("unreachable")
  389. }
  390. }