Skip to main content

squawk_ide/
expand_selection.rs

1// via https://github.com/rust-lang/rust-analyzer/blob/8d75311400a108d7ffe17dc9c38182c566952e6e/crates/ide/src/extend_selection.rs#L1C1-L1C1
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27// NOTE: this is pretty much copied as is from rust analyzer with some
28// simplifications. I imagine there's more we can do to adapt it for SQL.
29
30use rowan::{Direction, NodeOrToken, TextRange, TextSize};
31use squawk_line_index::find_newline;
32use squawk_syntax::{
33    SyntaxKind, SyntaxNode, SyntaxToken,
34    ast::{self, AstToken},
35};
36
37use crate::tokens::is_string_or_comment;
38
39const DELIMITED_LIST_KINDS: &[SyntaxKind] = &[
40    SyntaxKind::ALTER_OPTION_LIST,
41    SyntaxKind::ALTER_TYPE_ATTRIBUTE_ACTION_LIST,
42    SyntaxKind::ARG_LIST,
43    SyntaxKind::ATTRIBUTE_LIST,
44    SyntaxKind::BEGIN_FUNC_OPTION_LIST,
45    SyntaxKind::CHECKPOINT_OPTION_LIST,
46    SyntaxKind::COLUMN_DEF_LIST,
47    SyntaxKind::COLUMN_LIST,
48    SyntaxKind::COLUMN_REF_LIST,
49    SyntaxKind::COLUMN_TARGET_LIST,
50    SyntaxKind::COMPOSITE_FIELD_LIST,
51    SyntaxKind::CONFLICT_INDEX_ITEM_LIST,
52    SyntaxKind::CONSTRAINT_COLUMN_REF_LIST,
53    SyntaxKind::CONSTRAINT_EXCLUSION_LIST,
54    SyntaxKind::COPY_OPTION_LIST,
55    SyntaxKind::DROP_OP_CLASS_OPTION_LIST,
56    SyntaxKind::EXPLAIN_OPTION_LIST,
57    SyntaxKind::FDW_OPTION_LIST,
58    SyntaxKind::FOREIGN_KEY_COLUMN_LIST,
59    SyntaxKind::FUNCTION_SIG_LIST,
60    SyntaxKind::PROCEDURE_SIG_LIST,
61    SyntaxKind::ROUTINE_SIG_LIST,
62    SyntaxKind::GRANT_ROLE_OPTION_LIST,
63    SyntaxKind::GROUP_BY_LIST,
64    SyntaxKind::JSON_TABLE_COLUMN_LIST,
65    SyntaxKind::OPERATOR_CLASS_OPTION_LIST,
66    SyntaxKind::OPTION_ALTER_OPTION_LIST,
67    SyntaxKind::OPTION_ITEM_LIST,
68    SyntaxKind::OP_SIG_LIST,
69    SyntaxKind::OVERLAY_EXPRS,
70    SyntaxKind::PARAM_LIST,
71    SyntaxKind::PARTITION_ITEM_LIST,
72    SyntaxKind::PARTITION_LIST,
73    SyntaxKind::TABLE_NAME_REF_LIST,
74    SyntaxKind::REINDEX_OPTION_LIST,
75    SyntaxKind::RELATION_LIST,
76    SyntaxKind::RETURNING_OPTION_LIST,
77    SyntaxKind::REVOKE_COMMAND_LIST,
78    SyntaxKind::ROLE_REF_LIST,
79    SyntaxKind::ROW_LIST,
80    SyntaxKind::RULE_STMT_LIST,
81    SyntaxKind::EXPR_AS_COLUMN_NAME_LIST,
82    SyntaxKind::EXPR_AS_ELEMENT_TAG_LIST,
83    SyntaxKind::EXPR_AS_PROPERTY_NAME_LIST,
84    SyntaxKind::EXPR_AS_XML_ATTR_LIST,
85    SyntaxKind::XML_NAMESPACE_LIST,
86    SyntaxKind::SET_COLUMN_LIST,
87    SyntaxKind::SET_EXPR_LIST,
88    SyntaxKind::SET_OPTIONS_LIST,
89    SyntaxKind::SET_ALL_PUBLICATION_OBJECT_LIST,
90    SyntaxKind::SORT_BY_LIST,
91    SyntaxKind::TABLE_AND_COLUMNS_LIST,
92    SyntaxKind::TABLE_ARG_LIST,
93    SyntaxKind::TABLE_LIST,
94    SyntaxKind::TARGET_LIST,
95    SyntaxKind::TRANSACTION_MODE_LIST,
96    SyntaxKind::VACUUM_OPTION_LIST,
97    SyntaxKind::VARIANT_LIST,
98    SyntaxKind::XML_TABLE_COLUMN_LIST,
99    SyntaxKind::PATH_PATTERN_LIST,
100];
101
102pub fn extend_selection(root: &SyntaxNode, range: TextRange) -> TextRange {
103    try_extend_selection(root, range).unwrap_or(range)
104}
105
106fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange> {
107    if range.is_empty() {
108        let offset = range.start();
109        let mut leaves = root.token_at_offset(offset);
110        // Make sure that if we're on the whitespace at the start of a line, we
111        // expand to the node on that line instead of the previous one
112        if leaves.clone().all(|it| it.kind() == SyntaxKind::WHITESPACE) {
113            return Some(extend_ws(root, leaves.next()?, offset));
114        }
115        let leaf_range = match root.token_at_offset(offset) {
116            rowan::TokenAtOffset::None => return None,
117            rowan::TokenAtOffset::Single(l) => {
118                if is_string_or_comment(l.kind()) {
119                    extend_single_word_in_comment_or_string(&l, offset)
120                        .unwrap_or_else(|| l.text_range())
121                } else {
122                    l.text_range()
123                }
124            }
125            rowan::TokenAtOffset::Between(l, r) => pick_best(l, r).text_range(),
126        };
127        return Some(leaf_range);
128    }
129
130    let node = match root.covering_element(range) {
131        NodeOrToken::Token(token) => {
132            if token.text_range() != range {
133                return Some(token.text_range());
134            }
135            if let Some(comment) = ast::Comment::cast(token.clone())
136                && let Some(range) = extend_comments(comment)
137            {
138                return Some(range);
139            }
140            token.parent()?
141        }
142        NodeOrToken::Node(node) => node,
143    };
144
145    if node.text_range() != range {
146        return Some(node.text_range());
147    }
148
149    let node = shallowest_node(&node);
150
151    if node
152        .parent()
153        .is_some_and(|n| DELIMITED_LIST_KINDS.contains(&n.kind()))
154    {
155        if let Some(range) = extend_list_item(&node) {
156            return Some(range);
157        }
158    }
159
160    node.parent().map(|it| it.text_range())
161}
162
163/// Find the shallowest node with same range, which allows us to traverse siblings.
164fn shallowest_node(node: &SyntaxNode) -> SyntaxNode {
165    node.ancestors()
166        .take_while(|n| n.text_range() == node.text_range())
167        .last()
168        .unwrap()
169}
170
171/// Expand to the current word instead the full text range of the node.
172fn extend_single_word_in_comment_or_string(
173    leaf: &SyntaxToken,
174    offset: TextSize,
175) -> Option<TextRange> {
176    let text: &str = leaf.text();
177    let cursor_position: u32 = (offset - leaf.text_range().start()).into();
178
179    let (before, after) = text.split_at(cursor_position as usize);
180
181    fn non_word_char(c: char) -> bool {
182        !(c.is_alphanumeric() || c == '_')
183    }
184
185    let start_idx = before.rfind(non_word_char)? as u32;
186    let end_idx = after.find(non_word_char).unwrap_or(after.len()) as u32;
187
188    // FIXME: use `ceil_char_boundary` from `std::str` when it gets stable
189    // https://github.com/rust-lang/rust/issues/93743
190    fn ceil_char_boundary(text: &str, index: u32) -> u32 {
191        (index..)
192            .find(|&index| text.is_char_boundary(index as usize))
193            .unwrap_or(text.len() as u32)
194    }
195
196    let from: TextSize = ceil_char_boundary(text, start_idx + 1).into();
197    let to: TextSize = (cursor_position + end_idx).into();
198
199    let range = TextRange::new(from, to);
200    if range.is_empty() {
201        None
202    } else {
203        Some(range + leaf.text_range().start())
204    }
205}
206
207fn extend_comments(comment: ast::Comment) -> Option<TextRange> {
208    let prev = adj_comments(&comment, Direction::Prev);
209    let next = adj_comments(&comment, Direction::Next);
210    if prev != next {
211        Some(TextRange::new(
212            prev.syntax().text_range().start(),
213            next.syntax().text_range().end(),
214        ))
215    } else {
216        None
217    }
218}
219
220fn adj_comments(comment: &ast::Comment, dir: Direction) -> ast::Comment {
221    let mut res = comment.clone();
222    for element in comment.syntax().siblings_with_tokens(dir) {
223        let Some(token) = element.as_token() else {
224            break;
225        };
226        if let Some(c) = ast::Comment::cast(token.clone()) {
227            res = c
228        } else if let Some(ws) = ast::Whitespace::cast(token.clone()) {
229            if ws.spans_multiple_lines() {
230                break;
231            }
232        } else {
233            break;
234        }
235    }
236    res
237}
238
239fn extend_ws(root: &SyntaxNode, ws: SyntaxToken, offset: TextSize) -> TextRange {
240    let ws_text = ws.text();
241    let suffix = TextRange::new(offset, ws.text_range().end()) - ws.text_range().start();
242    let prefix = TextRange::new(ws.text_range().start(), offset) - ws.text_range().start();
243    let ws_suffix = &ws_text[suffix];
244    let ws_prefix = &ws_text[prefix];
245    if find_newline(ws_text).is_some()
246        && find_newline(ws_suffix).is_none()
247        && let Some(node) = ws.next_sibling_or_token()
248    {
249        let start = match last_newline_end(ws_prefix) {
250            Some(idx) => ws.text_range().start() + TextSize::from(idx as u32),
251            None => node.text_range().start(),
252        };
253        let node_end = node.text_range().end();
254        let line_ending_len = match root.text().char_at(node_end) {
255            Some('\r') if root.text().char_at(node_end + TextSize::of('\r')) == Some('\n') => {
256                TextSize::of("\r\n")
257            }
258            Some('\n' | '\r') => TextSize::of('\n'),
259            _ => TextSize::default(),
260        };
261        return TextRange::new(start, node_end + line_ending_len);
262    }
263    ws.text_range()
264}
265
266fn last_newline_end(text: &str) -> Option<usize> {
267    let mut rest = text;
268    let mut offset = 0;
269    let mut last = None;
270
271    while let Some((idx, line_ending)) = find_newline(rest) {
272        offset += idx + line_ending.as_str().len();
273        last = Some(offset);
274        rest = &text[offset..];
275    }
276
277    last
278}
279
280fn pick_best(l: SyntaxToken, r: SyntaxToken) -> SyntaxToken {
281    return if priority(&r) > priority(&l) { r } else { l };
282    fn priority(n: &SyntaxToken) -> usize {
283        match n.kind() {
284            SyntaxKind::WHITESPACE => 0,
285            // TODO: we can probably include more here, rust analyzer includes a
286            // handful of keywords
287            SyntaxKind::IDENT => 2,
288            _ => 1,
289        }
290    }
291}
292
293/// Extend list item selection to include nearby delimiter and whitespace.
294fn extend_list_item(node: &SyntaxNode) -> Option<TextRange> {
295    fn is_single_line_ws(node: &SyntaxToken) -> bool {
296        node.kind() == SyntaxKind::WHITESPACE && find_newline(node.text()).is_none()
297    }
298
299    fn nearby_comma(node: &SyntaxNode, dir: Direction) -> Option<SyntaxToken> {
300        node.siblings_with_tokens(dir)
301            .skip(1)
302            .find(|node| match node {
303                NodeOrToken::Node(_) => true,
304                NodeOrToken::Token(it) => !is_single_line_ws(it),
305            })
306            .and_then(|it| it.into_token())
307            .filter(|node| node.kind() == SyntaxKind::COMMA)
308    }
309
310    if let Some(comma) = nearby_comma(node, Direction::Next) {
311        // Include any following whitespace when delimiter is after list item.
312        let final_node = comma
313            .next_sibling_or_token()
314            .and_then(|n| n.into_token())
315            .filter(is_single_line_ws)
316            .unwrap_or(comma);
317
318        return Some(TextRange::new(
319            node.text_range().start(),
320            final_node.text_range().end(),
321        ));
322    }
323
324    if let Some(comma) = nearby_comma(node, Direction::Prev) {
325        return Some(TextRange::new(
326            comma.text_range().start(),
327            node.text_range().end(),
328        ));
329    }
330
331    None
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use crate::test_utils::Fixture;
338    use insta::assert_debug_snapshot;
339    use squawk_syntax::ast::AstNode;
340
341    #[must_use]
342    fn expand(sql: &str) -> Vec<String> {
343        let fixture = Fixture::new(sql);
344        let offset = fixture.marker().offset();
345        let sql = offset.file_id.content(fixture.db()).clone();
346        let tree = crate::db::parse(fixture.db(), offset.file_id).tree();
347        let root = tree.syntax();
348
349        let mut range = TextRange::empty(offset.value);
350        let mut results = vec![];
351
352        for _ in 0..20 {
353            let new_range = extend_selection(root, range);
354            if new_range == range {
355                break;
356            }
357            range = new_range;
358            results.push(sql[range].to_string());
359        }
360
361        results
362    }
363
364    #[test]
365    fn simple() {
366        assert_debug_snapshot!(expand(r#"select $01 + 1"#), @r#"
367        [
368            "1",
369            "1 + 1",
370            "select 1 + 1",
371        ]
372        "#);
373    }
374
375    #[test]
376    fn word_in_string_string() {
377        assert_debug_snapshot!(expand(r"
378select 'some stret$0ched out words in a string'
379"), @r#"
380        [
381            "stretched",
382            "'some stretched out words in a string'",
383            "select 'some stretched out words in a string'",
384            "\nselect 'some stretched out words in a string'\n",
385        ]
386        "#);
387    }
388
389    #[test]
390    fn string() {
391        assert_debug_snapshot!(expand(r"
392select e'foo$0 bar'
393'buzz';
394"), @r#"
395        [
396            "foo",
397            "e'foo bar'",
398            "e'foo bar'\n'buzz'",
399            "select e'foo bar'\n'buzz'",
400            "select e'foo bar'\n'buzz';",
401            "\nselect e'foo bar'\n'buzz';\n",
402        ]
403        "#);
404    }
405
406    #[test]
407    fn dollar_string() {
408        assert_debug_snapshot!(expand(r"
409select $$foo$0 bar$$;
410"), @r#"
411        [
412            "foo",
413            "$$foo bar$$",
414            "select $$foo bar$$",
415            "select $$foo bar$$;",
416            "\nselect $$foo bar$$;\n",
417        ]
418        "#);
419    }
420
421    #[test]
422    fn comment_muli_line() {
423        assert_debug_snapshot!(expand(r"
424-- foo bar
425-- buzz$0
426-- boo
427select 1
428"), @r#"
429        [
430            "-- buzz",
431            "-- foo bar\n-- buzz\n-- boo",
432            "\n-- foo bar\n-- buzz\n-- boo\nselect 1\n",
433        ]
434        "#);
435    }
436
437    #[test]
438    fn comments_separated_by_cr_blank_line() {
439        assert_debug_snapshot!(expand("-- first\r\r-- sec$0ond\rselect 1;"), @r#"
440        [
441            "second",
442            "-- second",
443            "-- first\r\r-- second\rselect 1;",
444        ]
445        "#);
446    }
447
448    #[test]
449    fn comment() {
450        assert_debug_snapshot!(expand(r"
451-- foo bar$0
452select 1
453"), @r#"
454        [
455            "-- foo bar",
456            "\n-- foo bar\nselect 1\n",
457        ]
458        "#);
459
460        assert_debug_snapshot!(expand(r"
461/* foo bar$0 */
462select 1
463"), @r#"
464        [
465            "bar",
466            "/* foo bar */",
467            "\n/* foo bar */\nselect 1\n",
468        ]
469        "#);
470    }
471
472    #[test]
473    fn create_table_with_comment() {
474        assert_debug_snapshot!(expand(r"
475-- foo bar buzz
476create table t(
477  x int$0,
478  y text
479);
480"), @r#"
481        [
482            "int",
483            "x int",
484            "x int,",
485            "(\n  x int,\n  y text\n)",
486            "create table t(\n  x int,\n  y text\n);",
487            "\n-- foo bar buzz\ncreate table t(\n  x int,\n  y text\n);\n",
488        ]
489        "#);
490    }
491
492    #[test]
493    fn column_list() {
494        assert_debug_snapshot!(expand(r#"create table t($0x int)"#), @r#"
495        [
496            "x",
497            "x int",
498            "(x int)",
499            "create table t(x int)",
500        ]
501        "#);
502
503        assert_debug_snapshot!(expand(r#"create table t($0x int, y int)"#), @r#"
504        [
505            "x",
506            "x int",
507            "x int, ",
508            "(x int, y int)",
509            "create table t(x int, y int)",
510        ]
511        "#);
512
513        assert_debug_snapshot!(expand(r#"create table t(x int, $0y int)"#), @r#"
514        [
515            "y",
516            "y int",
517            ", y int",
518            "(x int, y int)",
519            "create table t(x int, y int)",
520        ]
521        "#);
522    }
523
524    #[test]
525    fn start_of_line_whitespace_select() {
526        assert_debug_snapshot!(expand(r#"    
527select 1;
528
529$0    select 2;"#), @r#"
530        [
531            "    select 2;",
532            "    \nselect 1;\n\n    select 2;",
533        ]
534        "#);
535    }
536
537    #[test]
538    fn start_of_line_whitespace_select_with_cr_line_endings() {
539        assert_debug_snapshot!(expand("select 1;\r$0    select 2;"), @r#"
540        [
541            "    select 2;",
542            "select 1;\r    select 2;",
543        ]
544        "#);
545    }
546
547    #[test]
548    fn select_list() {
549        assert_debug_snapshot!(expand(r#"select x$0, y from t"#), @r#"
550        [
551            "x",
552            "x, ",
553            "x, y",
554            "select x, y",
555            "select x, y from t",
556        ]
557        "#);
558
559        assert_debug_snapshot!(expand(r#"select x, y$0 from t"#), @r#"
560        [
561            "y",
562            ", y",
563            "x, y",
564            "select x, y",
565            "select x, y from t",
566        ]
567        "#);
568    }
569
570    #[test]
571    fn expand_whitespace() {
572        assert_debug_snapshot!(expand(r#"select 1 + 
573$0
5741;"#), @r#"
575        [
576            " \n\n",
577            "1 + \n\n1",
578            "select 1 + \n\n1",
579            "select 1 + \n\n1;",
580        ]
581        "#);
582    }
583
584    #[test]
585    fn function_args() {
586        assert_debug_snapshot!(expand(r#"select f(1$0, 2)"#), @r#"
587        [
588            "1",
589            "1, ",
590            "(1, 2)",
591            "f(1, 2)",
592            "select f(1, 2)",
593        ]
594        "#);
595    }
596
597    #[test]
598    fn prefer_idents() {
599        assert_debug_snapshot!(expand(r#"select foo$0+bar"#), @r#"
600        [
601            "foo",
602            "foo+bar",
603            "select foo+bar",
604        ]
605        "#);
606
607        assert_debug_snapshot!(expand(r#"select foo+$0bar"#), @r#"
608        [
609            "bar",
610            "foo+bar",
611            "select foo+bar",
612        ]
613        "#);
614    }
615
616    #[test]
617    fn list_variants() {
618        let delimited_ws_list_kinds = &[
619            SyntaxKind::DATABASE_OPTION_LIST,
620            SyntaxKind::FUNC_OPTION_LIST,
621            SyntaxKind::ROLE_OPTION_LIST,
622            SyntaxKind::SEQUENCE_OPTION_LIST,
623            SyntaxKind::TRIGGER_EVENT_LIST,
624            SyntaxKind::XML_COLUMN_OPTION_LIST,
625            SyntaxKind::WHEN_CLAUSE_LIST,
626            SyntaxKind::LABEL_AND_PROPERTIES_LIST,
627        ];
628
629        let unhandled_list_kinds = (0..SyntaxKind::__LAST as u16)
630            .map(SyntaxKind::from)
631            .filter(|kind| {
632                format!("{kind:?}").ends_with("_LIST") && !delimited_ws_list_kinds.contains(kind)
633            })
634            .filter(|kind| !DELIMITED_LIST_KINDS.contains(kind))
635            .collect::<Vec<_>>();
636
637        assert_eq!(
638            unhandled_list_kinds,
639            vec![],
640            "We shouldn't have any unhandled list kinds"
641        )
642    }
643}