interp.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. use crate::ast::*;
  2. use rand::Rng;
  3. use std::collections::HashMap;
  4. use std::fmt;
  5. macro_rules! bail {
  6. ($fmt:expr) => { return Err(Error { message: format!($fmt), }) };
  7. ($fmt:expr, $($e:expr),*) => { return Err(Error { message: format!($fmt, $($e),*), }) }
  8. }
  9. #[derive(Debug, Clone)]
  10. pub enum Value {
  11. Lit(Literal),
  12. Tup(Vec<Value>),
  13. Builtin(&'static BuiltinFunc),
  14. }
  15. impl Value {
  16. fn as_num(&self) -> Result<i64, Error> {
  17. match self {
  18. Value::Lit(Literal::Num(n)) => Ok(*n),
  19. _ => self.with_str(|s| bail!("Expected number, got {}", s)),
  20. }
  21. }
  22. fn as_str(&self) -> Result<&str, Error> {
  23. match self {
  24. Value::Lit(Literal::Str(s)) => Ok(s),
  25. _ => self.with_str(|s| bail!("Expected string, got {}", s)),
  26. }
  27. }
  28. fn with_str<U>(&self, f: impl FnOnce(&str) -> U) -> U {
  29. match self {
  30. Value::Lit(Literal::Str(s)) => f(s),
  31. Value::Lit(Literal::Atom(s)) => f(&format!("{:?}", s)),
  32. Value::Lit(Literal::Num(n)) => f(&format!("{}", n)),
  33. Value::Tup(values) => {
  34. let mut buf = String::new();
  35. buf.push('<');
  36. for (i, val) in values.iter().enumerate() {
  37. if i > 0 {
  38. buf.push_str(", ");
  39. }
  40. buf.push_str(&val.to_string());
  41. }
  42. buf.push('>');
  43. f(&buf)
  44. }
  45. Value::Builtin(func) => f(&format!("#<builtin {}>", func.name)),
  46. }
  47. }
  48. }
  49. impl fmt::Display for Value {
  50. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  51. self.with_str(|s| write!(f, "{}", s))
  52. }
  53. }
  54. pub struct BuiltinFunc {
  55. name: &'static str,
  56. callback: &'static dyn Fn(&mut State, &Expr) -> Result<Value, Error>,
  57. }
  58. #[derive(Debug)]
  59. pub struct Error {
  60. message: String,
  61. }
  62. impl From<lalrpop_util::ParseError<usize, crate::lexer::Token<'_>, crate::lexer::LexerError>>
  63. for Error
  64. {
  65. fn from(
  66. err: lalrpop_util::ParseError<usize, crate::lexer::Token<'_>, crate::lexer::LexerError>,
  67. ) -> Error {
  68. Error {
  69. message: format!("{:?}", err),
  70. }
  71. }
  72. }
  73. impl fmt::Display for Error {
  74. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  75. write!(fmt, "{}", self.message)
  76. }
  77. }
  78. impl std::error::Error for Error {}
  79. const BUILTINS: &[BuiltinFunc] = &[
  80. BuiltinFunc {
  81. name: "rep",
  82. callback: &|state: &mut State, expr: &Expr| -> Result<Value, Error> {
  83. let args = match expr {
  84. Expr::Tup(tup) => tup,
  85. _ => bail!("`rep`: expected tuple"),
  86. };
  87. if args.len() != 2 {
  88. bail!("`rep`: expected two arguments, got {}", args.len())
  89. }
  90. let num = state.eval(&args[0])?.as_num()?;
  91. let rep = (0..num).map(|_| args[1].clone()).collect();
  92. state.eval(&Expr::Cat(rep))
  93. },
  94. },
  95. BuiltinFunc {
  96. name: "length",
  97. callback: &|_state: &mut State, expr: &Expr| -> Result<Value, Error> {
  98. let args = match expr {
  99. Expr::Tup(tup) => tup,
  100. _ => bail!("`length`: expected tuple"),
  101. };
  102. Ok(Value::Lit(Literal::Num(args.len() as i64)))
  103. },
  104. },
  105. BuiltinFunc {
  106. name: "to-upper",
  107. callback: &|state: &mut State, expr: &Expr| -> Result<Value, Error> {
  108. let s = state.eval(expr)?;
  109. Ok(Value::Lit(Literal::Str(s.as_str()?.to_uppercase())))
  110. },
  111. },
  112. BuiltinFunc {
  113. name: "to-lower",
  114. callback: &|state: &mut State, expr: &Expr| -> Result<Value, Error> {
  115. let s = state.eval(expr)?;
  116. Ok(Value::Lit(Literal::Str(s.as_str()?.to_lowercase())))
  117. },
  118. },
  119. ];
  120. impl fmt::Debug for BuiltinFunc {
  121. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  122. writeln!(fmt, "BuiltinFunc {{ name: {:?}, ... }}", self.name)
  123. }
  124. }
  125. enum NamedItem {
  126. Expr(Expr),
  127. Value(Value),
  128. Builtin(&'static BuiltinFunc),
  129. }
  130. pub struct State {
  131. ast: ASTArena,
  132. scope: HashMap<Name, NamedItem>,
  133. rand: rand::rngs::ThreadRng,
  134. parser: crate::grammar::StmtsParser,
  135. }
  136. impl Default for State {
  137. fn default() -> State {
  138. Self::new()
  139. }
  140. }
  141. impl State {
  142. pub fn new() -> State {
  143. let mut s = State {
  144. scope: HashMap::new(),
  145. rand: rand::thread_rng(),
  146. parser: crate::grammar::StmtsParser::new(),
  147. ast: ASTArena::new(),
  148. };
  149. for builtin in BUILTINS {
  150. let sym = s.ast.add_string(builtin.name);
  151. s.scope.insert(sym, NamedItem::Builtin(builtin));
  152. }
  153. s
  154. }
  155. pub fn run(&mut self, src: &str) -> Result<(), Error> {
  156. let lexed = crate::lexer::tokens(src);
  157. let stmts = self.parser.parse(&mut self.ast, lexed)?;
  158. for stmt in stmts {
  159. self.execute(&stmt)?;
  160. }
  161. Ok(())
  162. }
  163. pub fn run_repl(&mut self, src: &str) -> Result<(), Error> {
  164. let lexed = crate::lexer::tokens(src);
  165. let stmts = match self.parser.parse(&mut self.ast, lexed) {
  166. Ok(stmts) => stmts,
  167. Err(err) => {
  168. let with_puts = format!("puts {}", src);
  169. let lexed = crate::lexer::tokens(&with_puts);
  170. if let Ok(stmts) = self.parser.parse(&mut self.ast, lexed) {
  171. stmts
  172. } else {
  173. return Err(err.into());
  174. }
  175. }
  176. };
  177. for stmt in stmts {
  178. self.execute(&stmt)?;
  179. }
  180. Ok(())
  181. }
  182. pub fn autocomplete(&self, fragment: &str, at_beginning: bool) -> Vec<String> {
  183. let mut possibilities = Vec::new();
  184. for name in self.scope.keys() {
  185. if self.ast[*name].starts_with(fragment) {
  186. possibilities.push(self.ast[*name].to_string());
  187. }
  188. }
  189. if at_beginning && "puts".starts_with(fragment) {
  190. possibilities.push("puts ".to_owned());
  191. }
  192. possibilities
  193. }
  194. pub fn execute(&mut self, stmt: &Stmt) -> Result<(), Error> {
  195. match stmt {
  196. Stmt::Puts(expr) => {
  197. let val = self.eval(expr)?;
  198. println!("{}", val.to_string());
  199. }
  200. Stmt::Fix(name) => {
  201. let expr = match self.scope.get(name) {
  202. None => bail!("no such thing: {:?}", name),
  203. Some(NamedItem::Expr(e)) => e.clone(),
  204. // if it's not an expr, then our work here is done
  205. _ => return Ok(()),
  206. };
  207. let val = self.eval(&expr)?;
  208. self.scope.insert(*name, NamedItem::Value(val));
  209. }
  210. Stmt::Assn(fixed, name, expr) => {
  211. if *fixed {
  212. let val = self.eval(expr)?;
  213. self.scope.insert(*name, NamedItem::Value(val));
  214. } else {
  215. self.scope.insert(*name, NamedItem::Expr(expr.clone()));
  216. }
  217. }
  218. Stmt::LitAssn(fixed, name, strs) => {
  219. if *fixed {
  220. let choice = &strs[self.rand.gen_range(0..strs.len())];
  221. self.scope.insert(
  222. *name,
  223. NamedItem::Value(Value::Lit(Literal::Str(choice.clone()))),
  224. );
  225. return Ok(());
  226. }
  227. let choices = strs
  228. .iter()
  229. .map(|s| Choice {
  230. weight: None,
  231. value: Expr::Lit(Literal::Str(s.clone())),
  232. })
  233. .collect();
  234. self.scope
  235. .insert(*name, NamedItem::Expr(Expr::Chc(choices)));
  236. }
  237. }
  238. Ok(())
  239. }
  240. fn eval(&mut self, expr: &Expr) -> Result<Value, Error> {
  241. match expr {
  242. Expr::Lit(l) => Ok(Value::Lit(l.clone())),
  243. Expr::Var(v) => {
  244. let e = match self.scope.get(v) {
  245. Some(NamedItem::Expr(e)) => e.clone(),
  246. Some(NamedItem::Value(v)) => return Ok(v.clone()),
  247. Some(NamedItem::Builtin(b)) => return Ok(Value::Builtin(b)),
  248. None => bail!("no such thing: {:?}", v),
  249. };
  250. self.eval(&e)
  251. }
  252. Expr::Cat(cat) => {
  253. if cat.len() == 1 {
  254. self.eval(&cat[0])
  255. } else {
  256. let mut buf = String::new();
  257. for expr in cat {
  258. let val = self.eval(expr)?;
  259. buf.push_str(&val.to_string());
  260. }
  261. Ok(Value::Lit(Literal::Str(buf)))
  262. }
  263. }
  264. Expr::Chc(choices) => {
  265. if choices.len() == 1 {
  266. self.eval(&choices[0].value)
  267. } else {
  268. self.choose(choices)
  269. }
  270. }
  271. Expr::Tup(values) => Ok(Value::Tup(
  272. values
  273. .iter()
  274. .map(|v| self.eval(v))
  275. .collect::<Result<Vec<Value>, Error>>()?,
  276. )),
  277. Expr::Ap(fun, arg) => match self.eval(fun)? {
  278. Value::Builtin(builtin) => (builtin.callback)(self, arg),
  279. _ => bail!("bad function: {:?}", fun),
  280. },
  281. Expr::Range(from, to) => {
  282. let from = self.eval(from)?.as_num()?;
  283. let to = self.eval(to)?.as_num()?;
  284. Ok(Value::Lit(Literal::Num(self.rand.gen_range(from..=to))))
  285. }
  286. _ => bail!("unimplemented: {:?}", expr),
  287. }
  288. }
  289. fn choose(&mut self, choices: &[Choice]) -> Result<Value, Error> {
  290. let max = choices.iter().map(Choice::weight).sum();
  291. let mut choice = self.rand.gen_range(0..max);
  292. for ch in choices {
  293. if choice < ch.weight() {
  294. return self.eval(&ch.value);
  295. }
  296. choice -= ch.weight();
  297. }
  298. bail!("unreachable")
  299. }
  300. }