wp-lang 0.3.0

WPL language crate with AST, parser, evaluator, builtins, and generators.
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
use crate::ast::syntax::sep_pattern::SepPattern;
use crate::ast::{GenFmt, WplFmt};
use crate::parser::utils::{quot_r_str, quot_str, take_to_end};
use derive_getters::Getters;
use smol_str::SmolStr;
use std::fmt::{Display, Formatter};
use std::marker::PhantomData;
use winnow::combinator::{alt, opt, separated};
use winnow::stream::Range;
use winnow::token::{literal, take_until, take_while};
use wp_primitives::Parser;
use wp_primitives::WResult;
use wp_primitives::symbol::ctx_desc;

const DEFAULT_SEP: &str = " ";
pub trait DefaultSep {
    fn sep_str() -> &'static str;
}
impl DefaultSep for () {
    fn sep_str() -> &'static str {
        DEFAULT_SEP
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Getters)]
pub struct WplSepT<T> {
    prio: usize,
    cur_val: Option<SepEnum>,
    ups_val: Option<SmolStr>,
    infer: bool,
    is_take: bool,
    #[serde(skip)]
    _phant: PhantomData<T>,
}
pub type WplSep = WplSepT<()>;

impl<T> WplSepT<T> {
    pub fn from(value: &WplSep) -> Self {
        WplSepT {
            prio: value.prio,
            cur_val: value.cur_val.clone(),
            ups_val: value.ups_val.clone(),
            infer: value.infer,
            is_take: value.is_take,
            _phant: PhantomData,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SepEnum {
    Str(SmolStr),
    End,
    Whitespace, // Matches space or tab
    Pattern(SepPattern),
}
impl From<&str> for SepEnum {
    fn from(value: &str) -> Self {
        if value == "\\0" || value == "0" {
            SepEnum::End
        } else if value == "\\s" || value == "s" {
            SepEnum::Str(" ".into())
        } else if value == "\\t" || value == "t" {
            SepEnum::Str("\t".into())
        } else if value == "\\S" || value == "S" {
            SepEnum::Whitespace
        } else {
            SepEnum::Str(value.into())
        }
    }
}

impl From<String> for SepEnum {
    fn from(value: String) -> Self {
        Self::from(value.as_str())
    }
}

impl From<SmolStr> for SepEnum {
    fn from(value: SmolStr) -> Self {
        Self::from(value.as_str())
    }
}
impl<T> Default for WplSepT<T> {
    fn default() -> Self {
        Self {
            prio: 1,
            cur_val: None,
            ups_val: None,
            infer: false,
            is_take: true,
            _phant: PhantomData,
        }
    }
}

impl<T: DefaultSep + Clone> WplSepT<T> {
    /// 字段级分隔符(优先级 3),覆盖组级与上游
    pub fn field_sep<S: Into<SmolStr>>(val: S) -> Self {
        Self {
            prio: 3,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: None,
            infer: false,
            is_take: true,
            _phant: PhantomData,
        }
    }

    pub fn apply_default(&mut self, other: WplSep) {
        if other.prio > self.prio || self.cur_val.is_none() {
            self.prio = other.prio;
            self.cur_val = other.cur_val;
            // Pattern separators do not support ups_val; clear it to avoid stale state.
            if matches!(&self.cur_val, Some(SepEnum::Pattern(_))) {
                self.ups_val = None;
            }
        }
    }
    pub fn set_current<S: Into<SmolStr>>(&mut self, sep: S) {
        self.cur_val = Some(SepEnum::from(sep.into()))
    }
    pub fn is_unset(&self) -> bool {
        self.cur_val().is_none()
    }
    pub fn is_to_end(&self) -> bool {
        if let Some(x) = &self.cur_val {
            *x == SepEnum::End
        } else {
            false
        }
    }
    pub fn override_with(&mut self, other: &WplSep) {
        if other.prio > self.prio {
            self.prio = other.prio;
            self.cur_val = other.cur_val.clone();
            // Pattern separators do not support ups_val; clear it to avoid stale state.
            if matches!(&self.cur_val, Some(SepEnum::Pattern(_))) {
                self.ups_val = None;
            }
        }
    }
    pub fn sep_str(&self) -> &str {
        if let Some(val) = &self.cur_val {
            match val {
                SepEnum::Str(str) => str.as_str(),
                SepEnum::End => "\n",
                SepEnum::Whitespace => " ", // Default to space for display
                SepEnum::Pattern(p) => p.raw(),
            }
        } else {
            T::sep_str()
            //DEFAULT_SEP
        }
    }
    pub fn inherited_sep<S: Into<SmolStr>>(val: S) -> Self {
        Self {
            prio: 1,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: None,
            infer: false,
            is_take: true,
            ..Default::default()
        }
    }
    pub fn infer_inherited_sep<S: Into<SmolStr>>(val: S) -> Self {
        Self {
            prio: 1,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: None,
            infer: true,
            is_take: true,
            ..Default::default()
        }
    }
    pub fn infer_group_sep<S: Into<SmolStr>>(val: S) -> Self {
        Self {
            prio: 2,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: None,
            infer: true,
            is_take: true,
            ..Default::default()
        }
    }
    pub fn infer_clone(&self) -> Self {
        let mut c = self.clone();
        c.infer = true;
        c
    }
    pub fn group_sep<S: Into<SmolStr>>(val: S) -> Self {
        Self {
            prio: 2,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: None,
            infer: false,
            is_take: true,
            ..Default::default()
        }
    }
    pub fn field_sep_until<S: Into<SmolStr>>(val: S, sec: S, is_take: bool) -> Self {
        Self {
            prio: 3,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: Some(sec.into()),
            infer: false,
            is_take,
            ..Default::default()
        }
    }
    pub fn infer_field_sep<S: Into<SmolStr>>(val: S) -> Self {
        Self {
            prio: 3,
            cur_val: Some(SepEnum::from(val.into())),
            ups_val: None,
            infer: true,
            is_take: true,
            ..Default::default()
        }
    }
    pub fn field_sep_pattern(pattern: SepPattern) -> Self {
        Self {
            prio: 3,
            cur_val: Some(SepEnum::Pattern(pattern)),
            ups_val: None,
            infer: false,
            is_take: true,
            _phant: PhantomData,
        }
    }
    pub fn is_pattern(&self) -> bool {
        matches!(&self.cur_val, Some(SepEnum::Pattern(_)))
    }

    pub fn consume_sep(&self, input: &mut &str) -> WResult<()> {
        if self.is_take {
            if let Some(SepEnum::Whitespace) = &self.cur_val {
                // For Whitespace, accept either space or tab
                alt((literal(" "), literal("\t")))
                    .context(ctx_desc("take <whitespace>"))
                    .parse_next(input)?;
            } else if let Some(SepEnum::Pattern(pattern)) = &self.cur_val {
                match pattern.match_at_start(input) {
                    Some(m) => {
                        *input = &input[m.consumed..];
                    }
                    None => {
                        winnow::combinator::fail
                            .context(ctx_desc("take <sep pattern>"))
                            .parse_next(input)?;
                    }
                }
            } else {
                literal(self.sep_str())
                    .context(ctx_desc("take <sep>"))
                    .parse_next(input)?;
            }
        }
        Ok(())
    }
    pub fn try_consume_sep(&self, input: &mut &str) -> WResult<()> {
        if self.is_take {
            if let Some(SepEnum::Whitespace) = &self.cur_val {
                // For Whitespace, optionally accept either space or tab
                opt(alt((literal(" "), literal("\t")))).parse_next(input)?;
            } else if let Some(SepEnum::Pattern(pattern)) = &self.cur_val {
                if let Some(m) = pattern.match_at_start(input) {
                    *input = &input[m.consumed..];
                }
            } else {
                opt(literal(self.sep_str())).parse_next(input)?;
            }
        }
        Ok(())
    }
    pub fn is_space_sep(&self) -> bool {
        !self.is_pattern() && self.sep_str() == " "
    }

    pub fn need_take_sep(&self) -> bool {
        !(self.is_to_end() || self.is_space_sep())
    }

    pub fn read_until_any_char<'a>(end1: &str, end2: &str, data: &mut &'a str) -> WResult<&'a str> {
        let ends1 = end1.as_bytes();
        let ends2 = end2.as_bytes();
        alt((
            quot_r_str,
            quot_str,
            take_while(0.., |c: char| {
                !(ends1.contains(&(c as u8)) || ends2.contains(&(c as u8)))
            }),
            take_to_end,
        ))
        .parse_next(data)
    }

    pub fn read_until_sep(&self, data: &mut &str) -> WResult<String> {
        // 读到当前分隔符,若存在"次级结束符"(ups_val),应以"最近结束优先"裁剪。
        // 特殊值:\0 由 is_to_end() 覆盖;单字符对使用 read_until_any_char 快路径。
        if self.is_to_end() {
            let buf = take_to_end.parse_next(data)?;
            return Ok(buf.to_string());
        }

        // Handle Whitespace separator specially
        if let Some(SepEnum::Whitespace) = &self.cur_val {
            // Take until space or tab
            let buf = take_while(0.., |c: char| c != ' ' && c != '\t').parse_next(data)?;
            return Ok(buf.to_string());
        }

        // Handle Pattern separator
        if let Some(SepEnum::Pattern(pattern)) = &self.cur_val {
            let s = *data;
            // Exclude quoted segments (consistent with existing logic)
            if s.starts_with('"') || s.starts_with("r#\"") || s.starts_with("r\"") {
                let buf = alt((quot_r_str, quot_str)).parse_next(data)?;
                return Ok(buf.to_string());
            }
            return match pattern.find(s) {
                Some((offset, _sep_match)) => {
                    let content = &s[..offset];
                    // Only advance past field content; leave the separator
                    // in the input stream for consume_sep to handle.
                    *data = &s[offset..];
                    Ok(content.to_string())
                }
                None => Ok(take_to_end.parse_next(data)?.to_string()),
            };
        }

        if let Some(ups) = &self.ups_val {
            // 快路径:单字符对,使用按字符扫描,天然最近结束优先
            if self.sep_str().len() == 1 && ups.len() == 1 {
                let buf = Self::read_until_any_char(self.sep_str(), ups.as_str(), data)?;
                return Ok(buf.to_string());
            }
            // 常规:对多字符分隔的最近结束优先实现
            let s = *data;
            // 若下一个是引号,优先让上层调用流按引号解析;保持与既有行为一致
            // (复杂场景建议使用 json/kv 等协议解析器避免干扰)。
            if s.starts_with('"') || s.starts_with("r#\"") || s.starts_with("r\"") {
                // 引号或原始字符串优先整体解析,避免被错误切分
                let buf = alt((quot_r_str, quot_str)).parse_next(data)?;
                return Ok(buf.to_string());
            }
            let p = s.find(self.sep_str());
            let q = s.find(ups.as_str());
            let idx = match (p, q) {
                (Some(i), Some(j)) => Some(i.min(j)),
                (Some(i), None) => Some(i),
                (None, Some(j)) => Some(j),
                (None, None) => None,
            };
            if let Some(i) = idx {
                let (left, right) = s.split_at(i);
                *data = right; // 保持与 take_until 一致:不消费结束符本身
                return Ok(left.to_string());
            }
            let buf = take_to_end.parse_next(data)?;
            return Ok(buf.to_string());
        }
        // 无次级结束符:原有语义
        let buf = alt((
            quot_r_str,
            quot_str,
            take_until(0.., self.sep_str()),
            take_to_end,
        ))
        .parse_next(data)?;
        Ok(buf.to_string())
    }
    pub fn read_until_sep_repeat(&self, num: usize, data: &mut &str) -> WResult<String> {
        // Pattern separators are not supported in repeat mode.
        if self.is_pattern() {
            return winnow::combinator::fail
                .context(ctx_desc("sep pattern not supported in repeat mode"))
                .parse_next(data);
        }
        let buffer: Vec<&str> = separated(
            Range::from(num),
            take_until(1.., self.sep_str()),
            self.sep_str(),
        )
        .parse_next(data)?;

        let msg = buffer.join(self.sep_str());
        Ok(msg)
    }
}

impl Display for WplFmt<&WplSep> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if !self.0.infer {
            if let Some(SepEnum::Pattern(p)) = &self.0.cur_val {
                write!(f, "{{{}}}", p.raw())?;
            } else {
                for c in self.0.sep_str().chars() {
                    if c != ' ' {
                        write!(f, "\\{}", c)?;
                    }
                }
            }
        }
        Ok(())
    }
}

impl Display for GenFmt<&WplSep> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if let Some(SepEnum::Pattern(p)) = &self.0.cur_val {
            write!(f, "{{{}}}", p.raw())?;
        } else {
            write!(f, "{}", self.0.sep_str())?;
        }
        Ok(())
    }
}

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

    #[test]
    fn test_sep_enum_from_str() {
        // Test \s -> space
        assert_eq!(SepEnum::from("\\s"), SepEnum::Str(" ".into()));
        assert_eq!(SepEnum::from("s"), SepEnum::Str(" ".into()));

        // Test \t -> tab
        assert_eq!(SepEnum::from("\\t"), SepEnum::Str("\t".into()));
        assert_eq!(SepEnum::from("t"), SepEnum::Str("\t".into()));

        // Test \S -> Whitespace
        assert_eq!(SepEnum::from("\\S"), SepEnum::Whitespace);
        assert_eq!(SepEnum::from("S"), SepEnum::Whitespace);

        // Test \0 -> End
        assert_eq!(SepEnum::from("\\0"), SepEnum::End);
        assert_eq!(SepEnum::from("0"), SepEnum::End);

        // Test regular string
        assert_eq!(SepEnum::from(","), SepEnum::Str(",".into()));
    }

    #[test]
    fn test_whitespace_sep_read_until() {
        // Test reading until space
        let mut data = "hello world";
        let sep = WplSep::field_sep("\\S");
        let result = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(result, "hello");
        assert_eq!(data, " world");

        // Test reading until tab
        let mut data = "hello\tworld";
        let sep = WplSep::field_sep("\\S");
        let result = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(result, "hello");
        assert_eq!(data, "\tworld");
    }

    #[test]
    fn test_tab_sep_read_until() {
        // Test reading until tab
        let mut data = "field1\tfield2\tfield3";
        let sep = WplSep::field_sep("\\t");
        let result = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(result, "field1");
        assert_eq!(data, "\tfield2\tfield3");
    }

    #[test]
    fn test_whitespace_consume_sep() {
        // Test consuming space with Whitespace separator
        let mut data = " world";
        let sep = WplSep::field_sep("\\S");
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "world");

        // Test consuming tab with Whitespace separator
        let mut data = "\tworld";
        let sep = WplSep::field_sep("\\S");
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "world");
    }

    #[test]
    fn test_tab_consume_sep() {
        // Test consuming tab
        let mut data = "\tfield2";
        let sep = WplSep::field_sep("\\t");
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "field2");
    }

    // ── Pattern integration tests ────────────────────────────────────

    #[test]
    fn test_pattern_read_until_sep_literal() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("abc").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "xyzabcdef";
        let result = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(result, "xyz");
        // data stops AT the separator, not past it
        assert_eq!(data, "abcdef");
    }

    #[test]
    fn test_pattern_read_until_sep_glob() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("*=").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "key=value";
        let result = sep.read_until_sep(&mut data).unwrap();
        // Star non-greedy: "*=" → Star matches "key" (field content), "=" is separator
        // data stops AT the separator "=value"
        assert_eq!(result, "key");
        assert_eq!(data, "=value");
    }

    #[test]
    fn test_pattern_read_until_sep_no_match() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("xyz").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "abcdef";
        let result = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(result, "abcdef");
        assert_eq!(data, "");
    }

    #[test]
    fn test_pattern_consume_sep() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("\\s=").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "  =value";
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "value");
    }

    #[test]
    fn test_pattern_try_consume_sep() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("\\s=").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        // When it matches
        let mut data = " =value";
        sep.try_consume_sep(&mut data).unwrap();
        assert_eq!(data, "value");
        // When it doesn't match — input unchanged
        let mut data = "value";
        sep.try_consume_sep(&mut data).unwrap();
        assert_eq!(data, "value");
    }

    #[test]
    fn test_pattern_is_pattern() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("abc").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        assert!(sep.is_pattern());
        assert!(!sep.is_space_sep());

        let sep2 = WplSep::field_sep(",");
        assert!(!sep2.is_pattern());
    }

    #[test]
    fn test_pattern_display_wpl_fmt() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("*\\s(key=)").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let display = format!("{}", WplFmt(&sep));
        assert_eq!(display, "{*\\s(key=)}");
    }

    #[test]
    fn test_pattern_display_gen_fmt() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("abc").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let display = format!("{}", GenFmt(&sep));
        assert_eq!(display, "{abc}");
    }

    #[test]
    fn test_pattern_serde_roundtrip() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("*=").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let json = serde_json::to_string(&sep).unwrap();
        let sep2: WplSep = serde_json::from_str(&json).unwrap();
        assert_eq!(sep, sep2);
    }

    #[test]
    fn test_pattern_preserve_read_until() {
        use crate::ast::syntax::sep_pattern::build_pattern;
        let pat = build_pattern("*\\s(key=)").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "hello  key=value";
        let result = sep.read_until_sep(&mut data).unwrap();
        // Star matches "hello" (field content), data stops AT separator "  key=value"
        assert_eq!(result, "hello");
        assert_eq!(data, "  key=value");
    }

    #[test]
    fn test_pattern_read_then_consume() {
        // Verify read_until_sep + consume_sep round-trip works correctly.
        use crate::ast::syntax::sep_pattern::build_pattern;

        // Literal pattern
        let pat = build_pattern(",").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "aaa,bbb";
        let f1 = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(f1, "aaa");
        assert_eq!(data, ",bbb");
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "bbb");

        // Glob pattern with Star
        let pat = build_pattern("*=").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "key=value";
        let f1 = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(f1, "key");
        assert_eq!(data, "=value");
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "value");

        // Whitespace glob pattern
        let pat = build_pattern("\\s=").unwrap();
        let sep = WplSep::field_sep_pattern(pat);
        let mut data = "key  =value";
        let f1 = sep.read_until_sep(&mut data).unwrap();
        assert_eq!(f1, "key");
        assert_eq!(data, "  =value");
        sep.consume_sep(&mut data).unwrap();
        assert_eq!(data, "value");
    }
}