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
//! Lexer testing helpers.
//!
//! This type provides testing-oriented matchers for matching on a
//! [`TokenStream`][`crate::token::Stream`].
//!
//! These matchers are intended for writing *tests*. To write a parser, you\
//! should use [`Cursor`][crate::token::Cursor] instead.

use byteyarn::Yarn;
use std::env;
use std::fmt;
use std::fs;
use std::ops::Range;
use std::path::Path;

use crate::file::Context;
use crate::file::Span;
use crate::file::Spanned;
use crate::report::Report;
use crate::rule;
use crate::spec::Lexeme;
use crate::token;
use crate::token::Content;
use crate::token::Sign;

mod recognize;
use recognize::Kind;

/// Checks that `report` contains the expected diagnostics in `path`, verbatim.
///
/// If the contents do not match, it will print a diff to stderr and panic.
///
/// If the `ILEX_REGENERATE` env var is set, instead of reading the file and
/// performing the check, it will write the expected contents to the file,
/// allowing for easy generation of test data.
#[track_caller]
pub fn check_report(report: &Report, path: &(impl AsRef<Path> + ?Sized)) {
  let path = path.as_ref();
  let got = report.write_out_for_test();
  let want = if env::var("ILEX_REGENERATE").is_ok() {
    if let Some(parent) = path.parent() {
      fs::create_dir_all(parent).unwrap();
    }
    fs::write(path, got).unwrap();
    return;
  } else {
    fs::read_to_string(path).unwrap()
  };

  eprintln!("checking against {}...", path.display());
  similar_asserts::assert_eq!(got, want);
}

/// Checks that `report` contains no diagnostics.
///
/// If it does, it will print them to stderr and panic.
#[track_caller]
pub fn check_report_ok(report: &Report) {
  if let Err(e) = report.fatal_or(()) {
    e.panic();
  }
}

/// A matcher for a token stream.
///
/// For usage examples, see the `ilex/tests` directory.
pub struct Matcher {
  stream: Vec<recognize::Matcher>,
}

impl Matcher {
  /// Creates a new matcher.
  pub fn new() -> Self {
    Self { stream: Vec::new() }
  }

  /// Adds a new expected token for this matcher, from a lexeme and an argument.
  ///
  /// What is allowed for `arg` for a particular rule type is specified by
  /// the [`Match`] trait. You can even define your own!
  pub fn then1<R: Match<(A1,)>, A1>(
    mut self,
    lexeme: Lexeme<R>,
    a1: A1,
  ) -> Self {
    R::add_token(&mut self, lexeme, (a1,));
    self
  }

  /// Adds a new expected token for this matcher, from a lexeme and two
  /// arguments.
  ///
  /// What is allowed for `arg` for a particular rule type is specified by
  /// the [`Match`] trait. You can even define your own!
  pub fn then2<R: Match<(A1, A2)>, A1, A2>(
    mut self,
    lexeme: Lexeme<R>,
    a1: A1,
    a2: A2,
  ) -> Self {
    R::add_token(&mut self, lexeme, (a1, a2));
    self
  }

  /// Like [`Matcher::then1()`], but adds a prefix matcher too.
  pub fn prefix1<R: Match<(A1,)>, A1>(
    self,
    lexeme: Lexeme<R>,
    prefix: impl Into<Text>,
    a1: A1,
  ) -> Self {
    self.then1(lexeme, a1).prefix(prefix)
  }

  /// Like [`Matcher::then2()`], but adds a prefix matcher too.
  pub fn prefix2<R: Match<(A1, A2)>, A1, A2>(
    self,
    lexeme: Lexeme<R>,
    prefix: impl Into<Text>,
    a1: A1,
    a2: A2,
  ) -> Self {
    self.then2(lexeme, a1, a2).prefix(prefix)
  }

  /// Like [`Matcher::then1()`], but adds a suffix matcher too.
  pub fn suffix1<R: Match<(A1,)>, A1>(
    self,
    lexeme: Lexeme<R>,
    a1: A1,
    suffix: impl Into<Text>,
  ) -> Self {
    self.then1(lexeme, a1).suffix(suffix)
  }

  /// Like [`Matcher::then2()`], but adds a suffix matcher too.
  pub fn suffix2<R: Match<(A1, A2)>, A1, A2>(
    self,
    lexeme: Lexeme<R>,
    a1: A1,
    a2: A2,
    suffix: impl Into<Text>,
  ) -> Self {
    self.then2(lexeme, a1, a2).suffix(suffix)
  }

  /// Like [`Matcher::then1()`], but adds a prefix matcher and a suffix matcher too.
  pub fn affix1<R: Match<(A1,)>, A1>(
    self,
    lexeme: Lexeme<R>,
    prefix: impl Into<Text>,
    a1: A1,
    suffix: impl Into<Text>,
  ) -> Self {
    self.then1(lexeme, a1).prefix(prefix).suffix(suffix)
  }

  /// Like [`Matcher::then2()`], but adds a prefix matcher and a suffix matcher too.
  pub fn affix2<R: Match<(A1, A2)>, A1, A2>(
    self,
    lexeme: Lexeme<R>,
    prefix: impl Into<Text>,
    a1: A1,
    a2: A2,
    suffix: impl Into<Text>,
  ) -> Self {
    self.then2(lexeme, a1, a2).prefix(prefix).suffix(suffix)
  }

  /// Adds an EOF matcher.
  ///
  /// Every token stream ends with an EOF token, so you always need to include
  /// one.
  pub fn eof(mut self) -> Self {
    self.stream.push(recognize::Matcher {
      which: Some(Lexeme::eof().any()),
      span: Text::any(),
      comments: Vec::new(),
      kind: Kind::Eof,
    });
    self
  }

  /// Matches `cursor` against this matcher, and panics if it doesn't.
  #[track_caller]
  pub fn assert_matches<'lex>(
    &self,
    ctx: &Context,
    that: impl IntoIterator<Item = token::Any<'lex>>,
  ) {
    self.matches(ctx, that).unwrap()
  }

  /// Sets an expectation for the overall span of the most recently added
  /// token matcher.
  ///
  /// # Panics
  ///
  /// Panics if none of the matcher-adding methods has been called yet.
  pub fn span(mut self, text: impl Into<Text>) -> Self {
    self.stream.last_mut().unwrap().span = text.into();
    self
  }

  /// Adds some expected comments to the most recently added token matcher.
  ///
  /// # Panics
  ///
  /// Panics if none of the matcher-adding methods has been called yet.
  pub fn comments<I>(mut self, iter: I) -> Self
  where
    I: IntoIterator,
    I::Item: Into<Text>,
  {
    self
      .stream
      .last_mut()
      .unwrap()
      .comments
      .extend(iter.into_iter().map(Into::into));
    self
  }

  /// Matches `cursor` against this matcher.
  ///
  /// If matching fails, returns an error describing why.
  pub fn matches<'lex>(
    &self,
    ctx: &Context,
    that: impl IntoIterator<Item = token::Any<'lex>>,
  ) -> Result<(), impl fmt::Debug> {
    struct DebugBy(String);
    impl fmt::Debug for DebugBy {
      fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
      }
    }

    let mut state = recognize::MatchState::new(ctx);
    recognize::zip_eq(
      "token streams",
      &mut state,
      &self.stream,
      that,
      |state, ours, theirs| ours.recognizes(state, theirs, ctx),
    );
    state.finish().map_err(DebugBy)
  }

  /// Sets the prefix for the most recently added token matcher.
  ///
  /// # Panics
  ///
  /// Panics if [`Matcher::then()`] has not been called yet, or if the most
  /// recent matcher is not for [`rule::Ident`], [`rule::Digital`], or
  /// [`rule::Quoted`],
  fn prefix(mut self, text: impl Into<Text>) -> Self {
    match &mut self.stream.last_mut().unwrap().kind {
      Kind::Ident { prefix, .. } | Kind::Quoted { prefix, .. } => {
        *prefix = Some(text.into());
      }
      Kind::Digital { digits, .. } => digits[0].prefix = Some(text.into()),
      _ => panic!("cannot set prefix on this matcher"),
    }

    self
  }

  /// Sets the prefix for the most recently added token matcher.
  ///
  /// # Panics
  ///
  /// Panics if [`Matcher::then()`] has not been called yet, or if the most
  /// recent matcher is not for [`rule::Ident`], [`rule::Digital`], or
  /// [`rule::Quoted`],
  fn suffix(mut self, text: impl Into<Text>) -> Self {
    match &mut self.stream.last_mut().unwrap().kind {
      Kind::Ident { suffix, .. }
      | Kind::Quoted { suffix, .. }
      | Kind::Digital { suffix, .. } => {
        *suffix = Some(text.into());
      }
      _ => panic!("cannot set suffix on this matcher"),
    }

    self
  }
}

impl Default for Matcher {
  fn default() -> Self {
    Self::new()
  }
}

/// A matcher for a chunk of text from the input source.
///
/// This is slightly more general than a span, since it can specify the content
/// of the text and the offsets separately, and optionally. `Text` values are
/// intended to *recognize* various spans.
///
/// `&str` and `Range<usize>` are both convertible to `Text`.
#[derive(Clone)]
pub struct Text {
  text: Option<Yarn>,
  range: Option<Range<usize>>,
}

impl Text {
  /// Returns a matcher that recognizes all spans.
  pub fn any() -> Self {
    Text { text: None, range: None }
  }

  /// Returns a matcher that recognizes spans with the given text.
  pub fn new(text: impl Into<Yarn>) -> Self {
    Text { text: Some(text.into()), range: None }
  }

  /// Returns a matcher that recognizes spans with the given byte range.
  pub fn range(range: Range<usize>) -> Self {
    Text { text: None, range: Some(range) }
  }

  /// Returns a matcher that recognizes spans with the given byte range and
  /// text.
  pub fn text_and_range(text: impl Into<Yarn>, range: Range<usize>) -> Self {
    Text {
      text: Some(text.into()),
      range: Some(range),
    }
  }

  /// Returns whether this span recognizes a particular span.
  fn recognizes(&self, span: Span, ctx: &Context) -> bool {
    !self
      .text
      .as_ref()
      .is_some_and(|text| text != span.text(ctx))
      && !self.range.as_ref().is_some_and(|range| {
        let r = span.span(ctx);
        range != &(r.start()..r.end())
      })
  }
}

impl<Y: Into<Yarn>> From<Y> for Text {
  fn from(value: Y) -> Self {
    Text::new(value)
  }
}

impl fmt::Debug for Text {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match (&self.text, &self.range) {
      (Some(text), Some(range)) => write!(f, "{text:?} @ {range:?}"),
      (Some(text), None) => fmt::Debug::fmt(text, f),
      (None, Some(range)) => write!(f, "<any> @ {range:?}"),
      (None, None) => f.write_str("<any>"),
    }
  }
}

/// Records a way in which a matcher can be added for a particular token rule.
///
/// See [`Matcher::then1()`].
pub trait Match<Arg>: rule::Rule {
  /// Adds a new token to `matcher`.
  fn add_token(matcher: &mut Matcher, lexeme: Lexeme<Self>, arg: Arg);
}

impl<T: Into<Text>> Match<(T,)> for rule::Keyword {
  fn add_token(matcher: &mut Matcher, lexeme: Lexeme<Self>, (arg,): (T,)) {
    matcher.stream.push(recognize::Matcher {
      which: Some(lexeme.any()),
      span: arg.into(),
      comments: Vec::new(),
      kind: Kind::Keyword,
    })
  }
}

impl<Open, Close> Match<((Open, Close), Matcher)> for rule::Bracket
where
  Open: Into<Text>,
  Close: Into<Text>,
{
  fn add_token(
    matcher: &mut Matcher,
    lexeme: Lexeme<Self>,
    ((open, close), contents): ((Open, Close), Matcher),
  ) {
    matcher.stream.push(recognize::Matcher {
      which: Some(lexeme.any()),
      span: Text::any(),
      comments: Vec::new(),
      kind: Kind::Delimited {
        tokens: contents.stream,
        delims: (open.into(), close.into()),
      },
    })
  }
}

impl<T: Into<Text>> Match<(T,)> for rule::Ident {
  fn add_token(matcher: &mut Matcher, lexeme: Lexeme<Self>, (arg,): (T,)) {
    let arg = arg.into();
    matcher.stream.push(recognize::Matcher {
      which: Some(lexeme.any()),
      span: Text::any(),
      comments: Vec::new(),
      kind: Kind::Ident { name: arg, prefix: None, suffix: None },
    })
  }
}

/// A complex digital token matcher.
///
/// This type is used the matcher argument type for complex digital rules, such
/// as those that have signs and exponents.
#[derive(Default)]
pub struct DigitalMatcher {
  chunks: Vec<recognize::DigitalMatcher>,
}

impl DigitalMatcher {
  /// Creates a new matcher, with the given radix and digit blocks for the
  /// mantissa.
  pub fn new<D: Into<Text>>(
    radix: u8,
    digits: impl IntoIterator<Item = D>,
  ) -> Self {
    Self {
      chunks: vec![recognize::DigitalMatcher {
        radix,
        sign: None,
        digits: digits.into_iter().map(Into::into).collect(),
        prefix: None,
      }],
    }
  }

  /// Sets the sign for the most recently added chunk of digits.
  pub fn sign(self, sign: Sign) -> Self {
    self.sign_span(sign, Text::any())
  }

  /// Sets the sign (and sign span) for the most recently added chunk of digits.
  pub fn sign_span(mut self, sign: Sign, span: impl Into<Text>) -> Self {
    self
      .chunks
      .last_mut()
      .unwrap()
      .sign
      .get_or_insert_with(|| (sign, span.into()));
    self
  }

  /// Adds an expected exponent.
  ///
  /// The exponent must be in the given radix, delimited by the given prefix,
  /// and have the given digits.
  pub fn exp<D: Into<Text>>(
    mut self,
    radix: u8,
    prefix: impl Into<Text>,
    digits: impl IntoIterator<Item = D>,
  ) -> Self {
    self.chunks.push(recognize::DigitalMatcher {
      radix,
      sign: None,
      digits: digits.into_iter().map(Into::into).collect(),
      prefix: Some(prefix.into()),
    });
    self
  }
}

impl<Digits> Match<(u8, Digits)> for rule::Digital
where
  Digits: IntoIterator,
  Digits::Item: Into<Text>,
{
  fn add_token(
    matcher: &mut Matcher,
    lexeme: Lexeme<Self>,
    (radix, digits): (u8, Digits),
  ) {
    Self::add_token(matcher, lexeme, (DigitalMatcher::new(radix, digits),));
  }
}

impl Match<(DigitalMatcher,)> for rule::Digital {
  fn add_token(
    matcher: &mut Matcher,
    lexeme: Lexeme<Self>,
    digits: (DigitalMatcher,),
  ) {
    matcher.stream.push(recognize::Matcher {
      which: Some(lexeme.any()),
      span: Text::any(),
      comments: Vec::new(),
      kind: Kind::Digital { digits: digits.0.chunks, suffix: None },
    })
  }
}

impl From<&'static str> for Content<Text> {
  fn from(value: &'static str) -> Self {
    Content::lit(value)
  }
}

impl<Open, Close, Iter> Match<((Open, Close), Iter)> for rule::Quoted
where
  Open: Into<Text>,
  Close: Into<Text>,
  Iter: IntoIterator,
  Iter::Item: Into<Content<Text>>,
{
  fn add_token(
    matcher: &mut Matcher,
    lexeme: Lexeme<Self>,
    ((open, close), content): ((Open, Close), Iter),
  ) {
    matcher.stream.push(recognize::Matcher {
      which: Some(lexeme.any()),
      span: Text::any(),
      comments: Vec::new(),
      kind: Kind::Quoted {
        content: content.into_iter().map(Into::into).collect(),
        delims: (open.into(), close.into()),
        prefix: None,
        suffix: None,
      },
    })
  }
}