ast.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. type Name = String;
  2. #[derive(Debug, Clone)]
  3. pub enum Stmt {
  4. Puts(Expr),
  5. Fix(Name),
  6. Assn(Name, Expr),
  7. LitAssn(Name, Vec<String>),
  8. }
  9. #[derive(Debug, Clone)]
  10. pub enum Expr {
  11. Var(Name),
  12. Cat(Vec<Expr>),
  13. Chc(Vec<Choice>),
  14. Rep(i64, Box<Expr>),
  15. Lit(Literal),
  16. Ap(Box<Expr>, Box<Expr>),
  17. Tup(Vec<Expr>),
  18. Let(Name, Box<Expr>, Box<Expr>),
  19. Fun(Vec<Case>),
  20. Case(Box<Expr>, Vec<Case>),
  21. Range(Box<Expr>, Box<Expr>),
  22. }
  23. #[derive(Debug, Clone)]
  24. pub struct Case {
  25. pub pat: Pat,
  26. pub expr: Expr,
  27. }
  28. #[derive(Debug, Clone)]
  29. pub enum Pat {
  30. Var(Name),
  31. Lit(Literal),
  32. Tup(Vec<Pat>),
  33. }
  34. #[derive(Debug, Clone)]
  35. pub struct Choice {
  36. pub weight: Option<i64>,
  37. pub value: Expr,
  38. }
  39. impl Choice {
  40. pub fn weight(&self) -> i64 {
  41. self.weight.unwrap_or(1)
  42. }
  43. }
  44. #[derive(Debug, Clone)]
  45. pub enum Literal {
  46. Str(String),
  47. Atom(String),
  48. Num(i64),
  49. }
  50. impl Literal {
  51. pub fn from_str_literal(s: &str) -> Literal {
  52. // strip the outer pieces from the string
  53. let mut buf = String::new();
  54. let mut src = s[1..s.len() - 1].chars().into_iter();
  55. while let Some(c) = src.next() {
  56. if c == '\\' {
  57. match src.next() {
  58. Some('n') => buf.push('\n'),
  59. Some('t') => buf.push('\t'),
  60. Some('r') => buf.push('\r'),
  61. Some(c) => buf.push(c),
  62. None => panic!("bad escape"),
  63. }
  64. } else {
  65. buf.push(c);
  66. }
  67. }
  68. Literal::Str(buf)
  69. }
  70. }