ast.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. use std::fmt;
  2. pub type Name = string_interner::DefaultSymbol;
  3. pub struct ASTArena {
  4. strings: string_interner::StringInterner,
  5. }
  6. pub struct Debuggable<'a, T> {
  7. arena: &'a ASTArena,
  8. value: &'a T,
  9. }
  10. impl<'a> std::fmt::Debug for Debuggable<'a, Stmt> {
  11. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  12. self.arena.show_stmt(self.value, f)
  13. }
  14. }
  15. impl ASTArena {
  16. pub fn new() -> ASTArena {
  17. ASTArena {
  18. strings: string_interner::StringInterner::new(),
  19. }
  20. }
  21. pub fn add_string(&mut self, s: &str) -> Name {
  22. self.strings.get_or_intern(s)
  23. }
  24. pub fn show_stmt(&self, stmt: &Stmt, f: &mut fmt::Formatter) -> fmt::Result {
  25. match stmt {
  26. Stmt::Puts(expr) =>
  27. writeln!(f, "{:?}", expr),
  28. Stmt::Fix(name) =>
  29. writeln!(f, "Fix({})", &self[*name]),
  30. Stmt::Assn(name, expr) =>
  31. writeln!(f, "Assn(\n {},\n {:?}\n)", &self[*name], expr),
  32. Stmt::LitAssn(name, strs) => {
  33. write!(f, "LitAssn({}, [ ", &self[*name])?;
  34. for str in strs.iter() {
  35. write!(f, " {} ", str)?;
  36. }
  37. writeln!(f, "]")
  38. }
  39. }
  40. }
  41. }
  42. impl std::ops::Index<string_interner::DefaultSymbol> for ASTArena {
  43. type Output = str;
  44. fn index(&self, sf: string_interner::DefaultSymbol) -> &str {
  45. self.strings.resolve(sf).unwrap()
  46. }
  47. }
  48. #[derive(Debug, Clone)]
  49. pub enum Stmt {
  50. Puts(Expr),
  51. Fix(Name),
  52. Assn(Name, Expr),
  53. LitAssn(Name, Vec<String>),
  54. }
  55. impl Stmt {
  56. pub fn show<'a>(&'a self, ast: &'a ASTArena) -> Debuggable<'a, Stmt> {
  57. Debuggable {
  58. arena: ast,
  59. value: self,
  60. }
  61. }
  62. }
  63. #[derive(Debug, Clone)]
  64. pub enum Expr {
  65. Var(Name),
  66. Cat(Vec<Expr>),
  67. Chc(Vec<Choice>),
  68. Rep(i64, Box<Expr>),
  69. Lit(Literal),
  70. Ap(Box<Expr>, Box<Expr>),
  71. Tup(Vec<Expr>),
  72. Let(Name, Box<Expr>, Box<Expr>),
  73. Fun(Vec<Case>),
  74. Case(Box<Expr>, Vec<Case>),
  75. Range(Box<Expr>, Box<Expr>),
  76. }
  77. #[derive(Debug, Clone)]
  78. pub struct Case {
  79. pub pat: Pat,
  80. pub expr: Expr,
  81. }
  82. #[derive(Debug, Clone)]
  83. pub enum Pat {
  84. Var(Name),
  85. Lit(Literal),
  86. Tup(Vec<Pat>),
  87. }
  88. #[derive(Debug, Clone)]
  89. pub struct Choice {
  90. pub weight: Option<i64>,
  91. pub value: Expr,
  92. }
  93. impl Choice {
  94. pub fn weight(&self) -> i64 {
  95. self.weight.unwrap_or(1)
  96. }
  97. }
  98. #[derive(Debug, Clone)]
  99. pub enum Literal {
  100. Str(String),
  101. Atom(Name),
  102. Num(i64),
  103. }