summaryrefslogtreecommitdiffstats
path: root/rfc2822/src/grammar.lalrpop
blob: f20735edf93b3778879c395b142c9e40463f792c (plain)
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
698
// -*- mode: Rust; -*-
use Error;

use strings::{
    strings_flatten_into,
    strings_flatten2,
    strings_flatten,
};
use component::{
    Component,
    components_kill_ws,
    components_merge,
};
use lexer;
use lexer::Token;

grammar<'input>;

// RFC 4880 says:
//
//   5.11.  User ID Packet (Tag 13)
//
//   A User ID packet consists of UTF-8 text that is intended to represent
//   the name and email address of the key holder.  By convention, it
//   includes an RFC 2822 [RFC2822] mail name-addr, but there are no
//   restrictions on its content.
//
// At least today, the convention is more along the lines of RFC
// 2822's mailbox instead of its name-addr.  The only different is
// that the mailbox production allows for a bare email address i.e.,
// one without angle brackets whereas the name-addr production
// requires angle brackets.
//
// A further convention is an ssh-host-uri production:
//
//   ssh-host-uri = "ssh://" dns-hostname


CRLF: () = {
    CR LF
}

// text            =       %d1-9 /         ; Characters excluding CR and LF
//                         %d11 /
//                         %d12 /
//                         %d14-127 /
//                         obs-text
text : Token<'input> = {
    WSP,
    NO_WS_CTL,
    specials,
    OTHER,
}

// specials        =       "(" / ")" /     ; Special characters used in
//                         "<" / ">" /     ;  other parts of the syntax
//                         "[" / "]" /
//                         ":" / ";" /
//                         "@" / "\" /
//                         "," / "." /
//                         DQUOTE
specials : Token<'input> = {
    LPAREN,
    RPAREN,
    LANGLE,
    RANGLE,
    LBRACKET,
    RBRACKET,
    COLON,
    SEMICOLON,
    AT,
    BACKSLASH,
    COMMA,
    DOT,
    DQUOTE,
};


// 3.2.2. Quoted characters

// quoted-pair     =       ("\" text) / obs-qp
//
// In RFC 2822, text is a single character and the BACKSLAH is
// followed by exactly one character.  As an optimization, our lexer
// groups runs of 'text' characters into a single token, Token::OTHER.
// Since a quoted pair can always be followed by a run of OTHER
// characters, the semantics are preserved.
quoted_pair : Token<'input> = {
    BACKSLASH <text>,
}

// 3.2.3. Folding white space and comments

// Folding white space
//
// FWS             =       ([*WSP CRLF] 1*WSP) /   ;
//                         obs-FWS
//
//   Runs of FWS, comment or CFWS that occur between lexical tokens in
//   a structured field header are semantically interpreted as a
//   single space character.
#[inline]
FWS : Component = {
   (WSP* CRLF)? WSP+ => Component::WS,
}

// ctext           =       NO-WS-CTL /     ; Non white space controls
//                         %d33-39 /       ; The rest of the US-ASCII
//                         %d42-91 /       ;  characters not including "(",
//                         %d93-126        ;  ")", or "\"
ctext : Token<'input> = {
    NO_WS_CTL,

    // LPAREN,
    // RPAREN,
    LANGLE,
    RANGLE,
    LBRACKET,
    RBRACKET,
    COLON,
    SEMICOLON,
    AT,
    // BACKSLASH,
    COMMA,
    DOT,
    DQUOTE,

    OTHER,
}

// ccontent        =       ctext / quoted-pair / comment
ccontent : String = {
    <c:ctext> => c.to_string(),
    <c:quoted_pair> => c.to_string(),
    <c:comment> => {
        let mut s = String::new();
        s.push('(');
        if let Component::Comment(comment) = c {
            s.push_str(&comment[..]);
        } else {
            panic!("Expected a Component::Comment");
        }
        s.push(')');
        s
    },
}

// comment         =       "(" *([FWS] ccontent) [FWS] ")"
pub(crate) Comment : Component = {
    <comment>
}

comment : Component = {
    LPAREN <c:(<FWS?> <ccontent>)*> <d:FWS?> RPAREN => {
        let mut s = strings_flatten2(
            c.into_iter().map(|(fws, c)| (fws.is_some(), c)), " ");

        if d.is_some() {
            s.push(' ');
        }

        Component::Comment(s)
    },
}

// CFWS            =       *([FWS] comment) (([FWS] comment) / FWS)
pub(crate) Cfws : Vec<Component> = {
    <c:CFWS> => {
        components_merge(c)
    }
}

CFWS : Vec<Component> = {
    // <c:(FWS? <comment>)*> FWS? <d:comment> => ...,
    // <c:(FWS? <comment>)*> FWS => ...,

    // The following is equivalent to the above, but the actions are a
    // bit simpler.
    <c:(<FWS?> <comment>)+> => {
        let v : Vec<Component> = c.into_iter()
            .map(|(w, c)| {
                if let Some(w) = w {
                    vec![w, c]
                } else {
                    vec![c]
                }
            })
            .flatten()
            .collect();
        v
    },
    <c:(<FWS?> <comment>)*> <w2:FWS> => {
        let mut v : Vec<Component> = c.into_iter()
            .map(|(w, c)| {
                if let Some(w) = w {
                    vec![w, c]
                } else {
                    vec![c]
                }
            })
            .flatten()
            .collect();
        v.push(w2);
        v
    }
}

// 3.2.4. Atom

// atext           =       ALPHA / DIGIT / ; Any character except controls,
//                         "!" / "#" /     ;  SP, and specials.
//                         "$" / "%" /     ;  Used for atoms
//                         "&" / "'" /
//                         "*" / "+" /
//                         "-" / "/" /
//                         "=" / "?" /
//                         "^" / "_" /
//                         "`" / "{" /
//                         "|" / "}" /
//                         "~"
//
// As an optimization the lexer collects atexts, i.e., Token::OTHER is
// 1*atext.
atext_plus : String = {
    <a:OTHER> => {
        let a = a.to_string();
        assert!(a.len() > 0);
        a
    },
}


// The display-name in a name-addr production often includes a ., but
// is not quoted.  The RFC even recommends supporting this variation.
other_or_dot : String = {
    <a:OTHER> => a.to_string(),
    <d:DOT> => d.to_string(),
}

atext_dot_plus : String = {
    <a:other_or_dot+> => strings_flatten(a.into_iter(), ""),
}

// atom            =       [CFWS] 1*atext [CFWS]
//
// "Both atom and dot-atom are interpreted as a single unit, comprised
// of the string of characters that make it up.  Semantically, the
// optional comments and FWS surrounding the rest of the characters
// are not part of the atom"
pub(crate) Atom : Vec<Component> = {
    <a:atom> => components_merge(a),
}

atom : Vec<Component> = {
    <c1:CFWS?> <a:atext_dot_plus> <c2:CFWS?> =>
        components_concat!(
            components_kill_ws(c1, false, true),
            Component::Text(a),
            components_kill_ws(c2, true, false)),
}

// See the phrase production for this variant of the 'atom' production
// exists, and why the 'CFWS?'es are not included.
atom_prime : Component = {
    <a:atext_dot_plus> => Component::Text(a),
}

// dot-atom        =       [CFWS] dot-atom-text [CFWS]
//
// "Both atom and dot-atom are interpreted as a single unit, comprised
// of the string of characters that make it up.  Semantically, the
// optional comments and FWS surrounding the rest of the characters
// are not part of the atom"
pub(crate) DotAtom : Vec<Component> = {
    <d:dot_atom> => components_merge(d),
}

dot_atom : Vec<Component> = {
    <c1:CFWS?> <a:dot_atom_text> <c2:CFWS?> =>
        components_concat!(
            components_kill_ws(c1, false, true),
            a,
            components_kill_ws(c2, true, false)),
}

// A variant of dot_atom that places all comments to the left.
dot_atom_left : Vec<Component> = {
    <c1:CFWS?> <a:dot_atom_text> <c2:CFWS?> =>
        components_concat!(
            components_kill_ws(
                Some(components_concat!(c1, c2)), false, true),
            a),
}

// A variant of dot_atom that places all comments to the right.
dot_atom_right : Vec<Component> = {
    <c1:CFWS?> <a:dot_atom_text> <c2:CFWS?> =>
        components_concat!(
            a,
            components_kill_ws(
                Some(components_concat!(c1, c2)), true, false)),
}

// dot-atom-text   =       1*atext *("." 1*atext)
dot_atom_text : Component = {
    <v:atext_plus> <w:(DOT <atext_plus>)*> => {
        let mut v = v;
        if w.len() > 0 {
            v.push('.');
        }
        Component::Text(
            strings_flatten_into(v, w.into_iter(), "."))
    },
}

// 3.2.5. Quoted strings

// qtext           =       NO-WS-CTL /     ; Non white space controls
//                         %d33 /          ; The rest of the US-ASCII
//                         %d35-91 /       ;  characters not including "\"
//                         %d93-126        ;  or the quote character
qtext : Token<'input> = {
    NO_WS_CTL,

    LPAREN,
    RPAREN,
    LANGLE,
    RANGLE,
    LBRACKET,
    RBRACKET,
    COLON,
    SEMICOLON,
    AT,
    // BACKSLASH,
    COMMA,
    DOT,
    // DQUOTE,

    OTHER,
}

// qcontent        =       qtext / quoted-pair
qcontent : Component = {
    <c:qtext> => Component::Text(c.to_string()),
    <c:quoted_pair> => Component::Text(c.to_string()),
}

// quoted-string   =       [CFWS]
//                         DQUOTE *([FWS] qcontent) [FWS] DQUOTE
//                         [CFWS]
pub(crate) QuotedString : Vec<Component> = {
    <q:quoted_string> => components_merge(q),
}

quoted_string : Vec<Component> = {
    <c1:CFWS?> DQUOTE <c:(<FWS?> <qcontent>)*> <d:FWS?> DQUOTE <c2:CFWS?> => {
        // Make sure any leading and trailing whitespace *inside* the
        // quotes is turned into Component::Text.
        components_concat!(
            // c1 is an Option<Vec<Component>>.
            c1,
            // c is a Vec<(Option<Component>, Component)>.  Turn it
            // into a Vec<Component>.
            c.into_iter()
                .map(|(fws, c)| {
                    if let Some(_) = fws {
                        vec![Component::Text(" ".to_string()), c]
                    } else {
                        vec![c]
                    }
                })
                .flatten()
                .collect::<Vec<Component>>(),
            // d is an Option<Component>, turn it into a
            // Option<Vec<Component>>.
            d.map(|_| vec![Component::Text(" ".to_string())]),
            c2)
    },
}

// Variant of quoted_string that moves all comments to the left.
quoted_string_left : Vec<Component> = {
    <c1:CFWS?> DQUOTE <c:(<FWS?> <qcontent>)*> <d:FWS?> DQUOTE <c2:CFWS?> => {
        // Make sure any leading and trailing whitespace *inside* the
        // quotes is turned into Component::Text.
        components_concat!(
            // c1 is an Option<Vec<Component>>.
            components_kill_ws(Some(components_concat!(c1, c2)), false, true),
            // c is a Vec<(Option<Component>, Component)>.  Turn it
            // into a Vec<Component>.
            c.into_iter()
                .map(|(fws, c)| {
                    if let Some(_) = fws {
                        vec![Component::Text(" ".to_string()), c]
                    } else {
                        vec![c]
                    }
                })
                .flatten()
                .collect::<Vec<Component>>(),
            // d is an Option<Component>, turn it into a
            // Option<Vec<Component>>.
            d.map(|_| vec![Component::Text(" ".to_string())]))
    },
}

// See the phrase production for this variant of the 'quoted_string'
// production exists, and why the 'CFWS?'es are not included.
quoted_string_prime : Vec<Component> = {
    DQUOTE <c:(<FWS?> <qcontent>)*> <d:FWS?> DQUOTE => {
        // Make sure any leading and trailing whitespace *inside* the
        // quotes is turned into Component::Text.
        components_concat!(
            // c is a Vec<(Option<Component>, Component)>.  Turn it
            // into a Vec<Component>.
            c.into_iter()
                .map(|(fws, c)| {
                    if let Some(_) = fws {
                        vec![Component::Text(" ".to_string()), c]
                    } else {
                        vec![c]
                    }
                })
                .flatten()
                .collect::<Vec<Component>>(),
            // d is an Option<Component>, turn it into a
            // Option<Vec<Component>>.
            d.map(|_| vec![Component::Text(" ".to_string())]))
    },
}

// 3.2.6. Miscellaneous tokens

// word            =       atom / quoted-string
pub(crate) Word : Vec<Component> = {
    <w:word> => components_merge(w),
}

word : Vec<Component> = {
    atom,
    quoted_string,
}

// phrase          =       1*word / obs-phrase

pub(crate) Phrase : Vec<Component> = {
    <p:phrase> => components_merge(p),
}

// phrase : String = {
//     <v:word+> => strings_flatten(v, ""),
// }
//
// Note: consider the following parse tree:
//
//                         phrase
//                        /      \
//                  word           word
//                /                    \
//           atom                        atom
//       /    |    \                 /    |    \
// CFWS+?   atext+   CFWS?     CFWS+?   atext+   CFWS?
//
// This has an ambiguity!  Does a CFWS immediate after the first
// atext+ belong to the first atom or the second?  And, if there are
// no CFWSes, how do we split the atext?
//
// To avoid these problems, we modify the grammar as presented in the
// RFC as follows:
atom_or_quoted_string : Vec<Component> = {
    <a:atom_prime> <r:cfws_or_quoted_string?> => {
        // Note: it's not possible to have multiple atoms in a row.
        // The following:
        //
        //   foo bar
        //
        // is 'atom_prime CFWS atom_prime'.

        components_concat!(a, r)
    },
    <q:quoted_string_prime+> <r:cfws_or_atom?> => {
        // But, it's possible to have multiple quoted strings in a
        // row, e.g.:
        //
        //   "foo""bar"
        //
        // Note that '"foo" "bar"' would match quoted_string_prime,
        // CFWS, quoted_string_prime.

        components_concat!(
            q.into_iter().flatten().collect::<Vec<Component>>(), r)
    },
}

cfws_or_quoted_string : Vec<Component> = {
    <c:CFWS> <r:atom_or_quoted_string?> => components_concat!(c, r),
    <q:quoted_string_prime+> <r:cfws_or_atom?> =>
        components_concat!(
            q.into_iter().flatten().collect::<Vec<Component>>(), r),
}

cfws_or_atom : Vec<Component> = {
    <c:CFWS> <r:atom_or_quoted_string?> => components_concat!(c, r),
    <a:atom_prime> <r:cfws_or_quoted_string?> => components_concat!(a, r),
}

phrase : Vec<Component> = {
    <c:CFWS?> <r:atom_or_quoted_string> => components_concat!(c, r),
}

// 3.4. Address Specification

// mailbox         =       name-addr / addr-spec
// pub(crate) Mailbox : Vec<Component> = {
//     mailbox,
// }
// 
// mailbox : Vec<Component> = {
//     name_addr,
//     addr_spec,
// }

// name-addr       =       [display-name] angle-addr
pub(crate) NameAddr : Vec<Component> = {
    <n:name_addr> => components_merge(n),
}

// The display_name ends in an optional CFWS and the angle_addr starts
// with one.  This causes an ambiguity.  The angle_addr_prime
// production removes the optional leading CFWS non-terminal.
name_addr : Vec<Component> = {
    <n:display_name?> <a:angle_addr_prime> =>
        components_concat!(n, a),
}


// angle-addr      =       [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
pub(crate) AngleAddr : Vec<Component> = {
    <a:angle_addr> => components_merge(a),
}

angle_addr : Vec<Component> = {
    <c1:CFWS?> LANGLE <a:addr_spec> RANGLE <c2:CFWS?> =>
        components_concat!(c1, a, c2),
}

angle_addr_prime : Vec<Component> = {
    LANGLE <a:addr_spec> RANGLE <c2:CFWS?> =>
        components_concat!(a, c2),
}


// display-name    =       phrase
display_name : Vec<Component> = {
    <p:phrase> => components_kill_ws(Some(p), true, true),
}

// 3.4.1. Addr-spec specification

// addr-spec       =       local-part "@" domain
pub(crate) AddrSpec : Vec<Component> = {
    <a:addr_spec> => components_merge(a),
}

addr_spec : Vec<Component> = {
    <l:local_part> AT <d:domain> => {
        let mut l = components_merge(l);
        let mut d = components_merge(d);

        // local_part and domain can both be preceded or followed by
        // comment-folding whitespace.  So, something like:
        //
        //   "<(comment) (comment) \r\n foo (comment)@ (comment) bar.com (comment)>"
        //
        // is valid (it's foo@bar.com).

        // The local part may start with commends and the domain part
        // may end with comments.
        let local_part = l.pop().expect("empty local_part");
        let domain = d.remove(0);

        let mut v = components_merge(
            vec![local_part, Component::Text("@".into()), domain]);
        assert_eq!(v.len(), 1, "Expected 1 component, got: {:?}", v);
        let addr = match v.pop() {
            Some(Component::Text(addr)) =>
                Component::Address(addr),
            Some(c) =>
                panic!("addr_spec production failed: {:?}", c),
            None =>
                panic!("addr_spec production failed"),
        };

        components_concat!(l, addr, d)
    },
}

// local-part      =       dot-atom / quoted-string / obs-local-part
local_part : Vec<Component> = {
    dot_atom_left,
    quoted_string_left,
}

// domain          =       dot-atom / domain-literal / obs-domain
domain : Vec<Component> = {
    dot_atom_right,
    domain_literal,
}


// domain-literal  =       [CFWS] "[" *([FWS] dcontent) [FWS] "]" [CFWS]
pub(crate) DomainLiteral : Vec<Component> = {
    <d:domain_literal> => components_merge(d),
}

domain_literal : Vec<Component> = {
    <c1:CFWS?> LBRACKET <c:(<FWS?> <dcontent>)*> <d:FWS?> RBRACKET <c2:CFWS?> => {
        components_concat!(
            // c1 is an Option<Vec<Component>>.
            c1,
            Component::Text("[".into()),
            // c is a Vec<(Option<Component>, Component)>.  Turn it
            // into a Vec<Component>.
            c.into_iter()
                .map(|(fws, c)| {
                    let c = Component::Text(c.to_string());
                    if let Some(fws) = fws {
                        vec![fws, c]
                    } else {
                        vec![c]
                    }
                })
                .flatten()