-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathparser.rs
More file actions
3478 lines (3078 loc) · 118 KB
/
Copy pathparser.rs
File metadata and controls
3478 lines (3078 loc) · 118 KB
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 std::path::Path;
use crate::language::*;
use crate::regex::*;
// This could be adapted to return both the partial document and the errors.
// But for our purposes if the parse fails then there's no point trying to do
// deeper validation or analysis; the input syntax is broken and the user
// needs to fix it. Should a partial parse turn out have meaning then the
// return type of this can change to ParseResult<'i> but for now it is fine
// to use Result.
pub fn parse_with_recovery<'i>(
path: &'i Path,
content: &'i str,
) -> Result<Document<'i>, Vec<ParsingError>> {
let mut input = Parser::new();
input.filename(path);
input.initialize(content);
input.parse_collecting_errors()
}
// Most general errors first, most specific last (when removing redundant
// errors, we prefer being able to give a more specific error message to the
// user)
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ParsingError {
// lowest priority
IllegalParserState(Span),
Unimplemented(Span),
Unrecognized(Span),
UnexpectedEndOfInput(Span),
Expected(Span, &'static str),
ExpectedMatchingChar(Span, &'static str, char, char),
MissingParenthesis(Span),
// more specific errors
InvalidCharacter(Span, char),
InvalidHeader(Span),
InvalidIdentifier(Span, String),
InvalidForma(Span),
InvalidGenus(Span),
InvalidSignature(Span),
InvalidParameters(Span),
InvalidDeclaration(Span),
InvalidSection(Span),
MixedSectionContent(Span),
InvalidInvocation(Span),
InvalidFunction(Span),
InvalidTuple(Span),
InvalidCodeBlock(Span),
InvalidStep(Span),
InvalidSubstep(Span),
InvalidAttribute(Span),
InvalidResponse(Span),
InvalidMultiline(Span),
InvalidForeach(Span),
InvalidCost(Span),
InvalidIntegral(Span),
InvalidQuantity(Span),
InvalidQuantityDecimal(Span),
InvalidQuantityUncertainty(Span),
InvalidQuantityMagnitude(Span),
InvalidQuantitySymbol(Span),
// highest priority
UnclosedInterpolation(Span),
}
impl ParsingError {
pub fn span(&self) -> Span {
match self {
ParsingError::IllegalParserState(span)
| ParsingError::Unimplemented(span)
| ParsingError::Unrecognized(span)
| ParsingError::UnexpectedEndOfInput(span)
| ParsingError::MissingParenthesis(span)
| ParsingError::InvalidHeader(span)
| ParsingError::InvalidForma(span)
| ParsingError::InvalidGenus(span)
| ParsingError::InvalidSignature(span)
| ParsingError::InvalidParameters(span)
| ParsingError::InvalidDeclaration(span)
| ParsingError::InvalidSection(span)
| ParsingError::MixedSectionContent(span)
| ParsingError::InvalidInvocation(span)
| ParsingError::InvalidFunction(span)
| ParsingError::InvalidTuple(span)
| ParsingError::InvalidCodeBlock(span)
| ParsingError::InvalidStep(span)
| ParsingError::InvalidSubstep(span)
| ParsingError::InvalidAttribute(span)
| ParsingError::InvalidResponse(span)
| ParsingError::InvalidMultiline(span)
| ParsingError::InvalidForeach(span)
| ParsingError::InvalidCost(span)
| ParsingError::InvalidIntegral(span)
| ParsingError::InvalidQuantity(span)
| ParsingError::InvalidQuantityDecimal(span)
| ParsingError::InvalidQuantityUncertainty(span)
| ParsingError::InvalidQuantityMagnitude(span)
| ParsingError::InvalidQuantitySymbol(span)
| ParsingError::UnclosedInterpolation(span) => *span,
ParsingError::Expected(span, _)
| ParsingError::ExpectedMatchingChar(span, _, _, _)
| ParsingError::InvalidCharacter(span, _)
| ParsingError::InvalidIdentifier(span, _) => *span,
}
}
pub fn offset(&self) -> usize {
self.span()
.offset
}
pub fn width(&self) -> usize {
self.span()
.length
}
}
/// Remove redundant errors, keeping only the most specific error at each offset.
/// When multiple errors occur at the same offset, keep only the most specific one.
/// Since ParsingError derives Ord with general errors first and specific errors last,
/// we use > to prefer the higher Ord value (more specific) errors.
fn remove_redundant_errors(errors: Vec<ParsingError>) -> Vec<ParsingError> {
let mut deduped = Vec::new();
for error in errors {
let error_offset = error.offset();
// Check if we have an existing error at this offset
if let Some(existing_idx) = deduped
.iter()
.position(|e: &ParsingError| e.offset() == error_offset)
{
// Keep the more specific error
if error > deduped[existing_idx] {
deduped[existing_idx] = error;
}
// Otherwise, keep the existing error
} else {
// No error at this offset yet, add it
deduped.push(error);
}
}
deduped
}
#[derive(Debug)]
pub struct Parser<'i> {
filename: &'i Path,
original: &'i str,
source: &'i str,
offset: usize,
problems: Vec<ParsingError>,
}
impl<'i> Parser<'i> {
fn new() -> Parser<'i> {
Parser {
filename: Path::new("-"),
original: "",
source: "",
offset: 0,
problems: Vec::new(),
}
}
fn filename(&mut self, filename: &'i Path) {
self.filename = filename;
}
fn initialize(&mut self, content: &'i str) {
self.original = content;
self.source = content;
self.offset = 0;
self.problems
.clear();
}
fn advance(&mut self, width: usize) {
// advance the parser position
self.source = &self.source[width..];
self.offset += width;
}
/// Skip to the beginning of the next line (or end of input). This is used
/// when an error is encountered; we attempt to recover back to a newline
/// as that may well be in a parent scope and we can continue.
fn skip_to_next_line(&mut self) {
if let Some(pos) = self
.source
.find('\n')
{
self.advance(pos + 1);
} else {
self.advance(
self.source
.len(),
);
}
}
fn parse_collecting_errors(&mut self) -> Result<Document<'i>, Vec<ParsingError>> {
// Clear any existing errors
self.problems
.clear();
// Parse header, collecting errors if encountered
let header = if is_magic_line(self.source) {
match self.read_technique_header() {
Ok(header) => Some(header),
Err(error) => {
self.problems
.push(error);
None
}
}
} else {
None
};
// Parse zero or more procedures, handling sections if they exist
let mut procedures = Vec::new();
let mut sections = Vec::new();
while !self.is_finished() {
self.trim_whitespace();
if self.is_finished() {
break;
}
// Check if this Technique is a single set of one or more
// top-level Scopes (steps or sections)
if (is_section(self.source) || is_step(self.source)) && procedures.is_empty() {
while !self.is_finished() {
self.trim_whitespace();
if self.is_finished() {
break;
}
if is_section(self.source) {
match self.read_section() {
Ok(section) => sections.push(section),
Err(error) => {
self.problems
.push(error);
self.skip_to_next_line();
}
}
} else if is_step_dependent(self.source) {
match self.read_step_dependent() {
Ok(step) => sections.push(step),
Err(error) => {
self.problems
.push(error);
self.skip_to_next_line();
}
}
} else if is_step_parallel(self.source) {
match self.read_step_parallel() {
Ok(step) => sections.push(step),
Err(error) => {
self.problems
.push(error);
self.skip_to_next_line();
}
}
} else {
self.problems
.push(ParsingError::Unrecognized(Span::new(self.offset, 0)));
self.skip_to_next_line();
}
}
break;
} else if is_procedure_declaration(self.source) {
match self.take_block_lines(
is_procedure_declaration,
|line| is_section(line) || potential_procedure_declaration(line),
|inner| inner.read_procedure(),
) {
Ok(mut procedure) => {
// Check if there are sections following this procedure
while !self.is_finished() {
self.trim_whitespace();
if self.is_finished() {
break;
}
if is_section(self.source) {
match self.read_section() {
Ok(section) => {
if let Some(Element::Steps(steps, _)) = procedure
.elements
.last_mut()
{
steps.push(section);
} else {
// Create a new Steps element if one doesn't exist
procedure
.elements
.push(Element::Steps(
vec![section],
Span::default(),
));
}
}
Err(error) => {
self.problems
.push(error);
break;
}
}
} else {
// If we hit something that's not a section, stop parsing sections
break;
}
}
procedures.push(procedure);
}
Err(error) => {
self.problems
.push(error);
}
}
} else if potential_procedure_declaration(self.source) {
// It might be that we've encountered a malformed procedure
// declaration, so we try parsing it anyway to get a more
// specific error message.
match self.take_block_lines(
potential_procedure_declaration,
|line| is_section(line) || potential_procedure_declaration(line),
|inner| inner.read_procedure(),
) {
Ok(procedure) => {
procedures.push(procedure);
}
Err(error) => {
self.problems
.push(error);
}
}
} else {
self.problems
.push(ParsingError::Unrecognized(Span::new(self.offset, 0)));
self.skip_to_next_line();
}
}
let body = if !sections.is_empty() {
Some(Technique::Steps(sections))
} else if !procedures.is_empty() {
Some(Technique::Procedures(procedures))
} else {
None
};
// Strip the .tq file extension. We will evolved this when we have web
// based procedures, but for now the parser expects a file to read
// from so we can use its filename as the source.
let source = self
.filename
.to_str()
.filter(|s| !s.is_empty())
.map(|s| {
s.strip_suffix(".tq")
.unwrap_or(s)
});
let document = Document {
source,
header,
body,
};
let errors = std::mem::take(&mut self.problems);
if errors.is_empty() {
Ok(document)
} else {
// Remove redundant errors, keeping only the most specific error
// at each offset
let errors = remove_redundant_errors(errors);
Err(errors)
}
}
/// consume up to but not including newline (or end), then take newline
fn take_line<A, F>(&mut self, f: F) -> Result<A, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
let result = self.take_until(&['\n'], f)?;
self.require_newline()?;
Ok(result)
}
fn is_finished(&self) -> bool {
self.source
.is_empty()
}
fn take_block_lines<A, F, P1, P2>(
&mut self,
start_predicate: P1,
end_predicate: P2,
function: F,
) -> Result<A, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
P1: Fn(&str) -> bool,
P2: Fn(&str) -> bool,
{
let i = locate_block_lines(self.source, start_predicate, end_predicate);
// Extract the substring from start to the found position
let block = &self.source[..i];
let mut parser = self.subparser(0, block);
// Pass to closure for processing
let result = function(&mut parser);
self.problems
.extend(parser.problems);
// Advance parser state
self.source = &self.source[i..];
self.offset += i;
result
}
fn take_block_chars<A, F>(
&mut self,
subject: &'static str,
start_char: char,
end_char: char,
skip_string_content: bool,
function: F,
) -> Result<A, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
let mut l = 0;
let mut begun = false;
if start_char == end_char {
// Simple case: same character for start and end (like X...X)
for (i, c) in self
.source
.char_indices()
{
if !begun && c == start_char {
begun = true;
} else if begun && c == end_char {
l = i + 1; // add end character
break;
}
}
} else {
// Nesting case: different characters for start and end (like (...))
let mut depth = 0;
let mut in_string = false;
for (i, c) in self
.source
.char_indices()
{
if !begun && c == start_char {
begun = true;
depth = 1;
} else if begun {
if skip_string_content && c == '"' {
in_string = !in_string;
} else if !skip_string_content || !in_string {
if c == start_char {
depth += 1;
} else if c == end_char {
depth -= 1;
if depth == 0 {
l = i + 1; // add end character
break;
}
}
}
}
}
}
if !begun {
return Err(ParsingError::Expected(
Span::new(self.offset, 0),
"the start character",
));
}
if l == 0 {
return Err(ParsingError::ExpectedMatchingChar(
Span::new(self.offset, 0),
subject,
start_char,
end_char,
));
}
let block = &self.source[1..l - 1];
let mut parser = self.subparser(1, block);
// Pass to closure for processing
let result = function(&mut parser)?;
self.problems
.extend(parser.problems);
// Advance parser state
self.source = &self.source[l..];
self.offset += l;
Ok(result)
}
fn take_block_delimited<A, F>(
&mut self,
delimiter: &str,
function: F,
) -> Result<A, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
let width = delimiter.len();
// Find the start delimiter
let start = self
.source
.find(delimiter)
.ok_or(ParsingError::Expected(
Span::new(self.offset, 0),
"a starting delimiter",
))?;
// Look for the end delimiter after correcting for the starting one
let start = start + width;
let end = self.source[start..]
.find(delimiter)
.ok_or(ParsingError::Expected(
Span::new(self.offset, 0),
"the corresponding end delimiter",
))?;
// Correct actual positions in input
let end = start + end;
// Extract the content between delimiters
let block = &self.source[start..end];
let mut parser = self.subparser(start, block);
// Pass to closure for processing
let result = function(&mut parser)?;
self.problems
.extend(parser.problems);
// Advance parser state past the entire delimited block
let end = end + width;
self.source = &self.source[end..];
self.offset += end;
Ok(result)
}
fn take_until<A, F>(&mut self, pattern: &[char], function: F) -> Result<A, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
let content = self.source;
let end_pos = content
.find(pattern)
.unwrap_or(content.len());
let block = &content[..end_pos];
let mut parser = self.subparser(0, block);
// Pass to closure for processing
let result = function(&mut parser)?;
self.problems
.extend(parser.problems);
// Advance parser state
self.source = &self.source[end_pos..];
self.offset += end_pos;
Ok(result)
}
fn take_split_by<A, F>(&mut self, delimiter: char, function: F) -> Result<Vec<A>, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
let content = self.source;
let base = content.as_ptr() as usize;
let mut results = Vec::new();
for chunk in content.split(delimiter) {
let trimmed = chunk.trim_ascii();
if trimmed.is_empty() {
return Err(ParsingError::Expected(
Span::new(self.offset, 0),
"non-empty content between delimiters",
));
}
let indent = trimmed.as_ptr() as usize - base;
let mut parser = self.subparser(indent, trimmed);
results.push(function(&mut parser)?);
self.problems
.extend(parser.problems);
}
// Advance parser past all consumed content
self.advance(content.len());
Ok(results)
}
/// Split content into elements at each top-level comma (and, if
/// `allow_newline`, each top-level newline too — lists/tablets allow
/// either, tuples/arguments are comma-only). Separators inside parens,
/// brackets, strings, or a ``` multiline block don't split.
///
/// Slices each element out before parsing it, rather than parsing
/// incrementally and checking what follows, because some readers
/// reached from `read_expression` (e.g. `read_numeric_integral`, and
/// the `is_binding`/`is_numeric_integral` predicates) assume they're
/// handed exactly one isolated token and anchor to its end.
fn take_elements<A, F>(
&mut self,
allow_newline: bool,
function: F,
) -> Result<Vec<A>, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
let content = self.source;
let base = content.as_ptr() as usize;
let mut results = Vec::new();
let mut start = 0;
let mut depth = 0i32;
let mut in_string = false;
let mut in_multiline = false;
let mut backticks = 0u8;
let mut cut = |outer: &mut Parser<'i>, chunk: &'i str| -> Result<(), ParsingError> {
let trimmed = chunk.trim_ascii();
if trimmed.is_empty() {
return Ok(());
}
let indent = trimmed.as_ptr() as usize - base;
let mut parser = outer.subparser(indent, trimmed);
results.push(function(&mut parser)?);
outer
.problems
.extend(parser.problems);
Ok(())
};
for (i, c) in content.char_indices() {
if c == '`' {
backticks += 1;
if backticks == 3 {
in_multiline = !in_multiline;
backticks = 0;
}
continue;
}
backticks = 0;
match c {
_ if in_multiline => {}
'"' => in_string = !in_string,
_ if in_string => {}
'(' | '[' => depth += 1,
')' | ']' => depth -= 1,
',' if depth == 0 => {
cut(self, &content[start..i])?;
start = i + c.len_utf8();
}
'\n' if depth == 0 && allow_newline => {
cut(self, &content[start..i])?;
start = i + c.len_utf8();
}
_ => {}
}
}
cut(self, &content[start..])?;
self.advance(content.len());
Ok(results)
}
fn take_paragraph<A, F>(&mut self, function: F) -> Result<A, ParsingError>
where
F: Fn(&mut Parser<'i>) -> Result<A, ParsingError>,
{
// Find the end of this paragraph (\n\n or end of input)
let content = self.source;
let mut i = content
.find("\n\n")
.unwrap_or(content.len());
let paragraph = &content[..i];
let mut parser = self.subparser(0, paragraph);
let result = function(&mut parser)?;
self.problems
.extend(parser.problems);
// Advance past this paragraph and the \n\n delimiter if present
if i < content.len() {
i += 2;
}
self.advance(i);
Ok(result)
}
fn peek_next_char(&self) -> Option<char> {
self.source
.chars()
.next()
}
/// Given a string, fork a copy of the parser state and run a nested
/// parser on that string. Does NOT advance the parent's parser state;
/// the caller needs to do that via one of the take_*() methods.
fn subparser(&self, indent: usize, content: &'i str) -> Parser<'i> {
let parser = Parser {
filename: self.filename,
original: self.original,
source: content,
offset: indent + self.offset,
problems: Vec::new(),
};
// and return
parser
}
/// `slice` must be a sub-slice of `self.source`.
fn span_of(&self, slice: &str) -> Span {
let inner = (slice.as_ptr() as usize)
- (self
.source
.as_ptr() as usize);
Span::new(self.offset + inner, slice.len())
}
fn span_since(&self, start: usize) -> Span {
Span::new(start, self.offset - start)
}
// because test cases and trivial single-line examples might omit an
// ending newline, this also returns Ok if end of input is reached.
fn require_newline(&mut self) -> Result<(), ParsingError> {
for (i, c) in self
.source
.char_indices()
{
let l = i + 1;
if c == '\n' {
self.source = &self.source[l..];
self.offset += l;
return Ok(());
} else if c.is_ascii_whitespace() {
continue;
} else {
return Err(ParsingError::InvalidCharacter(Span::new(self.offset, 0), c));
}
}
// We don't actually require a newline to end the file.
self.source = "";
self.offset += self
.source
.len();
Ok(())
}
// hard wire the version for now. If we ever grow to supporting multiple major
// versions then this will be a lot more complicated than just dealing with a
// different natural number here.
fn read_magic_line(&mut self) -> Result<u8, ParsingError> {
self.take_until(&['\n'], |inner| {
let re = regex!(r"%\s*technique\s+v1\s*$");
if re.is_match(inner.source) {
Ok(1)
} else {
let error_offset = analyze_magic_line(inner.source);
Err(ParsingError::InvalidHeader(Span::new(
inner.offset + error_offset,
0,
)))
}
})
}
// This one is awkward because if a SPDX line is present, then it really needs
// to have a license, whereas the copyright part is optional.
fn read_spdx_line(&mut self) -> Result<(Option<&'i str>, Option<&'i str>), ParsingError> {
self.take_until(&['\n'], |inner| {
let re = regex!(r"^!\s*([^;]+)(?:;\s*(?:\(c\)|\(C\)|©)\s*(.+))?$");
let cap = re
.captures(inner.source)
.ok_or(ParsingError::InvalidHeader(Span::new(inner.offset, 0)))?;
// Now to extracting the values we need. We get the license code from
// the first capture. It must be present otherwise we don't have a
// valid SPDX line (and we declared that we're on an SPDX line by the
// presence of the '!' character at the beginning of the line).
let one = cap
.get(1)
.ok_or(ParsingError::Expected(
Span::new(inner.offset, 0),
"the license name",
))?;
let result = validate_license(one.as_str())
.ok_or(ParsingError::InvalidHeader(Span::new(inner.offset, 0)))?;
let license = Some(result);
// Now dig out the copyright, if present:
let copyright = match cap.get(2) {
Some(two) => {
let result = validate_copyright(two.as_str())
.ok_or(ParsingError::InvalidHeader(Span::new(inner.offset, 0)))?;
Some(result)
}
None => None,
};
Ok((license, copyright))
})
}
fn read_domain_line(&mut self) -> Result<Option<&'i str>, ParsingError> {
self.take_until(&['\n'], |inner| {
let re = regex!(r"^&\s*(.+)$");
let cap = re
.captures(inner.source)
.ok_or(ParsingError::InvalidHeader(Span::new(inner.offset, 0)))?;
let one = cap
.get(1)
.ok_or(ParsingError::Expected(
Span::new(inner.offset, 0),
"a domain name",
))?;
let result = validate_domain(one.as_str())
.ok_or(ParsingError::InvalidHeader(Span::new(inner.offset, 0)))?;
Ok(Some(result))
})
}
fn read_technique_header(&mut self) -> Result<Metadata<'i>, ParsingError> {
let start = self.offset;
// Process magic line
let version = if is_magic_line(self.source) {
let result = self.read_magic_line()?;
self.require_newline()?;
result
} else {
Err(ParsingError::Expected(Span::new(0, 0), "The % symbol"))?
};
// Process SPDX line
let (license, copyright) = if is_spdx_line(self.source) {
let result = self.read_spdx_line()?;
self.require_newline()?;
result
} else {
(None, None)
};
// Process domain line
let domain = if is_domain_line(self.source) {
let result = self.read_domain_line()?;
self.require_newline()?;
result
} else {
None
};
Ok(Metadata {
version,
license,
copyright,
domain,
span: self.span_since(start),
})
}
fn read_signature(&mut self) -> Result<Signature<'i>, ParsingError> {
let re = regex!(r"\s*(.+?)\s*->\s*(.+?)\s*$");
let cap = match re.captures(self.source) {
Some(c) => c,
None => {
let arrow_offset = analyze_malformed_signature(self.source);
return Err(ParsingError::InvalidSignature(Span::new(
self.offset + arrow_offset,
0,
)));
}
};
let one = cap
.get(1)
.ok_or(ParsingError::Expected(
Span::new(self.offset, 0),
"a Genus for the requires",
))?;
let two = cap
.get(2)
.ok_or(ParsingError::Expected(
Span::new(self.offset, 0),
"a Genus for the provides",
))?;
let one_span = Span::new(self.offset + one.start(), one.len());
let two_span = Span::new(self.offset + two.start(), two.len());
let requires = validate_genus(one.as_str(), one_span).ok_or(ParsingError::InvalidGenus(
Span::new(one_span.offset, one_span.length),
))?;
let provides = validate_genus(two.as_str(), two_span).ok_or(ParsingError::InvalidGenus(
Span::new(two_span.offset, two_span.length),
))?;
Ok(Signature { requires, provides })
}
fn parse_procedure_declaration(
&mut self,
) -> Result<
(
Identifier<'i>,
Option<Vec<Identifier<'i>>>,
Option<Signature<'i>>,
),
ParsingError,
> {
// These capture groups use .+? to make "match more than one, but
// lazily" so that the subsequent grabs of whitespace and the all
// important ':' character are not absorbed.
let re = regex!(r"(?s)^\s*(.+?)\s*:\s*(.+?)?\s*$");
let cap = re
.captures(self.source)
.ok_or(ParsingError::InvalidDeclaration(Span::new(self.offset, 0)))?;
let one = cap
.get(1)
.ok_or(ParsingError::Expected(
Span::new(self.offset, 0),
"an Identifier for the procedure declaration",
))?;
let text = one.as_str();
let (name, parameters) = if let Some((before, list)) = text.split_once('(') {
let before = before.trim();
let name = validate_identifier(before, self.span_of(before)).ok_or(
ParsingError::InvalidIdentifier(
Span::new(self.offset, before.len()),
before.to_string(),
),
)?;
// Extract parameters from parentheses
if !list.ends_with(')') {
return Err(ParsingError::InvalidDeclaration(Span::new(self.offset, 0)));
}
let list = &list[..list.len() - 1].trim_ascii();
let parameters = if list.is_empty() {
None
} else {
let mut params = Vec::new();
for item in list.split(',') {