sqruff_lib/utils/reflow/
rebreak.rs

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
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::base::{ErasedSegment, Tables};
use strum_macros::{AsRefStr, EnumString};

use super::elements::{ReflowElement, ReflowSequenceType};
use crate::core::rules::base::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};

#[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)
        {
            if elements[newline_point_idx as usize]
                .class_types()
                .contains(SyntaxKind::Newline)
                || elements[(newline_point_idx + dir as isize) as usize]
                    .segments()
                    .iter()
                    .any(|seg| seg.is_code())
            {
                break;
            }
            newline_point_idx += 2 * dir as isize;
        }

        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)
        {
            if elements[(pre_code_point_idx + dir as isize) as usize]
                .segments()
                .iter()
                .any(|seg| seg.is_code())
            {
                break;
            }
            pre_code_point_idx += 2 * dir as isize;
        }

        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, 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 {
        format!("{} {}", self.target.get_type().as_str(), self.target.raw())
    }
}

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 line_position = original_line_position.first().unwrap();
            spans.push(RebreakSpan {
                target: elem.segments().first().cloned().unwrap(),
                start_idx: idx,
                end_idx: idx,
                line_position: *line_position,
                strict: original_line_position.last() == Some(&LinePosition::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 in idx..element_buffer.len() {
                let end_elem = &element_buffer[end_idx];
                let ReflowElement::Block(end_block) = end_elem else {
                    continue;
                };

                if !end_block.depth_info().stack_positions.contains_key(key) {
                    final_idx = (end_idx - 2).into();
                } else if matches!(
                    end_block.depth_info().stack_positions[key].type_,
                    Some(StackPositionType::End) | Some(StackPositionType::Solo)
                ) {
                    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_configs = block.line_position_configs()[key]
                        .split(':')
                        .next()
                        .unwrap();
                    let line_position = LinePosition::from_str(line_position_configs).unwrap();

                    spans.push(RebreakSpan {
                        target,
                        start_idx: idx,
                        end_idx: final_idx,
                        line_position,
                        strict: block.line_position_configs()[key].ends_with("strict"),
                    });

                    break;
                }
            }
        }
    }

    spans
}

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.clone());

    let mut locations = Vec::new();
    for span in spans {
        if let Some(loc) = RebreakLocation::from_span(span, &elements) {
            locations.push(loc);
        }
    }

    // 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 {}. Expected only leading near line breaks.",
                    pretty_name
                )
            };

            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) {
                        if 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 {}. Expected only trailing near line breaks.",
                    pretty_name
                )
            };

            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();

            if elem_buff[loc.next.newline_pt_idx as usize].num_newlines() == 0 {
                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 elem_buff[loc.prev.adj_pt_idx as usize].num_newlines() == 0 {
                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,
            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::base::Tables;

    use crate::utils::reflow::sequence::{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);

            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);
            assert_eq!(new_seq.raw(), seq_sql_out);
        }
    }
}