srgn 0.14.2

A grep-like tool which understands source code syntax and allows for manipulation in addition to search
Documentation
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::collections::VecDeque;

#[cfg(test)]
use enum_iterator::{Sequence, all};

#[cfg(all(doc, feature = "german"))]
use super::German;
use crate::actions::Action;

pub mod inversion;

/// Replace ASCII symbols (`--`, `->`, `!=`, ...) with proper Unicode equivalents (`–`,
/// `→`, `≠`, ...).
///
/// This action is greedy, i.e. it will try to replace as many symbols as possible,
/// replacing left-to-right as greedily as possible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Symbols {}

macro_rules! fetch_next {
    ($it:expr, $stack:expr, $buf:expr $(, $label:tt)?) => {
        if let Some(c) = $it.pop_front() {
            $stack.push(c);
            c
        } else {
            $buf.push_str(&$stack.into_iter().collect::<String>());

            // Control flow, thus a macro is required. Optionally, allow a label for
            // more control, e.g. when looping while waiting.
            break $($label)?;
        }
    };
}

impl Action for Symbols {
    /// ## Implementation note
    ///
    /// Only relevant when looking at the source code.
    ///
    /// The implementation is in the style of coroutines as presented [in this
    /// article](https://www.chiark.greenend.org.uk/~sgtatham/quasiblog/coroutines-philosophy/).
    /// Instead of constructing an explicit state machine (like in [`German`]), we
    /// use a generator coroutine to consume values from. The position in code itself is
    /// then our state. `undo_overfetching` is a bit like sending a value back into the
    /// coroutine so it can be yielded again.
    ///
    /// All in all, ugly and verbose, would not recommend, but a worthwhile experiment.
    #[expect(clippy::cognitive_complexity)] // Yep, it's terrible alright
    fn act(&self, input: &str) -> String {
        let mut deque = input.chars().collect::<VecDeque<_>>();
        let mut out = String::new();

        'outer: loop {
            let mut stack = Vec::new();

            match fetch_next!(deque, stack, out) {
                '-' => match fetch_next!(deque, stack, out) {
                    '-' => {
                        // Be greedy, could be last character
                        replace(&mut stack, Symbol::EnDash);

                        match fetch_next!(deque, stack, out) {
                            '-' => replace(&mut stack, Symbol::EmDash),
                            '>' => replace(&mut stack, Symbol::LongRightArrow),
                            _ => undo_overfetching(&mut deque, &mut stack),
                        }
                    }
                    '>' => replace(&mut stack, Symbol::ShortRightArrow),
                    _ => undo_overfetching(&mut deque, &mut stack),
                },
                '<' => match fetch_next!(deque, stack, out) {
                    '-' => {
                        // Be greedy, could be last character
                        replace(&mut stack, Symbol::ShortLeftArrow);

                        match fetch_next!(deque, stack, out) {
                            '-' => replace(&mut stack, Symbol::LongLeftArrow),
                            '>' => replace(&mut stack, Symbol::LeftRightArrow),
                            _ => undo_overfetching(&mut deque, &mut stack),
                        }
                    }
                    '=' => replace(&mut stack, Symbol::LessThanOrEqual),
                    _ => undo_overfetching(&mut deque, &mut stack),
                },
                '>' => match fetch_next!(deque, stack, out) {
                    '=' => replace(&mut stack, Symbol::GreaterThanOrEqual),
                    _ => undo_overfetching(&mut deque, &mut stack),
                },
                '!' => match fetch_next!(deque, stack, out) {
                    '=' => replace(&mut stack, Symbol::NotEqual),
                    _ => undo_overfetching(&mut deque, &mut stack),
                },
                '=' => match fetch_next!(deque, stack, out) {
                    '>' => replace(&mut stack, Symbol::RightDoubleArrow),
                    _ => undo_overfetching(&mut deque, &mut stack),
                },
                // "Your scientists were so preoccupied with whether or not they could,
                // they didn't stop to think if they should." ... this falls into the
                // "shouldn't" category:
                'h' => match fetch_next!(deque, stack, out) {
                    't' => match fetch_next!(deque, stack, out) {
                        't' => match fetch_next!(deque, stack, out) {
                            'p' => match fetch_next!(deque, stack, out) {
                                // Sorry, `http` not supported. Neither is `ftp`,
                                // `file`, ...
                                's' => match fetch_next!(deque, stack, out) {
                                    ':' => match fetch_next!(deque, stack, out) {
                                        '/' => match fetch_next!(deque, stack, out) {
                                            '/' => loop {
                                                match fetch_next!(deque, stack, out, 'outer) {
                                                    ' ' | '"' => break,
                                                    _ => {
                                                        // building up stack, ignoring
                                                        // all characters other than
                                                        // non-URI ones
                                                    }
                                                }
                                            },
                                            _ => undo_overfetching(&mut deque, &mut stack),
                                        },
                                        _ => undo_overfetching(&mut deque, &mut stack),
                                    },
                                    _ => undo_overfetching(&mut deque, &mut stack),
                                },
                                _ => undo_overfetching(&mut deque, &mut stack),
                            },
                            _ => undo_overfetching(&mut deque, &mut stack),
                        },
                        _ => undo_overfetching(&mut deque, &mut stack),
                    },
                    _ => undo_overfetching(&mut deque, &mut stack),
                },
                _ => {}
            }

            out.push_str(&stack.into_iter().collect::<String>());
        }

        out
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(test, derive(Sequence))]
enum Symbol {
    // Typographic symbols
    EmDash,
    EnDash,
    // Arrows
    ShortRightArrow,
    ShortLeftArrow,
    LongRightArrow,
    LongLeftArrow,
    LeftRightArrow,
    RightDoubleArrow,
    // Math
    NotEqual,
    LessThanOrEqual,
    GreaterThanOrEqual,
}

impl From<Symbol> for char {
    fn from(symbol: Symbol) -> Self {
        match symbol {
            Symbol::EnDash => '',
            Symbol::EmDash => '',
            //
            Symbol::ShortRightArrow => '',
            Symbol::ShortLeftArrow => '',
            Symbol::LongRightArrow => '',
            Symbol::LongLeftArrow => '',
            Symbol::LeftRightArrow => '',
            Symbol::RightDoubleArrow => '',
            //
            Symbol::NotEqual => '',
            Symbol::LessThanOrEqual => '',
            Symbol::GreaterThanOrEqual => '',
        }
    }
}

impl TryFrom<char> for Symbol {
    type Error = ();

    fn try_from(c: char) -> Result<Self, Self::Error> {
        match c {
            // Typographic symbols
            '' => Ok(Self::EnDash),
            '' => Ok(Self::EmDash),
            // Arrows
            '' => Ok(Self::ShortRightArrow),
            '' => Ok(Self::ShortLeftArrow),
            '' => Ok(Self::LongRightArrow),
            '' => Ok(Self::LongLeftArrow),
            '' => Ok(Self::LeftRightArrow),
            '' => Ok(Self::RightDoubleArrow),
            // Math
            '' => Ok(Self::NotEqual),
            '' => Ok(Self::LessThanOrEqual),
            '' => Ok(Self::GreaterThanOrEqual),
            _ => Err(()),
        }
    }
}

/// We might greedily overfetch and then end up with a [`char`] on the `stack` we do not
/// know how to handle. However, *subsequent, other states might*. Hence, be a good
/// citizen and put it back where it came from.
///
/// This allows matching sequences like `--!=` to be `–≠`, which might otherwise end up
/// as `–!=` (because the next iteration only sees `=`, `!` was already consumed).
fn undo_overfetching<T>(deque: &mut VecDeque<T>, stack: &mut Vec<T>) {
    deque.push_front(
        stack
            .pop()
            .expect("Pop should only happen after having just pushed, so stack shouldn't be empty"),
    );
}

/// Replace the entire `stack` with the given `symbol`.
fn replace(stack: &mut Vec<char>, symbol: Symbol) {
    stack.clear();
    stack.push(symbol.into());
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case("", "")]
    #[case(" ", " ")]
    // Typographic symbols
    #[case("--", "")]
    #[case("---", "")]
    // Arrows
    #[case("->", "")]
    #[case("-->", "")]
    #[case("<-", "")]
    #[case("<--", "")]
    #[case("<->", "")]
    #[case("=>", "")]
    // Math
    #[case("<=", "")]
    #[case(">=", "")]
    #[case("!=", "")]
    fn test_symbol_substitution_base_cases(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("A-", "A-")]
    #[case("A--", "A–")]
    #[case("A---", "A—")]
    //
    #[case("-A", "-A")]
    #[case("--A", "–A")]
    #[case("---A", "—A")]
    //
    #[case("A->", "A→")]
    #[case("A-->", "A⟶")]
    #[case("A<->", "A↔")]
    #[case("A=>", "A⇒")]
    //
    #[case("<-A", "←A")]
    #[case("<--A", "⟵A")]
    #[case("<->A", "↔A")]
    #[case("=>A", "⇒A")]
    //
    #[case("A<=", "A≤")]
    #[case("A>=", "A≥")]
    #[case("A!=", "A≠")]
    fn test_symbol_substitution_neighboring_single_letter(
        #[case] input: &str,
        #[case] expected: &str,
    ) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("A-B", "A-B")]
    #[case("A--B", "A–B")]
    #[case("A---B", "A—B")]
    //
    #[case("A->B", "A→B")]
    #[case("A-->B", "A⟶B")]
    #[case("A<->B", "A↔B")]
    #[case("A=>B", "A⇒B")]
    #[case("A<-B", "A←B")]
    #[case("A<--B", "A⟵B")]
    #[case("A<->B", "A↔B")]
    #[case("A=>B", "A⇒B")]
    //
    #[case("A<=B", "A≤B")]
    #[case("A>=B", "A≥B")]
    #[case("A!=B", "A≠B")]
    fn test_symbol_substitution_neighboring_letters(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("A - B", "A - B")]
    #[case("A -- B", "A – B")]
    #[case("A --- B", "A — B")]
    //
    #[case("A -> B", "A → B")]
    #[case("A --> B", "A ⟶ B")]
    #[case("A <-> B", "A ↔ B")]
    #[case("A => B", "A ⇒ B")]
    #[case("A <- B", "A ← B")]
    #[case("A <-- B", "A ⟵ B")]
    #[case("A <-> B", "A ↔ B")]
    #[case("A => B", "A ⇒ B")]
    //
    #[case("A <= B", "A ≤ B")]
    #[case("A >= B", "A ≥ B")]
    #[case("A != B", "A ≠ B")]
    fn test_symbol_substitution_neighboring_letters_with_spaces(
        #[case] input: &str,
        #[case] expected: &str,
    ) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("-X-", "-X-")]
    #[case("--X--", "–X–")]
    #[case("---X---", "—X—")]
    //
    #[case("-X>", "-X>")]
    #[case("->X->", "→X→")]
    #[case("--X-->", "–X⟶")]
    #[case("---X-->", "—X⟶")]
    //
    #[case("<-X-", "←X-")]
    #[case("<--X--", "⟵X–")]
    //
    #[case("<--X-->", "⟵X⟶")]
    fn test_symbol_substitution_disrupting_symbols(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("I breathe -- I live.", "I breathe – I live.")]
    #[case("To think---to breathe.", "To think—to breathe.")]
    #[case("A joke --> A laugh.", "A joke ⟶ A laugh.")]
    #[case("A <= B => C", "A ≤ B ⇒ C")]
    #[case("->In->Out->", "→In→Out→")]
    fn test_symbol_substitution_sentences(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("----", "—-")]
    #[case("-----", "—–")]
    #[case("------", "——")]
    //
    #[case(">->", ">→")]
    #[case("->->", "→→")]
    #[case("->-->", "→⟶")]
    #[case("->--->", "→—>")]
    #[case("->--->->", "→—>→")]
    //
    #[case("<-<-", "←←")]
    #[case("<-<--", "←⟵")]
    #[case("<-<---", "←⟵-")]
    #[case("<-<---<", "←⟵-<")]
    //
    #[case("<->->", "↔→")]
    #[case("<-<->->", "←↔→")]
    //
    #[case("<=<=", "≤≤")]
    #[case("<=<=<=", "≤≤≤")]
    #[case(">=>=", "≥≥")]
    #[case(">=>=>=", "≥≥≥")]
    //
    #[case(">=<=", "≥≤")]
    #[case(">=<=<=", "≥≤≤")]
    //
    #[case("!=!=", "≠≠")]
    #[case("!=!=!=", "≠≠≠")]
    fn test_symbol_substitution_ambiguous_sequences(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    #[case("", "")]
    fn test_symbol_substitution_existing_symbol(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case("https://www.example.com", "https://www.example.com")]
    #[case("https://www.example.com/", "https://www.example.com/")]
    #[case("https://www.example.com/->", "https://www.example.com/->")]
    //
    #[case("\"https://www.example.com/\"->", "\"https://www.example.com/\"")]
    #[case("https://www.example.com/ ->", "https://www.example.com/ →")]
    //
    #[case("h->", "h→")]
    #[case("ht->", "ht→")]
    #[case("htt->", "htt→")]
    #[case("http->", "http→")]
    #[case("https->", "https→")]
    #[case("https:->", "https:→")]
    #[case("https:/->", "https:/→")]
    #[case("https://->", "https://->")] // Pivot point
    fn test_symbol_substitution_uri(#[case] input: &str, #[case] expected: &str) {
        let action = Symbols::default();
        let result = action.act(input);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_symbol_to_char_and_back_is_bijective() {
        let symbols: Vec<_> = all::<Symbol>().collect();

        for symbol in symbols {
            let c = char::from(symbol);
            let back = Symbol::try_from(c).expect("Should be able to convert back to symbol");

            assert_eq!(symbol, back);
        }
    }
}