lumis-core 6.0.0

Lumis shared core
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
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
//! Lumis-owned overlays composed into the highlight event stream.
//!
//! An [`Annotation`](crate::annotations::Annotation) carries data only the
//! caller understands, so the built-in formatters skip it. A [`Decoration`]
//! carries data Lumis owns, from a closed set every built-in formatter can
//! switch on, so it reaches the same event stream and is rendered rather than
//! skipped.
//!
//! Lines and rainbow brackets both travel this way. A highlighted line is a
//! line range plus a payload; a rainbow bracket is a byte range plus its real
//! nesting depth. Built-in formatters can render both without disguising either
//! one as a syntax capture.

use crate::annotations::{compose_annotations_innermost, Annotation};
use crate::diff_words::DiffWordRange;
use crate::events::HighlightEvent;
use crate::highlights::HIGHLIGHT_NAMES;
use std::borrow::Cow;
use std::ops::{Range, RangeInclusive};
use std::sync::LazyLock;

/// Scope names used to render rainbow brackets in built-in formatters.
pub const RAINBOW_BRACKET_SCOPES: [&str; 6] = [
    "punctuation.bracket.rainbow.1",
    "punctuation.bracket.rainbow.2",
    "punctuation.bracket.rainbow.3",
    "punctuation.bracket.rainbow.4",
    "punctuation.bracket.rainbow.5",
    "punctuation.bracket.rainbow.6",
];

/// Resolved scope indices for the six theme-compatible rainbow colors.
#[doc(hidden)]
pub static RAINBOW_SCOPE_INDICES: LazyLock<[usize; RAINBOW_BRACKET_SCOPES.len()]> =
    LazyLock::new(|| {
        let fallback = HIGHLIGHT_NAMES
            .iter()
            .position(|candidate| *candidate == "punctuation.bracket")
            .unwrap_or(0);
        std::array::from_fn(|index| {
            HIGHLIGHT_NAMES
                .iter()
                .position(|candidate| *candidate == RAINBOW_BRACKET_SCOPES[index])
                .unwrap_or(fallback)
        })
    });

/// An overlay whose data Lumis owns and every built-in formatter understands.
///
/// Delivered as
/// [`DecorationStart`](crate::events::HighlightEvent::DecorationStart) and
/// [`DecorationEnd`](crate::events::HighlightEvent::DecorationEnd), interleaved
/// with the syntax scopes and the caller's annotations.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Decoration {
    /// One rendered line of the document.
    ///
    /// Every line carries one, highlighted or not, because that is what lets a
    /// formatter number the lines it emits. The decoration covers the line's
    /// text *and* the newline that ends it; the last line of a source that does
    /// not end in one covers just the text.
    Line {
        /// The 1-based line number.
        number: usize,
        /// Whether the caller asked for this line to be highlighted.
        highlighted: bool,
    },
    /// One bracket in a matched pair.
    RainbowBracket {
        /// The zero-based nesting depth, before built-in formatters cycle it
        /// through their six theme scopes.
        depth: usize,
    },
    /// Text that changed between a diff's removed lines and the added lines
    /// that replace them.
    DiffWord {
        /// Which side of the change the text is on.
        kind: DiffWordKind,
    },
}

/// The side of a diff a [`Decoration::DiffWord`] marks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DiffWordKind {
    /// Text only the removed lines have.
    Removed,
    /// Text only the added lines have.
    Added,
}

impl DiffWordKind {
    /// `"removed"` or `"added"`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Removed => "removed",
            Self::Added => "added",
        }
    }

    /// The theme scope built-in formatters style this side with.
    #[doc(hidden)]
    #[must_use]
    pub const fn scope(self) -> &'static str {
        match self {
            Self::Removed => "diff.minus.word",
            Self::Added => "diff.plus.word",
        }
    }

    /// The index of [`scope`](Self::scope) in the highlight names.
    #[doc(hidden)]
    #[must_use]
    pub fn scope_index(self) -> usize {
        static INDICES: LazyLock<[usize; 2]> = LazyLock::new(|| {
            [DiffWordKind::Removed, DiffWordKind::Added].map(|kind| {
                HIGHLIGHT_NAMES
                    .iter()
                    .position(|candidate| *candidate == kind.scope())
                    .expect("highlights.toml names both diff word scopes")
            })
        });
        INDICES[self as usize]
    }
}

/// A rainbow-bracket range before it is composed into the event stream.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RainbowRange {
    pub start: usize,
    pub end: usize,
    pub depth: usize,
}

/// The theme-compatible scope index for a rainbow-bracket depth.
#[doc(hidden)]
pub fn rainbow_scope_index(depth: usize) -> usize {
    RAINBOW_SCOPE_INDICES[depth % RAINBOW_SCOPE_INDICES.len()]
}

/// The theme-compatible scope name for a rainbow-bracket depth.
#[doc(hidden)]
pub fn rainbow_scope(depth: usize) -> &'static str {
    RAINBOW_BRACKET_SCOPES[depth % RAINBOW_BRACKET_SCOPES.len()]
}

/// Compose rainbow-bracket ranges into a syntax event stream.
#[doc(hidden)]
pub fn compose_rainbow_decorations(
    source: &str,
    events: &[HighlightEvent<'_, ()>],
    ranges: &[RainbowRange],
) -> Vec<HighlightEvent<'static, ()>> {
    compose_innermost_decorations(
        source,
        events,
        ranges.iter().map(|range| {
            (
                range.start..range.end,
                Decoration::RainbowBracket { depth: range.depth },
            )
        }),
    )
}

/// Compose changed-word ranges into a syntax event stream.
#[doc(hidden)]
pub fn compose_diff_word_decorations(
    source: &str,
    events: &[HighlightEvent<'_, ()>],
    ranges: &[DiffWordRange],
) -> Vec<HighlightEvent<'static, ()>> {
    compose_innermost_decorations(
        source,
        events,
        ranges.iter().map(|range| {
            (
                range.start..range.end,
                Decoration::DiffWord { kind: range.kind },
            )
        }),
    )
}

/// Compose decorations inside the syntax layers they cross.
///
/// The range walk is the annotation composer: it splits source events and
/// closes and reopens any syntax layer a range crosses. The temporary
/// annotation payload is immediately materialized as an owned decoration, so
/// nothing in the returned stream borrows the ranges.
fn compose_innermost_decorations(
    source: &str,
    events: &[HighlightEvent<'_, ()>],
    ranges: impl Iterator<Item = (Range<usize>, Decoration)>,
) -> Vec<HighlightEvent<'static, ()>> {
    let annotations = ranges
        .map(|(range, decoration)| {
            Annotation::new(range, decoration)
                .expect("decoration ranges are ordered parser byte ranges")
        })
        .collect::<Vec<_>>();
    let composed = compose_annotations_innermost(source, events, &annotations)
        .expect("decoration ranges come from this parsed source");

    composed
        .into_iter()
        .map(|event| match event {
            HighlightEvent::Start {
                scope_index,
                language,
            } => HighlightEvent::Start {
                scope_index,
                language,
            },
            HighlightEvent::Source { start, end } => HighlightEvent::Source { start, end },
            HighlightEvent::End => HighlightEvent::End,
            HighlightEvent::AnnotationStart { data, .. } => {
                HighlightEvent::DecorationStart { decoration: *data }
            }
            HighlightEvent::AnnotationEnd | HighlightEvent::DecorationEnd => {
                HighlightEvent::DecorationEnd
            }
            HighlightEvent::DecorationStart { decoration } => {
                HighlightEvent::DecorationStart { decoration }
            }
        })
        .collect()
}

/// The number of the last line of a composed stream.
///
/// A gutter is padded to the widest number it will show, and a formatter only
/// knows that number once the lines are known. Composition numbered them
/// already, so this reads the answer off the stream rather than counting the
/// source a second time.
pub(crate) fn last_line_number<T>(events: &[HighlightEvent<'_, T>]) -> usize {
    events
        .iter()
        .rev()
        .find_map(|event| match event {
            HighlightEvent::DecorationStart {
                decoration: Decoration::Line { number, .. },
            } => Some(*number),
            _ => None,
        })
        .unwrap_or(1)
}

/// Digits in the widest number a gutter showing up to `last` has to fit.
pub(crate) fn gutter_width(last: usize) -> usize {
    last.max(1).ilog10() as usize + 1
}

/// A finite arithmetic progression of 1-based line numbers.
///
/// This is public only so language bindings can preserve a source runtime's
/// stepped-range semantics without expanding the range into one allocation per
/// selected line. Rust's formatter options continue to use
/// [`RangeInclusive<usize>`].
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SteppedLineRange {
    first: usize,
    last: usize,
    step: usize,
}

impl SteppedLineRange {
    /// Normalize an ascending or descending stepped range.
    ///
    /// Returns `None` for a zero step or when the step points away from the end.
    #[doc(hidden)]
    pub fn new(start: usize, end: usize, step: isize) -> Option<Self> {
        let stride = step.unsigned_abs();
        if stride == 0 {
            return None;
        }

        let (first, last) = if step > 0 {
            if start > end {
                return None;
            }
            let span = end - start;
            (start, start + span / stride * stride)
        } else {
            if start < end {
                return None;
            }
            let span = start - end;
            (start - span / stride * stride, start)
        };

        Some(Self {
            first,
            last,
            step: stride,
        })
    }

    /// Whether `line_number` is one of the range's selected lines.
    #[doc(hidden)]
    pub fn contains(&self, line_number: usize) -> bool {
        (self.first..=self.last).contains(&line_number)
            && (line_number - self.first).is_multiple_of(self.step)
    }
}

/// The lines a formatter was asked to highlight, resolved once.
///
/// Contiguous ranges are clamped, sorted and merged, so testing lines in
/// ascending order walks them with a cursor rather than rescanning. A stepped
/// range stays as three numbers and answers by arithmetic. Neither depends on
/// how many lines the document has, so a selection costs the same whether it
/// covers ten lines or a billion.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct LineSelection {
    /// Merged, disjoint, ascending, 1-based and inclusive at both ends.
    spans: Vec<(usize, usize)>,
    /// Only ranges with a stride above 1; a stride of 1 is a span either way round.
    stepped: Vec<SteppedLineRange>,
}

impl LineSelection {
    /// Resolves the plain and stepped ranges a formatter was configured with.
    pub(crate) fn new(ranges: &[RangeInclusive<usize>], stepped: &[SteppedLineRange]) -> Self {
        let mut spans: Vec<(usize, usize)> = ranges
            .iter()
            .map(|range| (*range.start(), *range.end()))
            .chain(
                stepped
                    .iter()
                    .filter(|range| range.step == 1)
                    .map(|range| (range.first, range.last)),
            )
            // Line 0 does not exist, and a reversed range covers nothing.
            .filter_map(|(start, end)| (start.max(1) <= end).then_some((start.max(1), end)))
            .collect();
        spans.sort_unstable();
        spans.dedup_by(|(next_start, next_end), (_, end)| {
            // `dedup_by` drops the first argument when this returns true, so
            // widening the second is how a merged span survives.
            let mergeable = *next_start <= end.saturating_add(1);
            if mergeable {
                *end = (*end).max(*next_end);
            }
            mergeable
        });

        Self {
            spans,
            stepped: stepped
                .iter()
                .filter(|range| range.step > 1)
                .cloned()
                .collect(),
        }
    }

    /// Whether no line is selected.
    pub(crate) fn is_empty(&self) -> bool {
        self.spans.is_empty() && self.stepped.is_empty()
    }

    /// A cursor for testing line numbers in ascending order.
    fn cursor(&self) -> LineCursor<'_> {
        LineCursor {
            selection: self,
            index: 0,
        }
    }
}

/// Tests ascending line numbers against a [`LineSelection`].
struct LineCursor<'a> {
    selection: &'a LineSelection,
    index: usize,
}

impl LineCursor<'_> {
    /// Whether `line` is selected.
    ///
    /// `line` must not go backwards between calls, which is how the composer
    /// visits lines.
    fn contains(&mut self, line: usize) -> bool {
        let spans = &self.selection.spans;
        while self.index < spans.len() && spans[self.index].1 < line {
            self.index += 1;
        }

        spans
            .get(self.index)
            .is_some_and(|(start, end)| *start <= line && line <= *end)
            || self
                .selection
                .stepped
                .iter()
                .any(|range| range.contains(line))
    }
}

/// One layer held open across a line boundary: the event that opened it,
/// which is also what reopens it on the next line.
struct OpenLayer<'e, 'a, T>(&'e HighlightEvent<'a, T>);

impl<'a, T> OpenLayer<'_, 'a, T> {
    fn closes(&self, event: &HighlightEvent<'a, T>) -> bool {
        matches!(
            (self.0, event),
            (HighlightEvent::Start { .. }, HighlightEvent::End)
                | (
                    HighlightEvent::AnnotationStart { .. },
                    HighlightEvent::AnnotationEnd
                )
                | (
                    HighlightEvent::DecorationStart { .. },
                    HighlightEvent::DecorationEnd
                )
        )
    }

    fn close_event(&self) -> HighlightEvent<'a, T> {
        match self.0 {
            HighlightEvent::AnnotationStart { .. } => HighlightEvent::AnnotationEnd,
            HighlightEvent::DecorationStart { .. } => HighlightEvent::DecorationEnd,
            _ => HighlightEvent::End,
        }
    }
}

/// Compose one [`Decoration::Line`] per rendered line into `events`.
///
/// Lines are the outermost layer, so every syntax scope and caller annotation
/// still open at a newline is closed before the line ends and reopened on the
/// next one only when another source or opening event needs them. Layers that
/// end immediately after the newline stay closed. That is the same close-and-reopen
/// [`compose_annotations`](crate::annotations::compose_annotations) does for a
/// scope an annotation cuts across, and it is why a formatter can write the
/// stream straight out instead of assembling lines and wrapping them
/// afterwards.
///
/// The returned stream always holds at least one line: an empty document is one
/// empty line, the same line a caller sees numbered `1`.
///
/// Line decorations already present in `events` are dropped rather than nested,
/// so composing twice gives the same answer as composing once.
pub(crate) fn compose_line_decorations<'a, T>(
    source: &str,
    events: &[HighlightEvent<'a, T>],
    selection: &LineSelection,
) -> Vec<HighlightEvent<'a, T>> {
    // One decoration pair per line, plus a close and reopen of every layer that
    // crosses one. The syntax events themselves pass through.
    let mut output = Vec::with_capacity(events.len() + 2);
    compose_line_decorations_into(source, events, selection, &mut |event| {
        output.push(event.into_owned());
    });
    output
}

/// [`compose_line_decorations`] without the vector.
///
/// The composed stream is the same size as the input, so a formatter that
/// materializes it holds the whole document's events twice. Handing each event
/// to `emit` as it is composed is what lets one be written and dropped. Events
/// that pass through, and the scopes reopened on each line, are lent from
/// `events` rather than cloned, because cloning a `Start` copies its language.
pub(crate) fn compose_line_decorations_into<'e, 'a, T>(
    source: &str,
    events: &'e [HighlightEvent<'a, T>],
    selection: &LineSelection,
    emit: &mut dyn FnMut(Cow<'e, HighlightEvent<'a, T>>),
) {
    let output = &mut Emit(emit);
    let mut layers: Vec<OpenLayer<'e, 'a, T>> = Vec::new();
    let mut cursor = selection.cursor();
    let mut line = 1usize;
    let mut pending = false;

    output.owned(line_start(line, &mut cursor));

    for event in events {
        if pending
            && matches!(
                event,
                HighlightEvent::Start { .. }
                    | HighlightEvent::AnnotationStart { .. }
                    | HighlightEvent::Source { .. }
                    | HighlightEvent::DecorationStart {
                        decoration: Decoration::RainbowBracket { .. } | Decoration::DiffWord { .. }
                    }
            )
        {
            reopen_layers(output, &layers);
            pending = false;
        }

        match event {
            HighlightEvent::Start { .. }
            | HighlightEvent::AnnotationStart { .. }
            | HighlightEvent::DecorationStart {
                decoration: Decoration::RainbowBracket { .. } | Decoration::DiffWord { .. },
            } => {
                output.lent(event);
                layers.push(OpenLayer(event));
            }
            HighlightEvent::Source { start, end } => {
                pending = split_source(
                    output,
                    source,
                    *start,
                    *end,
                    &layers,
                    &mut line,
                    &mut cursor,
                );
            }
            // A stream that already carries lines is re-composed, not nested.
            HighlightEvent::DecorationStart {
                decoration: Decoration::Line { .. },
            } => {}
            HighlightEvent::End | HighlightEvent::AnnotationEnd | HighlightEvent::DecorationEnd => {
                close_layer(output, &mut layers, event, pending);
            }
        }
    }

    // An unbalanced input stream would otherwise leave a scope open past the
    // last line, which no formatter can close.
    if !pending {
        close_layers(output, &layers);
    }
    output.owned(HighlightEvent::DecorationEnd);
}

/// A sink the composer pushes to, so one walk serves both entry points.
struct Emit<'s, 'e, 'a, T>(&'s mut dyn FnMut(Cow<'e, HighlightEvent<'a, T>>));

impl<'e, 'a, T> Emit<'_, 'e, 'a, T> {
    fn owned(&mut self, event: HighlightEvent<'a, T>) {
        (self.0)(Cow::Owned(event));
    }

    fn lent(&mut self, event: &'e HighlightEvent<'a, T>) {
        (self.0)(Cow::Borrowed(event));
    }
}

fn line_start<'a, T>(line: usize, cursor: &mut LineCursor<'_>) -> HighlightEvent<'a, T> {
    HighlightEvent::DecorationStart {
        decoration: Decoration::Line {
            number: line,
            highlighted: cursor.contains(line),
        },
    }
}

fn close_layers<'e, 'a, T>(output: &mut Emit<'_, 'e, 'a, T>, layers: &[OpenLayer<'e, 'a, T>]) {
    for layer in layers.iter().rev() {
        output.owned(layer.close_event());
    }
}

fn close_layer<'e, 'a, T>(
    output: &mut Emit<'_, 'e, 'a, T>,
    layers: &mut Vec<OpenLayer<'e, 'a, T>>,
    event: &'e HighlightEvent<'a, T>,
    pending: bool,
) {
    if layers.last().is_some_and(|layer| layer.closes(event)) {
        layers.pop();
        if !pending {
            output.lent(event);
        }
    }
}

fn reopen_layers<'e, 'a, T>(output: &mut Emit<'_, 'e, 'a, T>, layers: &[OpenLayer<'e, 'a, T>]) {
    for layer in layers {
        output.lent(layer.0);
    }
}

/// Emit `start..end`, ending a line at every newline it contains.
///
/// The newline stays inside the line it ends, so concatenating the `Source`
/// events of the composed stream still reproduces the source exactly.
/// Returns whether the layers are held closed at a trailing newline.
fn split_source<'e, 'a, T>(
    output: &mut Emit<'_, 'e, 'a, T>,
    source: &str,
    start: usize,
    end: usize,
    layers: &[OpenLayer<'e, 'a, T>],
    line: &mut usize,
    cursor: &mut LineCursor<'_>,
) -> bool {
    let mut cursor_offset = start.min(source.len());
    let end = end.min(source.len()).max(cursor_offset);

    while cursor_offset < end {
        let Some(newline) = source.as_bytes()[cursor_offset..end]
            .iter()
            .position(|byte| *byte == b'\n')
        else {
            break;
        };

        let line_end = cursor_offset + newline + 1;
        output.owned(HighlightEvent::Source {
            start: cursor_offset,
            end: line_end,
        });
        close_layers(output, layers);
        output.owned(HighlightEvent::DecorationEnd);

        *line += 1;
        output.owned(line_start(*line, cursor));

        cursor_offset = line_end;
        if cursor_offset == end {
            return true;
        }
        reopen_layers(output, layers);
    }

    if cursor_offset < end {
        output.owned(HighlightEvent::Source {
            start: cursor_offset,
            end,
        });
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::annotations::{compose_annotations, Annotation};

    fn selection(ranges: impl IntoIterator<Item = RangeInclusive<usize>>) -> LineSelection {
        LineSelection::new(&ranges.into_iter().collect::<Vec<_>>(), &[])
    }

    fn lines<T>(events: &[HighlightEvent<'_, T>]) -> Vec<(usize, bool)> {
        events
            .iter()
            .filter_map(|event| match event {
                HighlightEvent::DecorationStart {
                    decoration:
                        Decoration::Line {
                            number,
                            highlighted,
                        },
                } => Some((*number, *highlighted)),
                _ => None,
            })
            .collect()
    }

    fn rendered<T>(source: &str, events: &[HighlightEvent<'_, T>]) -> String {
        let mut out = String::new();
        for event in events {
            if let HighlightEvent::Source { start, end } = event {
                out.push_str(&source[*start..*end]);
            }
        }
        out
    }

    #[test]
    fn an_empty_document_is_one_line() {
        let events: [HighlightEvent<'_>; 0] = [];

        let composed = compose_line_decorations("", &events, &LineSelection::default());

        assert_eq!(lines(&composed), [(1, false)]);
        assert_eq!(composed.len(), 2, "a start and an end: {composed:?}");
    }

    #[test]
    fn a_trailing_newline_opens_one_more_line() {
        let source = "a\n";
        let events: [HighlightEvent<'_, ()>; 1] = [HighlightEvent::Source { start: 0, end: 2 }];

        let composed = compose_line_decorations(source, &events, &LineSelection::default());

        assert_eq!(lines(&composed), [(1, false), (2, false)]);
        assert_eq!(rendered(source, &composed), source);
    }

    #[test]
    fn source_events_still_reproduce_the_source() {
        let source = "one\ntwo\nthree";
        let events: [HighlightEvent<'_, ()>; 1] = [HighlightEvent::Source {
            start: 0,
            end: source.len(),
        }];

        let composed =
            compose_line_decorations(source, &events, &selection(std::iter::once(2..=2)));

        assert_eq!(lines(&composed), [(1, false), (2, true), (3, false)]);
        assert_eq!(rendered(source, &composed), source);
    }

    #[test]
    fn a_scope_crossing_a_newline_is_closed_and_reopened() {
        let source = "a\nb";
        let events: [HighlightEvent<'_, ()>; 3] = [
            HighlightEvent::Start {
                scope_index: 1,
                language: "rust".to_string(),
            },
            HighlightEvent::Source { start: 0, end: 3 },
            HighlightEvent::End,
        ];

        let composed = compose_line_decorations(source, &events, &LineSelection::default());

        assert_eq!(
            composed,
            [
                HighlightEvent::DecorationStart {
                    decoration: Decoration::Line {
                        number: 1,
                        highlighted: false
                    }
                },
                HighlightEvent::Start {
                    scope_index: 1,
                    language: "rust".to_string(),
                },
                HighlightEvent::Source { start: 0, end: 2 },
                HighlightEvent::End,
                HighlightEvent::DecorationEnd,
                HighlightEvent::DecorationStart {
                    decoration: Decoration::Line {
                        number: 2,
                        highlighted: false
                    }
                },
                HighlightEvent::Start {
                    scope_index: 1,
                    language: "rust".to_string(),
                },
                HighlightEvent::Source { start: 2, end: 3 },
                HighlightEvent::End,
                HighlightEvent::DecorationEnd,
            ]
        );
    }

    #[test]
    fn an_annotation_crossing_a_newline_is_closed_and_reopened() {
        let source = "ab\ncd";
        let syntax = [HighlightEvent::Source { start: 0, end: 5 }];
        let annotations = [Annotation::new(1..4, "span").unwrap()];
        let events = compose_annotations(source, &syntax, &annotations).unwrap();

        let composed = compose_line_decorations(source, &events, &LineSelection::default());

        let starts = composed
            .iter()
            .filter(|event| matches!(event, HighlightEvent::AnnotationStart { .. }))
            .count();
        let ends = composed
            .iter()
            .filter(|event| matches!(event, HighlightEvent::AnnotationEnd))
            .count();

        assert_eq!((starts, ends), (2, 2));
        assert_eq!(rendered(source, &composed), source);
    }

    #[test]
    fn an_unbalanced_stream_still_closes_before_the_last_line_ends() {
        let events: [HighlightEvent<'_, ()>; 1] = [HighlightEvent::Start {
            scope_index: 1,
            language: "rust".to_string(),
        }];

        let composed = compose_line_decorations("", &events, &LineSelection::default());

        assert_eq!(
            composed.last(),
            Some(&HighlightEvent::DecorationEnd),
            "{composed:?}"
        );
        assert!(
            matches!(composed[composed.len() - 2], HighlightEvent::End),
            "{composed:?}"
        );
    }

    #[test]
    fn composing_twice_gives_the_same_stream() {
        let source = "a\nb\n";
        let events: [HighlightEvent<'_, ()>; 1] = [HighlightEvent::Source { start: 0, end: 4 }];

        let once = compose_line_decorations(source, &events, &selection(std::iter::once(1..=1)));
        let twice = compose_line_decorations(source, &once, &selection(std::iter::once(1..=1)));

        assert_eq!(once, twice);
    }

    #[test]
    fn overlapping_ranges_merge_and_line_zero_is_dropped() {
        let selection = selection([0..=2, 2..=4, 8..=9]);

        assert_eq!(selection.spans, [(1, 4), (8, 9)]);
    }

    #[test]
    fn adjacent_ranges_merge() {
        assert_eq!(selection([1..=2, 3..=4]).spans, [(1, 4)]);
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)]
    fn a_reversed_range_selects_nothing() {
        assert!(selection(std::iter::once(5..=3)).is_empty());
    }

    #[test]
    fn a_selection_costs_nothing_for_a_range_larger_than_the_document() {
        let huge = selection(std::iter::once(1..=usize::MAX));
        let mut cursor = huge.cursor();

        assert!(cursor.contains(1));
        assert!(cursor.contains(1_000_000_000));
    }

    #[test]
    fn a_stride_of_one_is_a_span_either_way_round() {
        let ascending = SteppedLineRange::new(1, 1_000_000_000, 1).unwrap();
        let descending = SteppedLineRange::new(1_000_000_000, 1, -1).unwrap();

        let selection = LineSelection::new(&[], &[ascending, descending]);

        assert_eq!(selection.spans, [(1, 1_000_000_000)]);
        assert_eq!(selection.stepped, Vec::new());
    }

    #[test]
    fn stepped_ranges_stay_compact() {
        let ascending = SteppedLineRange::new(1, 1_000_000_000, 2).unwrap();
        let descending = SteppedLineRange::new(1_000_000_000, 1, -3).unwrap();
        let selection = LineSelection::new(&[], &[ascending, descending]);
        let mut cursor = selection.cursor();

        assert_eq!(
            (1..=6)
                .map(|line| cursor.contains(line))
                .collect::<Vec<_>>(),
            [true, false, true, true, true, false],
        );
    }

    #[test]
    fn a_descending_stepped_range_keeps_the_lines_the_step_lands_on() {
        let unaligned = SteppedLineRange::new(10, 2, -3).unwrap();

        assert!(unaligned.contains(4));
        assert!(!unaligned.contains(2));
    }

    #[test]
    fn many_ranges_merge_before_any_line_is_tested() {
        let ranges: Vec<_> = (1..=20_000).step_by(2).map(|line| line..=line).collect();
        let selection = selection(ranges);
        let mut cursor = selection.cursor();

        assert_eq!(selection.spans.len(), 10_000);
        assert_eq!(
            (1..=20_000).filter(|line| cursor.contains(*line)).count(),
            10_000
        );
    }
}

#[cfg(test)]
#[path = "decorations_parity.rs"]
mod parity;