Skip to main content

dsl_completion/
context.rs

1//! Detect what kinds of completion items make sense at the cursor.
2//!
3//! Token-only classifier: reads the text to the left of the cursor and
4//! recognises the high-value cases. Doesn't depend on the parser
5//! succeeding so we keep working on half-written SQL.
6//!
7//! | Cursor position             | Context        |
8//! |-----------------------------|----------------|
9//! | `<alias>.<partial>`         | `DotOf`        |
10//! | after FROM / JOIN / INTO / UPDATE / ALTER TABLE | `Table` |
11//! | after ON / WHERE / HAVING / AND / OR  | `Predicate` (columns + funcs + keywords) |
12//! | start of statement          | `Statement` (keywords-focused) |
13//! | inside SELECT list (after SELECT, before FROM) | `Projection` (columns of FROM + funcs) |
14//! | anywhere else               | `General` (everything merged) |
15
16use text_size::TextSize;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Context {
20  DotOf {
21    alias: String,
22  },
23  Table,
24  Projection,
25  Predicate,
26  Statement,
27  /// Cursor sits after `ALTER TABLE <name> ` -- expects a sub-action
28  /// (ADD COLUMN, DROP COLUMN, RENAME, ALTER COLUMN, ...). The table
29  /// name has already been chosen; the user is picking the operation.
30  AlterTableAction,
31  General,
32}
33
34pub fn detect(source: &str, offset: TextSize) -> Context {
35  let pos: usize = offset.into();
36  let before = &source[..pos.min(source.len())];
37
38  if let Some(ctx) = dot_context(before) {
39    return ctx;
40  }
41  // Match before the broader ALTER TABLE -> Table rule so the sub-
42  // action context wins once a table name has been typed.
43  if after_alter_table_name(before) {
44    return Context::AlterTableAction;
45  }
46  if is_after_keyword(before, &["FROM", "JOIN", "INTO", "UPDATE", "TABLE", "INSERT INTO", "ALTER TABLE"]) {
47    return Context::Table;
48  }
49  if is_after_keyword(before, &["ON", "WHERE", "HAVING", "AND", "OR"]) {
50    return Context::Predicate;
51  }
52  // Inside SELECT projection list: between SELECT and FROM on the same
53  // statement.
54  if in_projection_list(before) {
55    return Context::Projection;
56  }
57  // Start of a statement (only whitespace / semicolon before cursor's word).
58  if at_statement_start(before) {
59    return Context::Statement;
60  }
61  Context::General
62}
63
64fn dot_context(before: &str) -> Option<Context> {
65  let dot_idx = before.rfind('.')?;
66  let after_dot = &before[dot_idx + 1..];
67  if !after_dot.chars().all(|c| c.is_alphanumeric() || c == '_') {
68    return None;
69  }
70  let pre_dot = &before[..dot_idx];
71  let alias: String =
72    pre_dot.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>().chars().rev().collect();
73  if alias.is_empty() {
74    return None;
75  }
76  Some(Context::DotOf { alias })
77}
78
79/// Strip the partial token under the cursor, then check whether the
80/// preceding tokens end with any of `keywords` (case-insensitive).
81fn is_after_keyword(before: &str, keywords: &[&str]) -> bool {
82  let cur = before.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>();
83  let cut = before.len() - cur.len();
84  let trimmed_upper = before[..cut].trim_end().to_uppercase();
85  keywords.iter().any(|kw| trimmed_upper.ends_with(kw))
86}
87
88/// Heuristic: between the most recent SELECT and the next FROM (or end of
89/// buffer), we are likely in a projection list.
90fn in_projection_list(before: &str) -> bool {
91  let upper = before.to_uppercase();
92  let select_idx = upper.rfind("SELECT");
93  let Some(sel) = select_idx else {
94    return false;
95  };
96  // If there is a FROM after the SELECT we just found, we're past it.
97  if let Some(from) = upper[sel + 6..].find("FROM") {
98    // We're past FROM only if there's no newer SELECT after it.
99    let from_abs = sel + 6 + from;
100    if upper[from_abs..].rfind("SELECT").is_none() {
101      return false;
102    }
103  }
104  // Past the SELECT and not yet past FROM: treat as projection list.
105  // (Cursor position inside the list is permissive on purpose -- completion
106  // engine filters further once the partial token is known.)
107  true
108}
109
110/// True when `before` looks like `... ALTER TABLE [IF EXISTS] [ONLY]
111/// <ident> [<partial-token>]` -- the table name is parsed and we are
112/// either right after it (with whitespace), or in the middle of typing
113/// the sub-action verb. Used to switch from `Table` completion (just
114/// after `ALTER TABLE`) to `AlterTableAction` once the user has named
115/// the table.
116fn after_alter_table_name(before: &str) -> bool {
117  // Strip the partial word under the cursor; the sub-action verb may
118  // be in progress (e.g. `ALTER TABLE users AD<cursor>`).
119  let cur: String =
120    before.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>().chars().rev().collect();
121  let cut = before.len() - cur.len();
122  let head = before[..cut].trim_end();
123  // Need at least one identifier (the table name) before us.
124  let table_chars: String = head
125    .chars()
126    .rev()
127    .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '"' || *c == '.')
128    .collect::<String>()
129    .chars()
130    .rev()
131    .collect();
132  if table_chars.is_empty() {
133    return false;
134  }
135  let cut2 = head.len() - table_chars.len();
136  let head2 = head[..cut2].trim_end().to_ascii_uppercase();
137  // The fragment before the table name must end with `ALTER TABLE`,
138  // optionally with the IF EXISTS / ONLY modifiers in between.
139  let head2 = head2.trim_end_matches("IF EXISTS").trim_end();
140  let head2 = head2.trim_end_matches("ONLY").trim_end();
141  head2.ends_with("ALTER TABLE")
142}
143
144fn at_statement_start(before: &str) -> bool {
145  let cur = before.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>();
146  let cut = before.len() - cur.len();
147  let head = before[..cut].trim_end();
148  head.is_empty() || head.ends_with(';')
149}