Bladeren bron

implement wildcard patterns

Getty Ritter 2 jaren geleden
bovenliggende
commit
395ecb8e6b
4 gewijzigde bestanden met toevoegingen van 10 en 0 verwijderingen
  1. 2 0
      src/ast.rs
  2. 2 0
      src/grammar.lalrpop
  3. 3 0
      src/interp.rs
  4. 3 0
      src/lexer.rs

+ 2 - 0
src/ast.rs

@@ -75,6 +75,7 @@ impl ASTArena {
 
     fn show_pat(&self, pat: &Pat, f: &mut fmt::Formatter) -> fmt::Result {
         match pat {
+            Pat::Wildcard => write!(f, "_"),
             Pat::Var(n) => write!(f, "{}", &self[*n]),
             Pat::Lit(Literal::Atom(n)) => write!(f, "{}", &self[*n]),
             Pat::Lit(lit) => write!(f, "{:?}", lit),
@@ -268,6 +269,7 @@ pub struct Case {
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum Pat {
     Var(Name),
+    Wildcard,
     Lit(Literal),
     Tup(Vec<Pat>),
 }

+ 2 - 0
src/grammar.lalrpop

@@ -19,6 +19,7 @@ extern {
         "," => Token::Comma,
         ";" => Token::Semi,
         "." => Token::Dot,
+        "_" => Token::Underscore,
         ".." => Token::DotDot,
         "=>" => Token::Arrow,
         ":=" => Token::Assn,
@@ -124,6 +125,7 @@ pub Case: Case = {
 };
 
 pub Pat: Pat = {
+    "_" => Pat::Wildcard,
     <Literal> => Pat::Lit(<>),
     <Name> => Pat::Var(<>),
     "<" <mut ps:(<Pat> ",")*> <p:Pat> ">" => {

+ 3 - 0
src/interp.rs

@@ -451,6 +451,9 @@ impl State {
             bindings.push((*v, scrut.clone()));
             return Ok(true);
         }
+        if let Pat::Wildcard = pat {
+            return Ok(true);
+        }
         // if it's not just a variable, then we'll need to make sure
         // we've evaluated `scrut` at least one level from here
         if let Thunk::Expr(e, env) = scrut {

+ 3 - 0
src/lexer.rs

@@ -57,6 +57,9 @@ pub enum Token<'a> {
     #[token(".")]
     Dot,
 
+    #[token("_")]
+    Underscore,
+
     #[token("..")]
     DotDot,