proef-core 0.3.1

Engine-agnostic core of proef: parsing, binding, lowering, IR, emit, dispatch, World, events, errors
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
//! The `{name}` step matcher: cucumber-expression-style patterns binding Gherkin
//! prose to macros (TECH-SPEC ยง4.3).
//!
//! A pattern is literal text with `{name}` captures (`I search for {term}`).
//! Matching is **anchored and leftmost**: literals must appear in order (the
//! whole text must be consumed), and each capture extends to the leftmost
//! occurrence of the next literal. Captured values are trimmed; a value wrapped
//! in symmetric double or single quotes sheds them (quotes preserve inner
//! spaces and commas exactly).
//!
//! Guard rails ([`pattern_problems`], run at pack load โ€” validation pass 1):
//! a pattern must contain literal text to anchor on, adjacent captures are
//! rejected (the single-pass matcher cannot split them), braces must be
//! balanced, and every capture must name a declared param.

use std::collections::BTreeMap;

/// One token of a `match:` pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Token {
    /// Literal text that must appear verbatim.
    Literal(String),
    /// A `{name}` capture.
    Capture(String),
}

/// Split a pattern into [`Token`]s. An unclosed `{` degrades the remainder into
/// a literal โ€” [`pattern_problems`] rejects it at load; the matcher stays total.
pub fn tokenize(pattern: &str) -> Vec<Token> {
    let mut tokens = Vec::new();
    let mut rest = pattern;
    while let Some(open) = rest.find('{') {
        if open > 0 {
            tokens.push(Token::Literal(rest[..open].to_owned()));
        }
        let after = &rest[open + 1..];
        if let Some(close) = after.find('}') {
            tokens.push(Token::Capture(after[..close].trim().to_owned()));
            rest = &after[close + 1..];
        } else {
            tokens.push(Token::Literal(rest.to_owned()));
            return tokens;
        }
    }
    if !rest.is_empty() {
        tokens.push(Token::Literal(rest.to_owned()));
    }
    tokens
}

/// Match `text` against `pattern`, returning the captured args, or `None` when
/// the pattern does not apply. Total: never panics, any inputs.
pub fn match_pattern(pattern: &str, text: &str) -> Option<BTreeMap<String, String>> {
    let tokens = tokenize(pattern);
    let mut args = BTreeMap::new();
    let mut rest = text;
    let mut index = 0;
    while index < tokens.len() {
        match &tokens[index] {
            Token::Literal(lit) => rest = rest.strip_prefix(lit.as_str())?,
            Token::Capture(name) => {
                let next_literal = match tokens.get(index + 1) {
                    Some(Token::Literal(lit)) if !lit.is_empty() => Some(lit.as_str()),
                    _ => None,
                };
                let value = match next_literal {
                    Some(lit) => {
                        let end = rest.find(lit)?;
                        let (value, remainder) = rest.split_at(end);
                        rest = remainder;
                        value
                    }
                    None => std::mem::take(&mut rest),
                };
                args.insert(name.clone(), shed_quotes(value.trim()).to_owned());
            }
        }
        index += 1;
    }
    rest.is_empty().then_some(args)
}

/// Strip one symmetric pair of surrounding quotes (`"โ€ฆ"` or `'โ€ฆ'`), keeping the
/// inner text exactly โ€” the quoting mechanism that preserves spaces and commas.
fn shed_quotes(value: &str) -> &str {
    for quote in ['"', '\''] {
        if value.len() >= 2
            && let Some(inner) = value
                .strip_prefix(quote)
                .and_then(|v| v.strip_suffix(quote))
        {
            return inner;
        }
    }
    value
}

/// One problem found in a `match:` pattern (validation pass 1), typed so each
/// maps to a stable diagnostic code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatternProblem {
    /// No literal text to anchor on โ€” a bare capture matches every step.
    NoAnchor,
    /// Two captures with nothing between them โ€” the matcher cannot split them.
    AdjacentCaptures {
        /// First capture name.
        first: String,
        /// Second capture name.
        second: String,
    },
    /// A stray `{`/`}` inside literal text (unclosed or unescaped).
    UnsupportedBraces {
        /// The literal fragment near the problem.
        near: String,
    },
    /// An empty `{}` capture.
    EmptyCapture,
    /// A capture that names no declared param.
    UnknownCapture {
        /// The capture name as written.
        name: String,
        /// Closest declared param, when one is near.
        suggestion: Option<String>,
    },
}

impl PatternProblem {
    /// The stable diagnostic code for this problem.
    pub fn code(&self) -> &'static str {
        match self {
            Self::NoAnchor => "proef::pack::pattern_no_anchor",
            Self::AdjacentCaptures { .. } => "proef::pack::adjacent_captures",
            Self::UnsupportedBraces { .. } => "proef::pack::pattern_braces",
            Self::EmptyCapture => "proef::pack::pattern_empty_capture",
            Self::UnknownCapture { .. } => "proef::pack::pattern_unknown_capture",
        }
    }
}

impl std::fmt::Display for PatternProblem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoAnchor => f.write_str(
                "pattern has no literal text to match on โ€” a bare capture matches every step",
            ),
            Self::AdjacentCaptures { first, second } => write!(
                f,
                "adjacent captures `{{{first}}}{{{second}}}` are ambiguous โ€” put literal text between them"
            ),
            Self::UnsupportedBraces { near } => write!(
                f,
                "unsupported `{{` or `}}` in pattern (near `{near}`) โ€” captures are written `{{name}}`"
            ),
            Self::EmptyCapture => f.write_str("empty capture `{}`"),
            Self::UnknownCapture { name, suggestion } => {
                let hint = suggestion
                    .as_ref()
                    .map(|p| format!(" (did you mean `{p}`?)"))
                    .unwrap_or_default();
                write!(f, "capture `{{{name}}}` is not a declared param{hint}")
            }
        }
    }
}

/// The problems found in a `match:` pattern (validation pass 1); empty = sound.
pub fn pattern_problems(pattern: &str, params: &[String]) -> Vec<PatternProblem> {
    let tokens = tokenize(pattern);
    let mut problems = Vec::new();

    let has_anchor = tokens
        .iter()
        .any(|t| matches!(t, Token::Literal(lit) if !lit.trim().is_empty()));
    if !has_anchor {
        problems.push(PatternProblem::NoAnchor);
    }

    for pair in tokens.windows(2) {
        if let [Token::Capture(a), Token::Capture(b)] = pair {
            problems.push(PatternProblem::AdjacentCaptures {
                first: a.clone(),
                second: b.clone(),
            });
        }
    }

    for token in &tokens {
        match token {
            Token::Literal(lit) if lit.contains('{') || lit.contains('}') => {
                problems.push(PatternProblem::UnsupportedBraces {
                    near: lit.trim().to_owned(),
                });
            }
            Token::Capture(name) if name.is_empty() => {
                problems.push(PatternProblem::EmptyCapture);
            }
            Token::Capture(name) if !params.iter().any(|p| p == name) => {
                problems.push(PatternProblem::UnknownCapture {
                    name: name.clone(),
                    suggestion: closest(name, params.iter().map(String::as_str))
                        .map(ToOwned::to_owned),
                });
            }
            _ => {}
        }
    }
    problems
}

/// The literal skeleton of a pattern (captures dropped) โ€” the comparison basis
/// for closest-pattern suggestions on unbound steps.
pub fn literal_skeleton(pattern: &str) -> String {
    tokenize(pattern)
        .into_iter()
        .filter_map(|t| match t {
            Token::Literal(s) => Some(s),
            Token::Capture(_) => None,
        })
        .collect()
}

/// The candidate closest to `input` by edit distance, within the shared
/// "did you mean" threshold. `None` when nothing is close.
pub fn closest<'a>(input: &str, candidates: impl Iterator<Item = &'a str>) -> Option<&'a str> {
    candidates
        .map(|c| (levenshtein(input, c), c))
        .filter(|(distance, _)| *distance <= SUGGESTION_DISTANCE)
        .min_by_key(|(distance, _)| *distance)
        .map(|(_, c)| c)
}

/// Maximum edit distance for a "did you mean" suggestion.
const SUGGESTION_DISTANCE: usize = 3;

/// Levenshtein edit distance over chars (small inputs; O(aยทb) rolling row).
pub fn levenshtein(a: &str, b: &str) -> usize {
    let b_chars: Vec<char> = b.chars().collect();
    let mut row: Vec<usize> = (0..=b_chars.len()).collect();
    for (i, ca) in a.chars().enumerate() {
        let mut previous_diagonal = row[0];
        row[0] = i + 1;
        for (j, cb) in b_chars.iter().enumerate() {
            let substitution = previous_diagonal + usize::from(ca != *cb);
            previous_diagonal = row[j + 1];
            row[j + 1] = substitution.min(row[j] + 1).min(previous_diagonal + 1);
        }
    }
    row[b_chars.len()]
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use super::*;

    fn params(names: &[&str]) -> Vec<String> {
        names.iter().map(|s| (*s).to_owned()).collect()
    }

    #[test]
    fn literal_pattern_matches_exactly() {
        assert_eq!(
            match_pattern(
                "the client feed is activated and ready",
                "the client feed is activated and ready"
            ),
            Some(BTreeMap::new())
        );
        assert_eq!(
            match_pattern("I create a client", "I create a clients"),
            None
        );
        assert_eq!(
            match_pattern("I create a client", "so I create a client"),
            None
        );
    }

    #[test]
    fn captures_split_on_leftmost_literal() {
        let args = match_pattern(
            "the client {name} is resolved",
            "the client Bakker-${run:id} is resolved",
        )
        .unwrap();
        assert_eq!(args["name"], "Bakker-${run:id}");
    }

    #[test]
    fn multi_capture_binds_in_order() {
        let args =
            match_pattern("I search {index} for {term}", "I search clients for Jansen").unwrap();
        assert_eq!(args["index"], "clients");
        assert_eq!(args["term"], "Jansen");
    }

    #[test]
    fn quoted_capture_preserves_inner_text() {
        let args = match_pattern("I search for {term}", r#"I search for "Jansen, A. ""#).unwrap();
        assert_eq!(args["term"], "Jansen, A. ");
        let args = match_pattern("I search for {term}", "I search for 'de Vries'").unwrap();
        assert_eq!(args["term"], "de Vries");
    }

    #[test]
    fn unquoted_capture_is_trimmed() {
        let args = match_pattern("I search for {term} now", "I search for   Jansen   now").unwrap();
        assert_eq!(args["term"], "Jansen");
    }

    #[test]
    fn trailing_capture_takes_the_rest() {
        let args = match_pattern("say {message}", "say hello world").unwrap();
        assert_eq!(args["message"], "hello world");
    }

    #[test]
    fn guard_rails_reject_bad_patterns() {
        assert!(
            !pattern_problems("{a}", &params(&["a"])).is_empty(),
            "no anchor"
        );
        assert!(
            !pattern_problems("do {a}{b} now", &params(&["a", "b"])).is_empty(),
            "adjacent captures"
        );
        assert!(
            !pattern_problems("do {a", &params(&["a"])).is_empty(),
            "unclosed brace"
        );
        assert!(
            !pattern_problems("do {} now", &[]).is_empty(),
            "empty capture"
        );
        assert!(
            pattern_problems("do {a} now", &params(&["a"])).is_empty(),
            "sound pattern"
        );
    }

    #[test]
    fn unknown_capture_gets_a_suggestion() {
        let problems = pattern_problems("I log in as {rol}", &params(&["role"]));
        assert_eq!(problems.len(), 1);
        assert_eq!(problems[0].code(), "proef::pack::pattern_unknown_capture");
        assert!(
            problems[0].to_string().contains("did you mean `role`?"),
            "{}",
            problems[0]
        );
    }

    #[test]
    fn closest_respects_the_threshold() {
        assert_eq!(
            closest("serch", ["search", "create"].into_iter()),
            Some("search")
        );
        assert_eq!(closest("zzzzzz", ["search", "create"].into_iter()), None);
    }

    mod properties {
        #![allow(clippy::ignored_unit_patterns)]

        use super::*;
        use proptest::prelude::*;

        proptest! {
            /// Total on arbitrary inputs: never panics (fuzz target mirrors this).
            #[test]
            fn matcher_never_panics(pattern in ".{0,60}", text in ".{0,120}") {
                let _ = match_pattern(&pattern, &text);
                let _ = pattern_problems(&pattern, &[]);
            }

            /// A sound single-capture pattern round-trips a quoted value exactly.
            #[test]
            fn quote_round_trip(value in "[^\"{}]{0,40}") {
                let text = format!("I search for \"{value}\" now");
                let args = match_pattern("I search for {term} now", &text).unwrap();
                prop_assert_eq!(args["term"].as_str(), value.as_str());
            }

            /// Adjacent captures are always rejected by the guard rails.
            #[test]
            fn adjacent_captures_always_rejected(a in "[a-z]{1,8}", b in "[a-z]{1,8}") {
                let pattern = format!("go {{{a}}}{{{b}}} end");
                let names = vec![a.clone(), b.clone()];
                prop_assert!(!pattern_problems(&pattern, &names).is_empty());
            }

            /// Unquoted round-trip: generated capture text without quote/brace
            /// noise survives bind โ†’ args intact (modulo the documented trim).
            #[test]
            fn unquoted_round_trip(value in "[a-zA-Z0-9_-]{1,30}") {
                let text = format!("the client {value} is resolved");
                let args = match_pattern("the client {name} is resolved", &text).unwrap();
                prop_assert_eq!(args["name"].as_str(), value.as_str());
            }
        }
    }
}