-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathcode_actions.rs
More file actions
2399 lines (2091 loc) Β· 66.9 KB
/
code_actions.rs
File metadata and controls
2399 lines (2091 loc) Β· 66.9 KB
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use itertools::Itertools;
use rowan::{TextRange, TextSize};
use squawk_linter::Edit;
use squawk_syntax::{
SyntaxKind, SyntaxToken,
ast::{self, AstNode},
};
use std::iter;
use crate::{
binder,
column_name::ColumnName,
offsets::token_from_offset,
quote::{quote_column_alias, unquote_ident},
symbols::Name,
};
#[derive(Debug, Clone)]
pub enum ActionKind {
QuickFix,
RefactorRewrite,
}
#[derive(Debug, Clone)]
pub struct CodeAction {
pub title: String,
pub edits: Vec<Edit>,
pub kind: ActionKind,
}
pub fn code_actions(file: ast::SourceFile, offset: TextSize) -> Option<Vec<CodeAction>> {
let mut actions = vec![];
rewrite_as_regular_string(&mut actions, &file, offset);
rewrite_as_dollar_quoted_string(&mut actions, &file, offset);
remove_else_clause(&mut actions, &file, offset);
rewrite_table_as_select(&mut actions, &file, offset);
rewrite_select_as_table(&mut actions, &file, offset);
rewrite_from(&mut actions, &file, offset);
rewrite_leading_from(&mut actions, &file, offset);
rewrite_values_as_select(&mut actions, &file, offset);
rewrite_select_as_values(&mut actions, &file, offset);
add_schema(&mut actions, &file, offset);
quote_identifier(&mut actions, &file, offset);
unquote_identifier(&mut actions, &file, offset);
add_explicit_alias(&mut actions, &file, offset);
remove_redundant_alias(&mut actions, &file, offset);
rewrite_cast_to_double_colon(&mut actions, &file, offset);
rewrite_double_colon_to_cast(&mut actions, &file, offset);
rewrite_between_as_binary_expression(&mut actions, &file, offset);
rewrite_timestamp_type(&mut actions, &file, offset);
Some(actions)
}
fn rewrite_as_regular_string(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let dollar_string = file
.syntax()
.token_at_offset(offset)
.find(|token| token.kind() == SyntaxKind::DOLLAR_QUOTED_STRING)?;
let replacement = dollar_quoted_to_string(dollar_string.text())?;
actions.push(CodeAction {
title: "Rewrite as regular string".to_owned(),
edits: vec![Edit::replace(dollar_string.text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_as_dollar_quoted_string(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let string = file
.syntax()
.token_at_offset(offset)
.find(|token| token.kind() == SyntaxKind::STRING)?;
let replacement = string_to_dollar_quoted(string.text())?;
actions.push(CodeAction {
title: "Rewrite as dollar-quoted string".to_owned(),
edits: vec![Edit::replace(string.text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn string_to_dollar_quoted(text: &str) -> Option<String> {
let normalized = normalize_single_quoted_string(text)?;
let delimiter = dollar_delimiter(&normalized)?;
let boundary = format!("${}$", delimiter);
Some(format!("{boundary}{normalized}{boundary}"))
}
fn dollar_quoted_to_string(text: &str) -> Option<String> {
debug_assert!(text.starts_with('$'));
let (delimiter, content) = split_dollar_quoted(text)?;
let boundary = format!("${}$", delimiter);
if !text.starts_with(&boundary) || !text.ends_with(&boundary) {
return None;
}
// quotes are escaped by using two of them in Postgres
let escaped = content.replace('\'', "''");
Some(format!("'{}'", escaped))
}
fn split_dollar_quoted(text: &str) -> Option<(String, &str)> {
debug_assert!(text.starts_with('$'));
let second_dollar = text[1..].find('$')?;
// the `foo` in `select $foo$bar$foo$`
let delimiter = &text[1..=second_dollar];
let boundary = format!("${}$", delimiter);
if !text.ends_with(&boundary) {
return None;
}
let start = boundary.len();
let end = text.len().checked_sub(boundary.len())?;
let content = text.get(start..end)?;
Some((delimiter.to_owned(), content))
}
fn normalize_single_quoted_string(text: &str) -> Option<String> {
let body = text.strip_prefix('\'')?.strip_suffix('\'')?;
return Some(body.replace("''", "'"));
}
fn dollar_delimiter(content: &str) -> Option<String> {
// We can't safely transform a trailing `$` i.e., `select 'foo $'` with an
// empty delim, because we'll `select $$foo $$$` which isn't valid.
if !content.contains("$$") && !content.ends_with('$') {
return Some("".to_owned());
}
let mut delim = "q".to_owned();
// don't want to just loop forever
for idx in 0..10 {
if !content.contains(&format!("${}$", delim)) {
return Some(delim);
}
delim.push_str(&idx.to_string());
}
None
}
fn remove_else_clause(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let else_token = file
.syntax()
.token_at_offset(offset)
.find(|x| x.kind() == SyntaxKind::ELSE_KW)?;
let parent = else_token.parent()?;
let else_clause = ast::ElseClause::cast(parent)?;
let mut edits = vec![];
edits.push(Edit::delete(else_clause.syntax().text_range()));
if let Some(token) = else_token.prev_token()
&& token.kind() == SyntaxKind::WHITESPACE
{
edits.push(Edit::delete(token.text_range()));
}
actions.push(CodeAction {
title: "Remove `else` clause".to_owned(),
edits,
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_table_as_select(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let table = token.parent_ancestors().find_map(ast::Table::cast)?;
let relation_name = table.relation_name()?;
let table_name = relation_name.syntax().text();
let replacement = format!("select * from {}", table_name);
actions.push(CodeAction {
title: "Rewrite as `select`".to_owned(),
edits: vec![Edit::replace(table.syntax().text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_select_as_table(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let select = token.parent_ancestors().find_map(ast::Select::cast)?;
if !can_transform_select_to_table(&select) {
return None;
}
let from_clause = select.from_clause()?;
let from_item = from_clause.from_items().next()?;
let table_name = if let Some(name_ref) = from_item.name_ref() {
name_ref.syntax().text().to_string()
} else if let Some(field_expr) = from_item.field_expr() {
field_expr.syntax().text().to_string()
} else {
return None;
};
let replacement = format!("table {}", table_name);
actions.push(CodeAction {
title: "Rewrite as `table`".to_owned(),
edits: vec![Edit::replace(select.syntax().text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_from(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let select = token.parent_ancestors().find_map(ast::Select::cast)?;
if select.select_clause().is_some() {
return None;
}
select.from_clause()?;
actions.push(CodeAction {
title: "Insert leading `select *`".to_owned(),
edits: vec![Edit::insert(
"select * ".to_owned(),
select.syntax().text_range().start(),
)],
kind: ActionKind::QuickFix,
});
Some(())
}
fn rewrite_leading_from(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let select = token.parent_ancestors().find_map(ast::Select::cast)?;
let from_clause = select.from_clause()?;
let select_clause = select.select_clause()?;
if from_clause.syntax().text_range().start() >= select_clause.syntax().text_range().start() {
return None;
}
let select_text = select_clause.syntax().text().to_string();
let mut delete_start = select_clause.syntax().text_range().start();
if let Some(prev) = select_clause.syntax().prev_sibling_or_token()
&& prev.kind() == SyntaxKind::WHITESPACE
{
delete_start = prev.text_range().start();
}
let select_with_ws = TextRange::new(delete_start, select_clause.syntax().text_range().end());
actions.push(CodeAction {
title: "Swap `from` and `select` clauses".to_owned(),
edits: vec![
Edit::delete(select_with_ws),
Edit::insert(
format!("{} ", select_text),
from_clause.syntax().text_range().start(),
),
],
kind: ActionKind::QuickFix,
});
Some(())
}
/// Returns true if a `select` statement can be safely rewritten as a `table` statement.
///
/// We can only do this when there are no clauses besides the `select` and
/// `from` clause. Additionally, we can only have a table reference in the
/// `from` clause.
/// The `select`'s target list must only be a `*`.
fn can_transform_select_to_table(select: &ast::Select) -> bool {
if select.with_clause().is_some()
|| select.where_clause().is_some()
|| select.group_by_clause().is_some()
|| select.having_clause().is_some()
|| select.window_clause().is_some()
|| select.order_by_clause().is_some()
|| select.limit_clause().is_some()
|| select.fetch_clause().is_some()
|| select.offset_clause().is_some()
|| select.filter_clause().is_some()
|| select.locking_clauses().next().is_some()
{
return false;
}
let Some(select_clause) = select.select_clause() else {
return false;
};
if select_clause.distinct_clause().is_some() {
return false;
}
let Some(target_list) = select_clause.target_list() else {
return false;
};
let mut targets = target_list.targets();
let Some(target) = targets.next() else {
return false;
};
if targets.next().is_some() {
return false;
}
// only want to support: `select *`
if target.expr().is_some() || target.star_token().is_none() {
return false;
}
let Some(from_clause) = select.from_clause() else {
return false;
};
let mut from_items = from_clause.from_items();
let Some(from_item) = from_items.next() else {
return false;
};
// only can have one from item & no join exprs
if from_items.next().is_some() || from_clause.join_exprs().next().is_some() {
return false;
}
if from_item.alias().is_some()
|| from_item.tablesample_clause().is_some()
|| from_item.only_token().is_some()
|| from_item.lateral_token().is_some()
|| from_item.star_token().is_some()
|| from_item.call_expr().is_some()
|| from_item.paren_select().is_some()
|| from_item.json_table().is_some()
|| from_item.xml_table().is_some()
|| from_item.cast_expr().is_some()
{
return false;
}
// only want table refs
from_item.name_ref().is_some() || from_item.field_expr().is_some()
}
fn quote_identifier(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let parent = token.parent()?;
let name_node = if let Some(name) = ast::Name::cast(parent.clone()) {
name.syntax().clone()
} else if let Some(name_ref) = ast::NameRef::cast(parent) {
name_ref.syntax().clone()
} else {
return None;
};
let text = name_node.text().to_string();
if text.starts_with('"') {
return None;
}
let quoted = format!(r#""{}""#, text.to_lowercase());
actions.push(CodeAction {
title: "Quote identifier".to_owned(),
edits: vec![Edit::replace(name_node.text_range(), quoted)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn unquote_identifier(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let parent = token.parent()?;
let name_node = if let Some(name) = ast::Name::cast(parent.clone()) {
name.syntax().clone()
} else if let Some(name_ref) = ast::NameRef::cast(parent) {
name_ref.syntax().clone()
} else {
return None;
};
let unquoted = unquote_ident(&name_node)?;
actions.push(CodeAction {
title: "Unquote identifier".to_owned(),
edits: vec![Edit::replace(name_node.text_range(), unquoted)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
// Postgres docs call these output names.
// Postgres' parser calls this a column label.
// Third-party docs call these aliases, so going with that.
fn add_explicit_alias(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let target = token.parent_ancestors().find_map(ast::Target::cast)?;
if target.as_name().is_some() {
return None;
}
if let Some(ast::Expr::FieldExpr(field_expr)) = target.expr()
&& field_expr.star_token().is_some()
{
return None;
}
let alias = ColumnName::from_target(target.clone()).and_then(|c| c.0.to_string())?;
let expr_end = target.expr().map(|e| e.syntax().text_range().end())?;
let quoted_alias = quote_column_alias(&alias);
// Postgres docs recommend either using `as` or quoting the name. I think
// `as` looks a bit nicer.
let replacement = format!(" as {}", quoted_alias);
actions.push(CodeAction {
title: "Add explicit alias".to_owned(),
edits: vec![Edit::insert(replacement, expr_end)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn remove_redundant_alias(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let target = token.parent_ancestors().find_map(ast::Target::cast)?;
let as_name = target.as_name()?;
let (inferred_column, _) = ColumnName::inferred_from_target(target.clone())?;
let inferred_column_alias = inferred_column.to_string()?;
let alias = as_name.name()?;
if Name::from_node(&alias) != Name::from_string(inferred_column_alias) {
return None;
}
// TODO:
// This lets use remove any whitespace so we don't end up with:
// select x as x, b from t;
// becoming
// select x , b from t;
// but we probably want a better way to express this.
// Maybe a "Remove preceding whitespace" style option for edits.
let expr_end = target.expr()?.syntax().text_range().end();
let alias_end = as_name.syntax().text_range().end();
actions.push(CodeAction {
title: "Remove redundant alias".to_owned(),
edits: vec![Edit::delete(TextRange::new(expr_end, alias_end))],
kind: ActionKind::QuickFix,
});
Some(())
}
fn add_schema(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let range = token.parent_ancestors().find_map(|node| {
if let Some(path) = ast::Path::cast(node.clone()) {
if path.qualifier().is_some() {
return None;
}
return Some(path.syntax().text_range());
}
if let Some(from_item) = ast::FromItem::cast(node.clone()) {
let name_ref = from_item.name_ref()?;
return Some(name_ref.syntax().text_range());
}
if let Some(call_expr) = ast::CallExpr::cast(node) {
let ast::Expr::NameRef(name_ref) = call_expr.expr()? else {
return None;
};
return Some(name_ref.syntax().text_range());
}
None
})?;
if !range.contains(offset) {
return None;
}
let position = token.text_range().start();
// TODO: we should salsa this
let binder = binder::bind(file);
// TODO: we don't need the search path at the current position, we need to
// lookup the definition of the item and see what the definition's search
// path is.
//
// It tries to rewrite:
// `select now()::timestamptz;` as
// `select now()::public.timestamptz;`
// instead of
// `select now()::pg_catalog.timestamptz;`
let schema = binder.search_path_at(position).first()?.to_string();
let replacement = format!("{}.", schema);
actions.push(CodeAction {
title: "Add schema".to_owned(),
edits: vec![Edit::insert(replacement, position)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_cast_to_double_colon(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let cast_expr = token.parent_ancestors().find_map(ast::CastExpr::cast)?;
if cast_expr.colon_colon().is_some() {
return None;
}
let expr = cast_expr.expr()?;
let ty = cast_expr.ty()?;
let expr_text = expr.syntax().text();
let type_text = ty.syntax().text();
let replacement = format!("{}::{}", expr_text, type_text);
actions.push(CodeAction {
title: "Rewrite as cast operator `::`".to_owned(),
edits: vec![Edit::replace(cast_expr.syntax().text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_double_colon_to_cast(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let cast_expr = token.parent_ancestors().find_map(ast::CastExpr::cast)?;
if cast_expr.cast_token().is_some() {
return None;
}
let expr = cast_expr.expr()?;
let ty = cast_expr.ty()?;
let expr_text = expr.syntax().text();
let type_text = ty.syntax().text();
let replacement = format!("cast({} as {})", expr_text, type_text);
actions.push(CodeAction {
title: "Rewrite as cast function `cast()`".to_owned(),
edits: vec![Edit::replace(cast_expr.syntax().text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_between_as_binary_expression(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let between_expr = token.parent_ancestors().find_map(ast::BetweenExpr::cast)?;
let target = between_expr.target()?;
let start = between_expr.start()?;
let end = between_expr.end()?;
let is_not = between_expr.not_token().is_some();
let is_symmetric = between_expr.symmetric_token().is_some();
let target_text = target.syntax().text();
let start_text = start.syntax().text();
let end_text = end.syntax().text();
let replacement = match (is_not, is_symmetric) {
(false, false) => {
format!("{target_text} >= {start_text} and {target_text} <= {end_text}")
}
(true, false) => {
format!("({target_text} < {start_text} or {target_text} > {end_text})")
}
(false, true) => format!(
"{target_text} >= least({start_text}, {end_text}) and {target_text} <= greatest({start_text}, {end_text})"
),
(true, true) => format!(
"({target_text} < least({start_text}, {end_text}) or {target_text} > greatest({start_text}, {end_text}))"
),
};
actions.push(CodeAction {
title: "Rewrite as binary expression".to_owned(),
edits: vec![Edit::replace(
between_expr.syntax().text_range(),
replacement,
)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_timestamp_type(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let time_type = token.parent_ancestors().find_map(ast::TimeType::cast)?;
let replacement = match time_type.timezone()? {
ast::Timezone::WithoutTimezone(_) => {
if time_type.timestamp_token().is_some() {
"timestamp"
} else {
"time"
}
}
ast::Timezone::WithTimezone(_) => {
if time_type.timestamp_token().is_some() {
"timestamptz"
} else {
"timetz"
}
}
};
actions.push(CodeAction {
title: format!("Rewrite as `{replacement}`"),
edits: vec![Edit::replace(time_type.syntax().text_range(), replacement)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn rewrite_values_as_select(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let values = token.parent_ancestors().find_map(ast::Values::cast)?;
let value_token_start = values.values_token().map(|x| x.text_range().start())?;
let values_end = values.syntax().text_range().end();
// `values` but we skip over the possibly preceeding CTE
let values_range = TextRange::new(value_token_start, values_end);
let mut rows = values.row_list()?.rows();
let first_targets: Vec<_> = rows
.next()?
.exprs()
.enumerate()
.map(|(idx, expr)| format!("{} as column{}", expr.syntax().text(), idx + 1))
.collect();
if first_targets.is_empty() {
return None;
}
let mut select_parts = vec![format!("select {}", first_targets.join(", "))];
for row in rows {
let row_targets = row
.exprs()
.map(|e| e.syntax().text().to_string())
.join(", ");
if row_targets.is_empty() {
return None;
}
select_parts.push(format!("union all\nselect {}", row_targets));
}
let select_stmt = select_parts.join("\n");
actions.push(CodeAction {
title: "Rewrite as `select`".to_owned(),
edits: vec![Edit::replace(values_range, select_stmt)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn is_values_row_column_name(target: &ast::Target, idx: usize) -> bool {
let Some(as_name) = target.as_name() else {
return false;
};
let Some(name) = as_name.name() else {
return false;
};
let expected = format!("column{}", idx + 1);
if Name::from_node(&name) != Name::from_string(expected) {
return false;
}
true
}
enum SelectContext {
Compound(ast::CompoundSelect),
Single(ast::Select),
}
impl SelectContext {
fn iter(&self) -> Option<Box<dyn Iterator<Item = ast::Select>>> {
// Ideally we'd have something like Python's `yield` and `yield from`
// but instead we have to do all of this to avoid creating some temp
// vecs
fn variant_iter(
variant: ast::SelectVariant,
) -> Option<Box<dyn Iterator<Item = ast::Select>>> {
match variant {
ast::SelectVariant::Select(select) => Some(Box::new(iter::once(select))),
ast::SelectVariant::CompoundSelect(compound) => compound_iter(&compound),
ast::SelectVariant::ParenSelect(_)
| ast::SelectVariant::SelectInto(_)
| ast::SelectVariant::Table(_)
| ast::SelectVariant::Values(_) => None,
}
}
fn compound_iter(
node: &ast::CompoundSelect,
) -> Option<Box<dyn Iterator<Item = ast::Select>>> {
let lhs_iter = node
.lhs()
.map(variant_iter)
.unwrap_or_else(|| Some(Box::new(iter::empty())))?;
let rhs_iter = node
.rhs()
.map(variant_iter)
.unwrap_or_else(|| Some(Box::new(iter::empty())))?;
Some(Box::new(lhs_iter.chain(rhs_iter)))
}
match self {
SelectContext::Compound(compound) => compound_iter(compound),
SelectContext::Single(select) => Some(Box::new(iter::once(select.clone()))),
}
}
}
fn rewrite_select_as_values(
actions: &mut Vec<CodeAction>,
file: &ast::SourceFile,
offset: TextSize,
) -> Option<()> {
let token = token_from_offset(file, offset)?;
let parent = find_select_parent(token)?;
let mut selects = parent.iter()?.peekable();
let select_token_start = selects
.peek()?
.select_clause()
.and_then(|x| x.select_token())
.map(|x| x.text_range().start())?;
let mut rows = vec![];
for (idx, select) in selects.enumerate() {
let exprs: Vec<String> = select
.select_clause()?
.target_list()?
.targets()
.enumerate()
.map(|(i, t)| {
if idx != 0 || is_values_row_column_name(&t, i) {
t.expr().map(|expr| expr.syntax().text().to_string())
} else {
None
}
})
.collect::<Option<_>>()?;
if exprs.is_empty() {
return None;
}
rows.push(format!("({})", exprs.join(", ")));
}
let values_stmt = format!("values {}", rows.join(", "));
let select_end = match &parent {
SelectContext::Compound(compound) => compound.syntax().text_range().end(),
SelectContext::Single(select) => select.syntax().text_range().end(),
};
let select_range = TextRange::new(select_token_start, select_end);
actions.push(CodeAction {
title: "Rewrite as `values`".to_owned(),
edits: vec![Edit::replace(select_range, values_stmt)],
kind: ActionKind::RefactorRewrite,
});
Some(())
}
fn find_select_parent(token: SyntaxToken) -> Option<SelectContext> {
let mut found_select = None;
let mut found_compound = None;
for node in token.parent_ancestors() {
if let Some(compound_select) = ast::CompoundSelect::cast(node.clone()) {
if compound_select.union_token().is_some() && compound_select.all_token().is_some() {
found_compound = Some(SelectContext::Compound(compound_select));
} else {
break;
}
}
if found_select.is_none()
&& let Some(select) = ast::Select::cast(node)
{
found_select = Some(SelectContext::Single(select));
}
}
found_compound.or(found_select)
}
#[cfg(test)]
mod test {
use super::*;
use crate::test_utils::fixture;
use insta::assert_snapshot;
use rowan::TextSize;
use squawk_syntax::ast;
fn apply_code_action(
f: impl Fn(&mut Vec<CodeAction>, &ast::SourceFile, TextSize) -> Option<()>,
sql: &str,
) -> String {
let (mut offset, sql) = fixture(sql);
let parse = ast::SourceFile::parse(&sql);
let file: ast::SourceFile = parse.tree();
offset = offset.checked_sub(1.into()).unwrap_or_default();
let mut actions = vec![];
f(&mut actions, &file, offset);
assert!(
!actions.is_empty(),
"We should always have actions for `apply_code_action`. If you want to ensure there are no actions, use `code_action_not_applicable` instead."
);
let action = &actions[0];
match action.kind {
ActionKind::QuickFix => {
// Quickfixes can fix syntax errors so we don't assert
}
ActionKind::RefactorRewrite => {
assert_eq!(parse.errors(), vec![]);
}
}
let mut result = sql.clone();
let mut edits = action.edits.clone();
edits.sort_by_key(|e| e.text_range.start());
check_overlap(&edits);
edits.reverse();
for edit in edits {
let start: usize = edit.text_range.start().into();
let end: usize = edit.text_range.end().into();
let replacement = edit.text.as_deref().unwrap_or("");
result.replace_range(start..end, replacement);
}
let reparse = ast::SourceFile::parse(&result);
match action.kind {
ActionKind::QuickFix => {
// Quickfixes can fix syntax errors so we don't assert
}
ActionKind::RefactorRewrite => {
assert_eq!(
reparse.errors(),
vec![],
"Code actions shouldn't cause syntax errors"
);
}
}
result
}
// There's an invariant where the edits can't overlap.
// For example, if we have an edit that deletes the full `else clause` and
// another edit that deletes the `else` keyword and they overlap, then
// vscode doesn't surface the code action.
fn check_overlap(edits: &[Edit]) {
for (edit_i, edit_j) in edits.iter().zip(edits.iter().skip(1)) {
if let Some(intersection) = edit_i.text_range.intersect(edit_j.text_range) {
assert!(
intersection.is_empty(),
"Edit ranges must not overlap: {:?} and {:?} intersect at {:?}",
edit_i.text_range,
edit_j.text_range,
intersection
);
}
}
}
fn code_action_not_applicable_(
f: impl Fn(&mut Vec<CodeAction>, &ast::SourceFile, TextSize) -> Option<()>,
sql: &str,
allow_errors: bool,
) -> bool {
let (offset, sql) = fixture(sql);
let parse = ast::SourceFile::parse(&sql);
if !allow_errors {
assert_eq!(parse.errors(), vec![]);
}
let file: ast::SourceFile = parse.tree();
let mut actions = vec![];
f(&mut actions, &file, offset);
actions.is_empty()
}