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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use std::borrow::Cow;
use std::fmt;

use itertools::Itertools;
use log::{debug, trace, warn};

use crate::actions::{self, Action, ActionError};
use crate::scoping::Scoper;
use crate::scoping::dosfix::DosFix;
use crate::scoping::scope::Scope::{In, Out};
#[cfg(doc)]
use crate::scoping::scope::ScopeContext;
use crate::scoping::scope::{ROScope, ROScopes, RWScope, RWScopes};

/// A view of some input, sorted into parts, which are either [`In`] or [`Out`] of scope
/// for processing.
///
/// The view is **writable**. It can be manipulated by
/// [mapping][`Self::map_without_context`] [`Action`]s over it.
///
/// The main avenue for constructing a view is [`Self::builder`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedView<'viewee> {
    scopes: RWScopes<'viewee>,
}

/// Core implementations.
impl<'viewee> ScopedView<'viewee> {
    /// Create a new view from the given scopes.
    #[must_use]
    pub const fn new(scopes: RWScopes<'viewee>) -> Self {
        Self { scopes }
    }

    /// Access the scopes contained in this view.
    #[must_use]
    pub const fn scopes(&self) -> &RWScopes<'viewee> {
        &self.scopes
    }

    /// Return a builder for a view of the given input.
    ///
    /// For API discoverability.
    #[must_use]
    pub fn builder(input: &'viewee str) -> ScopedViewBuilder<'viewee> {
        ScopedViewBuilder::new(input)
    }

    /// Apply an `action` to all [`In`] scope items contained in this view.
    ///
    /// They are **replaced** with whatever the action returns for the particular scope.
    /// This method is infallible, as it does not access any [`ScopeContext`].
    ///
    /// See implementors of [`Action`] for available types.
    ///
    /// # Panics
    ///
    /// On internal programming error - "cannot happen".
    pub fn map_without_context(&mut self, action: &impl Action) -> &mut Self {
        self.map_impl(action, false)
            .expect("not accessing context, so is infallible");

        self
    }

    /// Same as [`Self::map_without_context`], but will access any [`ScopeContext`],
    /// which is fallible.
    ///
    /// # Errors
    ///
    /// See the concrete type of the [`Err`] variant for when this method errors.
    pub fn map_with_context(&mut self, action: &impl Action) -> Result<&mut Self, ActionError> {
        self.map_impl(action, true)?;

        Ok(self)
    }

    fn map_impl(
        &mut self,
        action: &impl Action,
        use_context: bool,
    ) -> Result<&mut Self, ActionError> {
        for scope in &mut self.scopes.0 {
            match scope {
                RWScope(In(s, ctx)) => {
                    debug!("Mapping with context: {ctx:?}");
                    let res = match (&ctx, use_context) {
                        (Some(c), true) => action.act_with_context(s, c)?,
                        _ => action.act(s),
                    };
                    debug!(
                        "Replacing '{}' with '{}'",
                        s.escape_debug(),
                        res.escape_debug()
                    );
                    *scope = RWScope(In(Cow::Owned(res), ctx.clone()));
                }
                RWScope(Out(s)) => {
                    debug!("Appending '{}'", s.escape_debug());
                }
            }
        }

        Ok(self)
    }

    /// Squeeze all consecutive [`In`] scopes into a single occurrence (the first one).
    pub fn squeeze(&mut self) -> &mut Self {
        debug!("Squeezing view by collapsing all consecutive in-scope occurrences.");

        let mut prev_was_in = false;
        self.scopes.0.retain(|scope| {
            let keep = !(prev_was_in && matches!(scope, RWScope(In { .. })));
            prev_was_in = matches!(scope, RWScope(In { .. }));
            trace!("keep: {keep}, scope: {scope:?}");
            keep
        });

        debug!("Squeezed: {:?}", self.scopes);

        self
    }

    /// Check whether anything is [`In`] scope for this view.
    #[must_use]
    pub fn has_any_in_scope(&self) -> bool {
        self.scopes.0.iter().any(|s| match s {
            RWScope(In { .. }) => true,
            RWScope(Out { .. }) => false,
        })
    }

    /// Split this item at newlines, into multiple [`ScopedView`]s.
    ///
    /// Scopes are retained, and broken across lines as needed.
    #[must_use]
    pub fn lines(&self) -> ScopedViewLines<'_> {
        let mut lines = Vec::new();
        let mut curr = Vec::new();

        for parent_scope in &self.scopes.0 {
            let s: &str = parent_scope.into();

            for potential_line in s.split_inclusive('\n') {
                // Is it supposed to be in or out of scope?
                let child_scope = match &parent_scope.0 {
                    In(_, ctx) => In(Cow::Borrowed(potential_line), ctx.clone()),
                    Out(_) => Out(potential_line),
                };

                // String might not have *any* newlines, so this isn't redundant
                let seen_newline = potential_line.ends_with('\n');

                curr.push(RWScope(child_scope));

                if seen_newline {
                    // Flush out
                    lines.push(RWScopes(curr));
                    curr = Vec::new();
                }
            }
        }

        if !curr.is_empty() {
            // Tail that wasn't flushed yet
            lines.push(RWScopes(curr));
        }

        ScopedViewLines(lines.into_iter().map(ScopedView::new).collect_vec())
    }
}

/// A view over a [`ScopedView`], split by its individual lines. Each line is its own
/// [`ScopedView`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedViewLines<'viewee>(Vec<ScopedView<'viewee>>);

impl<'viewee> IntoIterator for ScopedViewLines<'viewee> {
    type Item = ScopedView<'viewee>;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// Implementations of all available actions as dedicated methods.
///
/// Where actions don't take arguments, neither do the methods.
impl ScopedView<'_> {
    /// Apply the default [`actions::Deletion`] action to this view (see
    /// [`Self::map_without_context`]).
    pub fn delete(&mut self) -> &mut Self {
        let action = actions::Deletion::default();

        self.map_without_context(&action)
    }

    /// Apply the default [`actions::German`] action to this view (see
    /// [`Self::map_without_context`]).
    #[cfg(feature = "german")]
    pub fn german(&mut self) -> &mut Self {
        let action = actions::German::default();

        self.map_without_context(&action)
    }

    /// Apply the default [`actions::Lower`] action to this view (see
    /// [`Self::map_without_context`]).
    pub fn lower(&mut self) -> &mut Self {
        let action = actions::Lower::default();

        self.map_without_context(&action)
    }

    /// Apply the default [`actions::Normalization`] action to this view (see
    /// [`Self::map_without_context`]).
    pub fn normalize(&mut self) -> &mut Self {
        let action = actions::Normalization::default();

        self.map_without_context(&action)
    }

    /// Apply the [`actions::Replacement`] action to this view (see
    /// [`Self::map_with_context`]).
    ///
    /// ## Errors
    ///
    /// For why and how this can fail, see the implementation of [`TryFrom<String>`] for
    /// [`actions::Replacement`].
    pub fn replace(&mut self, replacement: String) -> Result<&mut Self, ActionError> {
        let action = actions::Replacement::try_from(replacement)?;

        self.map_with_context(&action)
    }

    /// Apply the [`actions::Symbols`] action to this view (see
    /// [`Self::map_without_context`]).
    #[cfg(feature = "symbols")]
    pub fn symbols(&mut self) -> &mut Self {
        let action = actions::Symbols::default();

        self.map_without_context(&action)
    }

    /// Apply the [`actions::SymbolsInversion`] action to this view (see
    /// [`Self::map_without_context`]).
    #[cfg(feature = "symbols")]
    pub fn invert_symbols(&mut self) -> &mut Self {
        let action = actions::SymbolsInversion::default();

        self.map_without_context(&action)
    }

    /// Apply the default [`actions::Titlecase`] action to this view (see
    /// [`Self::map_without_context`]).
    pub fn titlecase(&mut self) -> &mut Self {
        let action = actions::Titlecase::default();

        self.map_without_context(&action)
    }

    /// Apply the default [`actions::Upper`] action to this view (see
    /// [`Self::map_without_context`]).
    pub fn upper(&mut self) -> &mut Self {
        let action = actions::Upper::default();

        self.map_without_context(&action)
    }
}

impl fmt::Display for ScopedView<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for scope in &self.scopes.0 {
            let s: &str = scope.into();
            write!(f, "{s}")?;
        }
        Ok(())
    }
}

/// A builder for [`ScopedView`]. Chain [`Self::explode`] to build up the view, then
/// finally call [`Self::build`].
///
/// Note: while building, the view is **read-only**: no manipulation of the contents is
/// possible yet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedViewBuilder<'viewee> {
    scopes: ROScopes<'viewee>,
    viewee: &'viewee str,
}

/// Core implementations.
impl<'viewee> ScopedViewBuilder<'viewee> {
    /// Create a new builder from the given input.
    ///
    /// Initially, the entire `input` is [`In`] scope.
    #[must_use]
    pub fn new(input: &'viewee str) -> Self {
        Self {
            scopes: ROScopes(vec![ROScope(In(input, None))]),
            viewee: input,
        }
    }

    /// Build the view.
    ///
    /// This makes the view writable.
    #[must_use]
    pub fn build(mut self) -> ScopedView<'viewee> {
        self.apply_dos_line_endings_fix();

        ScopedView {
            scopes: RWScopes(self.scopes.0.into_iter().map(Into::into).collect()),
        }
    }

    /// See [`DosFix`].
    fn apply_dos_line_endings_fix(&mut self) {
        if self.scopes.0.windows(2).any(|window| match window {
            [ROScope(In(left, ..)), ROScope(Out(right))] => {
                left.ends_with('\r') && right.starts_with('\n')
            }
            _ => false,
        }) {
            warn!("Split CRLF detected. Likely scoper bug. Auto-fixing (globally).");
            // One issue with this: it's fixing *everything*, not just the location
            // where the split was detected. Implementing it differently is less
            // performant and more complex, and hitting a case where this distinction
            // (fixing globally vs. fixing locally) matters is quite unlikely.
            self.explode(&DosFix);
        }
    }

    /// Using a `scoper`, iterate over all scopes currently contained in this view under
    /// construction, apply the scoper to all [`In`] scopes, and **replace** each with
    /// whatever the scoper returned for the particular scope. These are *multiple*
    /// entries (hence 'exploding' this view: after application, it will likely be
    /// longer).
    ///
    /// Note this necessarily means a view can only be *narrowed*. What was previously
    /// [`In`] scope can be:
    ///
    /// - either still fully [`In`] scope,
    /// - or partially [`In`] scope, partially [`Out`] of scope
    ///
    /// after application. Anything [`Out`] out of scope can never be brought back.
    ///
    /// ## Panics
    ///
    /// Panics if the [`Scoper`] scopes such that the view is no longer consistent, i.e.
    /// gaps were created and the original input can no longer be reconstructed from the
    /// new view. This would be an internal bug.
    pub fn explode(&mut self, scoper: &dyn Scoper) -> &mut Self {
        trace!("Exploding scopes: {:?}", self.scopes);
        let mut new = Vec::with_capacity(self.scopes.0.len());
        for scope in self.scopes.0.drain(..) {
            trace!("Exploding scope: {scope:?}");

            if scope.is_empty() {
                trace!("Skipping empty scope");
                continue;
            }

            match scope {
                ROScope(In(s, ..)) => {
                    let mut new_scopes = scoper.scope(s);
                    new_scopes.0.retain(|s| !s.is_empty());
                    new.extend(new_scopes.0);
                }
                // Be explicit about the `Out(_)` case, so changing the enum is a
                // compile error
                ROScope(Out("")) => {}
                out @ ROScope(Out(_)) => new.push(out),
            }

            trace!("Exploded scope, new scopes are: {new:?}");
        }
        trace!("Done exploding scopes.");

        self.scopes.0 = new;

        assert_eq!(
            // Tried to do this 'more proper' using the `contracts` crate, but this
            // method `mut`ably borrows `self` and returns it as such, which is
            // worst-case and didn't play well with its macros. The crate doesn't do
            // much more than this manual `assert` anyway.
            self.scopes,
            self.viewee,
            "Post-condition violated: exploding scopes resulted in inconsistent view. \
            Aborting, as this is an unrecoverable bug in a scoper. \
            Please report at {}.",
            env!("CARGO_PKG_REPOSITORY")
        );

        self
    }
}

impl<'viewee> IntoIterator for ScopedViewBuilder<'viewee> {
    type Item = ROScope<'viewee>;

    type IntoIter = std::vec::IntoIter<ROScope<'viewee>>;

    fn into_iter(self) -> Self::IntoIter {
        self.scopes.0.into_iter()
    }
}

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

    use super::ScopedView;
    use crate::RegexPattern;
    use crate::scoping::scope::RWScopes;
    use crate::scoping::scope::Scope::{self, In, Out};
    use crate::scoping::view::ScopedViewBuilder;

    #[rstest]
    // Pattern only
    #[case("a", "a", "a")]
    #[case("aa", "a", "a")]
    #[case("aaa", "a", "a")]
    //
    // Pattern once; nothing to squeeze
    #[case("aba", "a", "aba")]
    #[case("bab", "a", "bab")]
    #[case("babab", "a", "babab")]
    #[case("ababa", "a", "ababa")]
    //
    // Squeezes only the pattern, no other repetitions
    #[case("aaabbb", "a", "abbb")]
    //
    // Squeezes start
    #[case("aab", "a", "ab")]
    //
    // Squeezes middle
    #[case("baab", "a", "bab")]
    //
    // Squeezes end
    #[case("abaa", "a", "aba")]
    //
    // Squeezes as soon as pattern occurs at least twice
    #[case("a", "ab", "a")]
    #[case("ab", "ab", "ab")]
    #[case("aba", "ab", "aba")]
    #[case("abab", "ab", "ab")]
    #[case("ababa", "ab", "aba")]
    #[case("ababab", "ab", "ab")]
    //
    // Squeezes nothing if pattern not present
    #[case("", "b", "")]
    #[case("a", "b", "a")]
    #[case("aa", "b", "aa")]
    #[case("aaa", "b", "aaa")]
    //
    // Deals with character classes (space)
    #[case("Hello World", r"\s", "Hello World")]
    #[case("Hello  World", r"\s", "Hello World")]
    #[case("Hello       World", r"\s", "Hello World")]
    #[case("Hello\tWorld", r"\t", "Hello\tWorld")]
    #[case("Hello\t\tWorld", r"\t", "Hello\tWorld")]
    //
    // Deals with character classes (inverted space)
    #[case("Hello World", r"\S", "H W")]
    #[case("Hello\t\tWorld", r"\S", "H\t\tW")]
    //
    // Deals with overlapping matches; behavior of `regex` crate
    #[case("abab", r"aba", "abab")]
    #[case("ababa", r"aba", "ababa")]
    #[case("ababab", r"aba", "ababab")]
    #[case("abababa", r"aba", "abababa")]
    #[case("aba", r"aba", "aba")]
    #[case("abaaba", r"aba", "aba")]
    //
    // Requires non-greedy matches for meaningful results
    #[case("ab", r"\s+?", "ab")]
    #[case("a b", r"\s+?", "a b")]
    #[case("a\t\tb", r"\s+?", "a\tb")]
    #[case("a\t\t  b", r"\s+?", "a\tb")]
    //
    // Deals with more complex patterns
    #[case("ab", "", "ab")] // Matches nothing
    //
    #[case("ab", r"[ab]", "a")]
    #[case("ab", r"[ab]+", "ab")]
    #[case("ab", r"[ab]+?", "a")]
    //
    #[case("abab", r"\D", "a")]
    //
    // Builds up properly; need non-capturing group
    #[case("abab", r"(?:ab){2}", "abab")]
    #[case("ababa", r"(?:ab){2}", "ababa")]
    #[case("ababab", r"(?:ab){2}", "ababab")]
    #[case("abababa", r"(?:ab){2}", "abababa")]
    #[case("abababab", r"(?:ab){2}", "abab")]
    #[case("ababababa", r"(?:ab){2}", "ababa")]
    #[case("ababababab", r"(?:ab){2}", "ababab")]
    #[case("abababababab", r"(?:ab){2}", "abab")]
    //
    #[case("Anything whatsoever gets rEkT", r".", "A")]
    #[case(
        "Anything whatsoever gets rEkT",
        r".*", // Greediness inverted
        "Anything whatsoever gets rEkT"
    )]
    //
    // Deals with Unicode shenanigans
    #[case("😎😎", r"😎", "😎")]
    #[case("\0😎\0😎\0", r"😎", "\0😎\0😎\0")]
    //
    #[case("你你好", r"", "你好")]
    //
    // Longer ("integration") tests; things that come up in the wild
    #[case(
        " dirty Strings  \t with  \t\t messed up  whitespace\n\n\n",
        r"\s",
        " dirty Strings with messed up whitespace\n"
    )]
    #[case(
        " dirty Strings  \t with  \t\t messed up  whitespace\n\n\n",
        r" ",
        " dirty Strings \t with \t\t messed up whitespace\n\n\n"
    )]
    fn test_squeeze(#[case] input: &str, #[case] pattern: RegexPattern, #[case] expected: &str) {
        let mut builder = ScopedViewBuilder::new(input);
        builder.explode(&crate::scoping::regex::Regex::new(pattern));
        let mut view = builder.build();

        view.squeeze();
        let result = view.to_string();

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case(
        // New newline at all: still works
        vec![
            In("Hello", None),
        ],
        vec![
            vec![
                In("Hello", None),
            ],
        ],
    )]
    #[case(
        // Single newline is fine
        vec![
            In("Hello\n", None),
        ],
        vec![
            vec![
                In("Hello\n", None),
            ],
        ],
    )]
    #[case(
        // Single scope is broken up across lines properly (multiple lines in single
        // scope)
        vec![
            In("Hello\nWorld", None),
        ],
        vec![
            vec![
                In("Hello\n", None),
            ],
            vec![
                In("World", None),
            ],
        ],
    )]
    #[case(
        // Single line across multiple scopes
        vec![
            In("Hello", None),
            Out("World"),
            In("!!\n", None),
            Out(" Goodbye"),
        ],
        vec![
            vec![
                In("Hello", None),
                Out("World"),
                In("!!\n", None),
            ],
            vec![
                Out(" Goodbye"),
            ],
        ],
    )]
    #[case(
        // Mixed scopes & trailing newline works
        vec![
            In("Hello\n", None),
            Out("World"),
        ],
        vec![
            vec![
                In("Hello\n", None),
            ],
            vec![
                Out("World"),
            ],
        ],
    )]
    #[case(
        // Mixed scopes & leading newline works
        vec![
            In("Hello", None),
            Out("\nWorld"),
        ],
        vec![
            vec![
                In("Hello", None),
                Out("\n"),
            ],
            vec![
                Out("World"),
            ],
        ],
    )]
    #[case(
        // Empty lines & empty scopes works
        vec![
            In("\n", None),
            Out("\n"),
            Out(""),
            In("World\n", None),
            Out(""),
        ],
        vec![
            vec![
                In("\n", None),
            ],
            vec![
                Out("\n"),
            ],
            vec![
                #[cfg(not(test))]Out(""), // Dropped! (do not compile)
                In("World\n", None),
            ],
            #[cfg(not(test))] // Dropped! (do not compile)
            vec![
                Out(""),
            ],
        ],
    )]
    fn test_lines(
        #[case] input: Vec<Scope<'_, &str>>,
        #[case] expected: Vec<Vec<Scope<'_, &str>>>,
    ) {
        let view = ScopedView {
            scopes: input.into(),
        };
        let result = view.lines().into_iter().collect_vec();
        let expected = expected
            .into_iter()
            .map(RWScopes::from)
            .map(ScopedView::new)
            .collect_vec();

        assert_eq!(result, expected);
    }

    #[rstest]
    #[case(
        "hello",
        &["hello"] // aka: it loops at least once!
    )]
    #[case(
        "hello\n",
        &["hello\n"]
    )]
    #[case(
        "hello\nworld",
        &["hello\n", "world"]
    )]
    #[case(
        "hello\nworld\n",
        &["hello\n", "world\n"]
    )]
    #[case(
        "",
        &[] // ⚠️ no iteration happens; empty string is dropped
    )]
    fn test_split_inclusive(#[case] input: &str, #[case] expected: &[&str]) {
        // This is not a useful unit test; it's just encoding and confirming the
        // behavior of `split_inclusive`, to convince myself.
        for (si, exp) in input.split_inclusive('\n').zip_eq(expected) {
            assert_eq!(si, *exp);
        }
    }
}