Skip to main content

passgen/
prepare.rs

1//! Prepare a Pattern for generation.
2//!
3//! This is where names in a pattern are replaced with what they stand for: wordlists and
4//! Markov chains are looked up, and presets are replaced with their patterns.
5
6use crate::{Data, parser::DEPTH_LIMIT, pattern::*};
7
8/// Error preparing a pattern for generation.
9#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
10pub enum Error {
11    /// The data has no wordlist with this name.
12    #[error("wordlist '{0}' not found")]
13    WordlistNotFound(String),
14    /// The wordlist (or the Markov chain built from it) has no words.
15    #[error("wordlist '{0}' is empty")]
16    WordlistEmpty(String),
17    /// The data has no Markov chain with this depth for the wordlist with this name.
18    #[error("Markov chain of length {depth} for wordlist '{name}' not found")]
19    MarkovNotFound {
20        /// Name of the wordlist.
21        name: String,
22        /// Depth of the chain.
23        depth: usize,
24    },
25    /// The data has no preset with this name.
26    #[error("preset '{0}' not found")]
27    PresetNotFound(String),
28    /// The pattern of the preset uses the preset itself, directly or through other presets.
29    #[error("preset '{0}' contains itself")]
30    PresetRecursive(String),
31    /// With the patterns of the presets in it, the pattern is nested too deeply.
32    #[error("pattern is nested too deeply")]
33    DepthLimit,
34}
35
36/// What is needed while preparing.
37pub struct Context<'a> {
38    data: &'a dyn Data,
39    /// Names of the presets that are being replaced, from the outermost one.
40    presets: Vec<String>,
41    /// How many groups the current position is inside of.
42    depth: usize,
43}
44
45pub trait Prepare {
46    type Output;
47
48    fn prepare(self, context: &mut Context) -> Result<Self::Output, Error>;
49}
50
51impl Pattern<Optimized> {
52    /// Prepares the pattern for generation, with the wordlists, Markov chains and presets
53    /// that it uses taken from the data.
54    pub fn prepare(self, data: &dyn Data) -> Result<Pattern<Prepared>, Error> {
55        let mut context = Context {
56            data,
57            presets: Vec::new(),
58            depth: 0,
59        };
60        Prepare::prepare(self, &mut context)
61    }
62}
63
64impl Prepare for Pattern<Optimized> {
65    type Output = Pattern<Prepared>;
66
67    fn prepare(self, context: &mut Context) -> Result<Self::Output, Error> {
68        let output = match self {
69            Self::Literal(literal) => Self::Output::Literal(literal.prepare(context)?),
70            Self::Group(group) => Self::Output::Group(group.prepare(context)?),
71            Self::Set(set) => Self::Output::Set(set.prepare(context)?),
72            Self::Special(special) => special.prepare(context)?,
73        };
74        Ok(output)
75    }
76}
77
78impl Prepare for Literal<Optimized> {
79    type Output = Literal<Prepared>;
80
81    fn prepare(self, _context: &mut Context) -> Result<Self::Output, Error> {
82        Ok(Self::Output { value: self.value })
83    }
84}
85
86impl Prepare for Set<Optimized> {
87    type Output = Set<Prepared>;
88
89    fn prepare(self, _context: &mut Context) -> Result<Self::Output, Error> {
90        Ok(self.into())
91    }
92}
93
94impl Prepare for Segment<Optimized> {
95    type Output = Segment<Prepared>;
96
97    fn prepare(self, context: &mut Context) -> Result<Self::Output, Error> {
98        Ok(Self::Output {
99            weight: self.weight,
100            items: self
101                .items
102                .into_iter()
103                .map(|i| i.prepare(context))
104                .collect::<Result<_, _>>()?,
105        })
106    }
107}
108
109impl Prepare for Item<Optimized> {
110    type Output = Item<Prepared>;
111
112    fn prepare(self, context: &mut Context) -> Result<Self::Output, Error> {
113        Ok(Self::Output {
114            pattern: Prepare::prepare(self.pattern, context)?,
115            repeat: self.repeat,
116            optional: self.optional,
117        })
118    }
119}
120
121impl Prepare for Group<Optimized> {
122    type Output = Group<Prepared>;
123
124    fn prepare(self, context: &mut Context) -> Result<Self::Output, Error> {
125        // a pattern on its own cannot be nested this deeply, but presets are patterns inside
126        // of patterns. the limit is one more than for parsing, where the outermost group
127        // (the pattern itself) is not counted.
128        if context.depth > DEPTH_LIMIT {
129            return Err(Error::DepthLimit);
130        }
131
132        context.depth += 1;
133        let segments = self
134            .segments
135            .into_iter()
136            .map(|s| s.prepare(context))
137            .collect::<Result<_, _>>();
138        context.depth -= 1;
139
140        Ok(Self::Output {
141            segments: segments?,
142        })
143    }
144}
145
146impl Prepare for Special<Optimized> {
147    /// A preset is replaced with its pattern, so this does not have to be a special.
148    type Output = Pattern<Prepared>;
149
150    fn prepare(self, context: &mut Context) -> Result<Self::Output, Error> {
151        let special = match self {
152            Self::Wordlist(name) => match context.data.wordlist(&name) {
153                None => return Err(Error::WordlistNotFound(name)),
154                Some(wordlist) if wordlist.is_empty() => return Err(Error::WordlistEmpty(name)),
155                Some(wordlist) => Special::Wordlist(wordlist),
156            },
157            Self::Markov(MarkovRef { name, depth }) => match context.data.markov(&name, depth) {
158                None => return Err(Error::MarkovNotFound { name, depth }),
159                Some(markov) if markov.is_empty() => return Err(Error::WordlistEmpty(name)),
160                Some(markov) => Special::Markov(markov),
161            },
162            Self::Preset(name) => {
163                let Some(preset) = context.data.preset(&name) else {
164                    return Err(Error::PresetNotFound(name));
165                };
166                if context.presets.contains(&name) {
167                    return Err(Error::PresetRecursive(name));
168                }
169
170                // the pattern of a preset is a group, so that `\p{name}` is the same as the
171                // pattern of the preset in parentheses.
172                context.presets.push(name);
173                let pattern = Prepare::prepare(Pattern::clone(&preset), context);
174                context.presets.pop();
175                return pattern;
176            }
177        };
178        Ok(Pattern::Special(special))
179    }
180}