grammar.lalrpop 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. use crate::ast::*;
  2. use crate::lexer::*;
  3. grammar<'input>;
  4. extern {
  5. type Location = usize;
  6. type Error = LexerError;
  7. enum Token<'input> {
  8. "<" => Token::LAngle,
  9. ">" => Token::RAngle,
  10. "(" => Token::LPar,
  11. ")" => Token::RPar,
  12. "{" => Token::LCurl,
  13. "}" => Token::RCurl,
  14. "|" => Token::Pipe,
  15. ":" => Token::Colon,
  16. "," => Token::Comma,
  17. ";" => Token::Semi,
  18. "." => Token::Dot,
  19. ".." => Token::DotDot,
  20. ":=" => Token::Assn,
  21. "::=" => Token::LitAssn,
  22. "puts" => Token::Puts,
  23. "case" => Token::Case,
  24. "let" => Token::Let,
  25. "in" => Token::In,
  26. "var" => Token::Var(<&'input str>),
  27. "atom" => Token::Atom(<&'input str>),
  28. "num" => Token::Num(<i64>),
  29. "str" => Token::Str(<String>)
  30. }
  31. }
  32. pub Stmts: Vec<Stmt> = {
  33. <mut stmts:(<Stmt> ";")*> <stmt:Stmt?> => match stmt {
  34. None => stmts,
  35. Some(stmt) => {
  36. stmts.push(stmt);
  37. stmts
  38. }
  39. },
  40. };
  41. pub Stmt: Stmt = {
  42. "puts" <Expr> => Stmt::Puts(<>),
  43. <Name> ":=" <Expr> => Stmt::Assn(<>),
  44. <name:Name> "::=" <strs:(<Name>)*> => Stmt::LitAssn(name, strs),
  45. };
  46. pub Name: String = {
  47. "var" => <>.to_owned(),
  48. };
  49. pub Expr: Expr = {
  50. <mut ts:(<Choice> "|")*> <t:Choice> => {
  51. ts.push(t);
  52. Expr::Chc(ts)
  53. }
  54. };
  55. pub Choice: Choice = {
  56. <weight:"num"> ":" <value:Term> => Choice {
  57. weight: Some(weight),
  58. value
  59. },
  60. <value:Term> => Choice {
  61. weight: None,
  62. value
  63. }
  64. };
  65. pub Term: Expr = {
  66. (<Branch>)* => Expr::Cat(<>),
  67. };
  68. pub Branch: Expr = {
  69. <l:Branch> "." <r:Subbranch> => Expr::Ap(Box::new(l), Box::new(r)),
  70. <Subbranch> => <>,
  71. };
  72. pub Subbranch: Expr = {
  73. <l:Subbranch> ".." <r:Leaf> => Expr::Range(Box::new(l), Box::new(r)),
  74. <Leaf> => <>,
  75. }
  76. pub Leaf: Expr = {
  77. <Literal> => Expr::Lit(<>),
  78. <Name> => Expr::Var(<>),
  79. "<" <mut es:(<Expr> ",")*> <e:Expr> ">" => {
  80. es.push(e);
  81. Expr::Tup(es)
  82. },
  83. "let" <name:Name> ":=" <e1:Expr> "{" <e2:Expr> "}" =>
  84. Expr::Let(name, Box::new(e1), Box::new(e2)),
  85. "(" <e:Expr> ")" => e,
  86. };
  87. pub Literal: Literal = {
  88. "num" => Literal::Num(<>),
  89. "str" => Literal::Str(<>),
  90. "atom" => Literal::Atom(<>.to_owned()),
  91. };