-
Notifications
You must be signed in to change notification settings - Fork 476
/
parser.rs
2810 lines (2448 loc) · 65.2 KB
/
parser.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 {super::*, TokenKind::*};
/// Just language parser
///
/// The parser is a (hopefully) straightforward recursive descent parser.
///
/// It uses a few tokens of lookahead to disambiguate different constructs.
///
/// The `expect_*` and `presume_`* methods are similar in that they assert the
/// type of unparsed tokens and consume them. However, upon encountering an
/// unexpected token, the `expect_*` methods return an unexpected token error,
/// whereas the `presume_*` tokens return an internal error.
///
/// The `presume_*` methods are used when the token stream has been inspected in
/// some other way, and thus encountering an unexpected token is a bug in Just,
/// and not a syntax error.
///
/// All methods starting with `parse_*` parse and return a language construct.
///
/// The parser tracks an expected set of tokens as it parses. This set contains
/// all tokens which would have been accepted at the current point in the
/// parse. Whenever the parser tests for a token that would be accepted, but
/// does not find it, it adds that token to the set. When the parser accepts a
/// token, the set is cleared. If the parser finds a token which is unexpected,
/// the elements of the set are printed in the resultant error message.
pub(crate) struct Parser<'run, 'src> {
expected_tokens: BTreeSet<TokenKind>,
file_depth: u32,
import_offsets: Vec<usize>,
module_namepath: &'run Namepath<'src>,
next_token: usize,
recursion_depth: usize,
tokens: &'run [Token<'src>],
unstable_features: BTreeSet<UnstableFeature>,
working_directory: &'run Path,
}
impl<'run, 'src> Parser<'run, 'src> {
/// Parse `tokens` into an `Ast`
pub(crate) fn parse(
file_depth: u32,
import_offsets: &[usize],
module_namepath: &'run Namepath<'src>,
tokens: &'run [Token<'src>],
working_directory: &'run Path,
) -> CompileResult<'src, Ast<'src>> {
Self {
expected_tokens: BTreeSet::new(),
file_depth,
import_offsets: import_offsets.to_vec(),
module_namepath,
next_token: 0,
recursion_depth: 0,
tokens,
unstable_features: BTreeSet::new(),
working_directory,
}
.parse_ast()
}
fn error(&self, kind: CompileErrorKind<'src>) -> CompileResult<'src, CompileError<'src>> {
Ok(self.next()?.error(kind))
}
/// Construct an unexpected token error with the token returned by
/// `Parser::next`
fn unexpected_token(&self) -> CompileResult<'src, CompileError<'src>> {
self.error(CompileErrorKind::UnexpectedToken {
expected: self
.expected_tokens
.iter()
.copied()
.filter(|kind| *kind != ByteOrderMark)
.collect::<Vec<TokenKind>>(),
found: self.next()?.kind,
})
}
fn internal_error(&self, message: impl Into<String>) -> CompileResult<'src, CompileError<'src>> {
self.error(CompileErrorKind::Internal {
message: message.into(),
})
}
/// An iterator over the remaining significant tokens
fn rest(&self) -> impl Iterator<Item = Token<'src>> + 'run {
self.tokens[self.next_token..]
.iter()
.copied()
.filter(|token| token.kind != Whitespace)
}
/// The next significant token
fn next(&self) -> CompileResult<'src, Token<'src>> {
if let Some(token) = self.rest().next() {
Ok(token)
} else {
Err(self.internal_error("`Parser::next()` called after end of token stream")?)
}
}
/// Check if the next significant token is of kind `kind`
fn next_is(&mut self, kind: TokenKind) -> bool {
self.next_are(&[kind])
}
/// Check if the next significant tokens are of kinds `kinds`
///
/// The first token in `kinds` will be added to the expected token set.
fn next_are(&mut self, kinds: &[TokenKind]) -> bool {
if let Some(&kind) = kinds.first() {
self.expected_tokens.insert(kind);
}
let mut rest = self.rest();
for kind in kinds {
match rest.next() {
Some(token) => {
if token.kind != *kind {
return false;
}
}
None => return false,
}
}
true
}
/// Advance past one significant token, clearing the expected token set.
fn advance(&mut self) -> CompileResult<'src, Token<'src>> {
self.expected_tokens.clear();
for skipped in &self.tokens[self.next_token..] {
self.next_token += 1;
if skipped.kind != Whitespace {
return Ok(*skipped);
}
}
Err(self.internal_error("`Parser::advance()` advanced past end of token stream")?)
}
/// Return the next token if it is of kind `expected`, otherwise, return an
/// unexpected token error
fn expect(&mut self, expected: TokenKind) -> CompileResult<'src, Token<'src>> {
if let Some(token) = self.accept(expected)? {
Ok(token)
} else {
Err(self.unexpected_token()?)
}
}
/// Return an unexpected token error if the next token is not an EOL
fn expect_eol(&mut self) -> CompileResult<'src> {
self.accept(Comment)?;
if self.next_is(Eof) {
return Ok(());
}
self.expect(Eol).map(|_| ())
}
fn expect_keyword(&mut self, expected: Keyword) -> CompileResult<'src> {
let found = self.advance()?;
if found.kind == Identifier && expected == found.lexeme() {
Ok(())
} else {
Err(found.error(CompileErrorKind::ExpectedKeyword {
expected: vec![expected],
found,
}))
}
}
/// Return an internal error if the next token is not of kind `Identifier`
/// with lexeme `lexeme`.
fn presume_keyword(&mut self, keyword: Keyword) -> CompileResult<'src> {
let next = self.advance()?;
if next.kind != Identifier {
Err(self.internal_error(format!(
"Presumed next token would have kind {Identifier}, but found {}",
next.kind
))?)
} else if keyword == next.lexeme() {
Ok(())
} else {
Err(self.internal_error(format!(
"Presumed next token would have lexeme \"{keyword}\", but found \"{}\"",
next.lexeme(),
))?)
}
}
/// Return an internal error if the next token is not of kind `kind`.
fn presume(&mut self, kind: TokenKind) -> CompileResult<'src, Token<'src>> {
let next = self.advance()?;
if next.kind == kind {
Ok(next)
} else {
Err(self.internal_error(format!(
"Presumed next token would have kind {kind:?}, but found {:?}",
next.kind
))?)
}
}
/// Return an internal error if the next token is not one of kinds `kinds`.
fn presume_any(&mut self, kinds: &[TokenKind]) -> CompileResult<'src, Token<'src>> {
let next = self.advance()?;
if kinds.contains(&next.kind) {
Ok(next)
} else {
Err(self.internal_error(format!(
"Presumed next token would be {}, but found {}",
List::or(kinds),
next.kind
))?)
}
}
/// Accept and return a token of kind `kind`
fn accept(&mut self, kind: TokenKind) -> CompileResult<'src, Option<Token<'src>>> {
if self.next_is(kind) {
Ok(Some(self.advance()?))
} else {
Ok(None)
}
}
/// Return an error if the next token is of kind `forbidden`
fn forbid<F>(&self, forbidden: TokenKind, error: F) -> CompileResult<'src>
where
F: FnOnce(Token) -> CompileError,
{
let next = self.next()?;
if next.kind == forbidden {
Err(error(next))
} else {
Ok(())
}
}
/// Accept a token of kind `Identifier` and parse into a `Name`
fn accept_name(&mut self) -> CompileResult<'src, Option<Name<'src>>> {
if self.next_is(Identifier) {
Ok(Some(self.parse_name()?))
} else {
Ok(None)
}
}
fn accepted_keyword(&mut self, keyword: Keyword) -> CompileResult<'src, bool> {
let next = self.next()?;
if next.kind == Identifier && next.lexeme() == keyword.lexeme() {
self.advance()?;
Ok(true)
} else {
Ok(false)
}
}
/// Accept a dependency
fn accept_dependency(&mut self) -> CompileResult<'src, Option<UnresolvedDependency<'src>>> {
if let Some(recipe) = self.accept_name()? {
Ok(Some(UnresolvedDependency {
arguments: Vec::new(),
recipe,
}))
} else if self.accepted(ParenL)? {
let recipe = self.parse_name()?;
let mut arguments = Vec::new();
while !self.accepted(ParenR)? {
arguments.push(self.parse_expression()?);
}
Ok(Some(UnresolvedDependency { recipe, arguments }))
} else {
Ok(None)
}
}
/// Accept and return `true` if next token is of kind `kind`
fn accepted(&mut self, kind: TokenKind) -> CompileResult<'src, bool> {
Ok(self.accept(kind)?.is_some())
}
/// Parse a justfile, consumes self
fn parse_ast(mut self) -> CompileResult<'src, Ast<'src>> {
fn pop_doc_comment<'src>(
items: &mut Vec<Item<'src>>,
eol_since_last_comment: bool,
) -> Option<&'src str> {
if !eol_since_last_comment {
if let Some(Item::Comment(contents)) = items.last() {
let doc = Some(contents[1..].trim_start());
items.pop();
return doc;
}
}
None
}
let mut items = Vec::new();
let mut eol_since_last_comment = false;
self.accept(ByteOrderMark)?;
loop {
let mut attributes = self.parse_attributes()?;
let mut take_attributes = || {
attributes
.take()
.map(|(_token, attributes)| attributes)
.unwrap_or_default()
};
let next = self.next()?;
if let Some(comment) = self.accept(Comment)? {
items.push(Item::Comment(comment.lexeme().trim_end()));
self.expect_eol()?;
eol_since_last_comment = false;
} else if self.accepted(Eol)? {
eol_since_last_comment = true;
} else if self.accepted(Eof)? {
break;
} else if self.next_is(Identifier) {
match Keyword::from_lexeme(next.lexeme()) {
Some(Keyword::Alias) if self.next_are(&[Identifier, Identifier, ColonEquals]) => {
items.push(Item::Alias(self.parse_alias(take_attributes())?));
}
Some(Keyword::Export) if self.next_are(&[Identifier, Identifier, ColonEquals]) => {
self.presume_keyword(Keyword::Export)?;
items.push(Item::Assignment(
self.parse_assignment(true, take_attributes())?,
));
}
Some(Keyword::Unexport)
if self.next_are(&[Identifier, Identifier, Eof])
|| self.next_are(&[Identifier, Identifier, Eol]) =>
{
self.presume_keyword(Keyword::Unexport)?;
let name = self.parse_name()?;
self.expect_eol()?;
items.push(Item::Unexport { name });
}
Some(Keyword::Import)
if self.next_are(&[Identifier, StringToken])
|| self.next_are(&[Identifier, Identifier, StringToken])
|| self.next_are(&[Identifier, QuestionMark]) =>
{
self.presume_keyword(Keyword::Import)?;
let optional = self.accepted(QuestionMark)?;
let (path, relative) = self.parse_string_literal_token()?;
items.push(Item::Import {
absolute: None,
optional,
path,
relative,
});
}
Some(Keyword::Mod)
if self.next_are(&[Identifier, Identifier, Comment])
|| self.next_are(&[Identifier, Identifier, Eof])
|| self.next_are(&[Identifier, Identifier, Eol])
|| self.next_are(&[Identifier, Identifier, Identifier, StringToken])
|| self.next_are(&[Identifier, Identifier, StringToken])
|| self.next_are(&[Identifier, QuestionMark]) =>
{
let doc = pop_doc_comment(&mut items, eol_since_last_comment);
self.presume_keyword(Keyword::Mod)?;
let optional = self.accepted(QuestionMark)?;
let name = self.parse_name()?;
let relative = if self.next_is(StringToken) || self.next_are(&[Identifier, StringToken])
{
Some(self.parse_string_literal()?)
} else {
None
};
items.push(Item::Module {
attributes: take_attributes(),
absolute: None,
doc,
name,
optional,
relative,
});
}
Some(Keyword::Set)
if self.next_are(&[Identifier, Identifier, ColonEquals])
|| self.next_are(&[Identifier, Identifier, Comment, Eof])
|| self.next_are(&[Identifier, Identifier, Comment, Eol])
|| self.next_are(&[Identifier, Identifier, Eof])
|| self.next_are(&[Identifier, Identifier, Eol]) =>
{
items.push(Item::Set(self.parse_set()?));
}
_ => {
if self.next_are(&[Identifier, ColonEquals]) {
items.push(Item::Assignment(
self.parse_assignment(false, take_attributes())?,
));
} else {
let doc = pop_doc_comment(&mut items, eol_since_last_comment);
items.push(Item::Recipe(self.parse_recipe(
doc,
false,
take_attributes(),
)?));
}
}
}
} else if self.accepted(At)? {
let doc = pop_doc_comment(&mut items, eol_since_last_comment);
items.push(Item::Recipe(self.parse_recipe(
doc,
true,
take_attributes(),
)?));
} else {
return Err(self.unexpected_token()?);
}
if let Some((token, attributes)) = attributes {
return Err(token.error(CompileErrorKind::ExtraneousAttributes {
count: attributes.len(),
}));
}
}
if self.next_token != self.tokens.len() {
return Err(self.internal_error(format!(
"Parse completed with {} unparsed tokens",
self.tokens.len() - self.next_token,
))?);
}
Ok(Ast {
items,
unstable_features: self.unstable_features,
warnings: Vec::new(),
working_directory: self.working_directory.into(),
})
}
/// Parse an alias, e.g `alias name := target`
fn parse_alias(
&mut self,
attributes: BTreeSet<Attribute<'src>>,
) -> CompileResult<'src, Alias<'src, Name<'src>>> {
self.presume_keyword(Keyword::Alias)?;
let name = self.parse_name()?;
self.presume_any(&[Equals, ColonEquals])?;
let target = self.parse_name()?;
self.expect_eol()?;
Ok(Alias {
attributes,
name,
target,
})
}
/// Parse an assignment, e.g. `foo := bar`
fn parse_assignment(
&mut self,
export: bool,
attributes: BTreeSet<Attribute<'src>>,
) -> CompileResult<'src, Assignment<'src>> {
let name = self.parse_name()?;
self.presume(ColonEquals)?;
let value = self.parse_expression()?;
self.expect_eol()?;
let private = attributes.contains(&Attribute::Private);
for attribute in attributes {
if attribute != Attribute::Private {
return Err(name.error(CompileErrorKind::InvalidAttribute {
item_kind: "Assignment",
item_name: name.lexeme(),
attribute,
}));
}
}
Ok(Assignment {
constant: false,
export,
file_depth: self.file_depth,
name,
private: private || name.lexeme().starts_with('_'),
value,
})
}
/// Parse an expression, e.g. `1 + 2`
fn parse_expression(&mut self) -> CompileResult<'src, Expression<'src>> {
if self.recursion_depth == if cfg!(windows) { 48 } else { 256 } {
let token = self.next()?;
return Err(CompileError::new(
token,
CompileErrorKind::ParsingRecursionDepthExceeded,
));
}
self.recursion_depth += 1;
let disjunct = self.parse_disjunct()?;
let expression = if self.accepted(BarBar)? {
self
.unstable_features
.insert(UnstableFeature::LogicalOperators);
let lhs = disjunct.into();
let rhs = self.parse_expression()?.into();
Expression::Or { lhs, rhs }
} else {
disjunct
};
self.recursion_depth -= 1;
Ok(expression)
}
fn parse_disjunct(&mut self) -> CompileResult<'src, Expression<'src>> {
let conjunct = self.parse_conjunct()?;
let disjunct = if self.accepted(AmpersandAmpersand)? {
self
.unstable_features
.insert(UnstableFeature::LogicalOperators);
let lhs = conjunct.into();
let rhs = self.parse_disjunct()?.into();
Expression::And { lhs, rhs }
} else {
conjunct
};
Ok(disjunct)
}
fn parse_conjunct(&mut self) -> CompileResult<'src, Expression<'src>> {
if self.accepted_keyword(Keyword::If)? {
self.parse_conditional()
} else if self.accepted(Slash)? {
let lhs = None;
let rhs = self.parse_conjunct()?.into();
Ok(Expression::Join { lhs, rhs })
} else {
let value = self.parse_value()?;
if self.accepted(Slash)? {
let lhs = Some(Box::new(value));
let rhs = self.parse_conjunct()?.into();
Ok(Expression::Join { lhs, rhs })
} else if self.accepted(Plus)? {
let lhs = value.into();
let rhs = self.parse_conjunct()?.into();
Ok(Expression::Concatenation { lhs, rhs })
} else {
Ok(value)
}
}
}
/// Parse a conditional, e.g. `if a == b { "foo" } else { "bar" }`
fn parse_conditional(&mut self) -> CompileResult<'src, Expression<'src>> {
let condition = self.parse_condition()?;
self.expect(BraceL)?;
let then = self.parse_expression()?;
self.expect(BraceR)?;
self.expect_keyword(Keyword::Else)?;
let otherwise = if self.accepted_keyword(Keyword::If)? {
self.parse_conditional()?
} else {
self.expect(BraceL)?;
let otherwise = self.parse_expression()?;
self.expect(BraceR)?;
otherwise
};
Ok(Expression::Conditional {
condition,
then: then.into(),
otherwise: otherwise.into(),
})
}
fn parse_condition(&mut self) -> CompileResult<'src, Condition<'src>> {
let lhs = self.parse_expression()?;
let operator = if self.accepted(BangEquals)? {
ConditionalOperator::Inequality
} else if self.accepted(EqualsTilde)? {
ConditionalOperator::RegexMatch
} else {
self.expect(EqualsEquals)?;
ConditionalOperator::Equality
};
let rhs = self.parse_expression()?;
Ok(Condition {
lhs: lhs.into(),
rhs: rhs.into(),
operator,
})
}
// Check if the next tokens are a shell-expanded string, i.e., `x"foo"`.
//
// This function skips initial whitespace tokens, but thereafter is
// whitespace-sensitive, so `x"foo"` is a shell-expanded string, whereas `x
// "foo"` is not.
fn next_is_shell_expanded_string(&self) -> bool {
let mut tokens = self
.tokens
.iter()
.skip(self.next_token)
.skip_while(|token| token.kind == Whitespace);
tokens
.next()
.is_some_and(|token| token.kind == Identifier && token.lexeme() == "x")
&& tokens.next().is_some_and(|token| token.kind == StringToken)
}
/// Parse a value, e.g. `(bar)`
fn parse_value(&mut self) -> CompileResult<'src, Expression<'src>> {
if self.next_is(StringToken) || self.next_is_shell_expanded_string() {
Ok(Expression::StringLiteral {
string_literal: self.parse_string_literal()?,
})
} else if self.next_is(Backtick) {
let next = self.next()?;
let kind = StringKind::from_string_or_backtick(next)?;
let contents =
&next.lexeme()[kind.delimiter_len()..next.lexeme().len() - kind.delimiter_len()];
let token = self.advance()?;
let contents = if kind.indented() {
unindent(contents)
} else {
contents.to_owned()
};
if contents.starts_with("#!") {
return Err(next.error(CompileErrorKind::BacktickShebang));
}
Ok(Expression::Backtick { contents, token })
} else if self.next_is(Identifier) {
if self.accepted_keyword(Keyword::Assert)? {
self.expect(ParenL)?;
let condition = self.parse_condition()?;
self.expect(Comma)?;
let error = Box::new(self.parse_expression()?);
self.expect(ParenR)?;
Ok(Expression::Assert { condition, error })
} else {
let name = self.parse_name()?;
if self.next_is(ParenL) {
let arguments = self.parse_sequence()?;
Ok(Expression::Call {
thunk: Thunk::resolve(name, arguments)?,
})
} else {
Ok(Expression::Variable { name })
}
}
} else if self.next_is(ParenL) {
self.presume(ParenL)?;
let contents = self.parse_expression()?.into();
self.expect(ParenR)?;
Ok(Expression::Group { contents })
} else {
Err(self.unexpected_token()?)
}
}
/// Parse a string literal, e.g. `"FOO"`, returning the string literal and the string token
fn parse_string_literal_token(
&mut self,
) -> CompileResult<'src, (Token<'src>, StringLiteral<'src>)> {
let expand = if self.next_is(Identifier) {
self.expect_keyword(Keyword::X)?;
true
} else {
false
};
let token = self.expect(StringToken)?;
let kind = StringKind::from_string_or_backtick(token)?;
let delimiter_len = kind.delimiter_len();
let raw = &token.lexeme()[delimiter_len..token.lexeme().len() - delimiter_len];
let unindented = if kind.indented() {
unindent(raw)
} else {
raw.to_owned()
};
let cooked = if kind.processes_escape_sequences() {
Self::cook_string(token, &unindented)?
} else {
unindented
};
let cooked = if expand {
shellexpand::full(&cooked)
.map_err(|err| token.error(CompileErrorKind::ShellExpansion { err }))?
.into_owned()
} else {
cooked
};
Ok((
token,
StringLiteral {
cooked,
expand,
kind,
raw,
},
))
}
// Transform escape sequences in from string literal `token` with content `text`
fn cook_string(token: Token<'src>, text: &str) -> CompileResult<'src, String> {
#[derive(PartialEq, Eq)]
enum State {
Initial,
Backslash,
Unicode,
UnicodeValue { hex: String },
}
let mut cooked = String::new();
let mut state = State::Initial;
for c in text.chars() {
match state {
State::Initial => {
if c == '\\' {
state = State::Backslash;
} else {
cooked.push(c);
}
}
State::Backslash if c == 'u' => {
state = State::Unicode;
}
State::Backslash => {
match c {
'n' => cooked.push('\n'),
'r' => cooked.push('\r'),
't' => cooked.push('\t'),
'\\' => cooked.push('\\'),
'\n' => {}
'"' => cooked.push('"'),
character => {
return Err(token.error(CompileErrorKind::InvalidEscapeSequence { character }))
}
}
state = State::Initial;
}
State::Unicode => match c {
'{' => {
state = State::UnicodeValue { hex: String::new() };
}
character => {
return Err(token.error(CompileErrorKind::UnicodeEscapeDelimiter { character }));
}
},
State::UnicodeValue { ref mut hex } => match c {
'}' => {
if hex.is_empty() {
return Err(token.error(CompileErrorKind::UnicodeEscapeEmpty));
}
let codepoint = u32::from_str_radix(hex, 16).unwrap();
cooked.push(char::from_u32(codepoint).ok_or_else(|| {
token.error(CompileErrorKind::UnicodeEscapeRange { hex: hex.clone() })
})?);
state = State::Initial;
}
'0'..='9' | 'A'..='F' | 'a'..='f' => {
hex.push(c);
if hex.len() > 6 {
return Err(token.error(CompileErrorKind::UnicodeEscapeLength { hex: hex.clone() }));
}
}
_ => {
return Err(token.error(CompileErrorKind::UnicodeEscapeCharacter { character: c }));
}
},
}
}
if state != State::Initial {
return Err(token.error(CompileErrorKind::UnicodeEscapeUnterminated));
}
Ok(cooked)
}
/// Parse a string literal, e.g. `"FOO"`
fn parse_string_literal(&mut self) -> CompileResult<'src, StringLiteral<'src>> {
let (_token, string_literal) = self.parse_string_literal_token()?;
Ok(string_literal)
}
/// Parse a name from an identifier token
fn parse_name(&mut self) -> CompileResult<'src, Name<'src>> {
self.expect(Identifier).map(Name::from_identifier)
}
/// Parse sequence of comma-separated expressions
fn parse_sequence(&mut self) -> CompileResult<'src, Vec<Expression<'src>>> {
self.presume(ParenL)?;
let mut elements = Vec::new();
while !self.next_is(ParenR) {
elements.push(self.parse_expression()?);
if !self.accepted(Comma)? {
break;
}
}
self.expect(ParenR)?;
Ok(elements)
}
/// Parse a recipe
fn parse_recipe(
&mut self,
doc: Option<&'src str>,
quiet: bool,
attributes: BTreeSet<Attribute<'src>>,
) -> CompileResult<'src, UnresolvedRecipe<'src>> {
let name = self.parse_name()?;
let mut positional = Vec::new();
while self.next_is(Identifier) || self.next_is(Dollar) {
positional.push(self.parse_parameter(ParameterKind::Singular)?);
}
let kind = if self.accepted(Plus)? {
ParameterKind::Plus
} else if self.accepted(Asterisk)? {
ParameterKind::Star
} else {
ParameterKind::Singular
};
let variadic = if kind.is_variadic() {
let variadic = self.parse_parameter(kind)?;
self.forbid(Identifier, |token| {
token.error(CompileErrorKind::ParameterFollowsVariadicParameter {
parameter: token.lexeme(),
})
})?;
Some(variadic)
} else {
None
};
self.expect(Colon)?;
let mut dependencies = Vec::new();
while let Some(dependency) = self.accept_dependency()? {
dependencies.push(dependency);
}
let priors = dependencies.len();
if self.accepted(AmpersandAmpersand)? {
let mut subsequents = Vec::new();
while let Some(subsequent) = self.accept_dependency()? {
subsequents.push(subsequent);
}
if subsequents.is_empty() {
return Err(self.unexpected_token()?);
}
dependencies.append(&mut subsequents);
}
self.expect_eol()?;
let body = self.parse_body()?;
let shebang = body.first().map_or(false, Line::is_shebang);
let script = attributes
.iter()
.any(|attribute| matches!(attribute, Attribute::Script(_)));
if shebang && script {
return Err(name.error(CompileErrorKind::ShebangAndScriptAttribute {
recipe: name.lexeme(),
}));
}
let private = name.lexeme().starts_with('_') || attributes.contains(&Attribute::Private);
let mut doc = doc.map(ToOwned::to_owned);
for attribute in &attributes {
if let Attribute::Doc(attribute_doc) = attribute {
doc = attribute_doc.as_ref().map(|doc| doc.cooked.clone());
}
}
Ok(Recipe {
shebang: shebang || script,
attributes,
body,
dependencies,
doc,
file_depth: self.file_depth,
import_offsets: self.import_offsets.clone(),
name,
namepath: self.module_namepath.join(name),
parameters: positional.into_iter().chain(variadic).collect(),
priors,
private,
quiet,
})
}
/// Parse a recipe parameter
fn parse_parameter(&mut self, kind: ParameterKind) -> CompileResult<'src, Parameter<'src>> {
let export = self.accepted(Dollar)?;
let name = self.parse_name()?;
let default = if self.accepted(Equals)? {
Some(self.parse_value()?)
} else {
None
};
Ok(Parameter {
default,
export,
kind,
name,
})
}
/// Parse the body of a recipe
fn parse_body(&mut self) -> CompileResult<'src, Vec<Line<'src>>> {
let mut lines = Vec::new();
if self.accepted(Indent)? {
while !self.accepted(Dedent)? {
let mut fragments = Vec::new();
let number = self
.tokens
.get(self.next_token)
.map(|token| token.line)
.unwrap_or_default();
if !self.accepted(Eol)? {
while !(self.accepted(Eol)? || self.next_is(Dedent)) {
if let Some(token) = self.accept(Text)? {
fragments.push(Fragment::Text { token });