-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
2191 lines (2188 loc) · 99.2 KB
/
lib.rs
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
use cobalt_errors::*;
use cobalt_ast::{*, ast::*};
use unicode_ident::*;
use either::Either;
mod utils;
/// General parsing return, return a value, the span it covers, the remaining string, and any
/// errors that were encountered
type ParserReturn<'a, T> = Option<(T, SourceSpan, &'a str, Vec<CobaltError>)>;
/// Get what comes at the start of a string.
/// If it is a valid identifier, return the full identifier, otherwise return the character
fn got(src: &str) -> (ParserFound, usize) {
let mut it = src.char_indices();
if let Some((_, c)) = it.next() {
if is_xid_start(c) {
let idx = it.find(|x| !is_xid_continue(x.1)).map_or(src.len(), |x| x.0);
(ParserFound::Str((&src[..idx]).into()), idx)
}
else {(ParserFound::Char(c), c.len_utf8())}
}
else {(ParserFound::Eof, 0)}
}
/// Take a parser function and update `src`, `start`, and `errs`
fn process<'a, T>(parser: impl FnOnce(&'a str, usize) -> ParserReturn<'a, T>, src: &mut &'a str, start: &mut usize, errs: &mut Vec<CobaltError>) -> Option<(T, SourceSpan)> {
let (found, span, rem, mut es) = parser(src, *start)?;
*start += span.len();
*src = rem;
errs.append(&mut es);
Some((found, span))
}
/// Things an identifier cannot be
const KEYWORDS: &[&str] = &[
"let", "mut", "const", "type", "fn", "module", "import", "if", "else", "while", "null", // currently in use
"trait", "spec", "break", "continue" // future-proofing
];
/// Parse an identifier
fn ident(allow_empty: bool, src: &str, start: usize) -> ParserReturn<&str> {
let mut it = src.char_indices();
let first = it.next()?;
let first = first.1;
if !(is_xid_start(first) || first == '$' || first == '_') {return allow_empty.then_some(("", start.into(), src, vec![]))}
let idx = it.find(|x| !is_xid_continue(x.1)).map_or(src.len(), |x| x.0);
let (mut id, rem) = src.split_at(idx);
let mut errs = vec![];
if KEYWORDS.contains(&id) {
if allow_empty {
errs.push(CobaltError::ExpectedFound {
ex: "identifier",
found: ParserFound::Str(id.into()),
loc: (start, idx).into()
});
id = "<error>";
}
else {return None}
}
Some((id, (start, idx).into(), rem, errs))
}
/// Parse any kind of whitepace
fn whitespace(src: &str, start: usize) -> ParserReturn<()> {
let idx = src.char_indices().find(|x| !x.1.is_whitespace()).map_or(src.len(), |x| x.0);
(idx > 0).then_some(((), (start, idx).into(), &src[idx..], vec![]))
}
/// Parse a comment
fn comment(src: &str, start: usize) -> ParserReturn<()> {
let mut it = src.char_indices();
if it.next() != Some((0, '#')) {return None}
match it.next() {
Some((1, '=')) => {
if let Some(c) = it.by_ref().find(|x| x.1 != '=').map(|x| x.0) {
if let Some(idx) = src[c..].find(&("=".repeat(c - 1) + "#")) {
let final_len = idx + 2 * c;
Some(((), (start, final_len).into(), &src[final_len..], vec![]))
}
else {Some(((), (start, c).into(), "", vec![CobaltError::UnclosedComment {loc: (start, c).into()}]))}
}
else {Some(((), (start, src.len()).into(), "", vec![CobaltError::UnclosedComment {loc: (start, src.len()).into()}]))}
},
Some((1, '\n')) => Some(((), (start, 1).into(), &src[1..], vec![])),
Some(_) => {
let idx = it.find(|x| x.1 == '\n').map_or(src.len(), |x| x.0);
Some(((), (start, idx).into(), &src[idx..], vec![]))
},
None => Some(((), (start, 1).into(), "", vec![]))
}
}
/// Match anything that should be ignored: whitespace or comments
fn ignored(mut src: &str, start: usize) -> ParserReturn<()> {
let mut cont = true;
let mut good = false;
let mut errs = vec![];
let mut current = start;
while cont {
cont = false;
if let Some((_, span, next, _)) = whitespace(src, current) {
cont = true;
good = true;
src = next;
current += span.len();
}
if let Some((_, span, next, mut es)) = comment(src, current) {
cont = true;
good = true;
src = next;
current += span.len();
errs.append(&mut es);
}
}
good.then_some(((), (start..current).into(), src, errs))
}
/// Used for parsing a keyword, followed by some whitespace
fn start_match<'a>(kw: &'static str, mut src: &'a str, mut start: usize) -> ParserReturn<'a, ()> {
let begin = start;
let kwl = kw.len();
src.starts_with(kw).then_some(())?;
src = &src[kwl..];
start += kwl;
(!src.chars().next().map_or(false, is_xid_continue)).then_some(())?;
let mut errs = vec![];
process(ignored, &mut src, &mut start, &mut errs);
Some(((), (begin..start).into(), src, errs))
}
/// A local identifier is just an ident
fn local_id(mut src: &str, mut start: usize) -> ParserReturn<DottedName> {
let mut errs = vec![];
let old = start;
if src.starts_with('.') {
errs.push(CobaltError::UnexpectedGlobal {loc: (start, 1).into()});
src = &src[1..];
}
process(ignored, &mut src, &mut start, &mut errs);
let name = vec![process(|src, start| ident(true, src, start), &mut src, &mut start, &mut errs).map_or((String::new(), start.into()), |(seg, loc)| (seg.to_string(), loc))];
process(ignored, &mut src, &mut start, &mut errs);
let begin = start;
process(global_id, &mut src, &mut start, &mut vec![]); // in case someone decided to try to make a global variable
if begin != start {
errs.push(CobaltError::UnexpectedGlobal {loc: (begin, 1).into()});
}
Some((DottedName::new(name, false), (old..start).into(), src, errs))
}
/// A global identifier is an optional '.', and then a series of idents separated by '.'s
fn global_id(mut src: &str, mut start: usize) -> ParserReturn<DottedName> {
let old = start;
let global = if src.starts_with('.') {src = &src[1..]; start += 1; true} else {false};
let mut errs = vec![];
process(ignored, &mut src, &mut start, &mut errs);
let mut name = vec![process(|src, start| ident(true, src, start), &mut src, &mut start, &mut errs).map_or((String::new(), start.into()), |(seg, loc)| (seg.to_string(), loc))];
loop {
process(ignored, &mut src, &mut start, &mut errs);
if !src.starts_with('.') {break}
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
if let Some((seg, loc)) = process(|src, start| ident(true, src, start), &mut src, &mut start, &mut errs) {name.push((seg.to_string(), loc))}
else {
// simple error recovery: look for a '.' (the next element) or ';' (the end)
let idx = src.find(['.', ';']);
let g = got(src);
if let Some(mut idx) = idx {
if src.as_bytes()[idx] == b';' {
idx -= 1;
while !src.is_char_boundary(idx) {idx -= 1} // src.floor_char_boundary isn't stable
}
start += idx;
src = &src[idx..];
}
else {
start += src.len();
src = "";
}
errs.push(CobaltError::ExpectedFound {
ex: r#""." between name elements"#,
found: g.0,
loc: (start, g.1).into()
});
}
}
Some((DottedName::new(name, global), (old..start).into(), src, errs))
}
/// Parse an annotation
fn annotation(mut src: &str, mut start: usize) -> ParserReturn<(&str, Option<&str>, SourceSpan)> {
let begin = start;
src.starts_with('@').then_some(())?;
src = &src[1..];
start += 1;
let mut errs = vec![];
let name = process(move |src, start| ident(true, src, start), &mut src, &mut start, &mut errs).unwrap().0;
let src_ = src;
let start_ = start;
process(ignored, &mut src, &mut start, &mut errs);
let arg = if src.starts_with('(') {
src = &src[1..];
start += 1;
let mut depth = 1;
while let Some(next) = src.find(['(', ')']) {
match src.as_bytes()[next] {
b'(' => depth += 1,
b')' => depth -= 1,
_ => unreachable!()
}
start += next + 1;
src = &src[(next + 1)..];
if depth == 0 {break}
}
if depth > 0 {
let got = got(src);
errs.push(CobaltError::UnmatchedDelimiter {
expected: ')',
found: got.0,
start: (start_ + 1, 1).into(),
end: (start, got.1).into()
});
}
let arg = &src_[1..(start - start_ - 1)];
Some(arg)
}
else {
src = src_;
start = start_;
None
};
let end = start;
process(ignored, &mut src, &mut start, &mut errs);
Some(((name, arg, (begin..end).into()), (begin..start).into(), src, errs))
}
/// Location of the declarations
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum DeclLoc {Local, Method, Global}
/// Parse declarations: `let`, `mut`, `const`, `type`, and `fn`
fn declarations<'a>(loc: DeclLoc, anns: Option<Vec<(&'a str, Option<&'a str>, SourceSpan)>>, mut src: &'a str, mut start: usize) -> ParserReturn<'a, Box<dyn AST>> {
let id_parser = if loc == DeclLoc::Global {global_id} else {local_id};
let mut errs = vec![];
let begin = start;
let anns = anns.unwrap_or_else(|| std::iter::from_fn(|| process(annotation, &mut src, &mut start, &mut errs)).map(|x| x.0).collect());
match src.as_bytes()[0] { // do a trie-like lookup for speed
b'l' => {
let (_, start_span, mut src, mut errs) = start_match("let", src, start)?;
start += start_span.len();
let name = process(id_parser, &mut src, &mut start, &mut errs).map_or(DottedName::local((String::new(), start.into())), |x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
let ty = src.starts_with(':').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(0, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten();
let val = src.starts_with('=').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(1, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten().unwrap_or_else(|| Box::new(NullAST::new(ty.as_ref().map_or(start_span, |x| x.loc()))));
let anns = anns.iter().copied().map(|(ann, arg, loc)| (ann.to_string(), arg.map(ToString::to_string), loc)).collect();
let ast = Box::new(VarDefAST::new((begin, 3).into(), name, val, ty, anns, loc != DeclLoc::Local));
Some((ast, merge_spans(start_span, start.into()), src, errs))
},
b'm' => {
let (_, start_span, mut src, mut errs) = start_match("mut", src, start)?;
start += start_span.len();
let name = process(id_parser, &mut src, &mut start, &mut errs).map_or(DottedName::local((String::new(), start.into())), |x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
let ty = src.starts_with(':').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(0, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten();
let val = src.starts_with('=').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(1, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten().unwrap_or_else(|| Box::new(NullAST::new(ty.as_ref().map_or(start_span, |x| x.loc()))));
let anns = anns.iter().copied().map(|(ann, arg, loc)| (ann.to_string(), arg.map(ToString::to_string), loc)).collect();
let ast = Box::new(MutDefAST::new((begin, 3).into(), name, val, ty, anns, loc != DeclLoc::Local));
Some((ast, merge_spans(start_span, start.into()), src, errs))
},
b'c' => {
let (_, start_span, mut src, mut errs) = start_match("const", src, start)?;
start += start_span.len();
let name = process(id_parser, &mut src, &mut start, &mut errs).map_or(DottedName::local((String::new(), start.into())), |x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
let ty = src.starts_with(':').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(0, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten();
let val = src.starts_with('=').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(1, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten().unwrap_or_else(|| Box::new(NullAST::new(ty.as_ref().map_or(start_span, |x| x.loc()))));
let anns = anns.iter().copied().map(|(ann, arg, loc)| (ann.to_string(), arg.map(ToString::to_string), loc)).collect();
let ast = Box::new(ConstDefAST::new((begin, 5).into(), name, val, ty, anns));
Some((ast, merge_spans(start_span, start.into()), src, errs))
},
b't' => {
let (_, start_span, mut src, mut errs) = start_match("type", src, start)?;
start += start_span.len();
let name = process(id_parser, &mut src, &mut start, &mut errs).map_or(DottedName::local((String::new(), start.into())), |x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
let val = src.starts_with('=').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(1, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten().unwrap_or_else(|| Box::new(NullAST::new(start_span)));
process(ignored, &mut src, &mut start, &mut errs);
let metds = src.starts_with("::").then(|| {
src = &src[2..];
start += 2;
process(ignored, &mut src, &mut start, &mut errs);
if !src.starts_with('{') {return vec![]}
let open = start;
src = &src[1..];
start += 1;
let metds = std::iter::from_fn(|| {
process(ignored, &mut src, &mut start, &mut errs);
if src.starts_with(';') {return Some(None)}
let ast = process(|src, start| declarations(DeclLoc::Method, None, src, start), &mut src, &mut start, &mut errs)?.0;
process(ignored, &mut src, &mut start, &mut errs);
if src.starts_with(';') {
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: r#"";" after declaration"#,
found: got.0,
loc: (start, got.1).into()
});
}
Some(Some(ast))
}).flatten().collect::<Vec<_>>();
process(ignored, &mut src, &mut start, &mut errs);
if src.starts_with('}') {
src = &src[1..];
start += 1;
}
else {
let g = got(src);
errs.push(CobaltError::UnmatchedDelimiter {
expected: '}',
found: g.0,
start: (open, 1).into(),
end: (start, g.1).into()
});
let idx = src.find(['}', ';']).unwrap_or(src.len());
src = &src[idx..];
start += idx;
}
metds
}).unwrap_or_default();
let ast = Box::new(TypeDefAST::new((begin, 4).into(), name, val, anns.iter().copied().map(|(ann, arg, loc)| (ann.to_string(), arg.map(ToString::to_string), loc)).collect(), metds));
Some((ast, merge_spans(start_span, start.into()), src, errs))
},
b'f' => {
let (_, start_span, mut src, mut errs) = start_match("fn", src, start)?;
start += start_span.len();
let name = process(id_parser, &mut src, &mut start, &mut errs).map_or(DottedName::local((String::new(), start.into())), |x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
let open = start;
if !src.starts_with('(') {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "function parameters",
found: got.0,
loc: (start, got.1).into()
});
}
else {
src = &src[1..];
start += 1;
}
fn param(mut src: &str, mut start: usize) -> ParserReturn<ast::funcs::Parameter> {
let mut errs = vec![];
let begin = start;
loop {
process(ignored, &mut src, &mut start, &mut errs);
if src.is_empty() || src.starts_with(')') {return None}
if src.starts_with(',') {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "parameter",
found: got.0,
loc: (start, got.1).into()
});
process(ignored, &mut src, &mut start, &mut errs);
} else {break}
}
let pt = process(|src, start| start_match("const", src, start), &mut src, &mut start, &mut errs).map(|_| ParamType::Constant)
.or_else(|| process(|src, start| start_match("const", src, start), &mut src, &mut start, &mut errs).map(|_| ParamType::Mutable))
.unwrap_or(ParamType::Normal);
let (id, iloc) = process(|src, start| ident(true, src, start), &mut src, &mut start, &mut errs).unwrap_or_else(|| {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "a parameter",
found: got.0,
loc: (start, got.1).into()
});
let s = start;
process(ignored, &mut src, &mut start, &mut errs);
("", s.into())
});
process(ignored, &mut src, &mut start, &mut errs);
let ty = src.starts_with(':').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(0, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten().unwrap_or_else(|| {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "parameter type",
found: got.0,
loc: (start, got.1).into()
});
process(ignored, &mut src, &mut start, &mut errs);
Box::new(ErrorTypeAST::new(iloc))
});
let val = src.starts_with('=').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
let res = process(|src, start| expr(1, src, start), &mut src, &mut start, &mut errs).map(|x| x.0);
process(ignored, &mut src, &mut start, &mut errs);
res
}).flatten();
match src.as_bytes().first().copied() {
Some(b')') => {},
Some(b',') => {
src = &src[1..];
start += 1;
},
_ => {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: r#""," between parameters"#,
found: got.0,
loc: (start, got.1).into()
});
}
}
Some(((id.to_string(), pt, ty, val), (begin..start).into(), src, errs))
}
let params = std::iter::from_fn(|| process(param, &mut src, &mut start, &mut errs)).map(|x| x.0).collect::<Vec<_>>();
process(ignored, &mut src, &mut start, &mut errs);
if src.starts_with(')') {
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::UnmatchedDelimiter {
expected: ')',
found: got.0,
start: (open, 1).into(),
end: (start, got.1).into()
});
}
let cparen = start;
process(ignored, &mut src, &mut start, &mut errs);
let ret = src.starts_with(':').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
process(|src, start| expr(0, src, start), &mut src, &mut start, &mut errs).map_or_else(|| {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "return type",
found: got.0,
loc: (start, got.1).into()
});
Box::new(ErrorTypeAST::new(cparen.into())) as _
}, |x| x.0)
}).unwrap_or_else(|| Box::new(NullAST::new(cparen.into())) as _);
process(ignored, &mut src, &mut start, &mut errs);
let body = src.starts_with('=').then(|| {
src = &src[1..];
start += 1;
process(ignored, &mut src, &mut start, &mut errs);
process(|src, start| expr(1, src, start), &mut src, &mut start, &mut errs).map_or_else(|| {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "function body",
found: got.0,
loc: (start, got.1).into()
});
Box::new(ErrorTypeAST::new(ret.loc())) as _
}, |x| x.0)
}).unwrap_or_else(|| Box::new(NullAST::new(ret.loc())) as _);
let anns = anns.iter().copied().map(|(ann, arg, loc)| (ann.to_string(), arg.map(ToString::to_string), loc)).collect();
Some((Box::new(FnDefAST::new((begin, 2).into(), name, ret, params, body, anns, loc == DeclLoc::Method)), (begin..start).into(), src, errs))
},
_ => None
}
}
/// Parse a statement
/// A statement is a local declaration, import, or expression
fn stmt(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
let mut errs = vec![];
process(ignored, &mut src, &mut start, &mut errs);
let src_ = src;
let start_ = start;
let anns: Vec<_> = std::iter::from_fn(|| process(annotation, &mut src, &mut start, &mut errs)).map(|x| x.0).collect();
None
.or_else(|| import(&anns, src, start))
.or_else(move || declarations(DeclLoc::Local, Some(anns), src, start))
.or_else(|| expr(1, src_, start_))
}
/// Parse an atom
/// An atom cannot be subdivided
fn atom(src: &str, start: usize) -> ParserReturn<Box<dyn AST>> {
fn varget(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
let global = if src.starts_with('.') {
src = &src[1..];
start += 1;
true
} else {false};
ident(false, src, start).map(|(name, loc, rem, errs)| (Box::new(VarGetAST::new(loc, name.to_string(), global)) as _, if global {(loc.offset() - 1, loc.len() + 1).into()} else {loc}, rem, errs))
}
fn speckw(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
let begin = start;
if src.starts_with("type") && !src[4..].chars().next().map_or(false, is_xid_continue) {
src = &src[4..];
start += 4;
let mut errs = vec![];
process(ignored, &mut src, &mut start, &mut errs);
Some((Box::new(TypeLiteralAST::new((begin, 4).into())), (begin..start).into(), src, errs))
}
else if src.starts_with("null") && !src[4..].chars().next().map_or(false, is_xid_continue) {
src = &src[4..];
start += 4;
let mut errs = vec![];
process(ignored, &mut src, &mut start, &mut errs);
Some((Box::new(NullAST::new((begin, 4).into())), (begin..start).into(), src, errs))
}
else {None}
}
fn intrin(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
src.starts_with('@').then_some(())?;
let begin = start;
src = &src[1..];
start += 1;
let name = process(|src, start| ident(true, src, start), &mut src, &mut start, &mut vec![]).unwrap().0;
Some((Box::new(IntrinsicAST::new((begin..start).into(), name.to_string())), (begin..start).into(), src, vec![]))
}
fn num(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
let mut errs = vec![];
let begin = start;
if src.starts_with('0') {
let val = match src.as_bytes().get(1).copied() {
Some(b'o') => {
src = &src[2..];
start += 2;
let mut val = 0u64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(8)) {
val *= 10;
val += d as u64;
src = &src[1..];
start += 1;
}
if src.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) {
errs.push(CobaltError::UnexpectedDecimal {
loc: (start, 1).into(),
lit: "octal"
});
let idx = src.find(|c: char| !c.is_ascii_digit()).unwrap_or(src.len()); // recovery: skip all decimal digits
start += idx;
src = &src[idx..];
}
let val = if src.starts_with('.') && src[1..].starts_with(|c: char| c.is_digit(8)) {
let mut val = val as f64;
let mut exp = 0.125f64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(8)) {
val += d as f64 * exp;
src = &src[1..];
start += 1;
exp *= 0.125;
}
Either::Right(val)
} else {Either::Left(val)};
if src.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) {
errs.push(CobaltError::UnexpectedDecimal {
loc: (start, 1).into(),
lit: "octal"
});
let idx = src.find(|c: char| !c.is_ascii_digit()).unwrap_or(src.len()); // recovery: skip all decimal digits
start += idx;
src = &src[idx..];
}
val
},
Some(b'x') => {
src = &src[2..];
start += 2;
let mut val = 0u64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(16)) {
val *= 10;
val += d as u64;
src = &src[1..];
start += 1;
}
if src.starts_with('.') && src[1..].starts_with(|c: char| c.is_ascii_hexdigit()) {
let mut val = val as f64;
let mut exp = 0.0625f64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(16)) {
val += d as f64 * exp;
src = &src[1..];
start += 1;
exp *= 0.0625;
}
Either::Right(val)
} else {Either::Left(val)}
},
Some(b'b') => {
src = &src[2..];
start += 2;
let mut val = 0u64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(2)) {
val *= 10;
val += d as u64;
src = &src[1..];
start += 1;
}
if src.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) {
errs.push(CobaltError::UnexpectedDecimal {
loc: (start, 1).into(),
lit: "binary"
});
let idx = src.find(|c: char| !c.is_ascii_digit()).unwrap_or(src.len()); // recovery: skip all decimal digits
start += idx;
src = &src[idx..];
}
let val = if src.starts_with('.') && src[1..].starts_with(|c: char| c.is_digit(2)) {
let mut val = val as f64;
let mut exp = 0.5f64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(2)) {
val += d as f64 * exp;
src = &src[1..];
start += 1;
exp *= 0.5;
}
Either::Right(val)
} else {Either::Left(val)};
if src.chars().next().map(|c: char| c.is_ascii_digit()).unwrap_or(false) {
errs.push(CobaltError::UnexpectedDecimal {
loc: (start, 1).into(),
lit: "binary"
});
let idx = src.find(|c: char| !c.is_ascii_digit()).unwrap_or(src.len()); // recovery: skip all decimal digits
start += idx;
src = &src[idx..];
}
val
},
Some(b'0'..=b'9') => {
let mut val = 0u64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(10)) {
val *= 10;
val += d as u64;
src = &src[1..];
start += 1;
}
if src.starts_with('.') && src[1..].starts_with(|c: char| c.is_ascii_digit()) {
let mut val = val as f64;
let mut exp = 0.1f64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(10)) {
val += d as f64 * exp;
src = &src[1..];
start += 1;
exp *= 0.1;
}
Either::Right(val)
} else {Either::Left(val)}
},
_ => {
src = &src[1..];
start += 1;
Either::Left(0)
},
};
let end = start;
process(ignored, &mut src, &mut start, &mut errs);
let suf = process(|src, start| ident(false, src, start), &mut src, &mut start, &mut errs).map(|(suf, loc)| (suf.to_string(), loc));
let ast = match val {
Either::Left(val) => Box::new(IntLiteralAST::new((begin..end).into(), val as i128, suf)) as Box<dyn AST>,
Either::Right(val) => Box::new(FloatLiteralAST::new((begin..end).into(), val, suf)) as Box<dyn AST>
};
Some((ast, (begin..start).into(), src, errs))
}
else if src.starts_with(['1', '2', '3', '4', '5', '6', '7', '8', '9']) {
let mut val = 0u64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(10)) {
val *= 10;
val += d as u64;
src = &src[1..];
start += 1;
}
let val = if src.starts_with('.') && src[1..].starts_with(|c: char| c.is_ascii_digit()) {
let mut val = val as f64;
let mut exp = 0.1f64;
while let Some(d) = src.chars().next().and_then(|c| c.to_digit(10)) {
val += d as f64 * exp;
src = &src[1..];
start += 1;
exp *= 0.1;
}
Either::Right(val)
} else {Either::Left(val)};
let end = start;
process(ignored, &mut src, &mut start, &mut errs);
let suf = process(|src, start| ident(false, src, start), &mut src, &mut start, &mut errs).map(|(suf, loc)| (suf.to_string(), loc));
let ast = match val {
Either::Left(val) => Box::new(IntLiteralAST::new((begin..end).into(), val as i128, suf)) as Box<dyn AST>,
Either::Right(val) => Box::new(FloatLiteralAST::new((begin..end).into(), val, suf)) as Box<dyn AST>
};
Some((ast, (begin..start).into(), src, errs))
}
else {None}
}
fn strlit(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
if !src.starts_with('"') {return None}
let begin = start;
src = &src[1..];
start += 1;
let mut errs = vec![];
let mut out = vec![];
let mut happy = false;
while let Some(idx) = src.find(['\\', '"']) {
out.extend_from_slice(&src.as_bytes()[..idx]);
src = &src[idx..];
start += idx;
if src.as_bytes()[0] == b'"' {
happy = true;
src = &src[1..];
start += 1;
break
}
src = &src[1..];
start += 1;
match src.chars().next() {
None => break,
Some(c @ ('n' | 'r' | 't' | 'a' | '0')) => {
src = &src[1..];
start += 1;
out.push(match c {
'n' => b'\n',
'r' => b'\r',
't' => b'\t',
'0' => b'\0',
'a' => 0x07,
'e' => 0x1b,
_ => unreachable!()
});
}
Some('x') => {
let mut byte = 0u8;
src = &src[1..];
start += 1;
if let Some(c) = src.chars().next() {
if let Some(d) = c.to_digit(16) {
byte = (d as u8) << 4;
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "hexadecimal character in escape code",
found: got.0,
loc: (start, got.1).into(),
});
src = &src[c.len_utf8()..];
start += c.len_utf8();
}
}
else {break}
if let Some(c) = src.chars().next() {
if let Some(d) = c.to_digit(16) {
byte |= d as u8;
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "hexadecimal character in escape code",
found: got.0,
loc: (start, got.1).into(),
});
src = &src[c.len_utf8()..];
start += c.len_utf8();
}
}
else {break}
out.push(byte);
},
Some('c') => {
let mut byte = 0u8;
src = &src[1..];
start += 1;
if let Some(c) = src.chars().next() {
if let Some(d) = c.to_digit(16) {
byte = (d as u8) << 4;
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "hexadecimal character in escape code",
found: got.0,
loc: (start, got.1).into(),
});
src = &src[c.len_utf8()..];
start += c.len_utf8();
}
}
else {break}
if let Some(c) = src.chars().next() {
if let Some(d) = c.to_digit(16) {
byte |= d as u8;
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "hexadecimal character in escape code",
found: got.0,
loc: (start, got.1).into(),
});
src = &src[c.len_utf8()..];
start += c.len_utf8();
}
}
else {break}
out.extend(utils::CharBytesIterator::from_u8(byte));
},
Some('u') => {
let mut cp = 0u32;
src = &src[1..];
start += 1;
let open = start;
if !src.starts_with('{') {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: r#""{" for unicode escape"#,
found: got.0,
loc: (start, got.1).into()
});
continue
}
src = &src[1..];
start += 1;
let mut happy = false;
let mut rem = false;
let mut chars = 0;
while let Some(c) = src.chars().next() {
if let Some(d) = c.to_digit(16) {
if chars < 6 {
cp <<= 4;
cp |= d;
src = &src[1..];
start += 1;
}
else {
errs.push(CobaltError::UnicodeSequenceTooLong {loc: (open + 1, 7).into()});
break
}
}
else if c == '}' {
happy = true;
rem = true;
src = &src[1..];
start += 1;
break
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "hexadecimal character in escape code",
found: got.0,
loc: (start, got.1).into(),
});
src = &src[c.len_utf8()..];
start += c.len_utf8();
rem = true;
break
}
chars += 1;
}
if !rem {break}
if !happy {
let got = got(src);
errs.push(CobaltError::UnmatchedDelimiter {
expected: '}',
found: got.0,
start: (open, 1).into(),
end: (start, got.1).into()
});
}
out.extend(utils::CharBytesIterator::from_u32(cp).unwrap_or_else(|| {
errs.push(CobaltError::InvalidCodepoint {
val: cp,
loc: ((open + 1)..(start - 1)).into()
});
utils::CharBytesIterator::from_u8(0)
}));
},
Some(c) => {
out.extend(utils::CharBytesIterator::from_char(c));
src = &src[c.len_utf8()..];
start += c.len_utf8();
}
}
}
if !happy {
errs.push(CobaltError::UnmatchedDelimiter {
expected: '"',
found: ParserFound::Eof,
start: (begin, 1).into(),
end: start.into()
});
}
let end = start;
process(ignored, &mut src, &mut start, &mut errs);
let suf = process(|src, start| ident(false, src, start), &mut src, &mut start, &mut errs).map(|(suf, loc)| (suf.to_string(), loc));
Some((Box::new(StringLiteralAST::new((begin..end).into(), out, suf)), (begin..start).into(), src, errs))
}
fn chrlit(mut src: &str, mut start: usize) -> ParserReturn<Box<dyn AST>> {
if !src.starts_with('\'') {return None}
let begin = start;
src = &src[1..];
start += 1;
let mut errs = vec![];
let ch = 'main: {
if src.starts_with('\\') {
src = &src[1..];
start += 1;
match src.chars().next() {
None => {
errs.push(CobaltError::UnmatchedDelimiter {
expected: '\'',
found: ParserFound::Eof,
start: (begin, 1).into(),
end: start.into()
});
0u32
},
Some(c @ ('n' | 'r' | 't' | 'a' | '0')) => {
src = &src[1..];
start += 1;
(match c {
'n' => b'\n',
'r' => b'\r',
't' => b'\t',
'0' => b'\0',
'a' => 0x07,
'e' => 0x1b,
_ => unreachable!()
}) as u32
},
Some('c') => {
let mut byte = 0u32;
src = &src[1..];
start += 1;
if let Some(c) = src.chars().next() {
if let Some(d) = c.to_digit(16) {
byte = d << 4;
src = &src[1..];
start += 1;
}
else {
let got = got(src);
errs.push(CobaltError::ExpectedFound {
ex: "hexadecimal character in escape code",
found: got.0,
loc: (start, got.1).into(),