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
//! Recursive descent parser for the fabula DSL.
//!
//! The parser is designed for composability: downstream DSLs can reuse it to
//! parse fabula pattern syntax embedded in their own blocks. Key entry points:
//!
//! - [`Parser::parse_pattern_body()`] — parse stages, negations, and temporals
//! without the `pattern name { }` wrapper
//! - [`Parser::pos()`] / [`Parser::into_inner()`] — read or recover the cursor
//! position for resumable parsing
//! - [`Parser::from_tokens_at()`] — construct a parser at a specific position
//! in an existing token stream
use crate::ast::*;
use crate::error::ParseError;
use crate::lexer::{Token, TokenKind};
/// Parser state: a cursor over a token stream.
pub struct Parser {
tokens: Vec<Token>,
pos: usize,
}
impl Parser {
/// Create a new parser from a token stream, starting at position 0.
pub fn new(tokens: Vec<Token>) -> Self {
Self { tokens, pos: 0 }
}
/// Create a parser starting at a specific position in the token stream.
///
/// Use this to resume parsing after handing the token stream to another
/// parser (e.g., a downstream DSL parser that calls fabula's parser for
/// pattern sections).
pub fn from_tokens_at(tokens: Vec<Token>, pos: usize) -> Self {
Self { tokens, pos }
}
/// Current cursor position in the token stream.
pub fn pos(&self) -> usize {
self.pos
}
/// Consume the parser, returning the token stream and cursor position.
///
/// Use this to recover the tokens after parsing a section, so a
/// downstream DSL can continue parsing from where fabula left off.
pub fn into_inner(self) -> (Vec<Token>, usize) {
(self.tokens, self.pos)
}
// ---- Document-level parsing ----
/// Parse a complete document (patterns, graphs, and compose directives).
pub fn parse_document(&mut self) -> Result<Document, ParseError> {
let mut items = Vec::new();
while !self.at_eof() {
match &self.peek().kind {
TokenKind::Ident(ref s) if s == "private" => {
self.advance(); // consume "private"
// Next token must be "pattern"
if !self.check(TokenKind::Pattern) {
return Err(self.error("expected 'pattern' after 'private'"));
}
let mut pat = self.parse_pattern()?;
pat.private = true;
items.push(DocumentItem::Pattern(pat));
}
TokenKind::Pattern => items.push(DocumentItem::Pattern(self.parse_pattern()?)),
TokenKind::Graph => items.push(DocumentItem::Graph(self.parse_graph()?)),
TokenKind::Compose => items.push(DocumentItem::Compose(self.parse_compose()?)),
_ => return Err(self.error("expected 'pattern', 'graph', or 'compose'")),
}
}
Ok(Document { items })
}
/// Parse a single pattern declaration, then assert EOF.
pub fn parse_pattern_only(&mut self) -> Result<PatternAst, ParseError> {
let pat = self.parse_pattern()?;
if !self.at_eof() {
return Err(self.error("unexpected content after pattern"));
}
Ok(pat)
}
/// Parse a single graph declaration, then assert EOF.
pub fn parse_graph_only(&mut self) -> Result<GraphAst, ParseError> {
let g = self.parse_graph()?;
if !self.at_eof() {
return Err(self.error("unexpected content after graph"));
}
Ok(g)
}
// ---- Pattern parsing ----
/// Parse a full `pattern name { ... }` declaration.
pub fn parse_pattern(&mut self) -> Result<PatternAst, ParseError> {
self.expect(TokenKind::Pattern)?;
let name = self.expect_ident()?;
self.expect(TokenKind::LBrace)?;
let body = self.parse_pattern_body()?;
self.expect(TokenKind::RBrace)?;
Ok(PatternAst {
name,
stages: body.stages,
negations: body.negations,
temporals: body.temporals,
metadata: body.metadata,
deadline: body.deadline,
unordered_groups: body.unordered_groups,
private: false,
})
}
/// Parse the body of a pattern — stages, negations, and temporal
/// constraints — without the `pattern name { }` wrapper.
///
/// Stops when it sees `}` or EOF but does **not** consume the closing
/// brace. The caller owns the block structure and is responsible for
/// consuming the delimiter.
///
/// This is the primary composability entry point for downstream DSLs
/// that embed fabula pattern syntax in their own blocks:
///
/// ```rust,ignore
/// // salience-dsl example
/// parser.expect_ident()?; // "precondition"
/// parser.expect(TokenKind::LBrace)?; // {
/// let body = parser.parse_pattern_body()?;
/// parser.expect(TokenKind::RBrace)?; // }
/// let pattern = compile_pattern_body_with("name", &body, &mapper)?;
/// ```
pub fn parse_pattern_body(&mut self) -> Result<PatternBody, ParseError> {
let mut stages = Vec::new();
let mut negations = Vec::new();
let mut temporals = Vec::new();
let mut metadata = Vec::new();
let mut deadline = None;
let mut unordered_groups = Vec::new();
while !self.check(TokenKind::RBrace) && !self.at_eof() {
match &self.peek().kind {
TokenKind::Stage => stages.push(self.parse_stage()?),
TokenKind::Unless => negations.push(self.parse_negation()?),
TokenKind::Temporal => temporals.push(self.parse_temporal()?),
TokenKind::Concurrent => {
self.advance();
self.expect(TokenKind::LBrace)?;
let group_start = stages.len();
while !self.check(TokenKind::RBrace) && !self.at_eof() {
if !self.check(TokenKind::Stage) {
return Err(
self.error("only 'stage' blocks are allowed inside 'concurrent'")
);
}
stages.push(self.parse_stage()?);
}
self.expect(TokenKind::RBrace)?;
let group_end = stages.len();
if group_end > group_start {
let indices: Vec<usize> = (group_start..group_end).collect();
unordered_groups.push(indices);
}
}
TokenKind::Ident(s) if s == "meta" => {
metadata.push(self.parse_meta()?);
}
TokenKind::Ident(s) if s == "deadline" => {
self.advance();
deadline = Some(self.expect_number()?);
}
_ => return Err(self.error(
"expected 'stage', 'unless', 'temporal', 'concurrent', 'meta', or 'deadline'",
)),
}
}
Ok(PatternBody {
stages,
negations,
temporals,
metadata,
deadline,
unordered_groups,
private: false,
})
}
/// Parse a `meta("key", "value")` clause.
fn parse_meta(&mut self) -> Result<(String, String), ParseError> {
// "meta" identifier already matched by caller; consume it
self.advance();
self.expect(TokenKind::LParen)?;
let key = match &self.peek().kind {
TokenKind::String(_) => {
if let TokenKind::String(s) = &self.advance().kind {
s.clone()
} else {
unreachable!()
}
}
_ => return Err(self.error("expected string literal for meta key")),
};
self.expect(TokenKind::Comma)?;
let value = match &self.peek().kind {
TokenKind::String(_) => {
if let TokenKind::String(s) = &self.advance().kind {
s.clone()
} else {
unreachable!()
}
}
_ => return Err(self.error("expected string literal for meta value")),
};
self.expect(TokenKind::RParen)?;
Ok((key, value))
}
/// Parse a `stage anchor { clauses... }` block.
pub fn parse_stage(&mut self) -> Result<StageAst, ParseError> {
self.expect(TokenKind::Stage)?;
let anchor = self.expect_ident()?;
self.expect(TokenKind::LBrace)?;
let mut clauses = Vec::new();
while !self.check(TokenKind::RBrace) {
clauses.push(self.parse_clause()?);
}
self.expect(TokenKind::RBrace)?;
Ok(StageAst { anchor, clauses })
}
/// Parse an `unless [between|after] ... { clauses }` negation block.
pub fn parse_negation(&mut self) -> Result<NegationAst, ParseError> {
self.expect(TokenKind::Unless)?;
let kind = if self.check(TokenKind::Between) {
self.advance();
let start = self.expect_ident()?;
let end = self.expect_ident()?;
NegationKind::Between(start, end)
} else if self.check(TokenKind::After) {
self.advance();
let start = self.expect_ident()?;
NegationKind::After(start)
} else {
// Global negation: unless { ... }
NegationKind::Global
};
self.expect(TokenKind::LBrace)?;
let mut clauses = Vec::new();
while !self.check(TokenKind::RBrace) {
clauses.push(self.parse_clause()?);
}
self.expect(TokenKind::RBrace)?;
Ok(NegationAst { kind, clauses })
}
/// Parse a `temporal left relation right [gap range]` constraint.
pub fn parse_temporal(&mut self) -> Result<TemporalAst, ParseError> {
self.expect(TokenKind::Temporal)?;
let left = self.expect_ident()?;
let relation = self.expect_ident()?;
let right = self.expect_ident()?;
// Optional: gap min..max
let (gap_min, gap_max) = if matches!(self.peek().kind, TokenKind::Ident(ref s) if s == "gap")
{
self.advance();
self.parse_gap_range()?
} else {
(None, None)
};
Ok(TemporalAst {
left,
relation,
right,
gap_min,
gap_max,
})
}
fn parse_gap_range(&mut self) -> Result<(Option<f64>, Option<f64>), ParseError> {
// Syntax: 3..10, ..10, 3..
if self.check(TokenKind::DotDot) {
// ..max (no min)
self.advance();
let max = self.expect_number()?;
Ok((None, Some(max)))
} else if matches!(self.peek().kind, TokenKind::Number(_) | TokenKind::Minus) {
let first = self.expect_number()?;
if self.check(TokenKind::DotDot) {
self.advance();
// min.. or min..max
if matches!(self.peek().kind, TokenKind::Number(_) | TokenKind::Minus) {
let second = self.expect_number()?;
Ok((Some(first), Some(second)))
} else {
// min.. (no max)
Ok((Some(first), None))
}
} else {
// Single number = exact gap (min == max)
Ok((Some(first), Some(first)))
}
} else {
Err(self.error("expected gap range (e.g., '3..10', '..10', '3..')"))
}
}
// ---- Compose parsing ----
/// Parse a `compose name = ...` directive.
pub fn parse_compose(&mut self) -> Result<ComposeAst, ParseError> {
self.expect(TokenKind::Compose)?;
let name = self.expect_ident()?;
self.expect(TokenKind::Eq)?;
// First operand is always a pattern name
let first = self.expect_ident()?;
// Determine operator: >> (sequence), | (choice), * (repeat)
let body = if self.check(TokenKind::GtGt) {
// Sequence: first >> second sharing(...)
self.advance();
let second = self.expect_ident()?;
let shared = self.parse_sharing_clause()?;
ComposeBody::Sequence {
left: first,
right: second,
shared,
}
} else if self.check(TokenKind::Pipe) {
// Choice: first | second | third ...
let mut alternatives = vec![first];
while self.check(TokenKind::Pipe) {
self.advance();
alternatives.push(self.expect_ident()?);
}
let exclusive = match &self.peek().kind {
TokenKind::Ident(s) if s == "nonexclusive" => {
self.advance();
false
}
_ => true,
};
ComposeBody::Choice {
alternatives,
exclusive,
}
} else if self.check(TokenKind::Star) {
// Repeat: first * N sharing(...) or first * N..M sharing(...) or first * N.. sharing(...)
self.advance();
let min = self.expect_number()? as usize;
let max = if self.check(TokenKind::DotDot) {
self.advance();
// Check for explicit max or unbounded
if matches!(self.peek().kind, TokenKind::Number(_) | TokenKind::Minus) {
Some(Some(self.expect_number()? as usize))
} else {
Some(None) // unbounded: N..
}
} else {
None // exact: N
};
let shared = self.parse_sharing_clause()?;
match max {
None => {
// Exact: * N → min=N, max=Some(N)
ComposeBody::Repeat {
pattern: first,
min,
max: Some(min),
shared,
}
}
Some(max_val) => {
// Range: * N..M or * N..
ComposeBody::Repeat {
pattern: first,
min,
max: max_val,
shared,
}
}
}
} else {
return Err(self.error("expected '>>' (sequence), '|' (choice), or '*' (repeat)"));
};
Ok(ComposeAst { name, body })
}
fn parse_sharing_clause(&mut self) -> Result<Vec<String>, ParseError> {
if !self.check(TokenKind::Sharing) {
return Ok(Vec::new());
}
self.advance(); // consume 'sharing'
self.expect(TokenKind::LParen)?;
let mut vars = vec![self.expect_ident()?];
while self.check(TokenKind::Comma) {
self.advance();
vars.push(self.expect_ident()?);
}
self.expect(TokenKind::RParen)?;
Ok(vars)
}
/// Parse a single clause: `[!] [?]source.label = | -> | < | > | <= | >= target`.
pub fn parse_clause(&mut self) -> Result<ClauseAst, ParseError> {
// Optional negation prefix: !
let negated = if self.check(TokenKind::Bang) {
self.advance();
true
} else {
false
};
// Check for ?var source (variable reference) vs bare literal
let source_kind = if self.check(TokenKind::Question) {
self.advance();
// Must be followed by an identifier (the variable name)
if !matches!(self.peek().kind, TokenKind::Ident(_)) {
return Err(self.error("expected variable name after '?'"));
}
SourceKind::Var
} else {
SourceKind::Literal
};
let source = self.expect_ident()?;
self.expect(TokenKind::Dot)?;
let label = self.expect_ident_or_string()?;
// Now: = value, = ?var, -> ?var, -> node, < num, < ?var, > num, > ?var, <= num, <= ?var, >= num, >= ?var
let target = if self.check(TokenKind::Eq) {
self.advance();
if self.check(TokenKind::Question) {
self.advance();
let var = self.expect_ident()?;
ClauseTarget::ConstraintVar(ConstraintOp::Eq, var)
} else {
self.parse_literal_target()?
}
} else if self.check(TokenKind::Arrow) {
self.advance();
if self.check(TokenKind::Question) {
self.advance();
let var = self.expect_ident()?;
ClauseTarget::Bind(var)
} else {
let node = self.expect_ident()?;
ClauseTarget::NodeRef(node)
}
} else if self.check(TokenKind::Lt) {
self.advance();
self.parse_constraint_target(ConstraintOp::Lt)?
} else if self.check(TokenKind::Gt) {
self.advance();
self.parse_constraint_target(ConstraintOp::Gt)?
} else if self.check(TokenKind::Lte) {
self.advance();
self.parse_constraint_target(ConstraintOp::Lte)?
} else if self.check(TokenKind::Gte) {
self.advance();
self.parse_constraint_target(ConstraintOp::Gte)?
} else {
return Err(self.error("expected '=', '->', '<', '>', '<=', or '>='"));
};
Ok(ClauseAst {
source,
source_kind,
label,
target,
negated,
})
}
fn parse_literal_target(&mut self) -> Result<ClauseTarget, ParseError> {
// Handle optional leading minus for negative number literals
if self.check(TokenKind::Minus) {
self.advance();
if let TokenKind::Number(n) = &self.advance().kind {
return Ok(ClauseTarget::LiteralNum(-n));
}
return Err(self.error("expected number after '-'"));
}
match &self.peek().kind {
TokenKind::String(_) => {
if let TokenKind::String(s) = &self.advance().kind {
Ok(ClauseTarget::LiteralStr(s.clone()))
} else {
unreachable!()
}
}
TokenKind::Number(_) => {
if let TokenKind::Number(n) = &self.advance().kind {
Ok(ClauseTarget::LiteralNum(*n))
} else {
unreachable!()
}
}
TokenKind::True => {
self.advance();
Ok(ClauseTarget::LiteralBool(true))
}
TokenKind::False => {
self.advance();
Ok(ClauseTarget::LiteralBool(false))
}
_ => Err(self.error("expected a string, number, or boolean value")),
}
}
fn parse_constraint_target(&mut self, op: ConstraintOp) -> Result<ClauseTarget, ParseError> {
if self.check(TokenKind::Question) {
self.advance();
let var = self.expect_ident()?;
Ok(ClauseTarget::ConstraintVar(op, var))
} else {
let val = self.parse_constraint_value()?;
Ok(ClauseTarget::Constraint(op, val))
}
}
fn parse_constraint_value(&mut self) -> Result<ConstraintValue, ParseError> {
let negative = if self.check(TokenKind::Minus) {
self.advance();
true
} else {
false
};
match &self.peek().kind {
TokenKind::Number(_) => {
if let TokenKind::Number(n) = &self.advance().kind {
Ok(ConstraintValue::Num(if negative { -*n } else { *n }))
} else {
unreachable!()
}
}
TokenKind::String(_) if !negative => {
if let TokenKind::String(s) = &self.advance().kind {
Ok(ConstraintValue::Str(s.clone()))
} else {
unreachable!()
}
}
_ => Err(self.error("expected a number or string value")),
}
}
// ---- Graph parsing ----
/// Parse a `graph { ... }` declaration.
pub fn parse_graph(&mut self) -> Result<GraphAst, ParseError> {
self.expect(TokenKind::Graph)?;
self.expect(TokenKind::LBrace)?;
let mut edges = Vec::new();
let mut now = None;
while !self.check(TokenKind::RBrace) {
if self.check(TokenKind::Now) {
self.advance();
self.expect(TokenKind::Eq)?;
let n = self.expect_number()?;
now = Some(n as i64);
} else if self.check(TokenKind::At) {
edges.push(self.parse_graph_edge()?);
} else {
return Err(self.error("expected '@' (edge) or 'now' in graph block"));
}
}
self.expect(TokenKind::RBrace)?;
Ok(GraphAst { edges, now })
}
fn parse_graph_edge(&mut self) -> Result<EdgeAst, ParseError> {
self.expect(TokenKind::At)?;
let time_start = self.expect_number()? as i64;
// Check for bounded interval: @1..5
let time_end = if self.check(TokenKind::DotDot) {
self.advance();
Some(self.expect_number()? as i64)
} else {
None
};
let source = self.expect_ident()?;
self.expect(TokenKind::Dot)?;
let label = self.expect_ident_or_string()?;
let target = if self.check(TokenKind::Eq) {
self.advance();
self.parse_edge_target_literal()?
} else if self.check(TokenKind::Arrow) {
self.advance();
let node = self.expect_ident()?;
EdgeTarget::NodeRef(node)
} else {
return Err(self.error("expected '=' or '->' in graph edge"));
};
Ok(EdgeAst {
time_start,
time_end,
source,
label,
target,
})
}
fn parse_edge_target_literal(&mut self) -> Result<EdgeTarget, ParseError> {
if self.check(TokenKind::Minus) {
self.advance();
if let TokenKind::Number(n) = &self.advance().kind {
return Ok(EdgeTarget::Num(-n));
}
return Err(self.error("expected number after '-'"));
}
match &self.peek().kind {
TokenKind::String(_) => {
if let TokenKind::String(s) = &self.advance().kind {
Ok(EdgeTarget::Str(s.clone()))
} else {
unreachable!()
}
}
TokenKind::Number(_) => {
if let TokenKind::Number(n) = &self.advance().kind {
Ok(EdgeTarget::Num(*n))
} else {
unreachable!()
}
}
TokenKind::True => {
self.advance();
Ok(EdgeTarget::Bool(true))
}
TokenKind::False => {
self.advance();
Ok(EdgeTarget::Bool(false))
}
_ => Err(self.error("expected a string, number, or boolean value")),
}
}
// ---- Token cursor utilities ----
/// Peek at the current token without advancing.
pub fn peek(&self) -> &Token {
&self.tokens[self.pos]
}
/// Advance the cursor and return the consumed token.
pub fn advance(&mut self) -> &Token {
let tok = &self.tokens[self.pos];
if self.pos + 1 < self.tokens.len() {
self.pos += 1;
}
tok
}
/// Check if the cursor is at the end of the token stream.
pub fn at_eof(&self) -> bool {
matches!(self.tokens[self.pos].kind, TokenKind::Eof)
}
/// Check if the current token matches the given kind (by discriminant).
pub fn check(&self, kind: TokenKind) -> bool {
std::mem::discriminant(&self.tokens[self.pos].kind) == std::mem::discriminant(&kind)
}
/// Expect the current token to be of the given kind, advance, and return it.
pub fn expect(&mut self, expected: TokenKind) -> Result<&Token, ParseError> {
if self.check(expected.clone()) {
Ok(self.advance())
} else {
Err(self.error(&format!("expected {:?}", expected)))
}
}
/// Expect and consume an identifier token. Some keywords are allowed as
/// identifiers in certain positions (between, after, compose, sharing).
pub fn expect_ident(&mut self) -> Result<String, ParseError> {
match &self.peek().kind {
TokenKind::Ident(_) => {
if let TokenKind::Ident(s) = &self.advance().kind {
Ok(s.clone())
} else {
unreachable!()
}
}
// Allow keywords as identifiers in certain positions
TokenKind::Between => {
self.advance();
Ok("between".to_string())
}
TokenKind::After => {
self.advance();
Ok("after".to_string())
}
TokenKind::Compose => {
self.advance();
Ok("compose".to_string())
}
TokenKind::Sharing => {
self.advance();
Ok("sharing".to_string())
}
TokenKind::Concurrent => {
self.advance();
Ok("concurrent".to_string())
}
_ => Err(self.error("expected identifier")),
}
}
/// Expect and consume an identifier or string literal token.
pub fn expect_ident_or_string(&mut self) -> Result<String, ParseError> {
match &self.peek().kind {
TokenKind::Ident(_) => {
if let TokenKind::Ident(s) = &self.advance().kind {
Ok(s.clone())
} else {
unreachable!()
}
}
TokenKind::String(_) => {
if let TokenKind::String(s) = &self.advance().kind {
Ok(s.clone())
} else {
unreachable!()
}
}
_ => Err(self.error("expected identifier or string")),
}
}
/// Expect and consume a number literal token, with optional leading `-`.
pub fn expect_number(&mut self) -> Result<f64, ParseError> {
let negative = if self.check(TokenKind::Minus) {
self.advance();
true
} else {
false
};
match &self.peek().kind {
TokenKind::Number(_) => {
if let TokenKind::Number(n) = &self.advance().kind {
Ok(if negative { -*n } else { *n })
} else {
unreachable!()
}
}
_ => Err(self.error("expected number")),
}
}
/// Create a parse error at the current token position.
pub fn error(&self, msg: &str) -> ParseError {
let tok = &self.tokens[self.pos];
ParseError {
line: tok.line,
column: tok.column,
span: tok.span(),
message: msg.to_string(),
}
}
}