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
use nom::branch::alt;
use nom::bytes::complete::{escaped_transform, take_while, take_while1, take_while_m_n};
use nom::character::complete::{char, none_of, one_of};
use nom::combinator::{cut, map_opt, map_res, not, opt, peek, success, value};
use nom::error::{context, FromExternalError, ParseError};
use nom::sequence::{delimited, preceded};
use nom::{IResult, Parser};
use crate::format::{ChildContent, LeadingText, TailingText, TemplateLiteral, Text};
use crate::result::ParseResult;
use super::comment::{span0, span0_inline};
use super::template::template_literal;
/// Parse tailing text in the format #<non-whitespace-chars>
/// Example: #tag, #tag_123, #标签, #tag-name.ext
pub fn tailing_text(input: &str) -> ParseResult<&str, TailingText> {
let mut parser = opt(preceded(
char('#'),
take_while1(|c: char| !c.is_whitespace()),
));
let (remaining, result) = parser.parse(input)?;
match result {
Some(tag) => Ok((remaining, TailingText::Text(tag.to_string()))),
None => Ok((remaining, TailingText::None)),
}
}
pub fn text_line(input: &str) -> ParseResult<&str, ChildContent> {
let (input, (_, _, leading, _, text, _, tailing)) = delimited(
span0,
(
not(one_of("}@#")),
span0_inline,
alt((leading_text, success(LeadingText::None))),
span0_inline,
text,
span0_inline,
alt((tailing_text, success(TailingText::None))),
),
span0_inline,
)
.parse(input)?;
Ok((input, ChildContent::TextLine(leading, text, tailing)))
}
pub fn leading_text(input: &str) -> ParseResult<&str, LeadingText> {
context(
"leading_text",
delimited(
one_of("["),
alt((
map_res(
// force quotes to be adjacent to the ] symbol to ensure that
// there is only one set of escaped text inside, otherwise it fails,
// fallback to plain text
(
span0_inline,
template_literal,
span0_inline,
peek(one_of("]")),
),
|s: ((), TemplateLiteral, (), char)| {
Ok::<LeadingText, nom::error::Error<&str>>(LeadingText::TemplateLiteral(
s.1,
))
},
),
map_res(
// force quotes to be adjacent to the ] symbol to ensure that
// there is only one set of escaped text inside, otherwise it fails,
// fallback to plain text
(span0_inline, escaped_text, span0_inline, peek(one_of("]"))),
|s: ((), String, (), char)| {
Ok::<LeadingText, nom::error::Error<&str>>(LeadingText::Text(s.1))
},
),
map_res(
take_while(|c| c != ']' && c != '\n' && c != '\r'),
|s: &str| {
Ok::<LeadingText, nom::error::Error<&str>>(LeadingText::Text(s.to_string()))
},
),
)),
char(']'),
),
)
.parse(input)
}
pub fn text(input: &str) -> ParseResult<&str, Text> {
context(
"text",
alt((
map_res(template_literal, |s| {
Ok::<Text, nom::error::Error<&str>>(Text::TemplateLiteral(s))
}),
map_res(escaped_text, |s| {
Ok::<Text, nom::error::Error<&str>>(Text::Text(s))
}),
map_res(plain_text, |s| {
Ok::<Text, nom::error::Error<&str>>(Text::Text(s))
}),
)),
)
.parse(input)
}
pub fn plain_text(input: &str) -> ParseResult<&str, String> {
// Find the end of plain text, which is a newline character.
// Note: '#' is NOT a stop character here — tailing text (#tag) is only
// allowed after quoted text ("...", '...', or `...`). When text is plain/bare,
// any '#' and subsequent characters become part of the text itself.
let mut end_pos = 0;
let chars: Vec<char> = input.chars().collect();
for i in 0..chars.len() {
let ch = chars[i];
// Stop at newline
if ch == '\n' || ch == '\r' {
break;
}
end_pos = i + 1;
}
if end_pos == 0 {
// Empty text is still valid
return Ok((input, String::new()));
}
let (text, remaining) = input.split_at(
input
.char_indices()
.nth(end_pos)
.map(|(pos, _)| pos)
.unwrap_or(input.len()),
);
Ok((remaining, text.to_string()))
}
pub fn escaped_text(input: &str) -> ParseResult<&str, String> {
let (input, s) = context(
"escaped_text",
alt((
delimited(
char('"'),
cut(alt((
value(String::new(), peek(char('"'))),
escaped_transform(
none_of("\"\\\n\r"),
'\\',
alt((
parse_unicode,
value('\n', char('n')),
value('\r', char('r')),
value('\t', char('t')),
value('\\', char('\\')),
value('/', char('/')),
value('"', char('"')),
value('\'', char('\'')),
value('`', char('`')),
)),
),
))),
char('"'),
),
delimited(
char('\''),
cut(alt((
value(String::new(), peek(char('\''))),
escaped_transform(
none_of("\'\\\n\r"),
'\\',
alt((
parse_unicode,
value('\n', char('n')),
value('\r', char('r')),
value('\t', char('t')),
value('\\', char('\\')),
value('/', char('/')),
value('"', char('"')),
value('\'', char('\'')),
value('`', char('`')),
)),
),
))),
char('\''),
),
)),
)
.parse(input)?;
Ok((input, s.to_string()))
}
// from https://github.com/rust-bakery/nom/blob/a44b52ed9052a66f5eb2add9aa5b314f034dc580/examples/string.rs#L30
// with some modifications
pub(crate) fn parse_unicode<'a, E>(input: &'a str) -> IResult<&'a str, char, E>
where
E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,
{
// `take_while_m_n` parses between `m` and `n` bytes (inclusive) that match
// a predicate. `parse_hex` here parses between 1 and 6 hexadecimal numerals.
let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit());
// `parse_hex2` parses between 1 and 4 hexadecimal numerals.
// This is used for the `uXXXX` format, which is a single unicode code point.
let parse_hex2 = take_while_m_n(1, 4, |c: char| c.is_ascii_hexdigit());
// `preceded` takes a prefix parser, and if it succeeds, returns the result
// of the body parser. In this case, it parses u{XXXX}.
let parse_delimited_hex = preceded(
char('u'),
// `delimited` is like `preceded`, but it parses both a prefix and a suffix.
// It returns the result of the middle parser. In this case, it parses
// {XXXX}, where XXXX is 1 to 6 hex numerals, and returns XXXX
alt((delimited(char('{'), parse_hex, char('}')), parse_hex2)),
);
// `map_res` takes the result of a parser and applies a function that returns
// a Result. In this case we take the hex bytes from parse_hex and attempt to
// convert them to a u32.
let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16));
// map_opt is like map_res, but it takes an Option instead of a Result. If
// the function returns None, map_opt returns an error. In this case, because
// not all u32 values are valid unicode code points, we have to fallibly
// convert to char with from_u32.
map_opt(parse_u32, std::char::from_u32).parse(input)
}
#[cfg(test)]
mod tests {
use crate::format::{Literal, RValue, TemplateLiteralPart, Text, Variable};
use super::*;
#[test]
fn test_plain_text() {
assert_eq!(plain_text("foo"), Ok(("", "foo".to_string())));
assert_eq!(plain_text("foo\n"), Ok(("\n", "foo".to_string())));
assert_eq!(plain_text("foo\r\n"), Ok(("\r\n", "foo".to_string())));
assert_eq!(plain_text("foo bar"), Ok(("", "foo bar".to_string())));
}
#[test]
fn test_escaped_text() {
assert_eq!(escaped_text(r#""""#), Ok(("", "".to_string())));
assert_eq!(escaped_text("''"), Ok(("", "".to_string())));
assert_eq!(escaped_text(r#""foo""#), Ok(("", "foo".to_string())));
assert_eq!(escaped_text(r#""foo\n""#), Ok(("", "foo\n".to_string())));
assert_eq!(
escaped_text(r#""foo\r\n""#),
Ok(("", "foo\r\n".to_string()))
);
assert_eq!(
escaped_text(r#""foo bar""#),
Ok(("", "foo bar".to_string()))
);
assert_eq!(
escaped_text(r#""foo\"bar""#),
Ok(("", "foo\"bar".to_string()))
);
assert_eq!(
escaped_text(r#""foo\'bar""#),
Ok(("", "foo'bar".to_string()))
);
assert_eq!(
escaped_text(r#""foo'bar""#),
Ok(("", "foo'bar".to_string()))
);
assert_eq!(
escaped_text(r#""foo\\bar""#),
Ok(("", "foo\\bar".to_string()))
);
assert_eq!(
escaped_text(r#""foo\u6D4B\u{8BD5}""#),
Ok(("", "foo测试".to_string()))
);
}
#[test]
fn test_leading_text() {
assert_eq!(
leading_text("[foo]"),
Ok(("", LeadingText::Text("foo".to_string())))
);
assert_eq!(
leading_text("[foo bar ]"),
Ok(("", LeadingText::Text("foo bar ".to_string())))
);
assert_eq!(
leading_text("['foo bar']"),
Ok(("", LeadingText::Text("foo bar".to_string())))
);
assert_eq!(
leading_text(r#"[foo"bar]"#),
Ok(("", LeadingText::Text("foo\"bar".to_string())))
);
assert_eq!(
leading_text(r#"[foo'bar]"#),
Ok(("", LeadingText::Text("foo'bar".to_string())))
);
assert_eq!(
leading_text(r#"[foo\\bar]"#),
Ok(("", LeadingText::Text("foo\\\\bar".to_string())))
);
assert_eq!(
leading_text(r#"['foo\u6D4B\u{8BD5}']"#),
Ok(("", LeadingText::Text("foo测试".to_string())))
);
}
#[test]
fn test_plain_text_line() {
assert_eq!(
text_line("foo"),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("foo".to_string()),
TailingText::None
)
))
);
assert_eq!(
text_line("foo\n \r"),
Ok((
"\n \r",
ChildContent::TextLine(
LeadingText::None,
Text::Text("foo".to_string()),
TailingText::None
)
))
);
}
#[test]
fn test_escaped_text_line() {
assert_eq!(
text_line(r#""foo\u6D4B\u{8BD5}""#),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("foo测试".to_string()),
TailingText::None
)
))
);
}
#[test]
fn test_leading_text_line() {
assert_eq!(
text_line("[foo] aaaaaa"),
Ok((
"",
ChildContent::TextLine(
LeadingText::Text("foo".to_string()),
Text::Text("aaaaaa".to_string()),
TailingText::None
)
))
);
assert_eq!(
text_line("[foo bar] aaaaaa"),
Ok((
"",
ChildContent::TextLine(
LeadingText::Text("foo bar".to_string()),
Text::Text("aaaaaa".to_string()),
TailingText::None
)
))
);
// backslash in plain text will be preserved
assert_eq!(
text_line(r#"[foo bar] aaa\aaa"#),
Ok((
"",
ChildContent::TextLine(
LeadingText::Text("foo bar".to_string()),
Text::Text(r#"aaa\aaa"#.to_string()),
TailingText::None
)
))
);
assert_eq!(
text_line(r#"[foo bar] aaa\n\raaa"#),
Ok((
"",
ChildContent::TextLine(
LeadingText::Text("foo bar".to_string()),
Text::Text(r#"aaa\n\raaa"#.to_string()),
TailingText::None
)
))
);
assert_eq!(
text_line(r#"aaa\n\raaa"#),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text(r#"aaa\n\raaa"#.to_string()),
TailingText::None
)
))
);
// spaces around the plain text will not be trimmed
assert_eq!(
text_line("[ foo bar ] aaaaaa\n"),
Ok((
"\n",
ChildContent::TextLine(
LeadingText::Text(" foo bar ".to_string()),
Text::Text("aaaaaa".to_string()),
TailingText::None
)
))
);
// spaces around the quoted text are ignored
assert_eq!(
text_line("[ 'foo bar' ] \naaaaaa\r\n"),
Ok((
"\naaaaaa\r\n",
ChildContent::TextLine(
LeadingText::Text("foo bar".to_string()),
Text::Text("".to_string()),
TailingText::None
)
))
);
// only one set of quotes is allowed, or it will fallback to plain text
assert_eq!(
text_line("[ 'foo bar' ''] \naaaaaa\r\n"),
Ok((
"\naaaaaa\r\n",
ChildContent::TextLine(
LeadingText::Text(" 'foo bar' ''".to_string()),
Text::Text("".to_string()),
TailingText::None
)
))
);
// use template literal in leading text
assert_eq!(
text_line("[ `foo ${bar}` ] \naaaaaa\r\n"),
Ok((
"\naaaaaa\r\n",
ChildContent::TextLine(
LeadingText::TemplateLiteral(TemplateLiteral {
parts: vec![
TemplateLiteralPart::Text("foo ".to_string()),
TemplateLiteralPart::Value(RValue::Variable(Variable {
chain: vec!["bar".to_string()],
})),
],
}),
Text::Text("".to_string()),
TailingText::None
)
))
);
}
#[test]
fn test_template_line() {
let input = " \n `hello \n${world} ${123} world` \n";
let (remaining, result) = text_line.parse(input).unwrap();
assert_eq!(remaining, "\n");
assert_eq!(
result,
ChildContent::TextLine(
LeadingText::None,
Text::TemplateLiteral(TemplateLiteral {
parts: vec![
TemplateLiteralPart::Text("hello \n".to_string()),
TemplateLiteralPart::Value(RValue::Variable(Variable {
chain: vec!["world".to_string()],
})),
TemplateLiteralPart::Text(" ".to_string()),
TemplateLiteralPart::Value(RValue::Literal(Literal::Integer(123))),
TemplateLiteralPart::Text(" world".to_string()),
],
}),
TailingText::None
)
);
}
#[test]
fn test_tailing_text() {
// Test with quoted text
assert_eq!(
text_line(r##""hello world"#tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world".to_string()),
TailingText::Text("tag".to_string())
)
))
);
// Test with space before tailing text
assert_eq!(
text_line(r##""hello world" #tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world".to_string()),
TailingText::Text("tag".to_string())
)
))
);
// Test with plain text - # is NOT a tailing separator; it becomes part of the text
assert_eq!(
text_line(r##"hello world #tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world #tag".to_string()),
TailingText::None
)
))
);
// Test with leading and tailing text
assert_eq!(
text_line(r##"[speaker] "dialogue"#tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::Text("speaker".to_string()),
Text::Text("dialogue".to_string()),
TailingText::Text("tag".to_string())
)
))
);
// Test with special characters in tailing text
assert_eq!(
text_line(r##""text"#tag_123-abc.xyz"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("text".to_string()),
TailingText::Text("tag_123-abc.xyz".to_string())
)
))
);
// Test with Unicode in tailing text
assert_eq!(
text_line(r##""text"#标签"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("text".to_string()),
TailingText::Text("标签".to_string())
)
))
);
// Test with template literal
assert_eq!(
text_line(r##"`hello ${world}`#tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::TemplateLiteral(TemplateLiteral {
parts: vec![
TemplateLiteralPart::Text("hello ".to_string()),
TemplateLiteralPart::Value(RValue::Variable(Variable {
chain: vec!["world".to_string()],
})),
],
}),
TailingText::Text("tag".to_string())
)
))
);
// Test without tailing text
assert_eq!(
text_line(r#""hello world""#),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world".to_string()),
TailingText::None
)
))
);
// Test plain text without tailing text
assert_eq!(
text_line(r#"hello world"#),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world".to_string()),
TailingText::None
)
))
);
// Test with # followed by space (should be part of text, not tailing)
assert_eq!(
text_line(r##"hello world # not a tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world # not a tag".to_string()),
TailingText::None
)
))
);
// Test with # at end of line (no non-whitespace after)
assert_eq!(
text_line(r##"hello world #"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("hello world #".to_string()),
TailingText::None
)
))
);
// Test tailing text not allowed after plain text — # becomes part of the text
assert_eq!(
text_line(r##"some text #tag"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("some text #tag".to_string()),
TailingText::None
)
))
);
// Test with emoji in tailing text
assert_eq!(
text_line(r##""text"#tag😀"##),
Ok((
"",
ChildContent::TextLine(
LeadingText::None,
Text::Text("text".to_string()),
TailingText::Text("tag😀".to_string())
)
))
);
}
}