Skip to main content

passgen/
optimize.rs

1//! Optimize a Pattern for generation.
2//!
3//! Optimizing never changes what is generated: an optimized pattern makes the same random
4//! choices in the same order, so it gives the same passphrases with the same entropy from
5//! the same randomness.
6//!
7//! This relies on what uses randomness when generating. A choice with only one option uses
8//! none: a group with a single segment (`(abc)`) and a set of a single character (`[a]`). The
9//! same goes for a fixed number of repetitions (`a{3}`). Whether something optional is there
10//! and a number of repetitions from a range are choices, also when nothing comes of them.
11//!
12//! What is done:
13//!
14//! - A group with a single segment is replaced with what is in it (`(abc)` becomes `abc`).
15//! - A set of a single character becomes a literal (`[a]` becomes `a`).
16//! - A literal that is repeated a fixed number of times becomes a longer literal (`a{3}`
17//!   becomes `aaa`).
18//! - Literals that follow each other become one literal.
19//! - What gives no output without any choice is removed (`()` and `a{0}`).
20
21use crate::pattern::*;
22use std::collections::BTreeSet;
23
24/// What a pattern needs to be there when it is prepared: the wordlists, Markov chains and
25/// presets that it uses.
26pub type Dependencies = BTreeSet<Special>;
27
28impl Pattern<Parsed> {
29    /// Optimizes the pattern, which does not change what it generates. Also returns what the
30    /// pattern needs to be there when it is prepared.
31    pub fn optimize(self) -> (Pattern<Optimized>, Dependencies) {
32        let mut dependencies = Dependencies::new();
33        let output = Optimize::optimize(self, &mut dependencies);
34        (output, dependencies)
35    }
36}
37
38pub trait Optimize {
39    type Output;
40
41    fn optimize(self, dependencies: &mut Dependencies) -> Self::Output;
42}
43
44impl Optimize for Literal<Parsed> {
45    type Output = Literal<Optimized>;
46
47    fn optimize(self, _dependencies: &mut Dependencies) -> Self::Output {
48        Self::Output {
49            value: self.value.to_string(),
50        }
51    }
52}
53
54impl Optimize for Special<Parsed> {
55    type Output = Special<Optimized>;
56
57    fn optimize(self, dependencies: &mut Dependencies) -> Self::Output {
58        dependencies.insert(self.clone());
59        match self {
60            Self::Wordlist(name) => Self::Output::Wordlist(name),
61            Self::Markov(name) => Self::Output::Markov(name),
62            Self::Preset(name) => Self::Output::Preset(name),
63        }
64    }
65}
66
67impl Optimize for Set<Parsed> {
68    type Output = Set<Optimized>;
69
70    fn optimize(self, _dependencies: &mut Dependencies) -> Self::Output {
71        self.into()
72    }
73}
74
75impl Optimize for Item<Parsed> {
76    type Output = Item<Optimized>;
77
78    fn optimize(self, dependencies: &mut Dependencies) -> Self::Output {
79        Self::Output {
80            pattern: Optimize::optimize(self.pattern, dependencies),
81            repeat: self.repeat,
82            optional: self.optional,
83        }
84    }
85}
86
87/// Largest literal that a repeated literal is replaced with, in bytes.
88const EXPAND_LIMIT: usize = 256;
89
90impl Pattern<Optimized> {
91    /// Whether generating this makes no random choice and gives no output.
92    fn is_nothing(&self) -> bool {
93        match self {
94            Pattern::Literal(literal) => literal.value.is_empty(),
95            // a single segment (which is not a choice) with nothing in it. with more than
96            // one segment there is a choice, even when all of them are empty.
97            Pattern::Group(group) => match &group.segments[..] {
98                [segment] => segment.items.is_empty(),
99                _ => false,
100            },
101            Pattern::Set(_) | Pattern::Special(_) => false,
102        }
103    }
104}
105
106impl Item<Optimized> {
107    /// Whether the item is there once every time, with nothing to choose about it.
108    fn is_modified(&self) -> bool {
109        self.optional || self.repeat != (1..=1)
110    }
111
112    /// Whether generating this makes no random choice and gives no output, so that it can be
113    /// left out.
114    fn is_nothing(&self) -> bool {
115        // whether it is there and how many times are choices, even when it is nothing.
116        if self.optional || self.repeat.start() != self.repeat.end() {
117            return false;
118        }
119
120        *self.repeat.start() == 0 || self.pattern.is_nothing()
121    }
122
123    /// Replaces a group that has a single segment with what is in the segment, where that
124    /// is the same. Such a group is not a choice.
125    ///
126    /// Without modifiers on the group, the items of the segment take its place: `a(bc)d` is
127    /// `abcd`. With them, this only works for a single item without modifiers of its own,
128    /// which gets those of the group: `([a-z]){3}` is `[a-z]{3}`.
129    fn flatten(self) -> Vec<Self> {
130        let modified = self.is_modified();
131        let Self {
132            pattern,
133            repeat,
134            optional,
135        } = self;
136
137        let pattern = match pattern {
138            Pattern::Group(mut group) if group.segments.len() == 1 => {
139                let items = &mut group.segments[0].items;
140                if !modified {
141                    return std::mem::take(items);
142                }
143                match &items[..] {
144                    [item] if !item.is_modified() => items.remove(0).pattern,
145                    _ => Pattern::Group(group),
146                }
147            }
148            pattern => pattern,
149        };
150
151        vec![Self {
152            pattern,
153            repeat,
154            optional,
155        }]
156    }
157
158    /// Replaces a set of a single character with a literal (which is not a choice either),
159    /// and a literal that is repeated a fixed number of times with a longer literal, as in
160    /// `a{3}`, which is the same as `aaa`.
161    fn simplify(mut self) -> Self {
162        if let Pattern::Set(set) = &self.pattern
163            && let Some(character) = set.single()
164        {
165            self.pattern = Pattern::Literal(Literal {
166                value: character.to_string(),
167            });
168        }
169
170        let amount = *self.repeat.start();
171        if self.optional || amount != *self.repeat.end() {
172            return self;
173        }
174
175        if let Pattern::Literal(literal) = &mut self.pattern
176            && literal.value.len().saturating_mul(amount) <= EXPAND_LIMIT
177        {
178            literal.value = literal.value.repeat(amount);
179            self.repeat = 1..=1;
180        }
181
182        self
183    }
184
185    /// Adds a literal to the end of this one, if both are literals that are not modified.
186    fn try_fuse(&mut self, item: Self) -> Result<(), Self> {
187        if self.is_modified() || item.is_modified() {
188            return Err(item);
189        }
190
191        match (&mut self.pattern, &item.pattern) {
192            (Pattern::Literal(left), Pattern::Literal(right)) => {
193                left.value.push_str(&right.value);
194                Ok(())
195            }
196            _ => Err(item),
197        }
198    }
199}
200
201impl Optimize for Segment<Parsed> {
202    type Output = Segment<Optimized>;
203
204    fn optimize(self, dependencies: &mut Dependencies) -> Self::Output {
205        Self::Output {
206            weight: self.weight,
207            items: self
208                .items
209                .into_iter()
210                .map(|item| item.optimize(dependencies))
211                .flat_map(Item::flatten)
212                .map(Item::simplify)
213                .filter(|item| !item.is_nothing())
214                // literals that follow each other become one
215                .fold(Vec::new(), |mut items, item| {
216                    if let Some(last) = items.last_mut() {
217                        if let Err(item) = last.try_fuse(item) {
218                            items.push(item);
219                        }
220                    } else {
221                        items.push(item);
222                    }
223                    items
224                }),
225        }
226    }
227}
228
229impl Optimize for Group<Parsed> {
230    type Output = Group<Optimized>;
231
232    fn optimize(self, dependencies: &mut Dependencies) -> Self::Output {
233        Self::Output {
234            segments: self
235                .segments
236                .into_iter()
237                .map(|segment| segment.optimize(dependencies))
238                .collect(),
239        }
240    }
241}
242
243impl Optimize for Pattern<Parsed> {
244    type Output = Pattern<Optimized>;
245
246    fn optimize(self, dependencies: &mut Dependencies) -> Self::Output {
247        match self {
248            Self::Group(group) => Self::Output::Group(group.optimize(dependencies)),
249            Self::Set(set) => Self::Output::Set(set.optimize(dependencies)),
250            Self::Literal(literal) => Self::Output::Literal(literal.optimize(dependencies)),
251            Self::Special(special) => Self::Output::Special(special.optimize(dependencies)),
252        }
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use crate::random::{RandomDesc, RandomSource};
260    use test_strategy::proptest;
261
262    /// Converts a pattern without optimizing anything.
263    fn plain(pattern: Pattern<Parsed>) -> Pattern<Optimized> {
264        match pattern {
265            Pattern::Literal(literal) => Pattern::Literal(Literal {
266                value: literal.value.to_string(),
267            }),
268            Pattern::Set(set) => Pattern::Set(set.into()),
269            Pattern::Special(special) => {
270                Pattern::Special(special.optimize(&mut Dependencies::new()))
271            }
272            Pattern::Group(group) => Pattern::Group(Group {
273                segments: group
274                    .segments
275                    .into_iter()
276                    .map(|segment| Segment {
277                        weight: segment.weight,
278                        items: segment
279                            .items
280                            .into_iter()
281                            .map(|item| Item {
282                                pattern: plain(item.pattern),
283                                repeat: item.repeat,
284                                optional: item.optional,
285                            })
286                            .collect(),
287                    })
288                    .collect(),
289            }),
290        }
291    }
292
293    fn optimized(pattern: &str) -> Pattern<Optimized> {
294        Pattern::parse(pattern).unwrap().optimize().0
295    }
296
297    /// Passphrases with their entropy from a number of seeds.
298    fn generate(pattern: Pattern<Optimized>) -> Vec<(String, crate::Entropy)> {
299        let pattern = pattern.prepare(&()).unwrap();
300        (1..=16)
301            .map(|seed| {
302                let random: RandomDesc = format!("xorshift:{seed}").parse().unwrap();
303                let random = random.open().unwrap();
304                pattern
305                    .generate_with_entropy(&mut random.stream(0))
306                    .unwrap()
307            })
308            .collect()
309    }
310
311    #[test]
312    fn literals() {
313        assert_eq!(optimized("a{3}b{2}c"), optimized("aaabbc"));
314        assert_eq!(optimized("ab{0}c"), optimized("ac"));
315        assert_eq!(optimized("a(b){0}c[d]{0}"), optimized("ac"));
316
317        // too long to write out.
318        let long = optimized("a{1000}");
319        assert_ne!(long, optimized(&"a".repeat(1000)));
320    }
321
322    /// Groups with a single segment are not a choice, so what is in them takes their place.
323    #[test]
324    fn groups_with_one_segment() {
325        assert_eq!(optimized("(abc)"), optimized("abc"));
326        assert_eq!(optimized("a(b)c"), optimized("abc"));
327        assert_eq!(optimized("a((b)(c(d)))e"), optimized("abcde"));
328        assert_eq!(optimized("({3}abc)"), optimized("abc"));
329        assert_eq!(optimized("a([b-c]d?)e"), optimized("a[b-c]d?e"));
330
331        // modifiers of the group go to a single item in it.
332        assert_eq!(optimized("(a){3}"), optimized("aaa"));
333        assert_eq!(optimized("(ab){2}c"), optimized("ababc"));
334        assert_eq!(optimized("([a-z]){2,3}"), optimized("[a-z]{2,3}"));
335        assert_eq!(optimized("(([a-z]))?"), optimized("[a-z]?"));
336        assert_eq!(optimized(r"(\w{words}){2}"), optimized(r"\w{words}{2}"));
337
338        // not when there is more than one item, or it has modifiers of its own.
339        assert_ne!(optimized("(a[b-c]){2}"), optimized("a[b-c]{2}"));
340        assert_ne!(optimized("([a-z]?){2}"), optimized("[a-z]{2}"));
341        assert_ne!(optimized("([a-z]{2}){3}"), optimized("[a-z]{6}"));
342
343        // groups with more than one segment are a choice.
344        assert_ne!(optimized("(a|b)"), optimized("ab"));
345    }
346
347    /// Sets of a single character are not a choice.
348    #[test]
349    fn sets_of_one_character() {
350        assert_eq!(optimized("[a]"), optimized("a"));
351        assert_eq!(optimized("x[a][bb][c-c]y"), optimized("xabcy"));
352        assert_eq!(optimized("[a]{3}"), optimized("aaa"));
353        assert_ne!(optimized("[ab]"), optimized("a"));
354        assert_ne!(optimized("[a]?"), optimized("a"));
355    }
356
357    /// Groups that are empty are removed, unless there is a choice about them.
358    #[test]
359    fn empty_groups() {
360        assert_eq!(optimized("()"), optimized(""));
361        assert_eq!(optimized("a()b(){3}c(())"), optimized("abc"));
362        assert_eq!(optimized("a(b{0})c"), optimized("ac"));
363        assert_ne!(optimized("a()?b"), optimized("ab"));
364        assert_ne!(optimized("a(){1,2}b"), optimized("ab"));
365        assert_ne!(optimized("a(|)b"), optimized("ab"));
366    }
367
368    /// Groups with a segment that is empty are not empty.
369    #[test]
370    fn empty_segments() {
371        for pattern in ["x(a|)y", "x(|a)y", "x(a|b|)y", "x(a|(|b))y", "(a|){8}"] {
372            let outputs: std::collections::BTreeSet<String> = generate(optimized(pattern))
373                .into_iter()
374                .map(|(output, _)| output)
375                .collect();
376            assert!(outputs.len() > 1, "{pattern}: {outputs:?}");
377        }
378    }
379
380    /// What has a choice in it is kept, even when it gives no output.
381    #[test]
382    fn choices_are_kept() {
383        for pattern in [
384            "a{0}?b",
385            "(a{0}|b{0})c",
386            "()?a",
387            "[a]?b",
388            "(a)?b",
389            "(|)a",
390            "a{0,3}",
391            "(){0,2}",
392            "([a-z]?){2}",
393        ] {
394            let parsed = Pattern::parse(pattern).unwrap();
395            assert_eq!(
396                generate(parsed.clone().optimize().0),
397                generate(plain(parsed)),
398                "{pattern}"
399            );
400        }
401    }
402
403    /// Optimizing does not change what is generated, nor the entropy of it.
404    #[proptest]
405    fn same_as_not_optimized(
406        #[strategy(
407            r"([ab(|)?]|[()]|\[a-c\]|\[a\]|\[bb\]|\{[0-3]\}|\{[0-2],[2-4]\}|\(\{[0-2]\}){0,16}"
408        )]
409        pattern: String,
410    ) {
411        if let Ok(parsed) = Pattern::parse(&pattern) {
412            assert_eq!(
413                generate(parsed.clone().optimize().0),
414                generate(plain(parsed)),
415                "{pattern}"
416            );
417        }
418    }
419}