ast.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. use std::fmt;
  2. pub type Name = string_interner::DefaultSymbol;
  3. pub struct ASTArena {
  4. strings: string_interner::StringInterner,
  5. exprs: Vec<Expr>,
  6. }
  7. impl Default for ASTArena {
  8. fn default() -> Self {
  9. Self::new()
  10. }
  11. }
  12. impl ASTArena {
  13. pub fn new() -> ASTArena {
  14. ASTArena {
  15. strings: string_interner::StringInterner::new(),
  16. exprs: vec![Expr::Nil],
  17. }
  18. }
  19. pub fn expr_nil(&self) -> ExprRef {
  20. ExprRef { idx: 0 }
  21. }
  22. pub fn add_expr(&mut self, e: Expr) -> ExprRef {
  23. let idx = self.exprs.len();
  24. self.exprs.push(e);
  25. ExprRef { idx }
  26. }
  27. pub fn add_string(&mut self, s: &str) -> Name {
  28. self.strings.get_or_intern(s)
  29. }
  30. pub fn show_stmt(&self, stmt: &Stmt, f: &mut fmt::Formatter) -> fmt::Result {
  31. match stmt {
  32. Stmt::Puts(expr) => {
  33. write!(f, "Puts ")?;
  34. self.show_expr(&self[*expr], f, 0)
  35. }
  36. Stmt::Fix(name) => writeln!(f, "Fix {}", &self[*name]),
  37. Stmt::Assn(fixed, name, expr) => {
  38. write!(
  39. f,
  40. "Assn {} {} ",
  41. if *fixed { "fixed" } else { "" },
  42. &self[*name]
  43. )?;
  44. self.show_expr(&self[*expr], f, 0)
  45. }
  46. Stmt::LitAssn(fixed, name, strs) => {
  47. write!(
  48. f,
  49. "LitAssn {} {}, [ ",
  50. if *fixed { "fixed" } else { "" },
  51. &self[*name],
  52. )?;
  53. for str in strs.iter() {
  54. write!(f, " {} ", str)?;
  55. }
  56. writeln!(f, "]")
  57. }
  58. }
  59. }
  60. fn indent(&self, f: &mut fmt::Formatter, depth: usize) -> fmt::Result {
  61. for _ in 0..depth {
  62. write!(f, " ")?;
  63. }
  64. Ok(())
  65. }
  66. fn show_pat(&self, pat: &Pat, f: &mut fmt::Formatter) -> fmt::Result {
  67. match pat {
  68. Pat::Wildcard => write!(f, "_"),
  69. Pat::Var(n) => write!(f, "{}", &self[*n]),
  70. Pat::Lit(Literal::Atom(n)) => write!(f, "{}", &self[*n]),
  71. Pat::Lit(lit) => write!(f, "{:?}", lit),
  72. Pat::Tup(tup) => {
  73. write!(f, "Tup( ")?;
  74. for t in tup {
  75. self.show_pat(t, f)?;
  76. write!(f, " ")?;
  77. }
  78. write!(f, ")")
  79. }
  80. }
  81. }
  82. fn show_expr(&self, expr: &Expr, f: &mut fmt::Formatter, depth: usize) -> fmt::Result {
  83. match expr {
  84. Expr::Nil => writeln!(f, "Nil"),
  85. Expr::Var(v) => writeln!(f, "Var({})", &self[*v]),
  86. Expr::Lit(Literal::Atom(n)) => writeln!(f, "Lit(Atom({}))", &self[*n]),
  87. Expr::Lit(lit) => writeln!(f, "{:?}", lit),
  88. Expr::Range(from, to) => {
  89. writeln!(f, "Range(")?;
  90. self.indent(f, depth + 2)?;
  91. self.show_expr(&self[*from], f, depth + 2)?;
  92. self.indent(f, depth + 2)?;
  93. self.show_expr(&self[*to], f, depth + 2)?;
  94. self.indent(f, depth)?;
  95. writeln!(f, ")")
  96. }
  97. Expr::Ap(func, arg) => {
  98. writeln!(f, "Ap(")?;
  99. self.indent(f, depth + 2)?;
  100. self.show_expr(&self[*func], f, depth + 2)?;
  101. self.indent(f, depth + 2)?;
  102. self.show_expr(&self[*arg], f, depth + 2)?;
  103. self.indent(f, depth)?;
  104. writeln!(f, ")")
  105. }
  106. Expr::Tup(expr) => {
  107. writeln!(f, "Tup(")?;
  108. for e in expr {
  109. self.indent(f, depth + 2)?;
  110. self.show_expr(&self[*e], f, depth + 2)?;
  111. }
  112. self.indent(f, depth)?;
  113. writeln!(f, ")")
  114. }
  115. Expr::Cat(expr) => {
  116. writeln!(f, "Cat(")?;
  117. for e in expr {
  118. self.indent(f, depth + 2)?;
  119. self.show_expr(&self[*e], f, depth + 2)?;
  120. }
  121. self.indent(f, depth)?;
  122. writeln!(f, ")")
  123. }
  124. Expr::Chc(expr) => {
  125. writeln!(f, "Chc(")?;
  126. for e in expr {
  127. if let Some(s) = e.weight {
  128. self.indent(f, depth + 2)?;
  129. writeln!(f, "{}:", s)?;
  130. self.indent(f, depth + 4)?;
  131. self.show_expr(&self[e.value], f, depth + 4)?;
  132. } else {
  133. self.indent(f, depth + 2)?;
  134. self.show_expr(&self[e.value], f, depth + 2)?;
  135. }
  136. }
  137. self.indent(f, depth)?;
  138. writeln!(f, ")")
  139. }
  140. Expr::Let(fixed, name, expr, body) => {
  141. writeln!(
  142. f,
  143. "Let({}{}",
  144. if *fixed { "fixed " } else { "" },
  145. &self[*name]
  146. )?;
  147. self.indent(f, depth + 2)?;
  148. self.show_expr(&self[*expr], f, depth + 2)?;
  149. self.indent(f, depth + 2)?;
  150. self.show_expr(&self[*body], f, depth + 2)?;
  151. self.indent(f, depth)?;
  152. writeln!(f, ")")
  153. }
  154. Expr::Fun(cases) => {
  155. writeln!(f, "Fun(")?;
  156. for case in cases {
  157. self.indent(f, depth + 2)?;
  158. self.show_pat(&case.pat, f)?;
  159. writeln!(f, " =>")?;
  160. self.indent(f, depth + 4)?;
  161. self.show_expr(&self[case.expr], f, depth + 4)?;
  162. }
  163. self.indent(f, depth)?;
  164. writeln!(f, ")")
  165. }
  166. Expr::Case(expr, cases) => {
  167. writeln!(f, "Case(")?;
  168. self.indent(f, depth)?;
  169. self.show_expr(&self[*expr], f, depth)?;
  170. for case in cases {
  171. self.indent(f, depth + 2)?;
  172. self.show_pat(&case.pat, f)?;
  173. writeln!(f, " =>")?;
  174. self.indent(f, depth + 4)?;
  175. self.show_expr(&self[case.expr], f, depth + 4)?;
  176. }
  177. self.indent(f, depth)?;
  178. writeln!(f, ")")
  179. }
  180. }
  181. }
  182. }
  183. impl std::ops::Index<string_interner::DefaultSymbol> for ASTArena {
  184. type Output = str;
  185. fn index(&self, sf: string_interner::DefaultSymbol) -> &str {
  186. self.strings.resolve(sf).unwrap()
  187. }
  188. }
  189. impl std::ops::Index<ExprRef> for ASTArena {
  190. type Output = Expr;
  191. fn index(&self, rf: ExprRef) -> &Self::Output {
  192. &self.exprs[rf.idx]
  193. }
  194. }
  195. /// A `Printable` struct is a bundle of another value and an
  196. /// `ASTArena`, which allows us to fetch the various indices and
  197. /// dereference the interned strings.
  198. pub struct Printable<'a, T> {
  199. arena: &'a ASTArena,
  200. value: &'a T,
  201. }
  202. impl<'a> std::fmt::Debug for Printable<'a, Stmt> {
  203. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  204. self.arena.show_stmt(self.value, f)
  205. }
  206. }
  207. impl<'a> std::fmt::Debug for Printable<'a, Expr> {
  208. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  209. self.arena.show_expr(self.value, f, 0)
  210. }
  211. }
  212. /// A top-level Matzo statement
  213. #[derive(Debug, Clone, PartialEq, Eq)]
  214. pub enum Stmt {
  215. /// evaluate and print the value of an expression
  216. Puts(ExprRef),
  217. /// replace a named item with the forced version of that item
  218. Fix(Name),
  219. /// assign a value to a name which may or may not be forced
  220. Assn(bool, Name, ExprRef),
  221. /// assign one of a set of strings to a name, which may or may not
  222. /// be forced
  223. LitAssn(bool, Name, Vec<String>),
  224. }
  225. impl Stmt {
  226. pub fn show<'a>(&'a self, ast: &'a ASTArena) -> Printable<'a, Stmt> {
  227. Printable {
  228. arena: ast,
  229. value: self,
  230. }
  231. }
  232. }
  233. /// A Matzo expression
  234. #[derive(Debug, Clone, PartialEq, Eq)]
  235. pub enum Expr {
  236. Var(Name),
  237. Cat(Vec<ExprRef>),
  238. Chc(Vec<Choice>),
  239. Lit(Literal),
  240. Ap(ExprRef, ExprRef),
  241. Tup(Vec<ExprRef>),
  242. Let(bool, Name, ExprRef, ExprRef),
  243. Fun(Vec<Case>),
  244. Range(ExprRef, ExprRef),
  245. Case(ExprRef, Vec<Case>),
  246. Nil,
  247. }
  248. #[derive(Debug, Copy, Clone, PartialEq, Eq)]
  249. pub struct ExprRef {
  250. idx: usize,
  251. }
  252. /// A single case in an anonymous function or `case` statement
  253. #[derive(Debug, Clone, PartialEq, Eq)]
  254. pub struct Case {
  255. pub pat: Pat,
  256. pub expr: ExprRef,
  257. }
  258. /// A pattern, e.g. in an anonymous function or `case` statement
  259. #[derive(Debug, Clone, PartialEq, Eq)]
  260. pub enum Pat {
  261. Var(Name),
  262. Wildcard,
  263. Lit(Literal),
  264. Tup(Vec<Pat>),
  265. }
  266. /// A single element in a choice, with an optional weight (which
  267. /// defaults to 1) and a value
  268. #[derive(Debug, Clone, PartialEq, Eq)]
  269. pub struct Choice {
  270. pub weight: Option<i64>,
  271. pub value: ExprRef,
  272. }
  273. impl Choice {
  274. /// Fetch a weight from a `Choice`, defaulting to 1
  275. pub fn weight(&self) -> i64 {
  276. self.weight.unwrap_or(1)
  277. }
  278. }
  279. /// An atomic literal: a string, a number, or an atom
  280. #[derive(Debug, Clone, PartialEq, Eq)]
  281. pub enum Literal {
  282. Str(String),
  283. Atom(Name),
  284. Num(i64),
  285. }