harper_core/patterns/
either_pattern.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use crate::Token;

use super::Pattern;

/// A pattern that returns the value of the first non-zero match in a list.
#[derive(Default)]
pub struct EitherPattern {
    patterns: Vec<Box<dyn Pattern>>,
}

impl EitherPattern {
    pub fn new(patterns: Vec<Box<dyn Pattern>>) -> Self {
        Self { patterns }
    }

    pub fn add(&mut self, pattern: Box<dyn Pattern>) {
        self.patterns.push(pattern);
    }
}

impl Pattern for EitherPattern {
    fn matches(&self, tokens: &[Token], source: &[char]) -> usize {
        for pattern in self.patterns.iter() {
            let match_len = pattern.matches(tokens, source);

            if match_len > 0 {
                return match_len;
            }
        }

        0
    }
}