zshrs 0.10.9

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, SQLite caching
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
//! PCRE module - port of Modules/pcre.c
//!
//! Provides PCRE regex matching through pcre_compile, pcre_match, pcre_study builtins.
//! Uses the Rust `regex` crate which provides Perl-compatible regex syntax.

use regex::Regex;
use std::collections::HashMap;

/// Compiled PCRE pattern state.
/// Port of the file-static `pcre_pattern` / `pcre_extra` /
/// `pcre_hints` slot Src/Modules/pcre.c keeps to share a compiled
/// regex between `bin_pcre_compile` (line 70), `bin_pcre_study`
/// (line 112), and `bin_pcre_match` (line 328). C zsh's source uses
/// PCRE2's `pcre2_code *`; the Rust `regex` crate gives us an
/// equivalent compiled handle.
#[derive(Debug)]
pub struct PcreState {
    pattern: Option<Regex>,
    pattern_str: Option<String>,
}

impl Default for PcreState {
    fn default() -> Self {
        Self::new()
    }
}

impl PcreState {
    pub fn new() -> Self {
        Self {
            pattern: None,
            pattern_str: None,
        }
    }

    pub fn has_pattern(&self) -> bool {
        self.pattern.is_some()
    }

    pub fn clear(&mut self) {
        self.pattern = None;
        self.pattern_str = None;
    }
}

/// Options for pcre_compile
#[derive(Debug, Default, Clone)]
pub struct PcreCompileOptions {
    pub anchored: bool,
    pub caseless: bool,
    pub multiline: bool,
    pub extended: bool,
    pub dotall: bool,
}

/// Options for pcre_match
#[derive(Debug, Default, Clone)]
pub struct PcreMatchOptions {
    pub match_var: Option<String>,
    pub array_var: Option<String>,
    pub assoc_var: Option<String>,
    pub offset: usize,
    pub return_offsets: bool,
    pub use_dfa: bool,
}

/// Result of a PCRE match
#[derive(Debug, Clone)]
pub struct PcreMatchResult {
    pub matched: bool,
    pub full_match: Option<String>,
    pub captures: Vec<Option<String>>,
    pub named_captures: HashMap<String, String>,
    pub match_start: Option<usize>,
    pub match_end: Option<usize>,
}

impl PcreMatchResult {
    pub fn no_match() -> Self {
        Self {
            matched: false,
            full_match: None,
            captures: Vec::new(),
            named_captures: HashMap::new(),
            match_start: None,
            match_end: None,
        }
    }
}

/// Compile a PCRE pattern.
/// Port of the `pcre2_compile_8()` core inside `bin_pcre_compile()`
/// from Src/Modules/pcre.c:70 — translates the option flag bag
/// (`-i` caseless, `-x` extended, `-m` multiline, `-s` dotall,
/// `-a` anchored) into the `(?i)` / `(?x)` / `(?m)` / `(?s)` /
/// `^` prefixes the Rust `regex` crate accepts and stores the
/// compiled handle in `state` for later `pcre_match`/`pcre_study`.
pub fn pcre_compile(
    pattern: &str,
    options: &PcreCompileOptions,
    state: &mut PcreState,
) -> Result<(), String> {
    state.clear();

    let mut pattern_str = String::new();

    if options.caseless {
        pattern_str.push_str("(?i)");
    }
    if options.multiline {
        pattern_str.push_str("(?m)");
    }
    if options.dotall {
        pattern_str.push_str("(?s)");
    }
    if options.extended {
        pattern_str.push_str("(?x)");
    }
    if options.anchored {
        pattern_str.push('^');
    }

    pattern_str.push_str(pattern);

    match Regex::new(&pattern_str) {
        Ok(re) => {
            state.pattern = Some(re);
            state.pattern_str = Some(pattern_str);
            Ok(())
        }
        Err(e) => Err(format!("error in regex: {}", e)),
    }
}

/// Study a compiled pattern.
/// Port of `bin_pcre_study()` from Src/Modules/pcre.c:112. The C
/// source calls `pcre2_jit_compile()` to JIT-optimize the compiled
/// pattern; the Rust `regex` crate already builds an optimal NFA
/// at compile time, so this is a no-op other than the "no pattern"
/// guard the C source also returns.
pub fn pcre_study(state: &PcreState) -> Result<(), String> {
    if state.pattern.is_none() {
        return Err("no pattern has been compiled for study".to_string());
    }
    Ok(())
}

/// Match a string against the compiled pattern.
/// Port of the `pcre2_match_8()` + `zpcre_get_substrings()` core of
/// `bin_pcre_match()` from Src/Modules/pcre.c:328 — runs the match,
/// captures numbered groups (the `ovector` walk in
/// `zpcre_get_substrings()` at line 157), and surfaces named
/// captures via the same `pcre2_substring_get_byname` lookup the C
/// source performs.
pub fn pcre_match(
    text: &str,
    options: &PcreMatchOptions,
    state: &PcreState,
) -> Result<PcreMatchResult, String> {
    let re = state
        .pattern
        .as_ref()
        .ok_or_else(|| "no pattern has been compiled".to_string())?;

    let search_text = if options.offset > 0 && options.offset < text.len() {
        &text[options.offset..]
    } else if options.offset >= text.len() {
        return Ok(PcreMatchResult::no_match());
    } else {
        text
    };

    let caps = match re.captures(search_text) {
        Some(c) => c,
        None => return Ok(PcreMatchResult::no_match()),
    };

    let full_match = caps.get(0).map(|m| m.as_str().to_string());
    let match_start = caps.get(0).map(|m| m.start() + options.offset);
    let match_end = caps.get(0).map(|m| m.end() + options.offset);

    let mut captures = Vec::new();
    for i in 1..caps.len() {
        captures.push(caps.get(i).map(|m| m.as_str().to_string()));
    }

    let mut named_captures = HashMap::new();
    for name in re.capture_names().flatten() {
        if let Some(m) = caps.name(name) {
            named_captures.insert(name.to_string(), m.as_str().to_string());
        }
    }

    Ok(PcreMatchResult {
        matched: true,
        full_match,
        captures,
        named_captures,
        match_start,
        match_end,
    })
}

/// `[[ s -pcre-match pat ]]` cond-test entry point.
/// Port of `cond_pcre_match()` from Src/Modules/pcre.c:422 — the
/// dispatch hook the lexer wires for the `-pcre-match` operator.
/// Compiles `rhs` on the fly (no shared compile state required) and
/// returns `(matched, result)` so the caller can decide whether to
/// install the match-vars side effects.
pub fn cond_pcre_match(lhs: &str, rhs: &str, caseless: bool) -> (bool, PcreMatchResult) {
    let options = PcreCompileOptions {
        caseless,
        ..Default::default()
    };

    let mut state = PcreState::new();

    if pcre_compile(rhs, &options, &mut state).is_err() {
        return (false, PcreMatchResult::no_match());
    }

    let match_options = PcreMatchOptions::default();

    match pcre_match(lhs, &match_options, &state) {
        Ok(result) => (result.matched, result),
        Err(_) => (false, PcreMatchResult::no_match()),
    }
}

/// `pcre_compile` builtin entry point.
/// Port of `bin_pcre_compile()` from Src/Modules/pcre.c:70 — wraps
/// `pcre_compile()` with the same "no args" diagnostic the C source
/// emits.
pub fn builtin_pcre_compile(
    args: &[&str],
    options: &PcreCompileOptions,
    state: &mut PcreState,
) -> (i32, String) {
    if args.is_empty() {
        return (1, "pcre_compile: pattern required\n".to_string());
    }

    match pcre_compile(args[0], options, state) {
        Ok(()) => (0, String::new()),
        Err(e) => (1, format!("pcre_compile: {}\n", e)),
    }
}

/// `pcre_study` builtin entry point.
/// Port of `bin_pcre_study()` from Src/Modules/pcre.c:112 — wraps
/// `pcre_study()` with the same exit-status convention.
pub fn builtin_pcre_study(state: &PcreState) -> (i32, String) {
    match pcre_study(state) {
        Ok(()) => (0, String::new()),
        Err(e) => (1, format!("pcre_study: {}\n", e)),
    }
}

/// `pcre_match` builtin entry point.
/// Port of `bin_pcre_match()` from Src/Modules/pcre.c:328 — wraps
/// `pcre_match()` with the C source's "1 on no-match, 0 on match"
/// exit-status convention.
pub fn builtin_pcre_match(
    args: &[&str],
    options: &PcreMatchOptions,
    state: &PcreState,
) -> (i32, PcreMatchResult) {
    if args.is_empty() {
        return (1, PcreMatchResult::no_match());
    }

    match pcre_match(args[0], options, state) {
        Ok(result) => {
            if result.matched {
                (0, result)
            } else {
                (1, result)
            }
        }
        Err(_) => (1, PcreMatchResult::no_match()),
    }
}

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

    #[test]
    fn test_pcre_state_new() {
        let state = PcreState::new();
        assert!(!state.has_pattern());
    }

    #[test]
    fn test_pcre_compile_simple() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();

        let result = pcre_compile("hello", &options, &mut state);
        assert!(result.is_ok());
        assert!(state.has_pattern());
    }

    #[test]
    fn test_pcre_compile_invalid() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();

        let result = pcre_compile("[invalid", &options, &mut state);
        assert!(result.is_err());
    }

    #[test]
    fn test_pcre_compile_caseless() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions {
            caseless: true,
            ..Default::default()
        };

        let result = pcre_compile("hello", &options, &mut state);
        assert!(result.is_ok());

        let match_opts = PcreMatchOptions::default();
        let result = pcre_match("HELLO WORLD", &match_opts, &state).unwrap();
        assert!(result.matched);
    }

    #[test]
    fn test_pcre_study_no_pattern() {
        let state = PcreState::new();
        let result = pcre_study(&state);
        assert!(result.is_err());
    }

    #[test]
    fn test_pcre_study_with_pattern() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        pcre_compile("hello", &options, &mut state).unwrap();

        let result = pcre_study(&state);
        assert!(result.is_ok());
    }

    #[test]
    fn test_pcre_match_simple() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        pcre_compile("hello", &options, &mut state).unwrap();

        let match_opts = PcreMatchOptions::default();
        let result = pcre_match("hello world", &match_opts, &state).unwrap();
        assert!(result.matched);
        assert_eq!(result.full_match, Some("hello".to_string()));
    }

    #[test]
    fn test_pcre_match_no_match() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        pcre_compile("hello", &options, &mut state).unwrap();

        let match_opts = PcreMatchOptions::default();
        let result = pcre_match("goodbye world", &match_opts, &state).unwrap();
        assert!(!result.matched);
    }

    #[test]
    fn test_pcre_match_captures() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        pcre_compile(r"(\w+) (\w+)", &options, &mut state).unwrap();

        let match_opts = PcreMatchOptions::default();
        let result = pcre_match("hello world", &match_opts, &state).unwrap();
        assert!(result.matched);
        assert_eq!(result.captures.len(), 2);
        assert_eq!(result.captures[0], Some("hello".to_string()));
        assert_eq!(result.captures[1], Some("world".to_string()));
    }

    #[test]
    fn test_pcre_match_named_captures() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        pcre_compile(r"(?P<first>\w+) (?P<second>\w+)", &options, &mut state).unwrap();

        let match_opts = PcreMatchOptions::default();
        let result = pcre_match("hello world", &match_opts, &state).unwrap();
        assert!(result.matched);
        assert_eq!(
            result.named_captures.get("first"),
            Some(&"hello".to_string())
        );
        assert_eq!(
            result.named_captures.get("second"),
            Some(&"world".to_string())
        );
    }

    #[test]
    fn test_pcre_match_with_offset() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        pcre_compile("world", &options, &mut state).unwrap();

        let match_opts = PcreMatchOptions {
            offset: 6,
            ..Default::default()
        };
        let result = pcre_match("hello world", &match_opts, &state).unwrap();
        assert!(result.matched);
        assert_eq!(result.match_start, Some(6));
    }

    #[test]
    fn test_cond_pcre_match() {
        let (matched, _) = cond_pcre_match("hello world", "hello", false);
        assert!(matched);

        let (matched, _) = cond_pcre_match("hello world", "HELLO", true);
        assert!(matched);

        let (matched, _) = cond_pcre_match("hello world", "HELLO", false);
        assert!(!matched);
    }

    #[test]
    fn test_builtin_pcre_compile_no_args() {
        let mut state = PcreState::new();
        let options = PcreCompileOptions::default();
        let (status, _) = builtin_pcre_compile(&[], &options, &mut state);
        assert_eq!(status, 1);
    }

    #[test]
    fn test_builtin_pcre_match_no_pattern() {
        let state = PcreState::new();
        let options = PcreMatchOptions::default();
        let (status, _) = builtin_pcre_match(&["test"], &options, &state);
        assert_eq!(status, 1);
    }
}