sqruff-lib 0.39.0

A high-speed SQL linter.
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
use std::cmp::PartialEq;
use std::str::FromStr;

use sqruff_lib_core::dialects::syntax::SyntaxKind;
use sqruff_lib_core::helpers::capitalize;
use sqruff_lib_core::lint_fix::LintFix;
use sqruff_lib_core::parser::segments::{ErasedSegment, Tables};
use strum_macros::{AsRefStr, EnumString};

use super::elements::{ReflowElement, ReflowSequenceType};
use crate::core::rules::LintResult;
use crate::utils::reflow::depth_map::StackPositionType;
use crate::utils::reflow::elements::ReflowPoint;
use crate::utils::reflow::helpers::{deduce_line_indent, fixes_from_results, pretty_segment_name};

#[derive(Debug)]
pub struct RebreakSpan {
    pub(crate) target: ErasedSegment,
    pub(crate) start_idx: usize,
    pub(crate) end_idx: usize,
    pub(crate) line_position: LinePosition,
    pub(crate) strict: bool,
}

#[derive(Debug)]
pub struct RebreakIndices {
    _dir: i32,
    adj_pt_idx: isize,
    newline_pt_idx: isize,
    pre_code_pt_idx: isize,
}

impl RebreakIndices {
    fn from_elements(elements: &ReflowSequenceType, start_idx: usize, dir: i32) -> Option<Self> {
        assert!(dir == 1 || dir == -1);
        let limit = if dir == -1 { 0 } else { elements.len() };
        let adj_point_idx = start_idx as isize + dir as isize;

        if adj_point_idx < 0 || adj_point_idx >= elements.len() as isize {
            return None;
        }

        let mut newline_point_idx = adj_point_idx;
        while (dir == 1 && newline_point_idx < limit as isize)
            || (dir == -1 && newline_point_idx >= 0)
        {
            // Check bounds for the adjacent element access. When traversing
            // backward (dir=-1) and reaching index 0, (idx + dir) would be -1
            // which wraps to usize::MAX causing a panic. Break here as we've
            // reached the boundary - there's nothing further in this direction.
            let adjacent_idx = newline_point_idx + dir as isize;
            if adjacent_idx < 0 || adjacent_idx >= elements.len() as isize {
                break;
            }
            if elements[newline_point_idx as usize]
                .class_types()
                .contains(SyntaxKind::Newline)
                || elements[adjacent_idx as usize]
                    .segments()
                    .iter()
                    .any(|seg| seg.is_code())
            {
                break;
            }
            newline_point_idx += 2 * dir as isize;
        }

        // Clamp to the adjacent point if scanning went out of bounds
        // (no newline or code found in this direction).
        if newline_point_idx < 0 || newline_point_idx >= elements.len() as isize {
            newline_point_idx = adj_point_idx;
        }

        let mut pre_code_point_idx = newline_point_idx;
        while (dir == 1 && pre_code_point_idx < limit as isize)
            || (dir == -1 && pre_code_point_idx >= 0)
        {
            // Same bounds check as above for the adjacent element access.
            let adjacent_idx = pre_code_point_idx + dir as isize;
            if adjacent_idx < 0 || adjacent_idx >= elements.len() as isize {
                break;
            }
            if elements[adjacent_idx as usize]
                .segments()
                .iter()
                .any(|seg| seg.is_code())
            {
                break;
            }
            pre_code_point_idx += 2 * dir as isize;
        }

        // Clamp to the newline point if scanning went out of bounds.
        if pre_code_point_idx < 0 || pre_code_point_idx >= elements.len() as isize {
            pre_code_point_idx = newline_point_idx;
        }

        RebreakIndices {
            _dir: dir,
            adj_pt_idx: adj_point_idx,
            newline_pt_idx: newline_point_idx,
            pre_code_pt_idx: pre_code_point_idx,
        }
        .into()
    }
}

#[derive(Debug)]
pub struct RebreakLocation {
    target: ErasedSegment,
    prev: RebreakIndices,
    next: RebreakIndices,
    line_position: LinePosition,
    strict: bool,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, AsRefStr, EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum LinePosition {
    Leading,
    Trailing,
    Alone,
    Strict,
}

impl RebreakLocation {
    /// Expand a span to a location.
    pub fn from_span(span: RebreakSpan, elements: &ReflowSequenceType) -> Option<Self> {
        Self {
            target: span.target,
            prev: RebreakIndices::from_elements(elements, span.start_idx, -1)?,
            next: RebreakIndices::from_elements(elements, span.end_idx, 1)?,
            line_position: span.line_position,
            strict: span.strict,
        }
        .into()
    }

    fn has_inappropriate_newlines(&self, elements: &ReflowSequenceType, strict: bool) -> bool {
        let n_prev_newlines = elements[self.prev.newline_pt_idx as usize].num_newlines();
        let n_next_newlines = elements[self.next.newline_pt_idx as usize].num_newlines();

        let newlines_on_neither_side = n_prev_newlines + n_next_newlines == 0;
        let newlines_on_both_sides = n_prev_newlines > 0 && n_next_newlines > 0;

        (newlines_on_neither_side && !strict) || newlines_on_both_sides
    }

    fn pretty_target_name(&self) -> String {
        pretty_segment_name(&self.target)
    }
}

pub fn identify_rebreak_spans(
    element_buffer: &ReflowSequenceType,
    root_segment: &ErasedSegment,
) -> Vec<RebreakSpan> {
    let mut spans = Vec::new();

    for (idx, elem) in element_buffer
        .iter()
        .enumerate()
        .take(element_buffer.len() - 2)
        .skip(2)
    {
        let ReflowElement::Block(block) = elem else {
            continue;
        };

        if let Some(original_line_position) = block.line_position() {
            let Some(pos_marker) = elem
                .segments()
                .first()
                .and_then(|seg| seg.get_position_marker())
            else {
                continue;
            };
            if !pos_marker.is_literal() {
                continue;
            }

            spans.push(RebreakSpan {
                target: elem.segments().first().cloned().unwrap(),
                start_idx: idx,
                end_idx: idx,
                line_position: original_line_position.position(),
                strict: original_line_position.is_strict(),
            });
        }

        for key in block.line_position_configs().keys() {
            let mut final_idx = None;
            if block.depth_info().stack_positions[key].idx != 0 {
                continue;
            }

            for (end_idx, end_elem) in element_buffer.iter().enumerate().skip(idx) {
                let ReflowElement::Block(end_block) = end_elem else {
                    continue;
                };

                if !end_block.depth_info().stack_positions.contains_key(key) {
                    // Left the scope. The last block inside is two positions back.
                    if final_idx.is_none() {
                        final_idx = (end_idx - 2).into();
                    }
                    break;
                } else if matches!(
                    end_block.depth_info().stack_positions[key].type_,
                    Some(StackPositionType::End) | Some(StackPositionType::Solo)
                ) {
                    // Track the latest End/Solo block but keep scanning,
                    // because multiple blocks within the last child all
                    // have End type at the parent level.
                    final_idx = end_idx.into();
                }
            }

            if let Some(final_idx) = final_idx {
                let target_depth = block
                    .depth_info()
                    .stack_hashes
                    .iter()
                    .position(|it| it == key)
                    .unwrap();
                let target = root_segment.path_to(&element_buffer[idx].segments()[0])[target_depth]
                    .segment
                    .clone();

                let line_position_config = block.line_position_configs()[key];

                spans.push(RebreakSpan {
                    target,
                    start_idx: idx,
                    end_idx: final_idx,
                    line_position: line_position_config.position(),
                    strict: line_position_config.is_strict(),
                });
            }
        }
    }

    spans
}

pub fn identify_keyword_rebreak_spans(element_buffer: &ReflowSequenceType) -> Vec<RebreakSpan> {
    let mut spans = Vec::new();

    for idx in 2..element_buffer.len().saturating_sub(2) {
        let ReflowElement::Block(block) = &element_buffer[idx] else {
            continue;
        };

        for key in block.keyword_line_position_configs().keys() {
            let line_position_config = &block.keyword_line_position_configs()[key];
            if line_position_config.eq_ignore_ascii_case("none") {
                continue;
            }

            if block.depth_info().stack_positions[key].idx > 1 {
                continue;
            }

            let configured_depth = block
                .depth_info()
                .stack_hashes
                .iter()
                .position(|it| it == key)
                .unwrap();
            if block.depth_info().stack_depth > configured_depth + 1 {
                continue;
            }

            if element_buffer[idx].segments().is_empty()
                || !element_buffer[idx].segments()[0].is_type(SyntaxKind::Keyword)
            {
                continue;
            }

            for end_idx in idx..element_buffer.len() {
                let end_elem = &element_buffer[end_idx];
                let final_idx = match end_elem {
                    ReflowElement::Point(point)
                        if point.segments().iter().any(|seg| seg.is_indent()) =>
                    {
                        Some(end_idx - 1)
                    }
                    ReflowElement::Point(_) => continue,
                    ReflowElement::Block(end_block)
                        if matches!(
                            end_block.depth_info().stack_positions[key].type_,
                            Some(StackPositionType::End) | Some(StackPositionType::Solo)
                        ) =>
                    {
                        Some(end_idx)
                    }
                    ReflowElement::Block(_) => continue,
                };

                if let Some(final_idx) = final_idx {
                    let parent_exclusion = block
                        .keyword_line_position_exclusions_configs()
                        .get(key)
                        .cloned()
                        .unwrap_or_default();
                    if block
                        .depth_info()
                        .stack_class_types
                        .iter()
                        .any(|class_types| class_types.intersects(&parent_exclusion))
                    {
                        break;
                    }

                    let line_position =
                        LinePosition::from_str(line_position_config.split(':').next().unwrap())
                            .unwrap();

                    spans.push(RebreakSpan {
                        target: element_buffer[idx].segments()[0].clone(),
                        start_idx: idx,
                        end_idx: final_idx,
                        line_position,
                        strict: line_position_config.ends_with("strict"),
                    });
                    break;
                }
            }
        }
    }

    spans
}

fn locations_from_spans(
    spans: Vec<RebreakSpan>,
    elements: &ReflowSequenceType,
) -> Vec<RebreakLocation> {
    spans
        .into_iter()
        .filter_map(|span| RebreakLocation::from_span(span, elements))
        .collect()
}

pub fn rebreak_sequence(
    tables: &Tables,
    elements: ReflowSequenceType,
    root_segment: &ErasedSegment,
) -> (ReflowSequenceType, Vec<LintResult>) {
    let mut lint_results = Vec::new();
    let mut fixes = Vec::new();
    let mut elem_buff = elements.clone();

    // Given a sequence we should identify the objects which
    // make sense to rebreak. That includes any raws with config,
    // but also and parent segments which have config and we can
    // find both ends for. Given those spans, we then need to find
    // the points either side of them and then the blocks either
    // side to respace them at the same time.

    // 1. First find appropriate spans.
    let spans = identify_rebreak_spans(&elem_buff, root_segment);
    let locations = locations_from_spans(spans, &elements);

    // Handle each span:
    for loc in locations {
        if loc.has_inappropriate_newlines(&elements, loc.strict) {
            continue;
        }

        // if loc.has_templated_newline(elem_buff) {
        //     continue;
        // }

        // Points and blocks either side are just offsets from the indices.
        let prev_point = elem_buff[loc.prev.adj_pt_idx as usize]
            .as_point()
            .unwrap()
            .clone();
        let next_point = elem_buff[loc.next.adj_pt_idx as usize]
            .as_point()
            .unwrap()
            .clone();

        // So we know we have a preference, is it ok?
        let new_results = if loc.line_position == LinePosition::Leading {
            if elem_buff[loc.prev.newline_pt_idx as usize].num_newlines() != 0 {
                // We're good. It's already leading.
                continue;
            }

            // Generate the text for any issues.
            let pretty_name = loc.pretty_target_name();
            let _desc = if loc.strict {
                format!(
                    "{} should always start a new line.",
                    capitalize(&pretty_name)
                )
            } else {
                format!("Found trailing {pretty_name}. Expected only leading near line breaks.")
            };

            if loc.next.adj_pt_idx == loc.next.pre_code_pt_idx
                && elem_buff[loc.next.newline_pt_idx as usize].num_newlines() == 1
            {
                // Simple case. No comments.
                // Strip newlines from the next point.
                // Apply the indent to the previous point.

                let desired_indent = next_point.get_indent().unwrap_or_default();

                let (new_results, prev_point) = prev_point.indent_to(
                    tables,
                    &desired_indent,
                    None,
                    loc.target.clone().into(),
                    None,
                    None,
                );

                let (new_results, next_point) = next_point.respace_point(
                    tables,
                    elem_buff[loc.next.adj_pt_idx as usize - 1].as_block(),
                    elem_buff[loc.next.adj_pt_idx as usize + 1].as_block(),
                    root_segment,
                    new_results,
                    true,
                    "before",
                );

                // Update the points in the buffer
                elem_buff[loc.prev.adj_pt_idx as usize] = prev_point.into();
                elem_buff[loc.next.adj_pt_idx as usize] = next_point.into();

                new_results
            } else {
                fixes.push(LintFix::delete(loc.target.clone()));
                for seg in elem_buff[loc.prev.adj_pt_idx as usize].segments() {
                    fixes.push(LintFix::delete(seg.clone()));
                }

                let (new_results, new_point) = ReflowPoint::new(Vec::new()).respace_point(
                    tables,
                    elem_buff[(loc.next.adj_pt_idx - 1) as usize].as_block(),
                    elem_buff[(loc.next.pre_code_pt_idx + 1) as usize].as_block(),
                    root_segment,
                    Vec::new(),
                    false,
                    "after",
                );

                let mut create_anchor = None;
                for i in 0..loc.next.pre_code_pt_idx {
                    let idx = loc.next.pre_code_pt_idx - i;
                    if let Some(elem) = elem_buff.get(idx as usize)
                        && let Some(segments) = elem.segments().last()
                    {
                        create_anchor = Some(segments.clone());
                        break;
                    }
                }

                if create_anchor.is_none() {
                    panic!("Could not find anchor for creation.");
                }

                fixes.push(LintFix::create_after(
                    create_anchor.unwrap(),
                    vec![loc.target.clone()],
                    None,
                ));

                rearrange_and_insert(&mut elem_buff, &loc, new_point);

                new_results
            }
        } else if loc.line_position == LinePosition::Trailing {
            if elem_buff[loc.next.newline_pt_idx as usize].num_newlines() != 0 {
                continue;
            }

            let pretty_name = loc.pretty_target_name();
            let _desc = if loc.strict {
                format!(
                    "{} should always be at the end of a line.",
                    capitalize(&pretty_name)
                )
            } else {
                format!("Found leading {pretty_name}. Expected only trailing near line breaks.")
            };

            if loc.prev.adj_pt_idx == loc.prev.pre_code_pt_idx
                && elem_buff[loc.prev.newline_pt_idx as usize].num_newlines() == 1
            {
                let (new_results, next_point) = next_point.indent_to(
                    tables,
                    prev_point.get_indent().as_deref().unwrap_or_default(),
                    Some(loc.target.clone()),
                    None,
                    None,
                    None,
                );

                let (new_results, prev_point) = prev_point.respace_point(
                    tables,
                    elem_buff[loc.prev.adj_pt_idx as usize - 1].as_block(),
                    elem_buff[loc.prev.adj_pt_idx as usize + 1].as_block(),
                    root_segment,
                    new_results,
                    true,
                    "before",
                );

                // Update the points in the buffer
                elem_buff[loc.prev.adj_pt_idx as usize] = prev_point.into();
                elem_buff[loc.next.adj_pt_idx as usize] = next_point.into();

                new_results
            } else {
                fixes.push(LintFix::delete(loc.target.clone()));
                for seg in elem_buff[loc.next.adj_pt_idx as usize].segments() {
                    fixes.push(LintFix::delete(seg.clone()));
                }

                let (new_results, new_point) = ReflowPoint::new(Vec::new()).respace_point(
                    tables,
                    elem_buff[(loc.prev.pre_code_pt_idx - 1) as usize].as_block(),
                    elem_buff[(loc.prev.adj_pt_idx + 1) as usize].as_block(),
                    root_segment,
                    Vec::new(),
                    false,
                    "before",
                );

                fixes.push(LintFix::create_before(
                    elem_buff[loc.prev.pre_code_pt_idx as usize].segments()[0].clone(),
                    vec![loc.target.clone()],
                ));

                reorder_and_insert(&mut elem_buff, &loc, new_point);

                new_results
            }
        } else if loc.line_position == LinePosition::Alone {
            let mut new_results = Vec::new();

            let needs_next_newline =
                elem_buff[loc.next.newline_pt_idx as usize].num_newlines() == 0;
            let needs_prev_newline = elem_buff[loc.prev.adj_pt_idx as usize].num_newlines() == 0;

            // Don't add a newline before a statement terminator (semicolon).
            // The terminator should stay on the same line as the preceding
            // clause content (e.g. `WHERE a = 1;` not `WHERE a = 1\n;`).
            let next_code_idx = (loc.next.pre_code_pt_idx + 1) as usize;
            let next_is_statement_terminator = next_code_idx < elem_buff.len()
                && elem_buff[next_code_idx]
                    .segments()
                    .iter()
                    .any(|seg| seg.get_type() == SyntaxKind::StatementTerminator);

            let skip_next_newline = needs_next_newline && next_is_statement_terminator;

            if (!needs_next_newline || skip_next_newline) && !needs_prev_newline {
                continue;
            }

            if needs_next_newline && !skip_next_newline {
                let (results, next_point) = next_point.indent_to(
                    tables,
                    &deduce_line_indent(
                        loc.target.get_raw_segments().last().unwrap(),
                        root_segment,
                    ),
                    loc.target.clone().into(),
                    None,
                    None,
                    None,
                );

                new_results = results;
                elem_buff[loc.next.adj_pt_idx as usize] = next_point.into();
            }

            if needs_prev_newline {
                let (results, prev_point) = prev_point.indent_to(
                    tables,
                    &deduce_line_indent(
                        loc.target.get_raw_segments().first().unwrap(),
                        root_segment,
                    ),
                    None,
                    loc.target.clone().into(),
                    None,
                    None,
                );

                new_results = results;
                elem_buff[loc.prev.adj_pt_idx as usize] = prev_point.into();
            }

            new_results
        } else {
            unimplemented!(
                "Unexpected line_position config: {}",
                loc.line_position.as_ref()
            )
        };

        let fixes = fixes_from_results(new_results.into_iter())
            .chain(std::mem::take(&mut fixes))
            .collect();
        lint_results.push(LintResult::new(
            loc.target.clone().into(),
            fixes,
            None,
            None,
        ));
    }

    (elem_buff, lint_results)
}

pub fn rebreak_keywords_sequence(
    tables: &Tables,
    elements: ReflowSequenceType,
    root_segment: &ErasedSegment,
) -> (ReflowSequenceType, Vec<LintResult>) {
    let mut lint_results = Vec::new();
    let mut fixes = Vec::new();
    let mut elem_buff = elements.clone();

    let spans = identify_keyword_rebreak_spans(&elem_buff);
    let locations = locations_from_spans(spans, &elements);

    for loc in locations {
        if loc.has_inappropriate_newlines(&elem_buff, true) {
            continue;
        }

        let prev_point = elem_buff[loc.prev.adj_pt_idx as usize]
            .as_point()
            .unwrap()
            .clone();
        let next_point = elem_buff[loc.next.adj_pt_idx as usize]
            .as_point()
            .unwrap()
            .clone();

        let (desc, new_results) = if loc.line_position == LinePosition::Leading {
            if elem_buff[loc.prev.newline_pt_idx as usize].num_newlines() != 0 {
                continue;
            }

            let pretty_name = loc.pretty_target_name();
            let desc = format!("The {pretty_name} should always start a new line.");

            let (new_results, prev_point) = prev_point.indent_to(
                tables,
                next_point.get_indent().as_deref().unwrap_or_default(),
                None,
                elem_buff[loc.prev.adj_pt_idx as usize + 1]
                    .segments()
                    .first()
                    .cloned(),
                None,
                None,
            );
            let (new_results, next_point) = next_point.respace_point(
                tables,
                elem_buff[loc.next.adj_pt_idx as usize - 1].as_block(),
                elem_buff[loc.next.adj_pt_idx as usize + 1].as_block(),
                root_segment,
                new_results,
                true,
                "before",
            );

            elem_buff[loc.prev.adj_pt_idx as usize] = prev_point.into();
            elem_buff[loc.next.adj_pt_idx as usize] = next_point.into();

            (desc, new_results)
        } else if loc.line_position == LinePosition::Trailing {
            if elem_buff[loc.next.newline_pt_idx as usize].num_newlines() != 0 {
                continue;
            }

            let pretty_name = loc.pretty_target_name();
            let desc = format!("The {pretty_name} should always be at the end of a line.");

            let (new_results, next_point) = next_point.indent_to(
                tables,
                prev_point.get_indent().as_deref().unwrap_or_default(),
                Some(
                    elem_buff[loc.next.adj_pt_idx as usize - 1]
                        .segments()
                        .last()
                        .cloned()
                        .unwrap(),
                ),
                None,
                None,
                None,
            );
            let (new_results, prev_point) = prev_point.respace_point(
                tables,
                elem_buff[loc.prev.adj_pt_idx as usize - 1].as_block(),
                elem_buff[loc.prev.adj_pt_idx as usize + 1].as_block(),
                root_segment,
                new_results,
                true,
                "before",
            );

            elem_buff[loc.prev.adj_pt_idx as usize] = prev_point.into();
            elem_buff[loc.next.adj_pt_idx as usize] = next_point.into();

            (desc, new_results)
        } else if loc.line_position == LinePosition::Alone {
            let pretty_name = loc.pretty_target_name();
            let desc =
                format!("The {pretty_name} should always have a line break both before and after.");
            let mut new_results = Vec::new();

            if elem_buff[loc.next.newline_pt_idx as usize].num_newlines() == 0 {
                let (results, next_point) = next_point.indent_to(
                    tables,
                    prev_point.get_indent().as_deref().unwrap_or_default(),
                    Some(
                        elem_buff[loc.next.adj_pt_idx as usize - 1]
                            .segments()
                            .last()
                            .cloned()
                            .unwrap(),
                    ),
                    None,
                    None,
                    None,
                );
                new_results = results;
                elem_buff[loc.next.adj_pt_idx as usize] = next_point.into();
            }

            if elem_buff[loc.prev.adj_pt_idx as usize].num_newlines() == 0 {
                let (results, prev_point) = prev_point.indent_to(
                    tables,
                    next_point.get_indent().as_deref().unwrap_or_default(),
                    None,
                    elem_buff[loc.prev.adj_pt_idx as usize + 1]
                        .segments()
                        .first()
                        .cloned(),
                    None,
                    None,
                );
                new_results = results;
                elem_buff[loc.prev.adj_pt_idx as usize] = prev_point.into();
            }

            (desc, new_results)
        } else {
            unimplemented!(
                "Unexpected line_position config: {}",
                loc.line_position.as_ref()
            )
        };

        let fixes = fixes_from_results(new_results.into_iter())
            .chain(std::mem::take(&mut fixes))
            .collect();
        lint_results.push(LintResult::new(
            loc.target.clone().into(),
            fixes,
            Some(desc),
            None,
        ));
    }

    (elem_buff, lint_results)
}

fn rearrange_and_insert(
    elem_buff: &mut Vec<ReflowElement>,
    loc: &RebreakLocation,
    new_point: ReflowPoint,
) {
    let mut new_buff = Vec::with_capacity(elem_buff.len() + 1);

    // First segment: up to loc.prev.adj_pt_idx (exclusive)
    new_buff.extend_from_slice(&elem_buff[..loc.prev.adj_pt_idx as usize]);

    // Second segment: loc.next.adj_pt_idx to loc.next.pre_code_pt_idx (inclusive)
    new_buff.extend_from_slice(
        &elem_buff[loc.next.adj_pt_idx as usize..=loc.next.pre_code_pt_idx as usize],
    );

    // Third segment: loc.prev.adj_pt_idx + 1 to loc.next.adj_pt_idx (exclusive, the
    // target)
    if loc.prev.adj_pt_idx + 1 < loc.next.adj_pt_idx {
        new_buff.extend_from_slice(
            &elem_buff[loc.prev.adj_pt_idx as usize + 1..loc.next.adj_pt_idx as usize],
        );
    }

    // Insert new_point here
    new_buff.push(new_point.into());

    // Last segment: after loc.next.pre_code_pt_idx
    if loc.next.pre_code_pt_idx as usize + 1 < elem_buff.len() {
        new_buff.extend_from_slice(&elem_buff[loc.next.pre_code_pt_idx as usize + 1..]);
    }

    // Replace old buffer with the new one
    *elem_buff = new_buff;
}

fn reorder_and_insert(
    elem_buff: &mut Vec<ReflowElement>,
    loc: &RebreakLocation,
    new_point: ReflowPoint,
) {
    let mut new_buff = Vec::with_capacity(elem_buff.len() + 1);

    // First segment: up to loc.prev.pre_code_pt_idx (exclusive)
    new_buff.extend_from_slice(&elem_buff[..loc.prev.pre_code_pt_idx as usize]);

    // Insert new_point here
    new_buff.push(new_point.into());

    // Second segment: loc.prev.adj_pt_idx + 1 to loc.next.adj_pt_idx (exclusive,
    // the target)
    if loc.prev.adj_pt_idx + 1 < loc.next.adj_pt_idx {
        new_buff.extend_from_slice(
            &elem_buff[loc.prev.adj_pt_idx as usize + 1..loc.next.adj_pt_idx as usize],
        );
    }

    // Third segment: loc.prev.pre_code_pt_idx to loc.prev.adj_pt_idx + 1
    // (inclusive)
    new_buff.extend_from_slice(
        &elem_buff[loc.prev.pre_code_pt_idx as usize..=loc.prev.adj_pt_idx as usize],
    );

    // Last segment: after loc.next.adj_pt_idx
    if loc.next.adj_pt_idx as usize + 1 < elem_buff.len() {
        new_buff.extend_from_slice(&elem_buff[loc.next.adj_pt_idx as usize + 1..]);
    }

    // Replace old buffer with the new one
    *elem_buff = new_buff;
}

#[cfg(test)]
mod tests {
    use sqruff_lib::core::test_functions::parse_ansi_string;
    use sqruff_lib_core::helpers::enter_panic;
    use sqruff_lib_core::parser::segments::Tables;

    use crate::utils::reflow::sequence::{RebreakType, ReflowSequence, TargetSide};

    #[test]
    fn test_reflow_sequence_rebreak_root() {
        let cases = [
            // Trivial Case
            ("select 1", "select 1"),
            // These rely on the default config being for leading operators
            ("select 1\n+2", "select 1\n+2"),
            ("select 1+\n2", "select 1\n+ 2"), // NOTE: Implicit respace.
            ("select\n  1 +\n  2", "select\n  1\n  + 2"),
            (
                "select\n  1 +\n  -- comment\n  2",
                "select\n  1\n  -- comment\n  + 2",
            ),
            // These rely on the default config being for trailing commas
            ("select a,b", "select a,b"),
            ("select a\n,b", "select a,\nb"),
            ("select\n  a\n  , b", "select\n  a,\n  b"),
            ("select\n    a\n    , b", "select\n    a,\n    b"),
            ("select\n  a\n    , b", "select\n  a,\n    b"),
            (
                "select\n  a\n  -- comment\n  , b",
                "select\n  a,\n  -- comment\n  b",
            ),
        ];

        let tables = Tables::default();
        for (raw_sql_in, raw_sql_out) in cases {
            let _panic = enter_panic(format!("{raw_sql_in:?}"));

            let root = parse_ansi_string(raw_sql_in);
            let config = <_>::default();
            let seq = ReflowSequence::from_root(&root, &config);
            let new_seq = seq.rebreak(&tables, RebreakType::Lines);

            assert_eq!(new_seq.raw(), raw_sql_out);
        }
    }

    #[test]
    fn test_reflow_sequence_rebreak_target() {
        let cases = [
            ("select 1+\n(2+3)", 4, "1+\n(", "1\n+ ("),
            ("select a,\n(b+c)", 4, "a,\n(", "a,\n("),
            ("select a\n  , (b+c)", 6, "a\n  , (", "a,\n  ("),
            // Here we don't have enough context to rebreak it so
            // it should be left unaltered.
            ("select a,\n(b+c)", 6, ",\n(b", ",\n(b"),
            // This intentionally targets an incomplete span.
            ("select a<=b", 4, "a<=", "a<="),
        ];

        let tables = Tables::default();
        for (raw_sql_in, target_idx, seq_sql_in, seq_sql_out) in cases {
            let root = parse_ansi_string(raw_sql_in);
            let target = &root.get_raw_segments()[target_idx];
            let config = <_>::default();
            let seq = ReflowSequence::from_around_target(target, &root, TargetSide::Both, &config);

            assert_eq!(seq.raw(), seq_sql_in);

            let new_seq = seq.rebreak(&tables, RebreakType::Lines);
            assert_eq!(new_seq.raw(), seq_sql_out);
        }
    }
}