mf2_parser 0.1.1

Parser and AST definitions for MessageFormat 2
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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
use std::fmt::Debug;

use crate::util::LengthShort;
use crate::util::Location;
use crate::util::Span;
use crate::util::Spanned;
use crate::visitor::Visit;
use crate::visitor::Visitable;

macro_rules! ast_enum {
  {
    #[visit($visit_method:ident)]
    pub enum $name:ident<$lifetime:lifetime> {
      $( $item:ident $(<$item_lifetime:lifetime>)? ),* $(,)?
    }
  } => {
    #[derive(Clone)]
    pub enum $name<$lifetime> {
      $( $item ( $item$(<$item_lifetime>)? ), )*
    }

    impl ::std::fmt::Debug for $name<'_> {
      fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        match self {
          $( $name::$item(item) => ::std::fmt::Debug::fmt(item, f), )*
        }
      }
    }

    impl crate::util::Spanned for $name<'_> {
      fn span(&self) -> Span {
        match self {
          $( $name::$item(item) => item.span(), )*
        }
      }
    }

    impl<'text> crate::visitor::Visitable<'text> for $name<'text> {
      fn apply_visitor<'ast, V: crate::visitor::Visit<'ast, 'text> + ?Sized>(&'ast self, visitor: &mut V) {
        visitor.$visit_method(self);
      }

      fn apply_visitor_to_children<'ast, V: crate::visitor::Visit<'ast, 'text> + ?Sized>(&'ast self, visitor: &mut V) {
        match self {
          $( $name::$item(item) => item.apply_visitor(visitor), )*
        }
      }
    }
  };
}

#[derive(Clone)]
pub enum Message<'text> {
  Simple(Pattern<'text>),
  Complex(ComplexMessage<'text>),
}

impl Debug for Message<'_> {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      Message::Simple(pattern) => Debug::fmt(pattern, f),
      Message::Complex(complex) => Debug::fmt(complex, f),
    }
  }
}

impl Spanned for Message<'_> {
  fn span(&self) -> Span {
    match self {
      Message::Simple(pattern) => pattern.span(),
      Message::Complex(complex) => complex.span(),
    }
  }
}

impl<'text> Visitable<'text> for Message<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_message(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    match self {
      Message::Simple(pattern) => pattern.apply_visitor(visitor),
      Message::Complex(complex) => complex.apply_visitor(visitor),
    }
  }
}

#[derive(Debug, Clone)]
pub struct Pattern<'text> {
  /// Must be non-empty. Instead of an empty parts list, add a
  /// [PatternPart::Text] with an empty string.
  pub parts: Vec<PatternPart<'text>>,
}

impl Spanned for Pattern<'_> {
  fn span(&self) -> Span {
    match (self.parts.first(), self.parts.last()) {
      (Some(first), Some(last)) => {
        Span::new(first.span().start..last.span().end)
      }
      _ => unreachable!("Pattern must have at least one part"),
    }
  }
}

impl<'text> Visitable<'text> for Pattern<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_pattern(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    for part in &self.parts {
      part.apply_visitor(visitor);
    }
  }
}

ast_enum! {
  #[visit(visit_pattern_part)]
  pub enum PatternPart<'text> {
    Text<'text>,
    Escape,
    Expression<'text>,
    Markup<'text>,
  }
}

#[derive(Debug, Clone)]
pub struct Text<'text> {
  pub start: Location,
  pub content: &'text str,
}

impl Spanned for Text<'_> {
  fn span(&self) -> Span {
    Span::new(self.start..self.start + self.content)
  }
}

impl<'text> Visitable<'text> for Text<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_text(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    _visitor: &mut V,
  ) {
  }
}

#[derive(Debug, Clone)]
pub struct Escape {
  pub start: Location,
  pub escaped_char: char,
}

impl Spanned for Escape {
  fn span(&self) -> Span {
    Span::new(self.start..self.start + '\\' + self.escaped_char)
  }
}

impl<'text> Visitable<'text> for Escape {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_escape(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    _visitor: &mut V,
  ) {
  }
}

ast_enum! {
  #[visit(visit_expression)]
  pub enum Expression<'text> {
    LiteralExpression<'text>,
    VariableExpression<'text>,
    AnnotationExpression<'text>,
  }
}

#[derive(Debug, Clone)]
pub struct LiteralExpression<'text> {
  pub span: Span,
  pub literal: Literal<'text>,
  pub annotation: Option<Annotation<'text>>,
  pub attributes: Vec<Attribute<'text>>,
}

impl Spanned for LiteralExpression<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for LiteralExpression<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_literal_expression(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.literal.apply_visitor(visitor);
    if let Some(annotation) = &self.annotation {
      annotation.apply_visitor(visitor);
    }
    for attribute in &self.attributes {
      attribute.apply_visitor(visitor);
    }
  }
}

#[derive(Debug, Clone)]
pub struct VariableExpression<'text> {
  pub span: Span,
  pub variable: Variable<'text>,
  pub annotation: Option<Annotation<'text>>,
  pub attributes: Vec<Attribute<'text>>,
}

impl Spanned for VariableExpression<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for VariableExpression<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_variable_expression(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.variable.apply_visitor(visitor);
    if let Some(annotation) = &self.annotation {
      annotation.apply_visitor(visitor);
    }
    for attribute in &self.attributes {
      attribute.apply_visitor(visitor);
    }
  }
}

#[derive(Debug, Clone)]
pub struct Variable<'text> {
  pub span: Span,
  pub name: &'text str,
}

impl Spanned for Variable<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl Variable<'_> {
  pub fn name_span(&self) -> Span {
    Span::new(self.span.start + '$'..self.span.end)
  }
}

impl<'text> Visitable<'text> for Variable<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_variable(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    _visitor: &mut V,
  ) {
  }
}

#[derive(Debug, Clone)]
pub struct AnnotationExpression<'text> {
  pub span: Span,
  pub annotation: Annotation<'text>,
  pub attributes: Vec<Attribute<'text>>,
}

impl Spanned for AnnotationExpression<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for AnnotationExpression<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_annotation_expression(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.annotation.apply_visitor(visitor);
    for attribute in &self.attributes {
      attribute.apply_visitor(visitor);
    }
  }
}

ast_enum! {
  #[visit(visit_annotation)]
  pub enum Annotation<'text> {
    Function<'text>,
  }
}

#[derive(Debug, Clone)]
pub struct Identifier<'text> {
  pub start: Location,
  pub namespace: Option<&'text str>,
  pub name: &'text str,
}

impl Spanned for Identifier<'_> {
  fn span(&self) -> Span {
    let mut end = self.start;
    if let Some(namespace) = self.namespace {
      end = end + namespace + ':';
    }
    end = end + self.name;

    Span::new(self.start..end)
  }
}

impl<'text> Visitable<'text> for Identifier<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_identifier(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    _visitor: &mut V,
  ) {
  }
}

#[derive(Debug, Clone)]
pub struct Function<'text> {
  pub start: Location,
  pub id: Identifier<'text>,
  pub options: Vec<FnOrMarkupOption<'text>>,
}

impl Spanned for Function<'_> {
  fn span(&self) -> Span {
    let start = self.start;
    let end = self
      .options
      .last()
      .map_or(self.id.span().end, |last| last.span().end);
    Span::new(start..end)
  }
}

impl<'text> Visitable<'text> for Function<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_function(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.id.apply_visitor(visitor);
    for option in &self.options {
      option.apply_visitor(visitor);
    }
  }
}

#[derive(Debug, Clone)]
pub struct FnOrMarkupOption<'text> {
  pub key: Identifier<'text>,
  pub value: LiteralOrVariable<'text>,
}

impl Spanned for FnOrMarkupOption<'_> {
  fn span(&self) -> Span {
    let start = self.key.span().start;
    let end = self.value.span().end;
    Span::new(start..end)
  }
}

impl<'text> Visitable<'text> for FnOrMarkupOption<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_fn_or_markup_option(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.key.apply_visitor(visitor);
    self.value.apply_visitor(visitor);
  }
}

#[derive(Debug, Clone)]
pub struct Attribute<'text> {
  pub span: Span,
  pub key: Identifier<'text>,
  pub value: Option<Literal<'text>>,
}

impl Spanned for Attribute<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for Attribute<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_attribute(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.key.apply_visitor(visitor);
    if let Some(value) = &self.value {
      value.apply_visitor(visitor);
    }
  }
}

ast_enum! {
  #[visit(visit_literal_or_variable)]
  pub enum LiteralOrVariable<'text> {
    Literal<'text>,
    Variable<'text>,
  }
}

ast_enum! {
  #[visit(visit_literal)]
  pub enum Literal<'text> {
    Quoted<'text>,
    Text<'text>,
    Number<'text>,
  }
}

#[derive(Debug, Clone)]
pub struct Quoted<'text> {
  pub span: Span,
  pub parts: Vec<QuotedPart<'text>>,
}

impl Spanned for Quoted<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for Quoted<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_quoted(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    for part in &self.parts {
      part.apply_visitor(visitor);
    }
  }
}

ast_enum! {
  #[visit(visit_quoted_part)]
  pub enum QuotedPart<'text> {
    Text<'text>,
    Escape,
  }
}

#[derive(Debug, Clone, Copy)]
pub enum ExponentSign {
  Plus,
  Minus,
  None,
}

#[derive(Debug, Clone)]
pub struct Number<'text> {
  pub start: Location,
  pub raw: &'text str,
  pub is_negative: bool,
  pub integral_len: LengthShort,
  pub fractional_len: Option<LengthShort>,
  pub exponent_len: Option<(ExponentSign, LengthShort)>,
}

impl Spanned for Number<'_> {
  fn span(&self) -> Span {
    Span::new(self.start..self.start + self.raw)
  }
}

impl<'text> Visitable<'text> for Number<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_number(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    _visitor: &mut V,
  ) {
  }
}

impl<'text> Number<'text> {
  fn slice(&self, span: Span) -> &'text str {
    &self.raw[span.start.inner() as usize..span.end.inner() as usize]
  }

  fn integral_start(&self) -> Location {
    if self.is_negative {
      self.start + '-'
    } else {
      self.start
    }
  }

  fn integral_end(&self) -> Location {
    self.integral_start() + self.integral_len
  }

  pub fn integral_span(&self) -> Span {
    Span::new(self.integral_start()..self.integral_end())
  }

  pub fn integral_part(&self) -> &'text str {
    self.slice(self.integral_span())
  }

  pub fn fractional_span(&self) -> Option<Span> {
    self.fractional_len.map(|fractional_len| {
      let start = self.integral_end() + '.';
      let end = start + fractional_len;
      Span::new(start..end)
    })
  }

  pub fn fractional_part(&self) -> Option<&'text str> {
    self.fractional_span().map(|span| self.slice(span))
  }

  pub fn exponent_span(&self) -> Option<Span> {
    self.exponent_len.map(|(sign, exponent_len)| {
      let mut start = self.integral_end();
      if let Some(fractional_len) = &self.fractional_len {
        start = start + '.';
        start = start + *fractional_len;
      }

      start = start + 'e';

      if !matches!(sign, ExponentSign::None) {
        start = start + '-';
      };

      let end = start + exponent_len;

      Span::new(start..end)
    })
  }

  pub fn exponent_part(&self) -> Option<(ExponentSign, &'text str)> {
    self
      .exponent_span()
      .map(|span| (self.exponent_len.as_ref().unwrap().0, self.slice(span)))
  }
}

#[derive(Debug, Clone)]
pub struct Markup<'text> {
  pub span: Span,
  pub kind: MarkupKind,
  pub id: Identifier<'text>,
  pub options: Vec<FnOrMarkupOption<'text>>,
  pub attributes: Vec<Attribute<'text>>,
}

#[derive(Debug, Clone)]
pub enum MarkupKind {
  Open,
  Standalone,
  Close,
}

impl Spanned for Markup<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for Markup<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_markup(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.id.apply_visitor(visitor);
    let mut options = self.options.iter().peekable();
    let mut attributes = self.attributes.iter().peekable();
    loop {
      match (options.peek(), attributes.peek()) {
        (Some(option), Some(attribute)) => {
          if option.span().end <= attribute.span().start {
            option.apply_visitor(visitor);
            options.next();
          } else {
            attribute.apply_visitor(visitor);
            attributes.next();
          }
        }
        (Some(option), None) => {
          option.apply_visitor(visitor);
          options.next();
        }
        (None, Some(attribute)) => {
          attribute.apply_visitor(visitor);
          attributes.next();
        }
        (None, None) => break,
      }
    }
  }
}

#[derive(Debug, Clone)]
pub struct ComplexMessage<'text> {
  pub span: Span,
  pub declarations: Vec<Declaration<'text>>,
  pub body: ComplexMessageBody<'text>,
}

impl Spanned for ComplexMessage<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for ComplexMessage<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_complex_message(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    let mut visited_body = false;
    for declaration in &self.declarations {
      if !visited_body && declaration.span().start >= self.body.span().end {
        visited_body = true;
        self.body.apply_visitor(visitor);
      }
      declaration.apply_visitor(visitor);
    }
    if !visited_body {
      self.body.apply_visitor(visitor);
    }
  }
}

ast_enum! {
  #[visit(visit_declaration)]
  pub enum Declaration<'text> {
    InputDeclaration<'text>,
    LocalDeclaration<'text>,
  }
}

#[derive(Debug, Clone)]
pub struct InputDeclaration<'text> {
  pub start: Location,
  pub expression: VariableExpression<'text>,
}

impl Spanned for InputDeclaration<'_> {
  fn span(&self) -> Span {
    let start = self.start;
    let end = self.expression.span().end;
    Span::new(start..end)
  }
}

impl<'text> Visitable<'text> for InputDeclaration<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_input_declaration(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.expression.apply_visitor(visitor);
  }
}

#[derive(Debug, Clone)]
pub struct LocalDeclaration<'text> {
  pub start: Location,
  pub variable: Variable<'text>,
  pub expression: Expression<'text>,
}

impl Spanned for LocalDeclaration<'_> {
  fn span(&self) -> Span {
    let start = self.start;
    let end = self.expression.span().end;
    Span::new(start..end)
  }
}

impl<'text> Visitable<'text> for LocalDeclaration<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_local_declaration(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.variable.apply_visitor(visitor);
    self.expression.apply_visitor(visitor);
  }
}

ast_enum! {
  #[visit(visit_complex_message_body)]
  pub enum ComplexMessageBody<'text> {
    QuotedPattern<'text>,
    Matcher<'text>,
  }
}

#[derive(Debug, Clone)]
pub struct QuotedPattern<'text> {
  pub span: Span,
  pub pattern: Pattern<'text>,
}

impl Spanned for QuotedPattern<'_> {
  fn span(&self) -> Span {
    self.span
  }
}

impl<'text> Visitable<'text> for QuotedPattern<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_quoted_pattern(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    self.pattern.apply_visitor(visitor);
  }
}

#[derive(Debug, Clone)]
pub struct Matcher<'text> {
  pub start: Location,
  pub selectors: Vec<Variable<'text>>,
  pub variants: Vec<Variant<'text>>,
}

impl Spanned for Matcher<'_> {
  fn span(&self) -> Span {
    let start = self.start;
    let end = self
      .variants
      .last()
      .map(|last| last.span().end)
      .unwrap_or_else(|| {
        self
          .selectors
          .last()
          .map(|last| last.span().end)
          .unwrap_or_else(|| start + ".match")
      });
    Span::new(start..end)
  }
}

impl<'text> Visitable<'text> for Matcher<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_matcher(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    for selector in &self.selectors {
      selector.apply_visitor(visitor);
    }
    for variant in &self.variants {
      variant.apply_visitor(visitor);
    }
  }
}

#[derive(Debug, Clone)]
pub struct Variant<'text> {
  pub keys: Vec<Key<'text>>,
  pub pattern: QuotedPattern<'text>,
}

impl Spanned for Variant<'_> {
  fn span(&self) -> Span {
    let start = self
      .keys
      .first()
      .map(|first| first.span().start)
      .unwrap_or_else(|| self.pattern.span().start);
    let end = self.pattern.span().end;
    Span::new(start..end)
  }
}

impl<'text> Visitable<'text> for Variant<'text> {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_variant(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    for key in &self.keys {
      key.apply_visitor(visitor);
    }
    self.pattern.apply_visitor(visitor);
  }
}

ast_enum! {
  #[visit(visit_key)]
  pub enum Key<'text> {
    Literal<'text>,
    Star,
  }
}

#[derive(Debug, Clone)]
pub struct Star {
  pub start: Location,
}

impl Spanned for Star {
  fn span(&self) -> Span {
    Span::new(self.start..self.start + '*')
  }
}

impl<'text> Visitable<'text> for Star {
  fn apply_visitor<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    visitor: &mut V,
  ) {
    visitor.visit_star(self);
  }

  fn apply_visitor_to_children<'ast, V: Visit<'ast, 'text> + ?Sized>(
    &'ast self,
    _visitor: &mut V,
  ) {
  }
}

macro_rules! any_node {
    (
      pub enum $name:ident<$ast_lifetime:lifetime, $text_lifetime:lifetime> {
        $( $item:ident $(<$item_lifetime:lifetime>)? ),* $(,)?
      }
    ) => {
      #[derive(Clone)]
      pub enum $name<$ast_lifetime, $text_lifetime> {
        $( $item ( &'ast $item$(<$item_lifetime>)? ), )*
      }

      impl $name<'_, '_> {
        pub fn same(&self, other: &Self) -> bool {
          match (self, other) {
            $( ($name::$item(a), $name::$item(b)) => ::std::ptr::eq(a as *const _, b as *const _), )*
            _ => false,
          }
        }
      }

      impl ::std::fmt::Debug for $name<'_, '_> {
        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
          match self {
            $( $name::$item(item) => ::std::fmt::Debug::fmt(item, f), )*
          }
        }
      }

      impl crate::util::Spanned for $name<'_, '_> {
        fn span(&self) -> Span {
          match self {
            $( $name::$item(item) => item.span(), )*
          }
        }
      }

      impl<'ast, 'text> $name<'ast, 'text> {
        pub fn apply_visitor<V: crate::visitor::Visit<'ast, 'text> + ?Sized>(&self, visitor: &mut V) {
          match self {
            $( $name::$item(item) => item.apply_visitor(visitor), )*
          }
        }
      }
    };
}

any_node! {
  pub enum AnyNode<'ast, 'text> {
    Message<'text>,
    Pattern<'text>,
    PatternPart<'text>,
    Text<'text>,
    Escape,
    Expression<'text>,
    LiteralExpression<'text>,
    VariableExpression<'text>,
    Variable<'text>,
    AnnotationExpression<'text>,
    Annotation<'text>,
    Function<'text>,
    FnOrMarkupOption<'text>,
    Attribute<'text>,
    LiteralOrVariable<'text>,
    Quoted<'text>,
    QuotedPart<'text>,
    Literal<'text>,
    Number<'text>,
    Markup<'text>,
    Identifier<'text>,
    ComplexMessage<'text>,
    Declaration<'text>,
    InputDeclaration<'text>,
    LocalDeclaration<'text>,
    ComplexMessageBody<'text>,
    QuotedPattern<'text>,
    Matcher<'text>,
    Variant<'text>,
    Key<'text>,
    Star,
  }
}