1use crate::{Data, parser::DEPTH_LIMIT, pattern::*};
7
8#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
10pub enum Error {
11 #[error("wordlist '{0}' not found")]
13 WordlistNotFound(String),
14 #[error("wordlist '{0}' is empty")]
16 WordlistEmpty(String),
17 #[error("Markov chain of length {depth} for wordlist '{name}' not found")]
19 MarkovNotFound {
20 name: String,
22 depth: usize,
24 },
25 #[error("preset '{0}' not found")]
27 PresetNotFound(String),
28 #[error("preset '{0}' contains itself")]
30 PresetRecursive(String),
31 #[error("pattern is nested too deeply")]
33 DepthLimit,
34}
35
36pub struct Context<'a> {
38 data: &'a dyn Data,
39 presets: Vec<String>,
41 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 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 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 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 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}