tokit 0.0.0

Blazing fast parser combinators: parse-while-lexing (zero-copy), deterministic LALR-style parsing, no backtracking. Flexible emitters for fail-fast runtime or greedy compiler diagnostics
Documentation
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
use super::{IntoComponents, SimpleSpan, Sliced, Spanned};

/// A value with complete location information: both which source and where in that source.
///
/// `Located<D, Sp, Sl>` combines a value of type `D` with:
/// - A slice identifier `Sl` indicating *which* source the data came from
/// - A span `Sp` indicating *where* within that source the data is located
///
/// This provides the most complete location tracking possible, combining the benefits
/// of both [`Sliced`] (source tracking) and [`Spanned`] (position tracking).
///
/// # Design
///
/// `Located` uses public fields for direct access, but also provides accessor methods
/// for consistency. It implements `Deref` and `DerefMut` to allow transparent access
/// to the inner data while keeping full location information available when needed.
///
/// # Common Patterns
///
/// ## Transparent Access via Deref
///
/// Thanks to `Deref`, you can call methods on the wrapped value directly:
///
/// ```rust
/// use tokit::utils::{Located, Span};
///
/// let located = Located::new("main.rs", Span::new(10, 15), "hello");
///
/// // Can call str methods directly
/// assert_eq!(located.len(), 5);
/// assert_eq!(located.to_uppercase(), "HELLO");
///
/// // But can still access location info
/// assert_eq!(located.slice(), "main.rs");
/// assert_eq!(located.span().start(), 10);
/// ```
///
/// ## Multi-File Error Reporting
///
/// ```rust,ignore
/// use tokit::utils::{Located, Span};
/// use std::path::PathBuf;
///
/// fn report_error<T>(loc: &Located<T, Span, PathBuf>, message: &str)
/// where
///     T: core::fmt::Debug
/// {
///     eprintln!(
///         "Error in {}:{}:{}: {}\n  {:?}",
///         loc.slice().display(),
///         get_line_number(loc.span().start()),
///         get_column_number(loc.span().start()),
///         message,
///         loc.data()
///     );
/// }
/// ```
///
/// ## Building Complete AST Nodes
///
/// ```rust,ignore
/// use tokit::utils::{Located, Span};
/// use std::path::PathBuf;
///
/// type Loc<T> = Located<T, Span, PathBuf>;
///
/// enum Expr {
///     Number(i64),
///     BinOp {
///         op: String,
///         left: Box<Loc<Expr>>,
///         right: Box<Loc<Expr>>,
///     },
/// }
///
/// // Each expression knows exactly where it came from
/// let expr = Loc::new(
///     PathBuf::from("src/calc.rs"),
///     Span::new(45, 52),
///     Expr::Number(42)
/// );
///
/// // Can report: "Error in src/calc.rs:3:12-19"
/// ```
///
/// ## Cross-File Reference Checking
///
/// ```rust,ignore
/// use tokit::utils::{Located, Span};
///
/// fn check_reference(
///     reference: &Located<String, Span, String>,
///     definition: &Located<String, Span, String>
/// ) -> Result<(), String> {
///     if reference.slice() != definition.slice() {
///         Err(format!(
///             "Cross-file reference: {} (in {}) references {} (in {})",
///             reference.data(),
///             reference.slice(),
///             definition.data(),
///             definition.slice()
///         ))
///     } else {
///         Ok(())
///     }
/// }
/// ```
///
/// ## Mapping Values While Preserving Full Location
///
/// ```rust
/// use tokit::utils::{Located, Span};
///
/// let located_str = Located::new("input.txt", Span::new(5, 7), "42");
///
/// // Parse the string, keeping both source and position
/// let parsed: Located<i32, Span, &str> = located_str.map_data(|s| s.parse().unwrap());
///
/// assert_eq!(*parsed, 42);
/// assert_eq!(parsed.slice(), "input.txt");
/// assert_eq!(parsed.span().start(), 5);
/// ```
///
/// ## IDE Integration
///
/// ```rust,ignore
/// use tokit::utils::{Located, Span};
/// use std::path::PathBuf;
///
/// struct Diagnostic {
///     severity: Severity,
///     message: String,
///     location: Located<(), Span, PathBuf>,
/// }
///
/// // Generate diagnostics with complete location info
/// fn undefined_variable(name: &Located<String, Span, PathBuf>) -> Diagnostic {
///     Diagnostic {
///         severity: Severity::Error,
///         message: format!("Undefined variable '{}'", name.data()),
///         location: name.as_ref().map_data(|_| ()),
///     }
/// }
///
/// // IDE can jump to exact location:
/// // - Open file: diagnostic.location.slice()
/// // - Navigate to: diagnostic.location.span()
/// ```
///
/// ## Incremental Compilation with Position Tracking
///
/// ```rust,ignore
/// use tokit::utils::{Located, Span};
/// use std::collections::HashMap;
///
/// struct Definition {
///     name: String,
///     location: Located<(), Span, String>,
/// }
///
/// // Track where each definition is located
/// let mut definitions: HashMap<String, Definition> = HashMap::new();
///
/// // When a file changes, only recheck definitions in that file
/// fn recheck_file(file: &str, definitions: &mut HashMap<String, Definition>) {
///     definitions.retain(|_, def| def.location.slice() != file);
///     // Re-parse and add new definitions from the changed file
/// }
/// ```
///
/// # Trait Implementations
///
/// - **`Deref` / `DerefMut`**: Access the inner data transparently
/// - **`Display`**: Delegates to the inner data's `Display` implementation
/// - **`IntoComponents`**: Destructure into `(Sl, Sp, D)` tuple
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use tokit::utils::{Located, Span};
///
/// let located = Located::new("file.rs", Span::new(0, 5), "hello");
///
/// assert_eq!(located.slice(), "file.rs");
/// assert_eq!(located.span(), Span::new(0, 5));
/// assert_eq!(located.data(), &"hello");
/// assert_eq!(*located, "hello"); // Via Deref
/// ```
///
/// ## Destructuring
///
/// ```rust
/// use tokit::utils::{Located, Span};
///
/// let located = Located::new("main.rs", Span::new(10, 20), 42);
///
/// let (slice, span, value) = located.into_components();
/// assert_eq!(slice, "main.rs");
/// assert_eq!(span, Span::new(10, 20));
/// assert_eq!(value, 42);
/// ```
///
/// ## Mutable Access
///
/// ```rust
/// use tokit::utils::{Located, Span};
///
/// let mut located = Located::new("input", Span::new(0, 2), 10);
///
/// // Modify the data
/// *located += 5;
/// assert_eq!(*located, 15);
///
/// // Modify the slice
/// *located.slice_mut() = "output";
/// assert_eq!(located.slice(), "output");
///
/// // Modify the span
/// located.span_mut().set_end(5);
/// assert_eq!(located.span().end(), 5);
/// ```
///
/// ## Conversion from Spanned or Sliced
///
/// ```rust
/// use tokit::utils::{Located, Span, Spanned, Sliced};
///
/// // From Spanned by adding slice info
/// let spanned = Spanned::new(Span::new(5, 10), "data");
/// let located = Located::new("file.rs", spanned.span(), spanned.into_data());
///
/// // From Sliced by adding span info
/// let sliced = Sliced::new("config.toml", "value");
/// let located = Located::new(sliced.into_slice(), Span::new(0, 5), "value");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct Located<D, Sp = SimpleSpan, Sl = ()> {
  /// The slice identifier indicating which source this data came from.
  pub(crate) slice: Sl,
  /// The span indicating where in the source this data is located.
  pub(crate) span: Sp,
  /// The wrapped data value.
  pub(crate) data: D,
}

impl<D, Sp, Sl> core::ops::Deref for Located<D, Sp, Sl> {
  type Target = D;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn deref(&self) -> &Self::Target {
    &self.data
  }
}

impl<D, Sp, Sl> core::ops::DerefMut for Located<D, Sp, Sl> {
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.data
  }
}

impl<D, Sp, Sl> core::fmt::Display for Located<D, Sp, Sl>
where
  D: core::fmt::Display,
{
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    self.data.fmt(f)
  }
}

impl<D, Sp, Sl> core::error::Error for Located<D, Sp, Sl>
where
  D: core::error::Error,
  Sp: core::fmt::Debug,
  Sl: core::fmt::Debug,
{
}

impl<D, Sp, Sl> IntoComponents for Located<D, Sp, Sl> {
  type Components = (Sl, Sp, D);

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn into_components(self) -> Self::Components {
    (self.slice, self.span, self.data)
  }
}

impl<D, Sp, Sl> Located<D, Sp, Sl> {
  /// Create a new located value.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new("file.rs", Span::new(10, 15), "hello");
  /// assert_eq!(located.slice(), "file.rs");
  /// assert_eq!(located.span(), Span::new(10, 15));
  /// assert_eq!(located.data(), &"hello");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(slice: Sl, span: Sp, data: D) -> Self {
    Self { slice, span, data }
  }

  /// Get a copy of the slice.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new("main.rs", Span::new(0, 5), "data");
  /// assert_eq!(located.slice(), "main.rs");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn slice(&self) -> Sl
  where
    Sl: Copy,
  {
    self.slice
  }

  /// Get a reference to the slice.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new("config.toml", Span::new(5, 10), "data");
  /// assert_eq!(located.slice_ref(), &"config.toml");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn slice_ref(&self) -> &Sl {
    &self.slice
  }

  /// Get a mutable reference to the slice.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let mut located = Located::new("old.txt", Span::new(0, 3), "data");
  /// *located.slice_mut() = "new.txt";
  /// assert_eq!(located.slice(), "new.txt");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn slice_mut(&mut self) -> &mut Sl {
    &mut self.slice
  }

  /// Get a copy of the span.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new("file.rs", Span::new(5, 10), "data");
  /// assert_eq!(located.span(), Span::new(5, 10));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> Sp
  where
    Sp: Copy,
  {
    self.span
  }

  /// Get a reference to the span.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new("file.rs", Span::new(5, 10), "data");
  /// assert_eq!(located.span_ref(), &Span::new(5, 10));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> &Sp {
    &self.span
  }

  /// Get a mutable reference to the span.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let mut located = Located::new("file.rs", Span::new(0, 5), "data");
  /// located.span_mut().set_end(10);
  /// assert_eq!(located.span().end(), 10);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> &mut Sp {
    &mut self.span
  }

  /// Get a reference to the data.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new("file.txt", Span::new(0, 2), 42);
  /// assert_eq!(*located.data(), 42);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn data(&self) -> &D {
    &self.data
  }

  /// Get a mutable reference to the data.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let mut located = Located::new("file.txt", Span::new(0, 2), 42);
  /// *located.data_mut() = 100;
  /// assert_eq!(*located.data(), 100);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn data_mut(&mut self) -> &mut D {
    &mut self.data
  }

  /// Returns a reference to the slice, span, and data.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let located = Located::new(
  ///     String::from("file.txt"),
  ///     Span::new(0, 5),
  ///     String::from("hello")
  /// );
  /// let borrowed: Located<&String, &Span, &String> = located.as_ref();
  /// assert_eq!(borrowed.data(), &"hello");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn as_ref(&self) -> Located<&D, &Sp, &Sl> {
    Located {
      slice: &self.slice,
      span: &self.span,
      data: &self.data,
    }
  }

  /// Returns a mutable reference to the slice, span, and data.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::utils::{Located, Span};
  ///
  /// let mut located = Located::new(
  ///     String::from("file.txt"),
  ///     Span::new(0, 5),
  ///     String::from("hello")
  /// );
  /// let mut borrowed: Located<&mut String, &mut Span, &mut String> = located.as_mut();
  /// borrowed.data_mut().push_str(" world");
  /// assert_eq!(located.data(), &"hello world");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn as_mut(&mut self) -> Located<&mut D, &mut Sp, &mut Sl> {
    Located {
      slice: &mut self.slice,
      span: &mut self.span,
      data: &mut self.data,
    }
  }

  /// Consume the located value and return the slice.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_slice(self) -> Sl {
    self.slice
  }

  /// Consume the located value and return the span.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_span(self) -> Sp {
    self.span
  }

  /// Consume the located value and return the data.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_data(self) -> D {
    self.data
  }

  /// Decompose the located value into its slice, span, and data.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_components(self) -> (Sl, Sp, D) {
    (self.slice, self.span, self.data)
  }

  /// Convert into a `Spanned` value, discarding the slice information.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_spanned(self) -> Spanned<D, Sp> {
    Spanned::new(self.span, self.data)
  }

  /// Convert into a `Sliced` value, discarding the span information.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_sliced(self) -> Sliced<D, Sl> {
    Sliced::new(self.slice, self.data)
  }

  /// Map the data to a new value, preserving the slice and span.
  #[inline]
  pub fn map_data<F, U>(self, f: F) -> Located<U, Sp, Sl>
  where
    F: FnOnce(D) -> U,
  {
    Located {
      slice: self.slice,
      span: self.span,
      data: f(self.data),
    }
  }
}