bcgen-lang 0.4.1

Compiles HIR to LSB bytecode: the path from a forged language's meaning to code bvm-lang runs.
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
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
//! Compilation options and source locations.

use alloc::string::String;
use alloc::vec::Vec;

use bytecode_lang::Hook;
use hir_lang::Span;

use crate::intrinsics::Intrinsics;

/// How arrays and maps behave when a value is copied.
///
/// # Examples
///
/// ```
/// use bcgen_lang::ArraySemantics;
///
/// assert_eq!(ArraySemantics::default(), ArraySemantics::Php);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ArraySemantics {
    /// PHP arrays: values. Assigning, passing, returning, capturing, or
    /// storing an array copies it (an O(1) copy-on-write `dup`), a nested
    /// write (`$a['x']['y'] = 1`) separates each intermediate array from any
    /// copy that shares it, and writing through `null` creates the array
    /// (auto-vivification).
    #[default]
    Php,
    /// Shared references, as in Python, JavaScript, and Ruby: a copy is the
    /// same object, nested writes go through, and writing into `null` is an
    /// error.
    Reference,
}

/// How map keys are normalized before a map is indexed.
///
/// # Examples
///
/// ```
/// use bcgen_lang::KeyCoercion;
///
/// assert_eq!(KeyCoercion::default(), KeyCoercion::Php);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KeyCoercion {
    /// PHP's array-key rules: a string holding a canonical decimal `i64`
    /// (`"7"`, `"-3"`, not `"07"`, `"-0"`, or `"+1"`) becomes that integer, a
    /// float is truncated toward zero (saturating at the `i64` range; NaN
    /// gives `0`), `true`/`false` become `1`/`0`, and `null` becomes `""`.
    /// Other keys are left as they are.
    #[default]
    Php,
    /// No normalization: keys compare by LSB's rules (`1` and `1.0` differ).
    None,
}

/// What the module body (`Module.body`) compiles to.
///
/// # Examples
///
/// ```
/// use bcgen_lang::BodyMode;
///
/// assert_eq!(BodyMode::default(), BodyMode::Start);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BodyMode {
    /// The body is part of the module's start function, which the VM runs
    /// once before the first call into the module; its value is kept in a
    /// global that the entry function returns. Scripts and modules.
    #[default]
    Start,
    /// The body is the entry function itself and returns its value on every
    /// call; the start function only initializes globals. REPL entries and
    /// tests that run the body more than once.
    Entry,
}

/// Compilation options: the dynamic profile's array and key semantics, the
/// body's role, host linkage, the intrinsic table, and budgets.
///
/// The default is the PHP profile Mox needs: value arrays and PHP keys.
///
/// # Examples
///
/// ```
/// use bcgen_lang::{ArraySemantics, Options};
///
/// let opts = Options::new()
///     .with_arrays(ArraySemantics::Reference)
///     .with_file("app.mox")
///     .with_max_instructions(1_000_000);
/// assert_eq!(opts.arrays(), ArraySemantics::Reference);
/// assert_eq!(opts.file(), "app.mox");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
    arrays: ArraySemantics,
    keys: KeyCoercion,
    body: BodyMode,
    file: String,
    host_module: String,
    hooks: Vec<(Hook, String, String)>,
    intrinsics: Intrinsics,
    max_instructions: u64,
    ignore_extra: bool,
    string_offsets: Option<String>,
    constructor: Option<String>,
    destructor: Option<String>,
    clone_method: Option<String>,
    reference_counting: bool,
}

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

impl Options {
    /// The default budget: 64 Mi instructions per module.
    pub const DEFAULT_MAX_INSTRUCTIONS: u64 = 64 << 20;

    /// The PHP profile: [`ArraySemantics::Php`], [`KeyCoercion::Php`],
    /// [`BodyMode::Start`], file name `<hir>`, host module `host`, no hooks,
    /// the built-in intrinsics ([`Intrinsics::core`]), extra arguments
    /// refused, string offsets read as bytes, and PHP's magic method names
    /// (`__construct`, `__destruct`, `__clone`).
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::{BodyMode, Options};
    ///
    /// assert_eq!(Options::new().body(), BodyMode::Start);
    /// assert_eq!(Options::new().host_module(), "host");
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            arrays: ArraySemantics::Php,
            keys: KeyCoercion::Php,
            body: BodyMode::Start,
            file: String::from("<hir>"),
            host_module: String::from("host"),
            hooks: Vec::new(),
            intrinsics: Intrinsics::core(),
            max_instructions: Self::DEFAULT_MAX_INSTRUCTIONS,
            ignore_extra: false,
            string_offsets: None,
            constructor: Some(String::from("__construct")),
            destructor: Some(String::from("__destruct")),
            clone_method: Some(String::from("__clone")),
            reference_counting: false,
        }
    }

    /// Sets the array semantics.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::{ArraySemantics, Options};
    ///
    /// let o = Options::new().with_arrays(ArraySemantics::Reference);
    /// assert_eq!(o.arrays(), ArraySemantics::Reference);
    /// ```
    #[must_use]
    pub fn with_arrays(mut self, arrays: ArraySemantics) -> Self {
        self.arrays = arrays;
        self
    }

    /// Sets the key coercion.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::{KeyCoercion, Options};
    ///
    /// assert_eq!(Options::new().with_keys(KeyCoercion::None).keys(), KeyCoercion::None);
    /// ```
    #[must_use]
    pub fn with_keys(mut self, keys: KeyCoercion) -> Self {
        self.keys = keys;
        self
    }

    /// Sets what the module body compiles to.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::{BodyMode, Options};
    ///
    /// assert_eq!(Options::new().with_body(BodyMode::Entry).body(), BodyMode::Entry);
    /// ```
    #[must_use]
    pub fn with_body(mut self, body: BodyMode) -> Self {
        self.body = body;
        self
    }

    /// Sets the file name written into line-table rows when no
    /// [`Locate`] is given.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().with_file("main.mox").file(), "main.mox");
    /// ```
    #[must_use]
    pub fn with_file(mut self, file: &str) -> Self {
        self.file = String::from(file);
        self
    }

    /// Sets the import module for host symbols that have no `.` in their
    /// name (`echo` imports as `host`.`echo` by default; `mox.concat` imports
    /// as `mox`.`concat` whatever this is).
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().with_host_module("env").host_module(), "env");
    /// ```
    #[must_use]
    pub fn with_host_module(mut self, module: &str) -> Self {
        self.host_module = String::from(module);
        self
    }

    /// Binds an LSB hook (§5.8) to the host function `module`.`name`, with
    /// the hook's signature (every operand `dyn`). A later binding of the same
    /// hook replaces an earlier one.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    /// use bytecode_lang::Hook;
    ///
    /// let o = Options::new().with_hook(Hook::Eq, "mox", "loose_eq");
    /// assert_eq!(o.hooks().len(), 1);
    /// ```
    #[must_use]
    pub fn with_hook(mut self, hook: Hook, module: &str, name: &str) -> Self {
        self.hooks.retain(|(h, _, _)| *h != hook);
        self.hooks
            .push((hook, String::from(module), String::from(name)));
        self
    }

    /// Sets the intrinsic table: how each named intrinsic compiles (an LSB
    /// sequence, a host function, or a guarded fast path over one). Names
    /// not in it do not compile
    /// ([`CompileError::UnknownIntrinsic`](crate::CompileError::UnknownIntrinsic)).
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::{Intrinsics, Options};
    ///
    /// let o = Options::new().with_intrinsics(Intrinsics::mox());
    /// assert!(o.intrinsics().get("mox.loose_eq").is_some());
    /// ```
    #[must_use]
    pub fn with_intrinsics(mut self, intrinsics: Intrinsics) -> Self {
        self.intrinsics = intrinsics;
        self
    }

    /// Sets the instruction budget for the whole module; compilation stops
    /// with [`CompileError::BudgetExceeded`](crate::CompileError) beyond it.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().with_max_instructions(10).max_instructions(), 10);
    /// ```
    #[must_use]
    pub fn with_max_instructions(mut self, limit: u64) -> Self {
        self.max_instructions = limit;
        self
    }

    /// Whether user functions, closures, and methods ignore extra positional
    /// arguments (PHP: `f(1, 2, 3)` of `function f($a)` drops the extras
    /// after evaluating them) instead of raising `ArgumentError` (E0114,
    /// Python's rule and the default). Sets LSB's `ignore_extra` on every
    /// parameter list the module carries, and direct calls evaluate and
    /// discard the extras. Named arguments that match no parameter are an
    /// error either way.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert!(Options::new().with_ignore_extra(true).ignore_extra());
    /// assert!(!Options::new().ignore_extra());
    /// ```
    #[must_use]
    pub fn with_ignore_extra(mut self, ignore: bool) -> Self {
        self.ignore_extra = ignore;
        self
    }

    /// Routes **string-offset reads** (`$s[i]` where `$s` holds a string)
    /// through the intrinsic `name` of the [intrinsic table](Self::intrinsics),
    /// called with the string and the (coerced) key; every other indexed read
    /// stays LSB's `dget_index`. Without it, a string offset reads LSB's
    /// answer: the byte as an `int` (LSB §5.7). PHP gives a one-character
    /// string, which [`Fast::StrOffset`](crate::Fast::StrOffset) computes
    /// inline (`Intrinsics::mox()` maps `mox.str_offset` to it). The entry
    /// must exist and take two operands, or compilation fails with
    /// [`CompileError::InvalidOption`](crate::CompileError::InvalidOption).
    /// String writes (`$s[0] = "x"`) are unchanged: LSB strings are
    /// immutable, so they go to the `set_index` hook.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::{Intrinsics, Options};
    ///
    /// let o = Options::new()
    ///     .with_intrinsics(Intrinsics::mox())
    ///     .with_string_offsets("mox.str_offset");
    /// assert_eq!(o.string_offsets(), Some("mox.str_offset"));
    /// ```
    #[must_use]
    pub fn with_string_offsets(mut self, name: &str) -> Self {
        self.string_offsets = Some(String::from(name));
        self
    }

    /// Names the constructor method `new` calls after initializing the
    /// instance's properties (`None`: classes have no constructor, and `new`
    /// evaluates and drops its arguments).
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().constructor(), Some("__construct"));
    /// assert_eq!(Options::new().with_constructor(Some("__init__")).constructor(), Some("__init__"));
    /// ```
    #[must_use]
    pub fn with_constructor(mut self, name: Option<&str>) -> Self {
        self.constructor = name.map(String::from);
        self
    }

    /// Names the destructor method. bcgen-lang does not call it: LSB format
    /// 2 has no destructor flag, so the host passes
    /// [`Compiled::destructor`](crate::Compiled::destructor) to bvm-lang's
    /// `Vm::set_destructor`. A class method of this name must take no
    /// parameters ([`ClassProblem::BadDestructor`](crate::ClassProblem::BadDestructor)).
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().destructor(), Some("__destruct"));
    /// assert_eq!(Options::new().with_destructor(None).destructor(), None);
    /// ```
    #[must_use]
    pub fn with_destructor(mut self, name: Option<&str>) -> Self {
        self.destructor = name.map(String::from);
        self
    }

    /// Emits code for a VM that counts references (bvm-lang's
    /// `Memory::Rc`, the language's `[runtime] memory = "rc"`), so objects
    /// die where PHP frees them: every temporary register and call window
    /// that may hold a reference is cleared (`load_nil`) when it dies, and a
    /// variable keeps its register until the function returns (PHP
    /// variables are function-scoped). Without it, a dead temporary keeps
    /// its object alive until the register is reused, which delays
    /// destructors. The cost is one `load_nil` per dying reference
    /// register; nothing changes under a tracing collector.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert!(Options::new().with_reference_counting(true).reference_counting());
    /// assert!(!Options::new().reference_counting());
    /// ```
    #[must_use]
    pub fn with_reference_counting(mut self, rc: bool) -> Self {
        self.reference_counting = rc;
        self
    }

    /// Names the method a clone ([`ClassOp::Clone`](crate::ClassOp::Clone))
    /// calls on the new copy (PHP's `__clone`), when the class has one.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().clone_method(), Some("__clone"));
    /// ```
    #[must_use]
    pub fn with_clone_method(mut self, name: Option<&str>) -> Self {
        self.clone_method = name.map(String::from);
        self
    }

    /// The array semantics.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().arrays(), bcgen_lang::ArraySemantics::Php);
    /// ```
    #[must_use]
    pub fn arrays(&self) -> ArraySemantics {
        self.arrays
    }

    /// The key coercion.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().keys(), bcgen_lang::KeyCoercion::Php);
    /// ```
    #[must_use]
    pub fn keys(&self) -> KeyCoercion {
        self.keys
    }

    /// What the module body compiles to.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().body(), bcgen_lang::BodyMode::Start);
    /// ```
    #[must_use]
    pub fn body(&self) -> BodyMode {
        self.body
    }

    /// The default file name for line-table rows.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().file(), "<hir>");
    /// ```
    #[must_use]
    pub fn file(&self) -> &str {
        &self.file
    }

    /// The import module for host symbols without a `.`.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().host_module(), "host");
    /// ```
    #[must_use]
    pub fn host_module(&self) -> &str {
        &self.host_module
    }

    /// The hook bindings, as (hook, module, name).
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(bcgen_lang::Options::new().hooks().is_empty());
    /// ```
    #[must_use]
    pub fn hooks(&self) -> &[(Hook, String, String)] {
        &self.hooks
    }

    /// The intrinsic table.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().intrinsics(), &bcgen_lang::Intrinsics::core());
    /// ```
    #[must_use]
    pub fn intrinsics(&self) -> &Intrinsics {
        &self.intrinsics
    }

    /// The instruction budget.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::Options;
    ///
    /// assert_eq!(Options::new().max_instructions(), Options::DEFAULT_MAX_INSTRUCTIONS);
    /// ```
    #[must_use]
    pub fn max_instructions(&self) -> u64 {
        self.max_instructions
    }

    /// Whether extra positional arguments are ignored (see
    /// [`with_ignore_extra`](Self::with_ignore_extra)).
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(!bcgen_lang::Options::new().ignore_extra());
    /// ```
    #[must_use]
    pub fn ignore_extra(&self) -> bool {
        self.ignore_extra
    }

    /// The intrinsic string-offset reads go through, if any (see
    /// [`with_string_offsets`](Self::with_string_offsets)).
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::Options::new().string_offsets(), None);
    /// ```
    #[must_use]
    pub fn string_offsets(&self) -> Option<&str> {
        self.string_offsets.as_deref()
    }

    /// The constructor method name.
    ///
    /// # Examples
    ///
    /// See [`with_constructor`](Self::with_constructor).
    #[must_use]
    pub fn constructor(&self) -> Option<&str> {
        self.constructor.as_deref()
    }

    /// The destructor method name.
    ///
    /// # Examples
    ///
    /// See [`with_destructor`](Self::with_destructor).
    #[must_use]
    pub fn destructor(&self) -> Option<&str> {
        self.destructor.as_deref()
    }

    /// Whether code is emitted for a reference-counting VM (see
    /// [`with_reference_counting`](Self::with_reference_counting)).
    ///
    /// # Examples
    ///
    /// See [`with_reference_counting`](Self::with_reference_counting).
    #[must_use]
    pub fn reference_counting(&self) -> bool {
        self.reference_counting
    }

    /// The clone method name.
    ///
    /// # Examples
    ///
    /// See [`with_clone_method`](Self::with_clone_method).
    #[must_use]
    pub fn clone_method(&self) -> Option<&str> {
        self.clone_method.as_deref()
    }
}

/// A source position for a line-table row: file, line, and column, numbered
/// as the [`Locate`] implementation numbers them.
///
/// # Examples
///
/// ```
/// use bcgen_lang::Location;
///
/// let at = Location { file: "a.mox", line: 3, column: 7 };
/// assert_eq!(at.line, 3);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Location<'a> {
    /// The file name.
    pub file: &'a str,
    /// The line.
    pub line: u32,
    /// The column.
    pub column: u32,
}

/// Maps HIR spans to source positions for LSB line tables.
///
/// HIR spans are byte ranges in a session-wide byte space; only the host
/// (typically a source-lang `SourceMap`) knows the files behind them. Without
/// a locator, rows carry the [`Options::file`] name, line `0` ("unknown"),
/// and the span's start byte offset as the column. The exact HIR node of
/// every instruction is always available from [`Compiled::origin`].
///
/// [`Compiled::origin`]: crate::Compiled::origin
///
/// # Examples
///
/// ```
/// use bcgen_lang::{Locate, Location};
/// use hir_lang::Span;
///
/// struct OneLine;
/// impl Locate for OneLine {
///     fn locate(&self, span: Span) -> Location<'_> {
///         Location { file: "x", line: 1, column: span.start().to_u32() + 1 }
///     }
/// }
/// assert_eq!(OneLine.locate(Span::new(4, 5)).column, 5);
/// ```
pub trait Locate {
    /// The position of `span`'s start.
    fn locate(&self, span: Span) -> Location<'_>;
}

/// A [`Locate`] for one source file: 1-based lines and byte columns from the
/// file's text, for spans that start at `base` in the session byte space.
///
/// # Examples
///
/// ```
/// use bcgen_lang::{LineIndex, Locate};
/// use hir_lang::Span;
///
/// let lines = LineIndex::new("app.mox", 0, "a = 1;\nb = 2;\n");
/// let at = lines.locate(Span::new(7, 8));
/// assert_eq!((at.file, at.line, at.column), ("app.mox", 2, 1));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LineIndex {
    file: String,
    base: u32,
    starts: Vec<u32>,
}

impl LineIndex {
    /// Indexes `text`, whose first byte is at offset `base` of the session
    /// byte space.
    ///
    /// # Examples
    ///
    /// ```
    /// use bcgen_lang::LineIndex;
    ///
    /// assert_eq!(LineIndex::new("f", 100, "x\ny").lines(), 2);
    /// ```
    #[must_use]
    pub fn new(file: &str, base: u32, text: &str) -> Self {
        let mut starts = Vec::with_capacity(text.len() / 32 + 1);
        starts.push(0);
        for (i, b) in text.bytes().enumerate() {
            if b == b'\n' {
                starts.push(u32::try_from(i + 1).unwrap_or(u32::MAX));
            }
        }
        Self {
            file: String::from(file),
            base,
            starts,
        }
    }

    /// The number of lines.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(bcgen_lang::LineIndex::new("f", 0, "").lines(), 1);
    /// ```
    #[must_use]
    pub fn lines(&self) -> usize {
        self.starts.len()
    }
}

impl Locate for LineIndex {
    fn locate(&self, span: Span) -> Location<'_> {
        let offset = span.start().to_u32().saturating_sub(self.base);
        // The last line start at or before the offset; offsets past the end
        // land on the last line.
        let line = self.starts.partition_point(|&s| s <= offset).max(1);
        let start = self.starts.get(line - 1).copied().unwrap_or(0);
        Location {
            file: &self.file,
            line: u32::try_from(line).unwrap_or(u32::MAX),
            column: offset - start + 1,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{LineIndex, Locate, Options};
    use hir_lang::Span;

    #[test]
    fn line_index_counts_from_the_base() {
        let l = LineIndex::new("f", 10, "ab\ncd\n\nx");
        let at = |o: u32| {
            let p = l.locate(Span::new(o, o));
            (p.line, p.column)
        };
        assert_eq!(at(10), (1, 1));
        assert_eq!(at(12), (1, 3));
        assert_eq!(at(13), (2, 1));
        assert_eq!(at(16), (3, 1));
        assert_eq!(at(17), (4, 1));
        // Before the base clamps to the start; past the end stays on the last line.
        assert_eq!(at(0), (1, 1));
        assert_eq!(at(1_000), (4, 984));
    }

    #[test]
    fn a_later_hook_binding_replaces_an_earlier_one() {
        let o = Options::new()
            .with_hook(bytecode_lang::Hook::Eq, "a", "b")
            .with_hook(bytecode_lang::Hook::Eq, "c", "d");
        assert_eq!(o.hooks().len(), 1);
        assert_eq!(o.hooks()[0].1, "c");
    }
}