interp.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 as_tup(&self) -> Result<&[Thunk], Error> {
  33. match self {
  34. Value::Tup(vals) => Ok(vals),
  35. _ => self.with_str(|s| bail!("Expected tuple, got {}", s)),
  36. }
  37. }
  38. fn as_closure(&self) -> Result<&Closure, Error> {
  39. match self {
  40. Value::Closure(closure) => Ok(closure),
  41. _ => self.with_str(|s| bail!("Expected tuple, got {}", s)),
  42. }
  43. }
  44. fn with_str<U>(&self, f: impl FnOnce(&str) -> U) -> U {
  45. match self {
  46. Value::Nil => f(""),
  47. Value::Lit(Literal::Str(s)) => f(s),
  48. Value::Lit(Literal::Atom(s)) => f(&format!("{:?}", s)),
  49. Value::Lit(Literal::Num(n)) => f(&format!("{}", n)),
  50. Value::Tup(values) => {
  51. let mut buf = String::new();
  52. buf.push('<');
  53. for (i, val) in values.iter().enumerate() {
  54. if i > 0 {
  55. buf.push_str(", ");
  56. }
  57. match val {
  58. Thunk::Value(v) => buf.push_str(&v.to_string()),
  59. Thunk::Expr(..) => buf.push_str("#<unevaluated>"),
  60. Thunk::Builtin(func) => buf.push_str(&format!("#<builtin {}>", func.name)),
  61. }
  62. }
  63. buf.push('>');
  64. f(&buf)
  65. }
  66. Value::Builtin(func) => f(&format!("#<builtin {}>", func.name)),
  67. Value::Closure(_) => f("#<lambda ...>"),
  68. }
  69. }
  70. }
  71. impl fmt::Display for Value {
  72. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  73. self.with_str(|s| write!(f, "{}", s))
  74. }
  75. }
  76. pub struct BuiltinFunc {
  77. name: &'static str,
  78. callback: &'static dyn Fn(&State, ExprRef, &Env) -> Result<Value, Error>,
  79. }
  80. #[derive(Debug)]
  81. pub struct Error {
  82. message: String,
  83. }
  84. impl From<lalrpop_util::ParseError<usize, crate::lexer::Token<'_>, crate::lexer::LexerError>>
  85. for Error
  86. {
  87. fn from(
  88. err: lalrpop_util::ParseError<usize, crate::lexer::Token<'_>, crate::lexer::LexerError>,
  89. ) -> Error {
  90. Error {
  91. message: format!("{:?}", err),
  92. }
  93. }
  94. }
  95. impl fmt::Display for Error {
  96. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  97. write!(fmt, "{}", self.message)
  98. }
  99. }
  100. impl std::error::Error for Error {}
  101. const BUILTINS: &[BuiltinFunc] = &[
  102. BuiltinFunc {
  103. name: "rep",
  104. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  105. let (rep, expr) = {
  106. let ast = state.ast.borrow();
  107. let args = match &ast[expr] {
  108. Expr::Tup(tup) => tup,
  109. _ => bail!("`rep`: expected tuple"),
  110. };
  111. if args.len() != 2 {
  112. bail!("`rep`: expected two arguments, got {}", args.len())
  113. }
  114. (args[0], args[1])
  115. };
  116. let mut buf = String::new();
  117. let num = state.eval(rep, env)?.as_num()?;
  118. for _ in 0..num {
  119. buf.push_str(&state.eval(expr, env)?.as_str()?.to_string());
  120. }
  121. Ok(Value::Lit(Literal::Str(buf)))
  122. },
  123. },
  124. BuiltinFunc {
  125. name: "length",
  126. callback: &|state: &State, expr: ExprRef, _env: &Env| -> Result<Value, Error> {
  127. let ast = state.ast.borrow();
  128. let args = match &ast[expr] {
  129. Expr::Tup(tup) => tup,
  130. _ => bail!("`length`: expected tuple"),
  131. };
  132. Ok(Value::Lit(Literal::Num(args.len() as i64)))
  133. },
  134. },
  135. BuiltinFunc {
  136. name: "to-upper",
  137. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  138. let s = state.eval(expr, env)?;
  139. Ok(Value::Lit(Literal::Str(s.as_str()?.to_uppercase())))
  140. },
  141. },
  142. BuiltinFunc {
  143. name: "to-lower",
  144. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  145. let s = state.eval(expr, env)?;
  146. Ok(Value::Lit(Literal::Str(s.as_str()?.to_lowercase())))
  147. },
  148. },
  149. BuiltinFunc {
  150. name: "concat",
  151. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  152. let val = state.eval(expr, env)?;
  153. let tup = val.as_tup()?;
  154. let mut contents = Vec::new();
  155. for elem in tup {
  156. for th in state.hnf(elem)?.as_tup()? {
  157. contents.push(th.clone());
  158. }
  159. }
  160. Ok(Value::Tup(contents))
  161. },
  162. },
  163. BuiltinFunc {
  164. name: "tuple-fold",
  165. callback: &|state: &State, expr: ExprRef, env: &Env| -> Result<Value, Error> {
  166. let val = state.eval(expr, env)?;
  167. let args = val.as_tup()?;
  168. if args.len() != 3 {
  169. bail!("`tuple-fold`: expected 3 arguments, got {}", args.len());
  170. }
  171. let func = &args[0];
  172. let init = &args[1];
  173. let tup = &args[2];
  174. let func = state.hnf(func)?;
  175. let tup = state.hnf(tup)?;
  176. let mut result = init.clone();
  177. for t in tup.as_tup()? {
  178. let partial = state.eval_closure(func.as_closure()?, result)?;
  179. result = Thunk::Value(state.eval_closure(partial.as_closure()?, t.clone())?);
  180. }
  181. state.hnf(&result)
  182. },
  183. },
  184. ];
  185. impl fmt::Debug for BuiltinFunc {
  186. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  187. writeln!(fmt, "BuiltinFunc {{ name: {:?}, ... }}", self.name)
  188. }
  189. }
  190. #[derive(Debug, Clone)]
  191. pub enum Thunk {
  192. Expr(ExprRef, Env),
  193. Value(Value),
  194. Builtin(&'static BuiltinFunc),
  195. }
  196. type Env = Option<Rc<Scope>>;
  197. #[derive(Debug)]
  198. pub struct Scope {
  199. vars: HashMap<Name, Thunk>,
  200. parent: Env,
  201. }
  202. #[derive(Debug, Clone)]
  203. pub struct Closure {
  204. func: ExprRef,
  205. scope: Env,
  206. }
  207. pub struct State {
  208. ast: RefCell<ASTArena>,
  209. root_scope: RefCell<HashMap<Name, Thunk>>,
  210. rand: RefCell<rand::rngs::ThreadRng>,
  211. parser: crate::grammar::StmtsParser,
  212. }
  213. impl Default for State {
  214. fn default() -> State {
  215. Self::new()
  216. }
  217. }
  218. impl State {
  219. pub fn new() -> State {
  220. let s = State {
  221. root_scope: RefCell::new(HashMap::new()),
  222. rand: RefCell::new(rand::thread_rng()),
  223. parser: crate::grammar::StmtsParser::new(),
  224. ast: RefCell::new(ASTArena::new()),
  225. };
  226. for builtin in BUILTINS {
  227. let sym = s.ast.borrow_mut().add_string(builtin.name);
  228. s.root_scope
  229. .borrow_mut()
  230. .insert(sym, Thunk::Builtin(builtin));
  231. }
  232. s
  233. }
  234. fn lookup(&self, env: &Env, name: Name) -> Result<Thunk, Error> {
  235. if let Some(env) = env {
  236. if let Some(ne) = env.vars.get(&name) {
  237. Ok(ne.clone())
  238. } else {
  239. self.lookup(&env.parent, name)
  240. }
  241. } else {
  242. match self.root_scope.borrow().get(&name) {
  243. None => bail!("no such thing: {}", &self.ast.borrow()[name]),
  244. Some(ne) => Ok(ne.clone()),
  245. }
  246. }
  247. }
  248. pub fn run(&self, src: &str) -> Result<(), Error> {
  249. let lexed = crate::lexer::tokens(src);
  250. let stmts = self.parser.parse(&mut self.ast.borrow_mut(), lexed)?;
  251. for stmt in stmts {
  252. self.execute(&stmt)?;
  253. }
  254. Ok(())
  255. }
  256. pub fn run_repl(&self, src: &str) -> Result<(), Error> {
  257. let lexed = crate::lexer::tokens(src);
  258. let stmts = {
  259. let mut ast = self.ast.borrow_mut();
  260. self.parser.parse(&mut ast, lexed)
  261. };
  262. let stmts = match stmts {
  263. Ok(stmts) => stmts,
  264. Err(err) => {
  265. let with_puts = format!("puts {}", src);
  266. let lexed = crate::lexer::tokens(&with_puts);
  267. if let Ok(stmts) = self.parser.parse(&mut self.ast.borrow_mut(), lexed) {
  268. stmts
  269. } else {
  270. return Err(err.into());
  271. }
  272. }
  273. };
  274. for stmt in stmts {
  275. self.execute(&stmt)?;
  276. }
  277. Ok(())
  278. }
  279. pub fn autocomplete(&self, fragment: &str, at_beginning: bool) -> Vec<String> {
  280. let mut possibilities = Vec::new();
  281. for name in self.root_scope.borrow().keys() {
  282. if self.ast.borrow()[*name].starts_with(fragment) {
  283. possibilities.push(self.ast.borrow()[*name].to_string());
  284. }
  285. }
  286. if at_beginning && "puts".starts_with(fragment) {
  287. possibilities.push("puts ".to_owned());
  288. }
  289. possibilities
  290. }
  291. pub fn execute(&self, stmt: &Stmt) -> Result<(), Error> {
  292. match stmt {
  293. Stmt::Puts(expr) => {
  294. let val = self.eval(*expr, &None)?;
  295. let val = self.force(val)?;
  296. println!("{}", val.to_string());
  297. }
  298. Stmt::Fix(name) => {
  299. let (expr, env) = match self.lookup(&None, *name)? {
  300. Thunk::Expr(e, env) => (e, env),
  301. // if it's not an expr, then our work here is done
  302. _ => return Ok(()),
  303. };
  304. let val = self.eval(expr, &env)?;
  305. let val = self.force(val)?;
  306. self.root_scope
  307. .borrow_mut()
  308. .insert(*name, Thunk::Value(val));
  309. }
  310. Stmt::Assn(fixed, name, expr) => {
  311. if *fixed {
  312. let val = self.eval(*expr, &None)?;
  313. self.root_scope
  314. .borrow_mut()
  315. .insert(*name, Thunk::Value(val));
  316. } else {
  317. self.root_scope
  318. .borrow_mut()
  319. .insert(*name, Thunk::Expr(*expr, None));
  320. }
  321. }
  322. Stmt::LitAssn(fixed, name, strs) => {
  323. if *fixed {
  324. let choice = &strs[self.rand.borrow_mut().gen_range(0..strs.len())];
  325. self.root_scope.borrow_mut().insert(
  326. *name,
  327. Thunk::Value(Value::Lit(Literal::Str(choice.clone()))),
  328. );
  329. return Ok(());
  330. }
  331. let choices = strs
  332. .iter()
  333. .map(|s| Choice {
  334. weight: None,
  335. value: self
  336. .ast
  337. .borrow_mut()
  338. .add_expr(Expr::Lit(Literal::Str(s.clone()))),
  339. })
  340. .collect();
  341. let choices = self.ast.borrow_mut().add_expr(Expr::Chc(choices));
  342. self.root_scope
  343. .borrow_mut()
  344. .insert(*name, Thunk::Expr(choices, None));
  345. }
  346. }
  347. Ok(())
  348. }
  349. fn force(&self, val: Value) -> Result<Value, Error> {
  350. match val {
  351. Value::Tup(values) => Ok(Value::Tup(
  352. values
  353. .into_iter()
  354. .map(|t| {
  355. let v = self.hnf(&t)?;
  356. let v = self.force(v)?;
  357. Ok(Thunk::Value(v))
  358. })
  359. .collect::<Result<Vec<Thunk>, Error>>()?,
  360. )),
  361. _ => Ok(val),
  362. }
  363. }
  364. fn hnf(&self, thunk: &Thunk) -> Result<Value, Error> {
  365. match thunk {
  366. Thunk::Expr(expr, env) => self.eval(*expr, env),
  367. Thunk::Value(val) => Ok(val.clone()),
  368. Thunk::Builtin(b) => Ok(Value::Builtin(b)),
  369. }
  370. }
  371. fn eval(&self, expr_ref: ExprRef, env: &Env) -> Result<Value, Error> {
  372. let expr = &self.ast.borrow()[expr_ref];
  373. match expr {
  374. Expr::Lit(l) => Ok(Value::Lit(l.clone())),
  375. Expr::Nil => Ok(Value::Nil),
  376. Expr::Var(v) => {
  377. let (e, env) = match self.lookup(env, *v)? {
  378. Thunk::Expr(e, env) => (e, env),
  379. Thunk::Value(v) => return Ok(v),
  380. Thunk::Builtin(b) => return Ok(Value::Builtin(b)),
  381. };
  382. self.eval(e, &env)
  383. }
  384. Expr::Cat(cat) => {
  385. if cat.len() == 1 {
  386. self.eval(cat[0], env)
  387. } else {
  388. let mut buf = String::new();
  389. for expr in cat {
  390. let val = self.eval(*expr, env)?;
  391. let val = self.force(val)?;
  392. buf.push_str(&val.to_string());
  393. }
  394. Ok(Value::Lit(Literal::Str(buf)))
  395. }
  396. }
  397. Expr::Chc(choices) => {
  398. if choices.len() == 1 {
  399. self.eval(choices[0].value, env)
  400. } else {
  401. self.choose(choices, env)
  402. }
  403. }
  404. Expr::Tup(values) => Ok(Value::Tup(
  405. values
  406. .iter()
  407. .map(|v| Thunk::Expr(*v, env.clone()))
  408. .collect::<Vec<Thunk>>(),
  409. )),
  410. Expr::Range(from, to) => {
  411. let from = self.eval(*from, env)?.as_num()?;
  412. let to = self.eval(*to, env)?.as_num()?;
  413. Ok(Value::Lit(Literal::Num(
  414. self.rand.borrow_mut().gen_range(from..=to),
  415. )))
  416. }
  417. Expr::Fun(_) => Ok(Value::Closure(Closure {
  418. func: expr_ref,
  419. scope: env.clone(),
  420. })),
  421. Expr::Ap(func, val) => match self.eval(*func, env)? {
  422. Value::Closure(c) => {
  423. let scrut = Thunk::Expr(*val, env.clone());
  424. self.eval_closure(&c, scrut)
  425. }
  426. Value::Builtin(builtin) => (builtin.callback)(self, *val, env),
  427. _ => bail!("Bad function: {:?}", func),
  428. },
  429. _ => bail!("unimplemented: {:?}", expr),
  430. }
  431. }
  432. fn eval_closure(&self, closure: &Closure, mut scrut: Thunk) -> Result<Value, Error> {
  433. let ast = self.ast.borrow();
  434. let cases = match &ast[closure.func] {
  435. Expr::Fun(cases) => cases,
  436. _ => bail!("INVARIANT FAILED"),
  437. };
  438. for c in cases {
  439. let mut bindings = Vec::new();
  440. if !self.match_pat(&c.pat, &mut scrut, &mut bindings)? {
  441. continue;
  442. }
  443. let mut new_scope = HashMap::new();
  444. for (name, binding) in bindings {
  445. new_scope.insert(name, binding);
  446. }
  447. let new_scope = Rc::new(Scope {
  448. vars: new_scope,
  449. parent: closure.scope.clone(),
  450. });
  451. return self.eval(c.expr, &Some(new_scope));
  452. }
  453. bail!("No pattern in {:?} matched {:?}", cases, scrut);
  454. }
  455. fn match_pat(
  456. &self,
  457. pat: &Pat,
  458. scrut: &mut Thunk,
  459. bindings: &mut Vec<(Name, Thunk)>,
  460. ) -> Result<bool, Error> {
  461. if let Pat::Var(v) = pat {
  462. bindings.push((*v, scrut.clone()));
  463. return Ok(true);
  464. }
  465. if let Pat::Wildcard = pat {
  466. return Ok(true);
  467. }
  468. // if it's not just a variable, then we'll need to make sure
  469. // we've evaluated `scrut` at least one level from here
  470. if let Thunk::Expr(e, env) = scrut {
  471. *scrut = Thunk::Value(self.eval(*e, env)?)
  472. };
  473. // now we can match deeper patterns, at least a little
  474. match pat {
  475. Pat::Lit(lhs) => {
  476. if let Thunk::Value(Value::Lit(rhs)) = scrut {
  477. Ok(lhs == rhs)
  478. } else {
  479. Ok(false)
  480. }
  481. }
  482. Pat::Tup(pats) => {
  483. if let Thunk::Value(Value::Tup(thunks)) = scrut {
  484. if pats.len() != thunks.len() {
  485. return Ok(false);
  486. }
  487. for (p, t) in pats.iter().zip(thunks) {
  488. if !self.match_pat(p, t, bindings)? {
  489. return Ok(false);
  490. }
  491. }
  492. Ok(true)
  493. } else {
  494. Ok(false)
  495. }
  496. }
  497. _ => Ok(false),
  498. }
  499. }
  500. fn choose(&self, choices: &[Choice], env: &Env) -> Result<Value, Error> {
  501. let max = choices.iter().map(Choice::weight).sum();
  502. let mut choice = self.rand.borrow_mut().gen_range(0..max);
  503. for ch in choices {
  504. if choice < ch.weight() {
  505. return self.eval(ch.value, env);
  506. }
  507. choice -= ch.weight();
  508. }
  509. bail!("unreachable")
  510. }
  511. }