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
use muncher::Muncher;
use rowan::SmolStr;

use super::err::{ParseTomlError, TomlErrorKind, TomlResult};
use super::kinds::TomlKind::{self, *};

use chrono::{NaiveDate, NaiveTime};

use super::common::{
    cmp_tokens, BOOL_END, DATE_CHAR, DATE_END, DATE_LIKE, DATE_TIME, EOL, IDENT_END, INT_END,
    KEY_END, NUM_END, SEG_END, TIME_CHAR, WHITESPACE,
};
use super::kinds::{Element, TomlNode, TomlToken};
use super::syntax::Parser;

impl Into<(TomlKind, SmolStr)> for Element {
    fn into(self) -> (TomlKind, SmolStr) {
        match self {
            Element::Node(n) => (n.kind, n.text),
            Element::Token(tkn) => (tkn.kind, tkn.text),
        }
    }
}

fn is_valid_key(s: &str) -> bool {
    s.chars()
        .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '-' | '\'' | '"'))
}

fn is_valid_datetime(s: &str) -> TomlResult<bool> {
    let dt = s.split(DATE_TIME).collect::<Vec<_>>();
    if dt.len() == 1 {
        if dt[0].contains(':') {
            let time = dt[0].split(':').collect::<Vec<_>>();
            if time[2].contains('.') {
                let (sec, milli) = {
                    let fractional = time[2].split('.').collect::<Vec<_>>();
                    (fractional[0].parse()?, fractional[1].parse()?)
                };
                NaiveTime::from_hms_milli(time[0].parse()?, time[1].parse()?, sec, milli);
            } else {
                NaiveTime::from_hms(time[0].parse()?, time[1].parse()?, time[2].parse()?);
            };
            Ok(true)
        } else {
            let date = dt[0].split('-').collect::<Vec<_>>();

            assert_eq!(date.len(), 3);

            let _ = NaiveDate::from_ymd(date[0].parse()?, date[1].parse()?, date[2].parse()?);
            Ok(true)
        }
    } else {
        let date = dt[0].split(DATE_CHAR).collect::<Vec<_>>();
        let time = dt[1].split(TIME_CHAR).collect::<Vec<_>>();
        let _ =
            if time.len() > 3 {
                if s.contains('+') {
                    // TODO dont include offset for now
                    NaiveDate::from_ymd(date[0].parse()?, date[1].parse()?, date[2].parse()?)
                        .and_hms(time[0].parse()?, time[1].parse()?, time[2].parse()?)
                } else {
                    NaiveDate::from_ymd(date[0].parse()?, date[1].parse()?, date[2].parse()?)
                        .and_hms_milli(
                            time[0].parse()?,
                            time[1].parse()?,
                            time[2].parse()?,
                            time[3].parse()?,
                        )
                }
            } else {
                NaiveDate::from_ymd(date[0].parse()?, date[1].parse()?, date[2].parse()?).and_hms(
                    time[0].parse()?,
                    time[1].parse()?,
                    time[2].parse()?,
                )
            };
        Ok(true)
    }
}

impl TomlToken {
    // fn whitespace(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
    //     let (s, e) = muncher.eat_until_count(|c| !cmp_tokens(c, WHITESPACE));
    //     // TODO is this more efficient than eat_until to String??
    //     let text = SmolStr::new(&muncher.text()[s..e]);
    //     parser.builder.token(Whitespace.into(), text);
    //     Ok(())
    // }

    /// Returns Element if whitespace was found.
    fn maybe_whitespace(muncher: &mut Muncher) -> Option<Element> {
        let (s, e) = muncher.eat_until_count(|c| !cmp_tokens(c, WHITESPACE));
        // TODO is this more efficient than eat_until to String??
        let text = SmolStr::new(&muncher.text()[s..e]);
        if e > s {
            Some(Element::Token(Self {
                kind: Whitespace,
                text,
            }))
        } else {
            None
        }
    }

    fn hash(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_hash());
        parser.builder.token(Hash.into(), SmolStr::new("#"));
        Ok(())
    }

    // fn plus(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
    //     assert!(muncher.eat_plus());
    //     parser.builder.token(Plus.into(), SmolStr::new("+"));
    //     Ok(())
    // }

    // fn minus(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
    //     assert!(muncher.eat_minus());
    //     parser.builder.token(Minus.into(), SmolStr::new("-"));
    //     Ok(())
    // }

    fn equal(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_eq());
        parser.builder.token(Equal.into(), SmolStr::new("="));
        Ok(())
    }

    // fn comma(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
    //     assert!(muncher.eat_comma());
    //     parser.builder.token(Comma.into(), SmolStr::new(","));
    //     Ok(())
    // }

    /// Returns Element if comma was found. The last item
    /// in an array may or may not have a comma.
    fn maybe_comma(muncher: &mut Muncher) -> Option<Element> {
        if muncher.eat_comma() {
            Some(Element::Token(Self {
                kind: Comma,
                text: SmolStr::new(","),
            }))
        } else {
            None
        }
    }

    fn dot(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_dot());
        parser.builder.token(Dot.into(), SmolStr::new("."));
        Ok(())
    }

    fn maybe_dot(muncher: &mut Muncher) -> Option<Element> {
        if muncher.eat_dot() {
            Some(Element::Token(Self {
                kind: Dot,
                text: SmolStr::new("."),
            }))
        } else {
            None
        }
    }

    fn double_quote(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_double_quote());
        parser.builder.token(DoubleQuote.into(), SmolStr::new("\""));
        Ok(())
    }

    fn triple_quote(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_double_quote());
        assert!(muncher.eat_double_quote());
        assert!(muncher.eat_double_quote());
        parser
            .builder
            .token(TripleQuote.into(), SmolStr::new("\"\"\""));
        Ok(())
    }

    fn single_quote(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_single_quote());
        parser.builder.token(SingleQuote.into(), SmolStr::new("\'"));
        Ok(())
    }

    fn ident(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| cmp_tokens(c, IDENT_END));
        // TODO is this more efficient than eat_until to String??
        let text = SmolStr::new(&muncher.text()[s..e]);
        parser.builder.token(Ident.into(), text);
        Ok(())
    }

    fn ident_seg(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| cmp_tokens(c, SEG_END));
        let text = SmolStr::new(&muncher.text()[s..e]);
        parser.builder.token(Ident.into(), text);
        Ok(())
    }

    fn ident_double_str(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| c == &'"');
        // TODO is this more efficient than eat_until to String??
        let text = SmolStr::new(&muncher.text()[s..e]);
        parser.builder.token(Ident.into(), text);
        Ok(())
    }

    fn ident_triple_str(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_range_of("\"\"\"");
        let text = SmolStr::new(&muncher.text()[s..e]);
        parser.builder.token(Ident.into(), text);
        Ok(())
    }

    fn ident_single_str(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| c == &'\'');
        let text = SmolStr::new(&muncher.text()[s..e]);
        parser.builder.token(Ident.into(), text);
        Ok(())
    }

    fn comment_text(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| cmp_tokens(c, EOL));
        let text = SmolStr::new(&muncher.text()[s..e]);
        parser.builder.token(CommentText.into(), text);
        Ok(())
    }

    fn open_brace(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_open_brc());
        parser.builder.token(OpenBrace.into(), SmolStr::new("["));
        Ok(())
    }
    fn close_brace(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_close_brc());
        parser.builder.token(CloseBrace.into(), SmolStr::new("]"));
        Ok(())
    }
    fn open_curly(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_open_curly());
        parser.builder.token(OpenCurly.into(), SmolStr::new("{"));
        Ok(())
    }
    fn close_curly(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        assert!(muncher.eat_close_curly());
        parser.builder.token(CloseCurly.into(), SmolStr::new("}"));
        Ok(())
    }

    fn boolean(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| cmp_tokens(c, BOOL_END));
        let boolean = &muncher.text()[s..e];

        let text = SmolStr::new(boolean);
        if boolean == "true" || boolean == "false" {
            parser.builder.token(Bool.into(), text);
            Ok(())
        } else {
            let (col, ln) = muncher.cursor_position();
            let msg = "invalid integer".into();
            Err(ParseTomlError::new(
                msg,
                TomlErrorKind::UnexpectedToken {
                    tkn: boolean.into(),
                    ln,
                    col,
                },
            ))
        }
    }

    fn integer(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.eat_until_count(|c| cmp_tokens(c, INT_END));
        let int = &muncher.text()[s..e];

        if int.chars().all(|c| c.is_numeric()) {
            let text = SmolStr::new(int);
            parser.builder.token(Integer.into(), text);
            Ok(())
        } else {
            let (col, ln) = muncher.cursor_position();
            let msg = "invalid integer".into();
            Err(ParseTomlError::new(
                msg,
                TomlErrorKind::UnexpectedToken {
                    tkn: int.into(),
                    ln,
                    col,
                },
            ))
        }
    }
}

/// All `TomlNodes` parse `Whitespace` token from the previous tokens
/// whitespace.
impl TomlNode {
    /// Builds `Whitespace` and `Hash` token and adds them as
    /// children.
    fn comment(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Comment.into());

        TomlToken::hash(muncher, parser)?;
        TomlToken::comment_text(muncher, parser)?;

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Whitespace`, `Integer`, `Dot` and `Integer token and adds them as
    /// children.
    fn float(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Float.into());

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }
        TomlToken::integer(muncher, parser)?;
        TomlToken::dot(muncher, parser)?;
        TomlToken::integer(muncher, parser)?;
        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Date` node from `Whitespace` and `Date` token and if valid adds them as
    /// children.
    fn date_time(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Date.into());
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }
        let (s, e) = muncher.eat_until_count(|c| cmp_tokens(c, DATE_END));

        let text = SmolStr::new(&muncher.text()[s..e]);

        if is_valid_datetime(&text) != Ok(true) {
            let (col, ln) = muncher.cursor_position();
            let msg = "invalid integer".into();
            Err(ParseTomlError::new(
                msg,
                TomlErrorKind::UnexpectedToken {
                    tkn: text.into(),
                    ln,
                    col,
                },
            ))
        } else {
            parser.builder.token(Ident.into(), text);
            parser.builder.finish_node();
            Ok(())
        }
    }

    /// Builds `Str` node from `Whitespace`, `SingleQuote` and `Ident` token and adds them as
    /// children.
    fn single_str(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Str.into());
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlToken::single_quote(muncher, parser)?;
        TomlToken::ident_single_str(muncher, parser)?;
        TomlToken::single_quote(muncher, parser)?;

        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Str` node from `Whitespace`, `DoubleQuote` and `Ident` token and adds them as
    /// children.
    fn double_str(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Str.into());
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlToken::double_quote(muncher, parser)?;
        TomlToken::ident_double_str(muncher, parser)?;
        TomlToken::double_quote(muncher, parser)?;

        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Str` node from `Whitespace`, `DoubleQuote` and `Ident` token and adds them as
    /// children.
    fn string(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Str.into());
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        if muncher.seek(2).map(|s| s == "\"\"") == Some(true) {
            TomlToken::triple_quote(muncher, parser)?;
            TomlToken::ident_triple_str(muncher, parser)?;
            TomlToken::triple_quote(muncher, parser)?;
        } else {
            TomlToken::double_quote(muncher, parser)?;
            TomlToken::ident_double_str(muncher, parser)?;
            TomlToken::double_quote(muncher, parser)?;
        }

        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Key` node from `Whitespace` and `Ident` token and adds them as
    /// children.
    fn key(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Key.into());

        // if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
        //     let (kind, text) = ws.into();
        //     parser.builder.token(kind.into(), text)
        // }
        let (s, e) = muncher.peek_until_count(|c| cmp_tokens(c, KEY_END));
        // muncher.reset_peek();
        match muncher.peek() {
            Some(&'"') => TomlNode::double_str(muncher, parser),
            Some(&'\'') => TomlNode::single_str(muncher, parser),
            Some(ch) if ch.is_ascii() => TomlToken::ident(muncher, parser),
            Some(tkn) => {
                let (col, ln) = muncher.cursor_position();
                let msg = "invalid token in key".into();
                let tkn = format!("{}", tkn);
                return Err(ParseTomlError::new(
                    msg,
                    TomlErrorKind::UnexpectedToken { tkn, ln, col },
                ));
            }
            None => unreachable!("NONE in key"),
        }?;

        let text = SmolStr::new(&muncher.text()[s..e]);
        if is_valid_key(&text) {
            parser.builder.finish_node();
            Ok(())
        } else {
            let (col, ln) = muncher.cursor_position();
            let msg = "invalid token in key".into();
            let tkn = format!("{}", text);
            Err(ParseTomlError::new(
                msg,
                TomlErrorKind::UnexpectedToken { tkn, ln, col },
            ))
        }
    }

    /// Builds `Value` node from `Whitespace` and whatever value node is present
    /// and adds them as children. this is called for top level key value pairs
    /// and tables.
    fn value(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Value.into());
        match muncher.peek() {
            Some('"') => TomlNode::string(muncher, parser),
            Some('\'') => TomlNode::single_str(muncher, parser),
            Some('t') | Some('f') => TomlToken::boolean(muncher, parser),
            Some('[') => TomlNode::array(muncher, parser),
            Some('{') => TomlNode::inline_table(muncher, parser),
            Some(digi) if digi.is_numeric() => {
                muncher.reset_peek();
                let raw = muncher
                    .peek_until(|c| cmp_tokens(c, NUM_END))
                    .collect::<String>();
                if raw.contains(DATE_LIKE) {
                    TomlNode::date_time(muncher, parser)
                } else if raw.contains('.') {
                    TomlNode::float(muncher, parser)
                } else {
                    TomlToken::integer(muncher, parser)
                }
            }
            None => unimplemented!("found EOF in value"),
            _ => {
                let msg = "invalid token in value";
                let tkn = if let Some(peek) = muncher.peek() {
                    format!("{:?}", peek)
                } else {
                    "no token".into()
                };
                let (col, ln) = muncher.cursor_position();
                return Err(ParseTomlError::new(
                    msg.into(),
                    TomlErrorKind::UnexpectedToken { tkn, ln, col },
                ));
            }
        }?;
        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `KeyValue` node from `Whitespace`, `Key` and whatever value node is present
    /// and adds them as children.
    fn key_value(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        if muncher.is_done() {
            unreachable!("BUG tokenizer should never hit DONE in key value")
        }

        if muncher.peek() == Some(&'#') {
            TomlNode::comment(muncher, parser)?;
            return Ok(());
        }

        parser.builder.start_node(KeyValue.into());

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlNode::key(muncher, parser)?;

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlToken::equal(muncher, parser)?;

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlNode::value(muncher, parser)?;

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `KeyValue` node from `Whitespace`, `Key` and whatever value node is present
    /// and adds them as children. This is only for `InlineTable`s.
    fn inline_key_value(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        if muncher.is_done() {
            unreachable!("BUG tokenizer should never hit DONE in inline key value")
        }
        parser.builder.start_node(KeyValue.into());

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlNode::key(muncher, parser)?;
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlToken::equal(muncher, parser)?;
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }
        TomlNode::inline_value(muncher, parser)?;
        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `ArrayItem` node from `Whitespace` and whatever `Value` node is present
    /// and adds them as children.
    fn array_item(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<Option<()>> {
        if muncher.peek() == Some(&']') {
            return Ok(None);
        }

        parser.builder.start_node(ArrayItem.into());
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlNode::value(muncher, parser)?;

        if let Some(comma) = TomlToken::maybe_comma(muncher) {
            let (kind, text) = comma.into();
            parser.builder.token(kind.into(), text);
        }
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text);
        }

        parser.builder.finish_node();
        Ok(Some(()))
    }

    /// Builds `Array` node from `Whitespace` and whatever `ArrayItem` nodes are present
    /// and adds them as children.
    fn array(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Array.into());
        TomlToken::open_brace(muncher, parser)?;
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        while TomlNode::array_item(muncher, parser)?.is_some() { /* loop to array end */ }

        TomlToken::close_brace(muncher, parser)?;
        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Value` node from `Whitespace` and whatever value node is present
    /// and adds them as children. This is called for inline tables only.
    fn inline_value(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Value.into());

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }
        match muncher.peek() {
            Some('"') => TomlNode::string(muncher, parser),
            Some('\'') => TomlNode::single_str(muncher, parser),
            Some('t') | Some('f') => TomlToken::boolean(muncher, parser),
            Some('[') => TomlNode::array(muncher, parser),
            Some('{') => TomlNode::inline_table(muncher, parser),
            Some(digi) if digi.is_numeric() => {
                muncher.reset_peek();
                let raw = muncher
                    .peek_until(|c| cmp_tokens(c, NUM_END))
                    .collect::<String>();
                if raw.contains(DATE_LIKE) {
                    TomlNode::date_time(muncher, parser)
                } else if raw.contains('.') {
                    TomlNode::float(muncher, parser)
                } else {
                    TomlToken::integer(muncher, parser)
                }
            }
            None => unimplemented!("value found EOF"),
            _ => {
                let msg = "invalid token in key value pairs";
                let tkn = if let Some(peek) = muncher.peek() {
                    format!("{:#?}", peek)
                } else {
                    "no token".into()
                };
                let (col, ln) = muncher.cursor_position();
                return Err(ParseTomlError::new(
                    msg.into(),
                    TomlErrorKind::UnexpectedToken { tkn, ln, col },
                ));
            }
        }?;
        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `InlineTable` node from `Whitespace` and whatever `KeyValue` nodes are present
    /// and adds them as children.
    fn inline_table(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(InlineTable.into());
        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlToken::open_curly(muncher, parser)?;
        loop {
            // TODO this is weak make some sort of stack machine.
            if muncher.peek() == Some(&'}') {
                break;
            }
            TomlNode::inline_key_value(muncher, parser)?;
            // an inline table and an array are the only two node types that
            // have comma's optionally eat comma and any following whitespace.
            if let Some(comma) = TomlToken::maybe_comma(muncher) {
                let (kind, text) = comma.into();
                parser.builder.token(kind.into(), text)
            }
            if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
                let (kind, text) = ws.into();
                parser.builder.token(kind.into(), text)
            }
        }
        TomlToken::close_curly(muncher, parser)?;
        parser.builder.finish_node();
        Ok(())
    }

    /// If `Heading` contains a '.' a `TomlNode` `SegIdent` is produced other wise
    /// a plain `TomlToken` `Ident` is added.
    fn ident_heading(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        let (s, e) = muncher.peek_until_count(|c| c == &']');
        // TODO is this more efficient than eat_until to String??
        let text = SmolStr::new(&muncher.text()[s..e]);

        if text.contains('"') {
            parser.builder.start_node(SegIdent.into());
            if text.contains('.') {
                let mut txt = text;
                loop {
                    // TODO if not in loop `value moved here, in previous iteration of loop` error BOOO
                    let mut in_str = false;
                    let dot_index = |ch: char| -> bool {
                        if ch == '"' && !in_str {
                            in_str = true;
                        } else if ch == '"' && in_str {
                            in_str = false;
                        };

                        ch == '.' && !in_str
                    };
                    if txt.starts_with('"') {
                        TomlNode::double_str(muncher, parser)?;
                        if let Some(dot) = TomlToken::maybe_dot(muncher) {
                            let (kind, text) = dot.into();
                            parser.builder.token(kind.into(), text)
                        }
                        if let Some(idx) = txt.chars().position(dot_index) {
                            txt = SmolStr::from(txt.split_at(idx).1);
                        } else {
                            break;
                        }
                    } else {
                        TomlToken::ident_seg(muncher, parser)?;
                        if let Some(dot) = TomlToken::maybe_dot(muncher) {
                            let (kind, text) = dot.into();
                            parser.builder.token(kind.into(), text)
                        }
                        if let Some(idx) = txt.chars().position(dot_index) {
                            txt = SmolStr::from(txt.split_at(idx + 1).1);
                        } else {
                            break;
                        }
                    }
                }
            } else {
                TomlNode::double_str(muncher, parser)?;
            }
            parser.builder.finish_node();
            Ok(())
        } else if text.contains('.') {
            parser.builder.start_node(SegIdent.into());

            TomlToken::ident_seg(muncher, parser)?;
            if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
                let (kind, text) = ws.into();
                parser.builder.token(kind.into(), text)
            }
            TomlToken::dot(muncher, parser)?;
            if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
                let (kind, text) = ws.into();
                parser.builder.token(kind.into(), text)
            }
            TomlToken::ident_seg(muncher, parser)?;

            // for all segments after the first we loop for each
            for _ in 2..text.split('.').count() {
                if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
                    let (kind, text) = ws.into();
                    parser.builder.token(kind.into(), text)
                }
                if let Some(dot) = TomlToken::maybe_dot(muncher) {
                    let (kind, text) = dot.into();
                    parser.builder.token(kind.into(), text);
                    TomlToken::ident_seg(muncher, parser)?;
                }
            }
            parser.builder.finish_node();
            Ok(())
        } else {
            parser.builder.token(Ident.into(), text);
            Ok(())
        }
    }

    /// Builds `Heading` node from `Whitespace` and either `Ident` token or
    /// `SegIdent` node and adds them as children.
    fn heading(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Heading.into());

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        if muncher.seek(2).map(|s| s.starts_with("[[")) == Some(true) {
            parser.builder.start_node(TomlKind::ArrayHeading.into());
            TomlToken::open_brace(muncher, parser)?;
            TomlToken::open_brace(muncher, parser)?;

            match muncher.peek() {
                Some(ch) if ch.is_ascii() => TomlNode::ident_heading(muncher, parser)?,
                Some(tkn) => {
                    let (col, ln) = muncher.cursor_position();
                    let msg = "invalid heading token".into();
                    let tkn = format!("{}", tkn);
                    return Err(ParseTomlError::new(
                        msg,
                        TomlErrorKind::UnexpectedToken { tkn, ln, col },
                    ));
                }
                None => unreachable!("empty toml heading"),
            };
            // although this is an iterator it advances the cursor which is what we want
            let _eaten = muncher.eat_until(|c| c == &']');

            TomlToken::close_brace(muncher, parser)?;
            TomlToken::close_brace(muncher, parser)?;

            if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
                let (kind, text) = ws.into();
                parser.builder.token(kind.into(), text)
            }
            // finishes ArrayHeading
            parser.builder.finish_node();
            // finishes Heading
            parser.builder.finish_node();
            return Ok(());
        };

        TomlToken::open_brace(muncher, parser)?;
        match muncher.peek() {
            Some(ch) if ch.is_ascii() => TomlNode::ident_heading(muncher, parser)?,
            Some(tkn) => {
                let (col, ln) = muncher.cursor_position();
                let msg = "invalid heading token".into();
                let tkn = format!("{}", tkn);
                return Err(ParseTomlError::new(
                    msg,
                    TomlErrorKind::UnexpectedToken { tkn, ln, col },
                ));
            }
            None => unreachable!("empty toml heading"),
        };
        // although this is an iterator it advances the cursor which is what we want
        let _eaten = muncher.eat_until(|c| c == &']');

        TomlToken::close_brace(muncher, parser)?;

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        parser.builder.finish_node();
        Ok(())
    }

    /// Builds `Table` node from `Whitespace` and whatever `KeyValue` nodes are present
    /// and adds them as children.
    fn table(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Table.into());

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        TomlNode::heading(muncher, parser)?;
        loop {
            if muncher.seek(5).map(|s| s.contains('[')) == Some(true) {
                break;
            }
            muncher.reset_peek();
            // TODO this is weak.
            if muncher.is_done() {
                break;
            }
            TomlNode::key_value(muncher, parser)?;
        }

        if let Some(ws) = TomlToken::maybe_whitespace(muncher) {
            let (kind, text) = ws.into();
            parser.builder.token(kind.into(), text)
        }

        parser.builder.finish_node();
        Ok(())
    }
}

pub struct Tokenizer;

impl Tokenizer {
    /// Returns a wrapper around a `rowan::GreenNodeBuilder` called `Parser`.
    /// The can be turned into a walk-able `SyntaxNode`.
    ///
    /// # Examples
    /// ```
    /// # use toml_parse::{Tokenizer, Parser};
    /// # use rowan::GreenNodeBuilder;
    /// let toml = "";
    /// let parse_builder = Parser::new();
    /// let parsed = Tokenizer::parse(toml, parse_builder).expect("parse failed");
    /// let green_node = parsed.parse().expect("parse failed");
    /// let root_node = green_node.syntax();
    /// ```
    pub fn parse(input: &str, mut p: Parser) -> TomlResult<Parser> {
        let mut muncher = Muncher::new(input);
        Tokenizer::parse_file(&mut muncher, &mut p)?;
        Ok(p)
    }

    /// It seems the only three top level Kinds are `KeyValue` pairs,
    /// `Table`s and `Comments`.
    fn parse_file(muncher: &mut Muncher, parser: &mut Parser) -> TomlResult<()> {
        parser.builder.start_node(Root.into());
        loop {
            if muncher.is_done() {
                parser.builder.token(EoF.into(), SmolStr::default());
                break;
            }

            match muncher.peek() {
                Some('#') => {
                    TomlNode::comment(muncher, parser)?;
                }
                Some('[') => {
                    TomlNode::table(muncher, parser)?;
                }
                Some(ch) if ch.is_ascii() => {
                    TomlNode::key_value(muncher, parser)?;
                }
                Some(tkn) => {
                    let msg = "toml file must be key values or tables".into();
                    let tkn = format!("{}", tkn);
                    let (col, ln) = muncher.cursor_position();
                    return Err(ParseTomlError::new(
                        msg,
                        TomlErrorKind::UnexpectedToken { tkn, ln, col },
                    ));
                }
                None => {
                    parser.builder.token(EoF.into(), SmolStr::default());
                    break;
                }
            }
        }
        parser.builder.finish_node();
        Ok(())
    }
}