Skip to main content

dsl_hover/
lib.rs

1//! Rich SQL hover.
2//!
3//! Resolution order (first match wins):
4//!   1. Column declaration when cursor sits on the column NAME inside
5//!      a CREATE TABLE in the current buffer.
6//!   2. Constraint / index / trigger identifier (pk_/fk_/idx_/...) -- catalog
7//!      lookup or fallback convention card.
8//!   3. Catalog table / column / DB function.
9//!   4. Multi-word SQL keyword (sliding window).
10//!   5. Single-word knowledge entry (keyword / type / built-in function).
11
12pub mod constraint_id;
13pub mod ddl;
14pub mod implicit;
15pub mod md_table;
16pub mod render;
17pub mod resolver;
18pub mod token;
19
20use dsl_catalog::Catalog;
21use text_size::TextSize;
22
23/// How keywords are cased in synthesized DDL fragments shown in hover.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum KeywordCase {
26  #[default]
27  Upper,
28  Lower,
29  Preserve,
30}
31
32impl KeywordCase {
33  pub fn apply(self, s: &str) -> String {
34    match self {
35      KeywordCase::Upper => s.to_ascii_uppercase(),
36      KeywordCase::Lower => s.to_ascii_lowercase(),
37      KeywordCase::Preserve => s.to_string(),
38    }
39  }
40}
41
42// Thread-local current keyword case so the render fns don't need a new
43// parameter on every call site. Set by `hover_with`. Default Upper.
44thread_local! {
45    static KW_CASE: std::cell::Cell<KeywordCase> = const { std::cell::Cell::new(KeywordCase::Upper) };
46}
47
48pub fn current_keyword_case() -> KeywordCase {
49  KW_CASE.with(|c| c.get())
50}
51
52pub fn hover(source: &str, offset: TextSize, catalog: &Catalog) -> Option<String> {
53  hover_with(source, offset, catalog, KeywordCase::Upper)
54}
55
56/// Like `hover` but applies the caller's preferred keyword casing to
57/// every synthesised DDL fragment.
58pub fn hover_with(source: &str, offset: TextSize, catalog: &Catalog, case: KeywordCase) -> Option<String> {
59  let file = dsl_parse::parse(source, dsl_parse::Dialect::Postgres);
60  hover_with_parsed(source, offset, &file, catalog, case)
61}
62
63/// Like `hover_with` but takes an already-parsed `file`, so a caller
64/// that maintains a per-document parse cache (dsl-server's
65/// `ParseCache`) can skip re-parsing the whole buffer on every hover
66/// request. `hover_with` itself parses fresh and delegates here.
67pub fn hover_with_parsed(
68  source: &str,
69  offset: TextSize,
70  file: &dsl_parse::ParsedFile,
71  catalog: &Catalog,
72  case: KeywordCase,
73) -> Option<String> {
74  KW_CASE.with(|c| c.set(case));
75  // Respect lexical boundaries: cursor inside `'...'` / `"..."` /
76  // `-- comment` / `/* ... */` / `$$ ... $$` body for a non-PL/pgSQL
77  // language returns None for keywords. Catches `'illegal order
78  // adding...'` so the ORDER keyword card doesn't fire on a literal.
79  //
80  // Inside a quoted string, surface a small "literal" card naming
81  // the inferred destination column type when we can resolve one
82  // (INSERT VALUES / UPDATE SET / WHERE col = ...).
83  let pos: usize = u32::from(offset) as usize;
84  // Double-quoted identifier (`"User Id"`) -- a case-preserved name,
85  // never a keyword. Suppress hover entirely so the lookup pipeline
86  // doesn't mis-resolve the inner text to a SQL keyword (e.g. cursor
87  // inside `"User Id"` mustn't fire the USER keyword card). A future
88  // iteration can try a column / table lookup using the unquoted name.
89  if cursor_inside_double_quoted_ident(source, pos) {
90    return None;
91  }
92  if inside_string_or_comment(source, pos) {
93    // Specific-card paths must run BEFORE the generic string-literal
94    // fallback. A cursor inside `'user_id_seq'` of `nextval(...)` wants
95    // the sequence card, not "text/string literal"; same for an arg
96    // inside `coalesce(name, 'fallback')` -- the function-arg card
97    // beats the generic literal card.
98    if let Some(md) = sequence_ref_at(source, offset) {
99      return Some(md);
100    }
101    if let Some(md) = function_arg_at(source, offset) {
102      return Some(md);
103    }
104    if let Some(card) = string_literal_hover(source, pos, catalog) {
105      return Some(card);
106    }
107    return None;
108  }
109  // Cursor sits on a numeric literal -- small card naming the literal
110  // kind + the destination column type when resolvable.
111  if let Some(card) = numeric_literal_hover(source, pos, catalog) {
112    return Some(card);
113  }
114  if let Some(md) = ddl::column_decl_at(file, source, offset) {
115    return Some(md);
116  }
117  // Sequence reference inside `nextval('seq_name')` / `currval(...)`
118  // / `setval(...)` -- when the cursor sits on the literal sequence
119  // name, return a card describing it.
120  if let Some(md) = sequence_ref_at(source, offset) {
121    return Some(md);
122  }
123  // Cursor on an argument literal inside `fn(arg, arg)`. Surface
124  // the function's signature with the current parameter highlighted
125  // so the user knows "I'm filling slot 2 of substring(text, int, int)".
126  // Gate: only fire when the cursor is NOT sitting on an identifier-
127  // shaped byte. Identifier hover (column / alias / table) is handled
128  // downstream and must win for cases like `count(u.id)` -- otherwise
129  // the function signature swallows the column the user pointed at.
130  if !cursor_on_word_byte(source, pos)
131    && let Some(md) = function_arg_at(source, offset)
132  {
133    return Some(md);
134  }
135
136  // Cursor on a KNN/distance/phrase operator (<->, <#>, <%>, ...).
137  // Must precede the jsonb-`->` lookup; otherwise `<-` would be matched
138  // as `->` partial.
139  if let Some(md) = distance_operator_hover(source, pos) {
140    return Some(md);
141  }
142  // Geometric / math / range comparison ops (|/, ||/, @-@, ##, &<,
143  // &>, &<|, |>>, <<|, &&). Runs after distance so `<->` isn't shadowed.
144  if let Some(md) = geometric_math_operator_hover(source, pos) {
145    return Some(md);
146  }
147  // Cursor on the JSON path operators (-> / ->> / #> / #>>). Surface
148  // a short card naming the operator's return type.
149  if let Some(md) = jsonb_operator_hover(source, pos) {
150    return Some(md);
151  }
152
153  // Cursor on a comparison / string / range operator (=, <>, !=,
154  // <, >, <=, >=, ||, @>, <@, ?, ?|, ?&). Surface a brief explanation.
155  if let Some(md) = comparison_operator_hover(source, pos) {
156    return Some(md);
157  }
158
159  // Cursor on the NULL keyword -- card explains three-valued logic
160  // and the destination column nullability when resolvable.
161  if let Some(md) = null_keyword_hover(source, pos, catalog) {
162    return Some(md);
163  }
164
165  // Cursor on a `*` token (SELECT projection / `u.*` / `count(*)`).
166  // The lexer-based token_at skips non-word chars so the star never
167  // makes it to the normal lookup path. Handle it explicitly.
168  if let Some(md) = star_hover(source, offset, file, catalog) {
169    return Some(md);
170  }
171
172  // Cursor on the `::` cast operator itself (between expr and type).
173  if cursor_on_double_colon(source, offset) {
174    return Some(
175      "# `::` cast operator\n\n_PG-specific shorthand for `CAST(expr AS type)`_\n\n\
176       ```sql\n\
177       '123'::int            -- string -> integer\n\
178       column_name::text     -- column to text\n\
179       now()::date           -- timestamp -> date\n\
180       arr::int[]            -- array element type cast\n\
181       data::jsonb           -- text -> jsonb\n\
182       ```\n\n\
183       Equivalent to `CAST(expr AS type)`. Errors at runtime if the value can't be converted; \
184       check with `IS NOT NULL` first when in doubt. Inside DDL prefer the standard CAST form."
185        .to_string(),
186    );
187  }
188
189  if let Some(tok) = token::token_at(source, offset) {
190    // Dotted token `a.b` -- narrow to the side under the cursor.
191    // Cursor on the alias side => table card. Cursor on the column
192    // side => single-column card resolved through the alias.
193    if tok.contains('.')
194      && let Some(part) = dotted_part_under_cursor(source, offset, &tok)
195    {
196      let last_seg = tok.rsplit('.').next().unwrap_or("");
197      let on_right = part == last_seg;
198      if on_right {
199        if let Some(md) = scope_column_lookup(source, offset, file, &tok, catalog) {
200          return Some(md);
201        }
202        if let Some(md) = catalog_lookup(&part, catalog) {
203          return Some(md);
204        }
205        // Schema-qualified function call: `gdpr.update_user_gdpr()`.
206        // Cursor on the function-name segment -- fire the function
207        // card, scoped to the schema when one is provided.
208        let left_seg = tok.split('.').next();
209        if let Some(md) = db_function_scoped(&part, left_seg, catalog) {
210          return Some(md);
211        }
212      } else {
213        if let Some(md) = alias_lookup(source, offset, file, &part, catalog) {
214          return Some(md);
215        }
216        if let Some(md) = catalog_lookup(&part, catalog) {
217          return Some(md);
218        }
219      }
220      if let Some(entry) = dsl_knowledge::lookup(&part) {
221        return Some(dsl_knowledge::render_markdown(entry));
222      }
223    }
224    // NEW / OLD trigger row aliases. Inside a CREATE TRIGGER body
225    // they bind to the trigger's target table; standalone we still
226    // explain what they are.
227    let upper_tok = tok.to_ascii_uppercase();
228    if upper_tok == "NEW" || upper_tok == "OLD" {
229      return Some(new_old_hover(&upper_tok, source));
230    }
231    // PL/pgSQL function parameter / DECLARE'd local. Cheap text scan
232    // of the enclosing CREATE FUNCTION header + DECLARE block.
233    if let Some(md) = plpgsql_local_hover(source, offset, &tok) {
234      return Some(md);
235    }
236    // Buffer-defined CREATE FUNCTION / CREATE INDEX / CREATE TRIGGER
237    // first -- if the user just wrote it, that's exactly what they
238    // want to see, not a generic "no match in catalog" card.
239    if let Some(md) = buffer_object(source, &tok) {
240      return Some(md);
241    }
242    // Alias resolution -- if the cursor sits on `u` in `FROM users u`
243    // or `JOIN orders AS o`, hover the underlying table.
244    if let Some(md) = alias_lookup(source, offset, file, &tok, catalog) {
245      return Some(md);
246    }
247    // Cursor inside a CREATE TABLE body? Resolve the column against
248    // just that table to avoid the "this column lives in 11 tables"
249    // ambiguity card -- inside `pk_users_id PRIMARY KEY (id)` the
250    // `id` means `users.id`, full stop.
251    if let Some(md) = enclosing_table_column(offset, file, &tok, catalog) {
252      return Some(md);
253    }
254    // Same scoping for CREATE INDEX ... ON <table> (col), UPDATE
255    // <table> SET col, DELETE FROM <table> WHERE col, INSERT INTO
256    // <table> (col, ...) -- if we can name the single target table
257    // from the surrounding text, narrow the hover to that table.
258    if let Some(md) = scoped_column_in_text(source, offset, file, &tok, catalog) {
259      return Some(md);
260    }
261    if let Some(md) = constraint_id::render_for(&tok, catalog) {
262      return Some(md);
263    }
264    // Scope-aware column hover: when the cursor sits on `id` or
265    // `ur.id` inside a SELECT / UPDATE / DELETE, resolve via the
266    // statement's FROM/JOIN bindings so the hover names the actual
267    // origin table instead of a "lives in N tables" card.
268    if let Some(md) = scope_column_lookup(source, offset, file, &tok, catalog) {
269      return Some(md);
270    }
271    // Role hover -- only resolves when the cursor sits in a role-name
272    // slot (OWNER TO, GRANT/REVOKE TO/FROM, SET ROLE, ...) so that a
273    // column / table / etc named the same thing wins elsewhere.
274    if let Some(md) = role_hover(source, offset, &tok, catalog) {
275      return Some(md);
276    }
277    if let Some(md) = catalog_lookup(&tok, catalog) {
278      return Some(md);
279    }
280    if let Some(md) = db_function(&tok, catalog) {
281      return Some(md);
282    }
283  }
284
285  let window = token::window_at(source, offset);
286  if let Some(md) = resolver::from_window(&window) {
287    return Some(md);
288  }
289
290  if let Some(tok) = token::token_at(source, offset) {
291    // Field-list context priority: when the cursor sits inside a
292    // column-list paren (CREATE TABLE / INSERT cols / CREATE INDEX
293    // ON t (...) / RETURNING / GROUP BY / ORDER BY / SET / UNIQUE /
294    // PRIMARY KEY paren), the token is almost certainly an
295    // identifier of a column -- NOT a keyword. Skip the keyword
296    // card fallback so `password` in `(name, email, password)`
297    // doesn't pop the PASSWORD reserved-word reference.
298    if in_field_list_context(source, u32::from(offset) as usize) {
299      // Grouping / window / sub-query operators are genuine SQL
300      // keywords (not column names) and are useful to hover even
301      // when they appear inside a GROUP BY / ORDER BY / RETURNING /
302      // SET clause that otherwise suppresses keyword cards.
303      //
304      // Types (`int`, `text`, `varchar`, `jsonb`, `timestamptz`, ...)
305      // appear in the type position of a CREATE TABLE column decl
306      // and should also surface their docs -- they are NOT column
307      // references. Check the knowledge entry's kind: TYPE entries
308      // fall through to the lookup below; KEYWORD entries stay
309      // suppressed so `password` in `(name, email, password)`
310      // doesn't pop the PASSWORD reserved-word card.
311      let utok = tok.to_ascii_uppercase();
312      let is_grouping_op = matches!(utok.as_str(), "ROLLUP" | "CUBE" | "LATERAL" | "OVER");
313      let is_type = dsl_knowledge::lookup(&tok).is_some_and(|e| e.kind == dsl_knowledge::Kind::Type);
314      // Column-definition / table-constraint keywords inside a CREATE TABLE
315      // body are real SQL keywords, not column-name uses, so they should
316      // surface their docs the same as outside the paren. Cursor inside
317      // `id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY` previously got
318      // suppressed because the paren-context check assumed every word was
319      // an identifier.
320      let is_col_decl_kw = matches!(
321        utok.as_str(),
322        "PRIMARY"
323          | "KEY"
324          | "UNIQUE"
325          | "REFERENCES"
326          | "CHECK"
327          | "NOT"
328          | "NULL"
329          | "DEFAULT"
330          | "GENERATED"
331          | "ALWAYS"
332          | "BY"
333          | "AS"
334          | "STORED"
335          | "IDENTITY"
336          | "CONSTRAINT"
337          | "COLLATE"
338          | "DEFERRABLE"
339          | "DEFERRED"
340          | "INITIALLY"
341          | "MATCH"
342          | "ON"
343          | "DELETE"
344          | "UPDATE"
345          | "CASCADE"
346          | "RESTRICT"
347          | "SET"
348      );
349      if !is_grouping_op && !is_type && !is_col_decl_kw {
350        return None;
351      }
352    }
353    if let Some(entry) = dsl_knowledge::lookup(&tok) {
354      return Some(dsl_knowledge::render_markdown(entry));
355    }
356  }
357  None
358}
359
360/// True when the cursor lies inside a parenthesised column list of:
361///   INSERT INTO t (...)
362///   CREATE TABLE t (...)
363///   CREATE INDEX ... ON t (...)
364///   CREATE UNIQUE INDEX ... ON t (...)
365///   PRIMARY KEY (...)
366///   UNIQUE (...)
367///   FOREIGN KEY (...) REFERENCES other (...)
368///   RETURNING ...
369///   GROUP BY ...
370///   ORDER BY ...
371///   UPDATE ... SET ... (the LHS of an assignment)
372///
373/// Used to suppress the keyword fallback so `password`, `order`,
374/// `role`, etc don't pop the reserved-word card when the user
375/// clearly wrote them as identifiers.
376fn in_field_list_context(src: &str, pos: usize) -> bool {
377  let bytes = src.as_bytes();
378  let mut i = pos.min(bytes.len());
379  // Walk back finding unbalanced `(` or a clause keyword on the way.
380  let mut depth = 0i32;
381  while i > 0 {
382    let b = bytes[i - 1];
383    if !b.is_ascii() {
384      i -= 1;
385      continue;
386    }
387    let c = b as char;
388    if c == ')' {
389      depth += 1;
390      i -= 1;
391      continue;
392    }
393    if c == '(' {
394      if depth == 0 {
395        // Unbalanced `(` -- check what precedes the paren.
396        return preceded_by_field_list_intro(src, i - 1);
397      }
398      depth -= 1;
399      i -= 1;
400      continue;
401    }
402    if c == ';' {
403      return false;
404    }
405    // Clause-introducer keywords without needing a paren.
406    if depth == 0 {
407      for kw in ["RETURNING", "GROUP BY", "ORDER BY"] {
408        let len = kw.len();
409        // Guard against mid-codepoint slicing: only inspect when the
410        // would-be start byte is a UTF-8 char boundary.
411        if i >= len && src.is_char_boundary(i - len) {
412          let slice = &src[i - len..i];
413          if slice.to_ascii_uppercase() == kw {
414            let prev_ok = i == len || !is_word_ch(bytes[i - len - 1]);
415            if prev_ok {
416              return true;
417            }
418          }
419        }
420      }
421      // UPDATE ... SET <col> = ... : when cursor sits on a column
422      // name on the LHS of a SET assignment.
423      if i >= 4 && src.is_char_boundary(i - 4) && src[i - 4..i].eq_ignore_ascii_case(" SET") {
424        return true;
425      }
426    }
427    i -= 1;
428  }
429  false
430}
431
432fn is_word_ch(b: u8) -> bool {
433  b.is_ascii_alphanumeric() || b == b'_'
434}
435
436fn preceded_by_field_list_intro(src: &str, paren_pos: usize) -> bool {
437  // Trim whitespace before `(`.
438  let bytes = src.as_bytes();
439  let mut k = paren_pos;
440  while k > 0 && bytes[k - 1].is_ascii() && bytes[k - 1].is_ascii_whitespace() {
441    k -= 1;
442  }
443  // Pull preceding word (could be the table name in CREATE TABLE t (...)
444  // or the keyword we care about). Accept `.` as part of the word so that
445  // schema-qualified names (`public.users`) are consumed as one token and
446  // the head-trim lookup sees `CREATE TABLE` ahead of the paren.
447  let word_end = k;
448  while k > 0 && bytes[k - 1].is_ascii() && (is_word_ch(bytes[k - 1]) || bytes[k - 1] == b'.') {
449    k -= 1;
450  }
451  let last_word = &src[k..word_end];
452  let upper_word = last_word.to_ascii_uppercase();
453  // INSERT INTO t (   -- the previous word is the table name; check
454  // further back for INTO / TABLE / INDEX / KEY / UNIQUE / etc.
455  let head_upper = src[..k].to_ascii_uppercase();
456  let head_trimmed = head_upper.trim_end();
457  for kw in [
458    "INSERT INTO",
459    "CREATE TABLE",
460    "CREATE TABLE IF NOT EXISTS",
461    "CREATE TEMP TABLE",
462    "CREATE TEMPORARY TABLE",
463    "CREATE INDEX",
464    "CREATE UNIQUE INDEX",
465    "CREATE INDEX IF NOT EXISTS",
466    "CREATE UNIQUE INDEX IF NOT EXISTS",
467    "PRIMARY KEY",
468    "FOREIGN KEY",
469    "UNIQUE",
470    "REFERENCES",
471    "USING",
472  ] {
473    if head_trimmed.ends_with(kw) {
474      return true;
475    }
476    // Also: ON t ( for CREATE INDEX -- previous word is `t`, before
477    // that `ON`. Need to step back another word.
478  }
479  // Two-word lookback: previous word may be `t` (table); look further.
480  let mut k2 = k;
481  while k2 > 0 && bytes[k2 - 1].is_ascii() && bytes[k2 - 1].is_ascii_whitespace() {
482    k2 -= 1;
483  }
484  let word_end2 = k2;
485  while k2 > 0 && bytes[k2 - 1].is_ascii() && is_word_ch(bytes[k2 - 1]) {
486    k2 -= 1;
487  }
488  if word_end2 > k2 {
489    let upper2 = src[k2..word_end2].to_ascii_uppercase();
490    if upper2 == "ON" {
491      // CREATE INDEX ... ON t (
492      return true;
493    }
494  }
495  let _ = upper_word;
496  false
497}
498
499fn catalog_lookup(token: &str, catalog: &Catalog) -> Option<String> {
500  // Schema-qualified 3-segment path: `schema.table.column`.
501  let segs: Vec<&str> = token.split('.').collect();
502  if segs.len() == 3 {
503    let (schema, table, column) = (segs[0], segs[1], segs[2]);
504    if let Some(t) = catalog.find_table(Some(schema), table) {
505      if let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column)) {
506        return Some(render::column(t, c));
507      }
508      // 3rd segment is not a column -- still a valid table card.
509      return Some(render::table_with_catalog(t, catalog));
510    }
511  }
512  if let Some((left, right)) = token.split_once('.') {
513    if let Some(t) = catalog.find_table(Some(left), right) {
514      return Some(render::table_with_catalog(t, catalog));
515    }
516    if let Some(t) = catalog.find_table(None, left)
517      && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(right))
518    {
519      return Some(render::column(t, c));
520    }
521  }
522  if let Some(t) = catalog.find_table(None, token) {
523    return Some(render::table(t));
524  }
525  if let Some(ty) = catalog.find_type(None, token) {
526    return Some(render::user_type(ty));
527  }
528  // Schema card: cursor on a bare identifier that names a schema in
529  // the catalog. Schema membership is detected through THREE sources
530  // so the card fires even when `CREATE SCHEMA <name>` wasn't seen:
531  //   1. catalog.schemas       (declared schemas)
532  //   2. catalog.functions[*].schema (function definitions)
533  //   3. catalog.types[*].schema     (user-defined types)
534  let schema_known = catalog.schemas.iter().any(|s| s.name.eq_ignore_ascii_case(token))
535    || catalog.functions.iter().any(|f| f.schema.eq_ignore_ascii_case(token))
536    || catalog.types.iter().any(|t| t.schema.eq_ignore_ascii_case(token));
537  if schema_known {
538    let name =
539      catalog.schemas.iter().find(|s| s.name.eq_ignore_ascii_case(token)).map(|s| s.name.as_str()).unwrap_or(token);
540    let mut card = format!("# `{name}`\n_schema_\n\n");
541    let tables: Vec<&dsl_catalog::Table> = catalog
542      .schemas
543      .iter()
544      .find(|s| s.name.eq_ignore_ascii_case(token))
545      .map(|s| s.tables.iter().collect())
546      .unwrap_or_default();
547    if !tables.is_empty() {
548      card.push_str(&format!("**{} table(s):**\n", tables.len()));
549      for t in tables.iter().take(20) {
550        card.push_str(&format!("- `{}`\n", t.name));
551      }
552      if tables.len() > 20 {
553        card.push_str(&format!("- _\u{2026} +{} more_\n", tables.len() - 20));
554      }
555    }
556    let fns: Vec<&dsl_catalog::Function> =
557      catalog.functions.iter().filter(|f| f.schema.eq_ignore_ascii_case(token)).collect();
558    if !fns.is_empty() {
559      card.push_str(&format!("\n**{} function(s):**\n", fns.len()));
560      for f in fns.iter().take(20) {
561        let ret = if f.return_type.is_empty() { String::new() } else { format!(" -> `{}`", f.return_type) };
562        card.push_str(&format!("- `{}({} args)`{}\n", f.name, f.arguments.len(), ret));
563      }
564      if fns.len() > 20 {
565        card.push_str(&format!("- _\u{2026} +{} more_\n", fns.len() - 20));
566      }
567    }
568    let types_in_schema: Vec<&dsl_catalog::Type> =
569      catalog.types.iter().filter(|t| t.schema.eq_ignore_ascii_case(token)).collect();
570    if !types_in_schema.is_empty() {
571      card.push_str(&format!("\n**{} type(s):**\n", types_in_schema.len()));
572      for t in types_in_schema.iter().take(20) {
573        card.push_str(&format!("- `{}`\n", t.name));
574      }
575    }
576    return Some(card);
577  }
578  if let Some((t, p)) = catalog.find_policy(token) {
579    return Some(format!(
580      "# `{}`\n_RLS policy on `{}.{}`_\n\n- **command**: `{}`\n- **roles**: `{}`\n- **permissive**: `{}`{}{}\n",
581      p.name,
582      t.schema,
583      t.name,
584      p.command,
585      p.roles,
586      p.permissive,
587      p.using_expr.as_ref().map(|e| format!("\n- **USING**: `{e}`")).unwrap_or_default(),
588      p.check_expr.as_ref().map(|e| format!("\n- **WITH CHECK**: `{e}`")).unwrap_or_default(),
589    ));
590  }
591  if let Some((t, tr)) = catalog.find_trigger(token) {
592    let mut s = format!(
593      "# `{}`\n_trigger on `{}.{}`_\n\n- **timing**: `{}`\n- **event**: `{}`\n- **granularity**: `{}`\n- **executes**: `{}`\n",
594      tr.name, t.schema, t.name, tr.timing, tr.event, tr.granularity, tr.function,
595    );
596    // Append the handler function's source if it's in the catalog.
597    let fn_name = tr.function.rsplit('.').next().unwrap_or(&tr.function);
598    if let Some(f) = catalog.functions.iter().find(|f| f.name.eq_ignore_ascii_case(fn_name))
599      && let Some(body) = f.comment.as_ref()
600    {
601      let trimmed = body.trim();
602      if trimmed.to_ascii_uppercase().starts_with("CREATE") {
603        s.push_str("\n**Handler function**\n\n```sql\n");
604        s.push_str(trimmed);
605        s.push_str("\n```\n");
606      }
607    }
608    return Some(s);
609  }
610  if let Some((t, i)) = catalog.find_index(token) {
611    let def = i.definition.as_deref().unwrap_or("");
612    let lead = i.columns.first().cloned().unwrap_or_default();
613    let mut s = format!(
614      "# `{}`\n_index on `{}.{}`_\n\n- **columns**: `{}`\n- **unique**: `{}`\n",
615      i.name,
616      t.schema,
617      t.name,
618      i.columns.join(", "),
619      i.unique,
620    );
621    if !def.is_empty() {
622      s.push_str(&format!("\n```sql\n{def}\n```\n"));
623    }
624    // Workload hint: leading column drives B-tree usage. Equality +
625    // range on the leading column hits this index; predicates that
626    // touch only later columns do NOT use it for index access.
627    if !lead.is_empty() {
628      s.push_str(&format!(
629        "\n**Best for**\n\n- `WHERE {lead} = ...`\n- `WHERE {lead} BETWEEN ... AND ...`\n- `ORDER BY {lead}` (no extra sort)\n",
630      ));
631      if i.columns.len() > 1 {
632        s.push_str(&format!("- Multi-column equality starting from `{lead}` ({})\n", i.columns.join(", ")));
633      }
634      if i.unique {
635        s.push_str(&format!("- `SELECT ... WHERE {lead} = ...` -> at most one row\n"));
636      }
637    }
638    return Some(s);
639  }
640  if let Some((t, c)) = catalog.find_constraint(token) {
641    let kind = match c.kind {
642      dsl_catalog::ConstraintKind::PrimaryKey => "PRIMARY KEY",
643      dsl_catalog::ConstraintKind::ForeignKey => "FOREIGN KEY",
644      dsl_catalog::ConstraintKind::Unique => "UNIQUE",
645      dsl_catalog::ConstraintKind::Check => "CHECK",
646    };
647    let mut s = format!(
648      "# `{}`\n_{} constraint on `{}.{}`_\n\n- **columns**: `{}`\n",
649      c.name,
650      kind,
651      t.schema,
652      t.name,
653      c.columns.join(", "),
654    );
655    if let Some(r) = &c.references {
656      s.push_str(&format!("- **references**: `{}.{}` ({})\n", r.schema, r.table, r.columns.join(", "),));
657    }
658    if let Some(def) = &c.definition {
659      s.push_str(&format!("\n```sql\n{def}\n```\n"));
660    }
661    return Some(s);
662  }
663  if let Some(s) = catalog.find_sequence(None, token) {
664    let cycle = if s.cycle { "yes" } else { "no" };
665    let owner = s.owned_by_column.as_deref().unwrap_or("(standalone)");
666    return Some(format!(
667      "# `{}.{}`\n_sequence_\n\n- **type**: `{}`\n- **start**: `{}`\n- **min**: `{}`\n- **max**: `{}`\n- **increment**: `{}`\n- **cycle**: `{}`\n- **owned by**: `{}`\n",
668      s.schema, s.name, s.data_type, s.start_value, s.min_value, s.max_value, s.increment_by, cycle, owner,
669    ));
670  }
671  if let Some(e) = catalog.extensions().find(|e| e.name.eq_ignore_ascii_case(token)) {
672    let comment = e.comment.as_deref().map(|c| format!("\n_{c}_\n")).unwrap_or_default();
673    return Some(format!(
674      "# `{}`\n_extension installed in `{}`_\n\n- **version**: `{}`\n{}",
675      e.name, e.schema, e.version, comment,
676    ));
677  }
678  let cols = catalog.columns_named(token);
679  if !cols.is_empty() {
680    return Some(render::column_in_tables(&cols));
681  }
682  None
683}
684
685/// Cursor on the NULL keyword. Returns a small card explaining
686/// three-valued logic + the destination column's nullability when
687/// inferrable from INSERT VALUES / UPDATE SET / WHERE.
688fn null_keyword_hover(source: &str, pos: usize, catalog: &Catalog) -> Option<String> {
689  let bytes = source.as_bytes();
690  if pos >= bytes.len() {
691    return None;
692  }
693  // Read the word under the cursor.
694  let mut s = pos;
695  while s > 0 && (bytes[s - 1].is_ascii_alphanumeric() || bytes[s - 1] == b'_') {
696    s -= 1;
697  }
698  let mut e = pos;
699  while e < bytes.len() && (bytes[e].is_ascii_alphanumeric() || bytes[e] == b'_') {
700    e += 1;
701  }
702  if s == e {
703    return None;
704  }
705  if !source[s..e].eq_ignore_ascii_case("NULL") {
706    return None;
707  }
708  let mut card = "# `NULL`\n\n_unknown / absent value_\n\nSQL uses three-valued logic. \
709     Any expression involving `NULL` (except `IS NULL` / `IS NOT NULL` / \
710     `IS [NOT] DISTINCT FROM`) returns `NULL`, not true/false. Use \
711     `COALESCE(x, default)` or `x IS NULL` for safe comparisons.\n"
712    .to_string();
713  if let Some((schema, table, col, ty)) = infer_assigned_column(source, s.saturating_sub(1), catalog) {
714    card.push_str(&format!("\n- **assigned to:** `{schema}.{table}.{col}`\n- **column type:** `{ty}`\n",));
715    // Find nullability flag in catalog.
716    if let Some(t) = catalog.find_table(Some(&schema), &table)
717      && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(&col))
718      && !c.nullable
719    {
720      card.push_str(
721            "\n_Warning:_ destination column is **NOT NULL** -- PG will reject this INSERT with `null value in column \"...\" violates not-null constraint`.\n",
722          );
723    }
724  }
725  Some(card)
726}
727
728/// Hover card for the four JSONB path operators -- ->, ->>, #>, #>>.
729/// Each returns a different type so users get caught out by mixing
730/// them (especially -> vs ->>). Fires when the cursor sits on any
731/// byte of the operator.
732/// Hover for common comparison / string / range operators that aren't
733/// covered by the JSON path or `::` cast paths. Returns a brief
734/// markdown card explaining the operator's meaning.
735fn comparison_operator_hover(source: &str, pos: usize) -> Option<String> {
736  let bytes = source.as_bytes();
737  if pos >= bytes.len() {
738    return None;
739  }
740  // Find the maximal operator span (consecutive ASCII-punctuation chars
741  // commonly used in PG operators) containing `pos`.
742  let is_op_byte = |b: u8| matches!(b, b'=' | b'<' | b'>' | b'!' | b'|' | b'@' | b'?' | b'&' | b'~' | b'^' | b'#');
743  if !is_op_byte(bytes[pos]) {
744    return None;
745  }
746  let mut s = pos;
747  while s > 0 && is_op_byte(bytes[s - 1]) {
748    s -= 1;
749  }
750  let mut e = pos;
751  while e < bytes.len() && is_op_byte(bytes[e]) {
752    e += 1;
753  }
754  let op = &source[s..e];
755  // Reject operators handled elsewhere (json-path `->` / `->>` / `#>` /
756  // `#>>`, cast `::`). Bare `#` (bitwise XOR) is fine, only multi-char
757  // forms involving `#` go to jsonb_operator_hover.
758  if op.contains('-') || op.contains(':') || (op.contains('#') && op.len() > 1) {
759    return None;
760  }
761  let card = match op {
762    "=" => {
763      "# `=`\n\n_Equality comparison_\n\nReturns `true` when both operands are equal, \
764            `false` when not, and `NULL` if either operand is `NULL` (three-valued logic). \
765            Use `IS NOT DISTINCT FROM` to treat `NULL = NULL` as true.\n"
766    },
767    "<>" | "!=" => {
768      "# `<>` (also `!=`)\n\n_Inequality comparison_\n\nReturns `true` when operands differ. \
769            Like `=`, returns `NULL` when either side is `NULL`. Use `IS DISTINCT FROM` for \
770            NULL-aware inequality.\n"
771    },
772    "<" => {
773      "# `<`\n\n_Less-than comparison_\n\nStandard ordering on the operand type. \
774            Uses lexicographic order for strings, byte order for `bytea`, and the type's natural \
775            ordering for numbers / dates.\n"
776    },
777    ">" => "# `>`\n\n_Greater-than comparison_\n\nMirror of `<`.\n",
778    "<=" => "# `<=`\n\n_Less-than-or-equal comparison_\n",
779    ">=" => "# `>=`\n\n_Greater-than-or-equal comparison_\n",
780    "||" => {
781      "# `||`\n\n_String / array concatenation_\n\nFor text operands: \
782            `'a' || 'b'` -> `'ab'`. For arrays: `ARRAY[1,2] || ARRAY[3]` -> `{1,2,3}`. \
783            Returns `NULL` if either operand is `NULL` (text); for arrays, prepending or \
784            appending `NULL` returns the other array.\n"
785    },
786    "@>" => {
787      "# `@>`\n\n_Contains operator_\n\nReturns `true` when the left operand contains the \
788            right (jsonb / arrays / ranges). `'{\"a\":1, \"b\":2}'::jsonb @> '{\"a\":1}'::jsonb` -> `true`.\n"
789    },
790    "<@" => "# `<@`\n\n_Contained-by operator_\n\nMirror of `@>`. The left operand is contained by the right.\n",
791    "?" => {
792      "# `?`\n\n_jsonb key existence_\n\nReturns `true` when the left jsonb has a top-level \
793            key (or array element) equal to the right text. `'{\"a\":1}'::jsonb ? 'a'` -> `true`.\n"
794    },
795    "?|" => {
796      "# `?|`\n\n_jsonb any-key existence_\n\nReturns `true` when ANY key in the right `text[]` is present in the left jsonb.\n"
797    },
798    "?&" => {
799      "# `?&`\n\n_jsonb all-keys existence_\n\nReturns `true` when ALL keys in the right `text[]` are present in the left jsonb.\n"
800    },
801    "@@" => {
802      "# `@@`\n\n_Full-text search match_\n\nReturns `true` when the right-hand `tsquery` matches the left-hand `tsvector`. \
803            `to_tsvector('quick brown fox') @@ to_tsquery('fox & jump:*')`. Index with GIN on the tsvector for fast lookups.\n"
804    },
805    "~" => {
806      "# `~`\n\n_POSIX regex match (case-sensitive)_\n\nReturns `true` when the left text matches the right regex. \
807            Pair with `||` to build dynamic patterns; for case-insensitive use `~*`. Escape regex metachars with `\\`.\n"
808    },
809    "~*" => "# `~*`\n\n_POSIX regex match (case-insensitive)_\n\n`name ~* '^a'` matches both `Alice` and `aaron`.\n",
810    "!~" => {
811      "# `!~`\n\n_POSIX regex NON-match (case-sensitive)_\n\nInverse of `~`. NULL-propagates like the other comparison operators.\n"
812    },
813    "!~*" => "# `!~*`\n\n_POSIX regex NON-match (case-insensitive)_\n\nInverse of `~*`.\n",
814    "~~" => {
815      "# `~~`\n\n_Internal name of the `LIKE` operator_\n\n`x LIKE 'a%'` is syntactic sugar for `x ~~ 'a%'`. Prefer `LIKE` in source.\n"
816    },
817    "~~*" => {
818      "# `~~*`\n\n_Internal name of the `ILIKE` operator_\n\n`x ILIKE 'a%'` is syntactic sugar for `x ~~* 'a%'`. Prefer `ILIKE` in source.\n"
819    },
820    "!~~" => "# `!~~`\n\n_Internal name of `NOT LIKE`_\n",
821    "!~~*" => "# `!~~*`\n\n_Internal name of `NOT ILIKE`_\n",
822    "^" => {
823      "# `^`\n\n_Exponentiation_\n\n`2 ^ 10` -> `1024`. Returns `double precision` or `numeric` depending on operand types.\n"
824    },
825    "&" => {
826      "# `&`\n\n_Bitwise AND_ (integer / bit / inet)\n\n`5 & 3` -> `1`. For inet: \
827            address-bit AND between the two networks. For bit strings: per-position AND.\n"
828    },
829    "|" => {
830      "# `|`\n\n_Bitwise OR_ (integer / bit / inet)\n\n`5 | 2` -> `7`. \
831            (Do not confuse with `||` -- text/array concatenation.)\n"
832    },
833    "#" => "# `#`\n\n_Bitwise XOR_ (integer / bit)\n\n`5 # 3` -> `6`. Returns the per-bit exclusive-or.\n",
834    _ => return None,
835  };
836  Some(card.to_string())
837}
838
839fn jsonb_operator_hover(source: &str, pos: usize) -> Option<String> {
840  let bytes = source.as_bytes();
841  if pos >= bytes.len() {
842    return None;
843  }
844  let b = bytes[pos];
845  if b != b'-' && b != b'>' && b != b'#' && b != b'@' && b != b'?' {
846    return None;
847  }
848  // Find the operator span this byte belongs to.
849  let mut s = pos;
850  while s > 0 && matches!(bytes[s - 1], b'-' | b'>' | b'#' | b'@' | b'?') {
851    s -= 1;
852  }
853  let mut e = pos;
854  while e < bytes.len() && matches!(bytes[e], b'-' | b'>' | b'#' | b'@' | b'?') {
855    e += 1;
856  }
857  let op = &source[s..e];
858  match op {
859    "->" => Some(
860      "# `->`\n\n_JSON / JSONB path operator_\n\n\
861       Returns the **JSON value** at the given key (or array index).\
862       Result type matches the operand type -- `json -> 'k'` returns json, \
863       `jsonb -> 'k'` returns jsonb.\n\n\
864       ```sql\n\
865       data -> 'profile'        -- jsonb\n\
866       items -> 0               -- first array element as jsonb\n\
867       data -> 'a' -> 'b'       -- chain\n\
868       ```\n"
869        .into(),
870    ),
871    "->>" => Some(
872      "# `->>`\n\n_JSON path operator returning TEXT_\n\n\
873       Same as `->` but always returns **text**, not json. Use this when \
874       you need the unquoted string value.\n\n\
875       ```sql\n\
876       data ->> 'email'         -- text (not jsonb)\n\
877       items ->> 0              -- first element coerced to text\n\
878       ```\n\n\
879       Compares with `=` against a string literal directly: `data ->> 'k' = 'x'`. \
880       Compare with `->` against a json literal: `data -> 'k' = '\"x\"'::jsonb`.\n"
881        .into(),
882    ),
883    "#>" => Some(
884      "# `#>`\n\n_JSON path lookup (array form)_\n\n\
885       Returns the **JSON value** at the path specified by an array of keys.\n\n\
886       ```sql\n\
887       data #> '{a,b,0}'        -- equivalent to data -> 'a' -> 'b' -> 0\n\
888       ```\n"
889        .into(),
890    ),
891    "#>>" => Some(
892      "# `#>>`\n\n_JSON path lookup returning TEXT_\n\n\
893       Same as `#>` but coerces the final value to text.\n\n\
894       ```sql\n\
895       data #>> '{profile,email}'   -- text\n\
896       ```\n"
897        .into(),
898    ),
899    "@?" => Some(
900      "# `@?`\n\n_jsonpath predicate match_\n\n\
901       Returns `true` when the right-side `jsonpath` matches *any* value in the left jsonb. \
902       Companion of `@@` which returns the boolean of the path's filter expression.\n\n\
903       ```sql\n\
904       data @? '$.items[*] ? (@.qty > 0)'\n\
905       ```\n"
906        .into(),
907    ),
908    _ => None,
909  }
910}
911
912/// Cursor on a geometric / math / range comparison operator that
913/// the comparison_operator_hover byte set doesn't cover: `|/`, `||/`,
914/// `@-@`, `##`, `&<`, `&>`, `&<|`, `|>>`, `<<|`, `&&`.
915fn geometric_math_operator_hover(source: &str, pos: usize) -> Option<String> {
916  let bytes = source.as_bytes();
917  if pos >= bytes.len() {
918    return None;
919  }
920  let is_op_byte = |b: u8| matches!(b, b'|' | b'/' | b'@' | b'-' | b'#' | b'&' | b'<' | b'>' | b'?' | b'~' | b'=');
921  if !is_op_byte(bytes[pos]) {
922    return None;
923  }
924  let mut s = pos;
925  while s > 0 && is_op_byte(bytes[s - 1]) {
926    s -= 1;
927  }
928  let mut e = pos;
929  while e < bytes.len() && is_op_byte(bytes[e]) {
930    e += 1;
931  }
932  let op = &source[s..e];
933  let card = match op {
934    "|/" => {
935      "# `|/`\n\n_Square root_\n\n`|/ 25.0` -> `5`. Prefix operator. Prefer the SQL-standard `sqrt()` for readability.\n"
936    },
937    "||/" => "# `||/`\n\n_Cube root_\n\n`||/ 27.0` -> `3`. Prefix operator. Use `cbrt()` for clarity.\n",
938    "@-@" => {
939      "# `@-@`\n\n_Geometric length / circumference_\n\nReturns the length of a path / lseg / line, or the circumference of a circle. \
940              `@-@ lseg '((0,0),(3,4))'` -> `5`.\n"
941    },
942    "##" => "# `##`\n\n_Closest-point operator_\n\nReturns the point on the first object closest to the second.\n",
943    "&<" => {
944      "# `&<`\n\n_Overlaps-to-left_ (geometric / range)\n\nReturns `true` when the left operand does not extend to the right of the right operand.\n"
945    },
946    "&>" => "# `&>`\n\n_Overlaps-to-right_ (geometric / range)\n\nMirror of `&<`.\n",
947    "&<|" => "# `&<|`\n\n_Overlaps-below_ (geometric)\n\nLeft operand does not extend above the right.\n",
948    "|>>" => "# `|>>`\n\n_Strictly above_ (geometric / range)\n\nLeft operand is strictly above the right.\n",
949    "<<|" => "# `<<|`\n\n_Strictly below_ (geometric / range)\n\nLeft operand is strictly below the right.\n",
950    "&&" => {
951      "# `&&`\n\n_Overlaps_ (range / array / multirange)\n\nReturns `true` when the two ranges (or arrays) share at least one element. \
952              `int4range(1,10) && int4range(5,20)` -> `true`. Index with GiST/SP-GiST for fast lookups.\n"
953    },
954    "<<" => {
955      "# `<<`\n\n_Strictly left of_ (range / multirange / inet)\n\n`int4range(1,5) << int4range(10,20)` -> `true`. \
956              For inet: subnet is strictly to the left of the other.\n"
957    },
958    ">>" => "# `>>`\n\n_Strictly right of_ (range / multirange / inet)\n\nMirror of `<<`.\n",
959    "-|-" => {
960      "# `-|-`\n\n_Adjacent to_ (range / multirange)\n\nReturns `true` when the two ranges abut but do not overlap. \
961              `int4range(1,5) -|- int4range(5,10)` -> `true`.\n"
962    },
963    "?-" => {
964      "# `?-`\n\n_Horizontal alignment_ (geometric)\n\nReturns `true` when the operands are on the same horizontal line. \
965              `point '(1,0)' ?- point '(5,0)'` -> `true`.\n"
966    },
967    "?|" => {
968      "# `?|`\n\n_Vertical alignment_ (geometric -- shared with jsonb any-key existence)\n\nFor points/lines: \
969              true when the operands are on the same vertical line. For jsonb: see jsonb path operator card.\n"
970    },
971    "?-|" => {
972      "# `?-|`\n\n_Perpendicular_ (line/lseg)\n\nReturns `true` when the two segments / lines are perpendicular.\n"
973    },
974    "?||" => "# `?||`\n\n_Parallel_ (line/lseg)\n\nReturns `true` when the two segments / lines are parallel.\n",
975    "?#" => {
976      "# `?#`\n\n_Intersects_ (geometric)\n\nReturns `true` when the two objects intersect at a point or share an edge.\n"
977    },
978    "@" => {
979      "# `@`\n\n_Center of_ / contained-by (geometric)\n\nUnary: `@ box '(...)'` returns its center point. Binary: `<obj> @ <obj>` -- left contained by right (geometric).\n"
980    },
981    "~=" => {
982      "# `~=`\n\n_Same as_ (geometric)\n\nReturns `true` when the two geometric objects are equal (point-wise).\n"
983    },
984    ">>=" => {
985      "# `>>=`\n\n_Contains-or-equals_ (inet)\n\n`192.168.0.0/16 >>= 192.168.1.0/24` -> `true`. \
986              Left network contains, or equals, the right. Use for CIDR membership checks.\n"
987    },
988    "<<=" => {
989      "# `<<=`\n\n_Contained-by-or-equals_ (inet)\n\nMirror of `>>=`. The left network is contained by, \
990              or equals, the right.\n"
991    },
992    _ => return None,
993  };
994  Some(card.to_string())
995}
996
997/// Cursor on `<->`, `<#>`, `<%>`, `<<->>`, `<<#>>` operators (KNN
998/// distance / phrase / pg_trgm). Surface a brief explanation.
999fn distance_operator_hover(source: &str, pos: usize) -> Option<String> {
1000  let bytes = source.as_bytes();
1001  if pos >= bytes.len() {
1002    return None;
1003  }
1004  let b = bytes[pos];
1005  if !matches!(b, b'<' | b'>' | b'-' | b'#' | b'%') {
1006    return None;
1007  }
1008  let mut s = pos;
1009  while s > 0 && matches!(bytes[s - 1], b'<' | b'>' | b'-' | b'#' | b'%') {
1010    s -= 1;
1011  }
1012  let mut e = pos;
1013  while e < bytes.len() && matches!(bytes[e], b'<' | b'>' | b'-' | b'#' | b'%') {
1014    e += 1;
1015  }
1016  let op = &source[s..e];
1017  let card = match op {
1018    "<->" => {
1019      "# `<->`\n\n_KNN distance / phrase distance_\n\nGeometric distance (point/box/circle), \
1020              vector L2 distance (pgvector), pg_trgm similarity-distance, or FTS phrase distance \
1021              (immediately adjacent). Index with GiST/SP-GiST/ivfflat for KNN ordering.\n\n\
1022              ```sql\n\
1023              ORDER BY position <-> point '(0,0)' LIMIT 10;\n\
1024              SELECT * FROM articles WHERE doc @@ to_tsquery('quick <-> brown');\n\
1025              ```\n"
1026    },
1027    "<#>" => {
1028      "# `<#>`\n\n_pgvector inner-product distance_\n\nNegative dot product. Use with ivfflat / hnsw \
1029              vector indexes for fast approximate nearest neighbour.\n"
1030    },
1031    "<%>" => {
1032      "# `<%>`\n\n_pg_trgm trigram word-similarity distance_\n\n`1 - word_similarity(a, b)`. \
1033              Pair with `ORDER BY a <%> b LIMIT 10` for fuzzy lookup.\n"
1034    },
1035    "<<->>" => "# `<<->>`\n\n_GiST KNN distance for ranges_\n\nDistance between two range values.\n",
1036    "<<#>>" => "# `<<#>>`\n\n_Index-only KNN distance variant_\n",
1037    _ => return None,
1038  };
1039  Some(card.to_string())
1040}
1041
1042/// Numeric literal hover. Cursor on `123` / `12.5` / `-7` returns a
1043/// tiny card naming kind (integer / float) + the assigned column
1044/// type when in INSERT VALUES / UPDATE SET / WHERE.
1045fn numeric_literal_hover(source: &str, pos: usize, catalog: &Catalog) -> Option<String> {
1046  let bytes = source.as_bytes();
1047  if pos >= bytes.len() {
1048    return None;
1049  }
1050  let here = bytes[pos];
1051  if !here.is_ascii_digit() && here != b'.' {
1052    return None;
1053  }
1054  // Walk back over digits / `.` / `-+`.
1055  let mut s = pos;
1056  while s > 0 && (bytes[s - 1].is_ascii_digit() || bytes[s - 1] == b'.') {
1057    s -= 1;
1058  }
1059  if s > 0 && (bytes[s - 1] == b'-' || bytes[s - 1] == b'+') {
1060    // Only treat as sign when preceded by space / operator / `(` /
1061    // `,` -- not when it's a subtraction in `a-1`.
1062    if s == 1 || matches!(bytes[s - 2], b' ' | b'\t' | b'\n' | b',' | b'(' | b'=' | b'<' | b'>') {
1063      s -= 1;
1064    }
1065  }
1066  let mut e = pos;
1067  while e < bytes.len() && (bytes[e].is_ascii_digit() || bytes[e] == b'.') {
1068    e += 1;
1069  }
1070  let lit = &source[s..e];
1071  if lit.is_empty() || lit == "-" || lit == "+" || lit == "." {
1072    return None;
1073  }
1074  let kind = if lit.contains('.') { "float / numeric" } else { "integer" };
1075  let mut card = format!("# `{lit}`\n\n_{kind} literal_\n");
1076  if let Some((schema, table, col, ty)) = infer_assigned_column(source, s.saturating_sub(1), catalog) {
1077    card.push_str(&format!("\n- **assigned to:** `{schema}.{table}.{col}`\n- **column type:** `{ty}`\n",));
1078  }
1079  Some(card)
1080}
1081
1082/// String-literal hover card. Resolves the literal's destination
1083/// column when the cursor sits inside a `'...'` in INSERT VALUES /
1084/// UPDATE SET / WHERE / ON predicates, and surfaces the column's
1085/// declared type. Falls back to a generic "text/string literal"
1086/// card when no destination can be inferred.
1087fn string_literal_hover(source: &str, pos: usize, catalog: &Catalog) -> Option<String> {
1088  let bytes = source.as_bytes();
1089  // Find the bounds of the enclosing single-quoted literal.
1090  let mut s = pos;
1091  while s > 0 && bytes[s - 1] != b'\'' {
1092    s -= 1;
1093  }
1094  if s == 0 {
1095    return None;
1096  }
1097  let lit_start = s; // first byte inside the quotes
1098  let mut e = pos;
1099  while e < bytes.len() && bytes[e] != b'\'' {
1100    e += 1;
1101  }
1102  let lit_end = e;
1103  let lit = if lit_end > lit_start { &source[lit_start..lit_end] } else { "" };
1104
1105  // Walk back from the opening quote to find the destination column.
1106  let dest_col = infer_assigned_column(source, lit_start - 1, catalog);
1107  let header = format!("# `'{}'`\n\n_text/string literal_\n", lit.chars().take(60).collect::<String>());
1108  let mut body = header;
1109  if let Some((schema, table, col, ty)) = dest_col {
1110    body.push_str(&format!("\n- **assigned to:** `{schema}.{table}.{col}`\n- **column type:** `{ty}`\n",));
1111    // Compatibility heuristic.
1112    let lower = ty.to_ascii_lowercase();
1113    if lower.contains("int")
1114      || lower.contains("numeric")
1115      || lower.contains("decimal")
1116      || lower.contains("real")
1117      || lower.contains("double")
1118      || lower.contains("float")
1119    {
1120      body.push_str(
1121        "\n_Warning:_ destination is numeric -- the literal will be cast at runtime; \
1122         malformed strings raise an `invalid input syntax` error.\n",
1123      );
1124    } else if lower.contains("bool") {
1125      body.push_str(
1126        "\n_Warning:_ destination is boolean -- PG accepts only `'t'`/`'f'`/`'true'`/\
1127         `'false'`/`'yes'`/`'no'`/`'y'`/`'n'`/`'on'`/`'off'`/`'1'`/`'0'`.\n",
1128      );
1129    }
1130  }
1131  Some(body)
1132}
1133
1134/// Walk back from the byte just before the literal's opening quote
1135/// to figure out which column the literal is being assigned to.
1136/// Returns `(schema, table, col, type)` when resolvable.
1137fn infer_assigned_column(
1138  source: &str,
1139  before_quote: usize,
1140  catalog: &Catalog,
1141) -> Option<(String, String, String, String)> {
1142  let bytes = source.as_bytes();
1143  // Strip whitespace + commas back.
1144  let mut i = before_quote;
1145  while i > 0 && bytes[i - 1].is_ascii_whitespace() {
1146    i -= 1;
1147  }
1148  // Three contexts: INSERT VALUES (positional), UPDATE SET col = '...',
1149  // WHERE/ON col = '...'.
1150  // For SET/WHERE: previous non-ws should be `=`; before that an
1151  // identifier (possibly qualified).
1152  if i > 0 && bytes[i - 1] == b'=' {
1153    let mut k = i - 1;
1154    while k > 0 && bytes[k - 1].is_ascii_whitespace() {
1155      k -= 1;
1156    }
1157    let id_end = k;
1158    while k > 0
1159      && (bytes[k - 1].is_ascii_alphanumeric() || bytes[k - 1] == b'_' || bytes[k - 1] == b'.' || bytes[k - 1] == b'"')
1160    {
1161      k -= 1;
1162    }
1163    let raw = &source[k..id_end];
1164    let bare = raw.rsplit('.').next().unwrap_or(raw).trim_matches('"');
1165    if bare.is_empty() {
1166      return None;
1167    }
1168    // Look back further for the FROM / UPDATE / INSERT context to pin
1169    // down which table the column lives in.
1170    if let Some(table) = enclosing_table_name(source, k)
1171      && let Some(t) = catalog.find_table(None, &table)
1172      && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(bare))
1173    {
1174      return Some((t.schema.clone(), t.name.clone(), c.name.clone(), c.data_type.clone()));
1175    }
1176    // Fall back: search every catalog table for the column name.
1177    let hits = catalog.columns_named(bare);
1178    if hits.len() == 1 {
1179      let (t, c) = hits[0];
1180      return Some((t.schema.clone(), t.name.clone(), c.name.clone(), c.data_type.clone()));
1181    }
1182    return None;
1183  }
1184  None
1185}
1186
1187/// Best-effort: walk back through statement and return the latest
1188/// table name following UPDATE / INSERT INTO / FROM keywords.
1189fn enclosing_table_name(source: &str, before: usize) -> Option<String> {
1190  let stmt_start = source[..before].rfind(';').map(|i| i + 1).unwrap_or(0);
1191  let slice = &source[stmt_start..before];
1192  let upper = slice.to_ascii_uppercase();
1193  for kw in ["UPDATE ", "INSERT INTO ", "FROM "] {
1194    if let Some(at) = upper.rfind(kw) {
1195      let after = &slice[at + kw.len()..];
1196      let lead = after.len() - after.trim_start().len();
1197      let raw = &after[lead..];
1198      let id_end =
1199        raw.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.' && c != '"').unwrap_or(raw.len());
1200      if id_end == 0 {
1201        continue;
1202      }
1203      let bare = raw[..id_end].rsplit('.').next().unwrap_or(&raw[..id_end]).trim_matches('"');
1204      return Some(bare.to_string());
1205    }
1206  }
1207  None
1208}
1209
1210/// True when `pos` sits strictly inside a `"..."` double-quoted
1211/// identifier (cursor on the opening or closing quote returns false).
1212/// Walks byte-by-byte from BOF skipping single-quoted strings, line
1213/// comments, block comments, and dollar-quoted bodies so a `"` byte
1214/// nested in any of those doesn't open a phantom identifier.
1215fn cursor_inside_double_quoted_ident(src: &str, pos: usize) -> bool {
1216  let bytes = src.as_bytes();
1217  let n = bytes.len();
1218  let cap = pos.min(n);
1219  let mut i = 0usize;
1220  while i < n {
1221    let c = bytes[i];
1222    // Skip `-- line comment`.
1223    if c == b'-' && i + 1 < n && bytes[i + 1] == b'-' {
1224      let mut j = i + 2;
1225      while j < n && bytes[j] != b'\n' {
1226        j += 1;
1227      }
1228      i = j;
1229      continue;
1230    }
1231    // Skip `/* block comment */`.
1232    if c == b'/' && i + 1 < n && bytes[i + 1] == b'*' {
1233      let mut j = i + 2;
1234      while j + 1 < n && !(bytes[j] == b'*' && bytes[j + 1] == b'/') {
1235        j += 1;
1236      }
1237      i = (j + 2).min(n);
1238      continue;
1239    }
1240    // Skip single-quoted string `'...'` with `''` escape.
1241    if c == b'\'' {
1242      let mut j = i + 1;
1243      while j < n {
1244        if bytes[j] == b'\'' {
1245          if j + 1 < n && bytes[j + 1] == b'\'' {
1246            j += 2;
1247            continue;
1248          }
1249          j += 1;
1250          break;
1251        }
1252        j += 1;
1253      }
1254      i = j;
1255      continue;
1256    }
1257    // Skip dollar-quoted body `$tag$ ... $tag$`.
1258    if c == b'$' {
1259      let mut j = i + 1;
1260      while j < n && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
1261        j += 1;
1262      }
1263      if j < n && bytes[j] == b'$' {
1264        let tag = &bytes[i..=j];
1265        let body_start = j + 1;
1266        let mut k = body_start;
1267        while k + tag.len() <= n && &bytes[k..k + tag.len()] != tag {
1268          k += 1;
1269        }
1270        i = (k + tag.len()).min(n);
1271        continue;
1272      }
1273    }
1274    // Double-quoted identifier `"..."` with `""` escape.
1275    if c == b'"' {
1276      let open = i;
1277      let mut j = i + 1;
1278      while j < n {
1279        if bytes[j] == b'"' {
1280          if j + 1 < n && bytes[j + 1] == b'"' {
1281            j += 2;
1282            continue;
1283          }
1284          break;
1285        }
1286        j += 1;
1287      }
1288      let close = j; // index of closing `"` or n if unterminated.
1289      if cap > open && cap < close {
1290        return true;
1291      }
1292      i = (close + 1).min(n);
1293      continue;
1294    }
1295    i += 1;
1296  }
1297  false
1298}
1299
1300/// True when `pos` sits inside a single-quoted string literal, a
1301/// double-quoted identifier, a `-- line comment`, or a `/* block
1302/// comment */`. Walk byte-by-byte from BOF tracking the current
1303/// lex mode; cheap and exact.
1304fn inside_string_or_comment(src: &str, pos: usize) -> bool {
1305  let bytes = src.as_bytes();
1306  let n = bytes.len().min(pos.max(pos));
1307  let mut i = 0usize;
1308  let cap = pos.min(bytes.len());
1309  while i < cap {
1310    let c = bytes[i];
1311    // Line comment runs to end of line.
1312    if c == b'-' && i + 1 < bytes.len() && bytes[i + 1] == b'-' {
1313      let mut j = i + 2;
1314      while j < bytes.len() && bytes[j] != b'\n' {
1315        j += 1;
1316      }
1317      if pos > i && pos <= j {
1318        return true;
1319      }
1320      i = j + 1;
1321      continue;
1322    }
1323    // Block comment.
1324    if c == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
1325      let start = i;
1326      let mut j = i + 2;
1327      while j + 1 < bytes.len() && !(bytes[j] == b'*' && bytes[j + 1] == b'/') {
1328        j += 1;
1329      }
1330      let end = (j + 2).min(bytes.len());
1331      if pos > start && pos < end {
1332        return true;
1333      }
1334      i = end;
1335      continue;
1336    }
1337    // Single-quoted string. `''` is an escape; treat as continued.
1338    if c == b'\'' {
1339      let start = i;
1340      i += 1;
1341      while i < bytes.len() {
1342        if bytes[i] == b'\'' {
1343          if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
1344            i += 2;
1345            continue;
1346          }
1347          i += 1;
1348          break;
1349        }
1350        i += 1;
1351      }
1352      if pos > start && pos < i {
1353        return true;
1354      }
1355      continue;
1356    }
1357    // Dollar-quoted body `$tag$ ... $tag$`. PL/pgSQL function bodies
1358    // and DO blocks live in this form. They contain *code*, not
1359    // literal text, so the body itself is NOT inert -- hovering on a
1360    // PL/pgSQL keyword like RAISE / EXCEPTION / PERFORM inside the
1361    // body should still surface its knowledge card. We only treat
1362    // string literals / comments WITHIN the body as inert; recurse
1363    // with the body slice so they're detected at the inner cursor.
1364    if c == b'$' {
1365      let tag_start = i;
1366      let mut j = i + 1;
1367      while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
1368        j += 1;
1369      }
1370      if j < bytes.len() && bytes[j] == b'$' {
1371        let tag = &src[tag_start..=j];
1372        let body_start = j + 1;
1373        let mut k = body_start;
1374        while k + tag.len() <= bytes.len() && &src[k..k + tag.len()] != tag {
1375          k += 1;
1376        }
1377        let body_end = k;
1378        if pos >= body_start && pos < body_end {
1379          // Cursor inside the body -- recurse so an inner `'literal'`
1380          // / `-- comment` / `/* ... */` still suppresses hover, but
1381          // keyword positions stay live.
1382          return inside_string_or_comment(&src[body_start..body_end], pos - body_start);
1383        }
1384        i = (k + tag.len()).min(bytes.len());
1385        continue;
1386      }
1387    }
1388    i += 1;
1389  }
1390  let _ = n;
1391  false
1392}
1393
1394/// True when the cursor sits exactly on a `:` byte that's part of
1395/// the `::` cast operator (either the first or second colon).
1396fn cursor_on_double_colon(source: &str, offset: TextSize) -> bool {
1397  let pos: usize = u32::from(offset) as usize;
1398  let bytes = source.as_bytes();
1399  if pos >= bytes.len() {
1400    return false;
1401  }
1402  if bytes[pos] != b':' {
1403    return false;
1404  }
1405  let prev = if pos > 0 { bytes[pos - 1] } else { 0 };
1406  let next = if pos + 1 < bytes.len() { bytes[pos + 1] } else { 0 };
1407  prev == b':' || next == b':'
1408}
1409
1410/// Hover handler for the `*` token. Three flavours:
1411///   * `SELECT *` (no qualifier) -> list every column of every FROM
1412///     table in the current statement.
1413///   * `<alias>.*` -> list every column of `alias`'s bound table.
1414///   * `count(*)` / `count(*)`-like aggregates -> render the function
1415///     card explaining the implicit-all semantics.
1416///
1417/// Returns None when the cursor is not on a star.
1418fn star_hover(source: &str, offset: TextSize, file: &dsl_parse::ParsedFile, catalog: &Catalog) -> Option<String> {
1419  let pos: usize = u32::from(offset) as usize;
1420  let bytes = source.as_bytes();
1421  if pos >= bytes.len() || bytes[pos] != b'*' {
1422    return None;
1423  }
1424  // Walk back over whitespace; if the preceding non-ws char is `.`,
1425  // grab the qualifier (alias / table).
1426  let mut k = pos;
1427  while k > 0 && bytes[k - 1].is_ascii_whitespace() {
1428    k -= 1;
1429  }
1430  if k > 0 && bytes[k - 1] == b'.' {
1431    let id_end = k - 1;
1432    let mut id_start = id_end;
1433    while id_start > 0 {
1434      let c = bytes[id_start - 1] as char;
1435      if c.is_ascii_alphanumeric() || c == '_' || c == '"' {
1436        id_start -= 1;
1437      } else {
1438        break;
1439      }
1440    }
1441    if id_start < id_end {
1442      let qualifier = source[id_start..id_end].trim_matches('"');
1443      if let Some(md) = qualified_star_hover(offset, file, qualifier, catalog) {
1444        return Some(md);
1445      }
1446    }
1447    let _ = id_end;
1448  }
1449  // Walk back over whitespace; if preceded by `(`, look for the
1450  // function call name before the paren (`count(`, `avg(`, etc).
1451  let mut k = pos;
1452  while k > 0 && bytes[k - 1].is_ascii_whitespace() {
1453    k -= 1;
1454  }
1455  if k > 0 && bytes[k - 1] == b'(' {
1456    let paren = k - 1;
1457    let mut fn_end = paren;
1458    while fn_end > 0 && bytes[fn_end - 1].is_ascii_whitespace() {
1459      fn_end -= 1;
1460    }
1461    let mut fn_start = fn_end;
1462    while fn_start > 0 {
1463      let c = bytes[fn_start - 1] as char;
1464      if c.is_ascii_alphanumeric() || c == '_' {
1465        fn_start -= 1;
1466      } else {
1467        break;
1468      }
1469    }
1470    if fn_start < fn_end {
1471      let fname = &source[fn_start..fn_end];
1472      let mut card = format!("# `{fname}(*)`\n\n_aggregate-over-all-rows form_\n\n",);
1473      if let Some(entry) = dsl_knowledge::lookup(fname) {
1474        card.push_str(&dsl_knowledge::render_markdown(entry));
1475        card.push_str("\n\n");
1476      }
1477      card.push_str(
1478        "`*` here means \"count every row\" (no column referenced). \
1479         Equivalent to `count(1)` for COUNT; for other aggregates the \
1480         expansion depends on the function.",
1481      );
1482      return Some(card);
1483    }
1484  }
1485  // Bare `*` in a SELECT projection.
1486  unqualified_star_hover(offset, file, catalog)
1487}
1488
1489fn qualified_star_hover(
1490  offset: TextSize,
1491  file: &dsl_parse::ParsedFile,
1492  alias: &str,
1493  catalog: &Catalog,
1494) -> Option<String> {
1495  // Resolve alias -> bound table via the existing alias_lookup path,
1496  // but we want the column list, not the table card. Find the
1497  // binding directly.
1498  let pos: usize = u32::from(offset) as usize;
1499  let scopes = dsl_resolve::resolve(&file.statements);
1500  let idx = file.statements.iter().position(|s| {
1501    let lo: u32 = s.range.start().into();
1502    let hi: u32 = s.range.end().into();
1503    pos >= lo as usize && pos <= hi as usize
1504  });
1505  let table_name = if let Some(i) = idx {
1506    scopes.get(i).and_then(|scope| {
1507      scope.bindings.iter().find_map(|(k, v)| {
1508        if v.alias.eq_ignore_ascii_case(alias) || k.eq_ignore_ascii_case(alias) {
1509          Some(v.table.name.clone())
1510        } else {
1511          None
1512        }
1513      })
1514    })
1515  } else {
1516    None
1517  };
1518  let table_name = table_name.unwrap_or_else(|| alias.to_string());
1519  let table = catalog.find_table(None, &table_name)?;
1520  let cols: Vec<String> = table.columns.iter().map(|c| format!("{alias}.{}", c.name)).collect();
1521  if cols.is_empty() {
1522    return None;
1523  }
1524  Some(format!(
1525    "# `{alias}.*`\n\n_expands to every column of `{}.{}`_\n\n```sql\n{}\n```\n",
1526    table.schema,
1527    table.name,
1528    cols.join(",\n"),
1529  ))
1530}
1531
1532fn unqualified_star_hover(offset: TextSize, file: &dsl_parse::ParsedFile, catalog: &Catalog) -> Option<String> {
1533  let pos: usize = u32::from(offset) as usize;
1534  // Find the enclosing SELECT statement.
1535  let stmt = file.statements.iter().find(|s| {
1536    let lo: u32 = s.range.start().into();
1537    let hi: u32 = s.range.end().into();
1538    pos >= lo as usize && pos <= hi as usize
1539  })?;
1540  let dsl_parse::StatementKind::Select(sel) = &stmt.kind else { return None };
1541  let mut lines: Vec<String> = Vec::new();
1542  for from in &sel.from {
1543    let alias = from.alias.as_deref().unwrap_or(&from.name);
1544    if let Some(table) = catalog.find_table(from.schema.as_deref(), &from.name) {
1545      for c in &table.columns {
1546        lines.push(format!("{alias}.{}", c.name));
1547      }
1548    }
1549  }
1550  for join in &sel.joins {
1551    let alias = join.table.alias.as_deref().unwrap_or(&join.table.name);
1552    if let Some(table) = catalog.find_table(join.table.schema.as_deref(), &join.table.name) {
1553      for c in &table.columns {
1554        lines.push(format!("{alias}.{}", c.name));
1555      }
1556    }
1557  }
1558  if lines.is_empty() {
1559    return None;
1560  }
1561  Some(format!("# `*`\n\n_expands to every column of every FROM/JOIN table_\n\n```sql\n{}\n```\n", lines.join(",\n"),))
1562}
1563
1564fn role_hover(source: &str, offset: TextSize, token: &str, catalog: &Catalog) -> Option<String> {
1565  let pos: usize = u32::from(offset) as usize;
1566  if !near_role_slot(source, pos) {
1567    return None;
1568  }
1569  let role_norm = token.to_ascii_lowercase();
1570  let in_catalog = catalog.roles.iter().any(|r| r.eq_ignore_ascii_case(&role_norm));
1571  let is_builtin_postgres = role_norm == "postgres";
1572  let is_pg_internal = role_norm.starts_with("pg_");
1573  let is_pseudo = role_norm == "public";
1574  let is_session_kw = matches!(role_norm.as_str(), "current_user" | "session_user" | "current_role");
1575
1576  let label = if is_pseudo {
1577    "_pseudo-role_ -- every existing role and every future role"
1578  } else if is_session_kw {
1579    "_session built-in_ -- resolves to the role that owns this connection"
1580  } else if is_builtin_postgres {
1581    "_bootstrap superuser_ -- created at initdb time"
1582  } else if is_pg_internal {
1583    "_built-in group role_ -- created by initdb / Postgres extensions"
1584  } else if in_catalog {
1585    "_role_ -- present in pg_roles"
1586  } else if catalog.roles.is_empty() {
1587    "_role_ -- catalog not loaded (offline?), cannot verify"
1588  } else {
1589    "_role_ -- **not found** in pg_roles (sql169 will flag this)"
1590  };
1591  Some(format!("# `{token}`\n{label}\n"))
1592}
1593
1594/// True when the cursor's surrounding tokens look like a role-name slot
1595/// in a DDL or session statement. Inspects up to ~60 chars before the
1596/// cursor for one of the role-introducing keyword phrases.
1597fn near_role_slot(source: &str, pos: usize) -> bool {
1598  let take = 60usize.min(pos);
1599  let start = pos.saturating_sub(take);
1600  // Snap to a char boundary so the slice doesn't panic on multi-byte
1601  // chars in a free-form comment / string above the cursor.
1602  let mut start = start;
1603  while start < pos && !source.is_char_boundary(start) {
1604    start += 1;
1605  }
1606  let mut end = pos;
1607  while end > start && !source.is_char_boundary(end) {
1608    end -= 1;
1609  }
1610  let window = source[start..end].to_ascii_uppercase();
1611  // Bare role-introducing keyword phrases. Deliberately does NOT
1612  // include a bare "POLICY" -- CREATE POLICY's role slot is `TO
1613  // <role>`, already caught by " TO " below; a bare "POLICY" used to
1614  // be in this list and matched any identifier within 60 chars of the
1615  // word, including columns inside a completely unrelated USING (...)
1616  // / WITH CHECK (...) expression.
1617  for kw in ["OWNER TO", "GRANT", "REVOKE", "SET ROLE", "RESET ROLE", " TO "] {
1618    if window.contains(kw) {
1619      return true;
1620    }
1621  }
1622  // `FROM` is a role-list slot only when paired with REVOKE
1623  // (`REVOKE ... FROM <role>`). Bare `FROM` appears in every SELECT
1624  // statement and must NOT collapse hover into the role-card path.
1625  // We still cover the explicit REVOKE case via the loop above; this
1626  // branch is just a no-op now.
1627  false
1628}
1629
1630/// Find the CREATE TABLE body that encloses `offset` and resolve the
1631/// column reference against it (using either the live catalog row when
1632/// available, or the parsed buffer ColumnDef when not).
1633fn enclosing_table_column(
1634  offset: TextSize,
1635  file: &dsl_parse::ParsedFile,
1636  token: &str,
1637  catalog: &Catalog,
1638) -> Option<String> {
1639  let pos: usize = u32::from(offset) as usize;
1640  for stmt in &file.statements {
1641    let s: u32 = stmt.range.start().into();
1642    let e: u32 = stmt.range.end().into();
1643    if pos < s as usize || pos > e as usize {
1644      continue;
1645    }
1646    if let dsl_parse::StatementKind::CreateTable(ct) = &stmt.kind {
1647      // Prefer the live catalog row so we get types / nullability /
1648      // FK info. Fall back to the buffer ColumnDef when the table
1649      // isn't yet in the catalog.
1650      if let Some(t) = catalog.find_table(None, &ct.table.name)
1651        && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(token))
1652      {
1653        return Some(render::column(t, c));
1654      }
1655      if let Some(col) = ct.columns.iter().find(|c| c.name.eq_ignore_ascii_case(token)) {
1656        return Some(render::column_decl(&ct.table.name, col));
1657      }
1658    }
1659  }
1660  None
1661}
1662
1663/// If `token` is a FROM / JOIN alias in the enclosing statement, render
1664/// the hover for the actual underlying table instead of "no match". When
1665/// the cursor sits inside a `$$ ... $$` function body, the body text is
1666/// re-parsed standalone so the alias resolves against its inner SELECT.
1667fn alias_lookup(
1668  source: &str,
1669  offset: TextSize,
1670  file: &dsl_parse::ParsedFile,
1671  token: &str,
1672  catalog: &Catalog,
1673) -> Option<String> {
1674  let pos: usize = u32::from(offset) as usize;
1675  // First try resolving in the top-level statement at this offset --
1676  // uses the caller's already-parsed `file`, no parse of its own.
1677  if let Some(t) = resolve_alias_in(source, pos, file, token, catalog) {
1678    return Some(t);
1679  }
1680  // Fallback: re-parse the dollar-quoted body the cursor sits in. This
1681  // is a genuinely different (and much smaller) parse target than
1682  // `file` (parsed from the whole buffer), so it can't reuse `file`
1683  // and still needs its own dsl_parse::parse call -- but it's only
1684  // reached when the top-level resolution above (now free of any
1685  // parse of its own) doesn't find anything, and only parses the body
1686  // substring, not the whole buffer.
1687  if let Some((body_start, body_end)) = enclosing_dollar_body(source, pos) {
1688    let body = &source[body_start..body_end];
1689    let body_pos = pos.saturating_sub(body_start);
1690    let body_file = dsl_parse::parse(body, dsl_parse::Dialect::Postgres);
1691    if let Some(t) = resolve_alias_in(body, body_pos, &body_file, token, catalog) {
1692      return Some(t);
1693    }
1694  }
1695  None
1696}
1697
1698/// When `tok` is a dotted identifier (`a.b` or longer), return only the
1699/// segment the cursor sits in. Returns `None` when `tok` has no `.`.
1700/// Cursor exactly on the dot snaps to the left side.
1701fn dotted_part_under_cursor(source: &str, offset: TextSize, tok: &str) -> Option<String> {
1702  if !tok.contains('.') {
1703    return None;
1704  }
1705  // Re-derive the token's byte range from the source so the cursor
1706  // offset is interpreted in source coordinates, not token-local.
1707  let pos: usize = u32::from(offset) as usize;
1708  let bytes = source.as_bytes();
1709  let mut start = pos;
1710  while start > 0 {
1711    let c = bytes[start - 1] as char;
1712    if c.is_alphanumeric() || c == '_' || c == '.' {
1713      start -= 1;
1714    } else {
1715      break;
1716    }
1717  }
1718  let mut end = pos;
1719  while end < bytes.len() {
1720    let c = bytes[end] as char;
1721    if c.is_alphanumeric() || c == '_' || c == '.' {
1722      end += 1;
1723    } else {
1724      break;
1725    }
1726  }
1727  if pos < start || pos > end {
1728    return None;
1729  }
1730  // Walk segments left-to-right; return the one containing the cursor.
1731  let mut seg_start = start;
1732  for (i, b) in source[start..end].bytes().enumerate() {
1733    if b == b'.' {
1734      let abs = start + i;
1735      if pos <= abs {
1736        return Some(source[seg_start..abs].to_string());
1737      }
1738      seg_start = abs + 1;
1739    }
1740  }
1741  Some(source[seg_start..end].to_string())
1742}
1743
1744/// Scope-aware column hover for `tok` (bare column or `alias.col`).
1745///
1746/// Parses + resolves the statement enclosing `offset`, looks up `tok`
1747/// against its FROM/JOIN bindings, and returns a single-column hover
1748/// when the column belongs to exactly one in-scope table. Falls back to
1749/// `None` so the catalog-wide hover (which shows the "in N tables"
1750/// table when ambiguous) still runs.
1751fn scope_column_lookup(
1752  source: &str,
1753  offset: TextSize,
1754  file: &dsl_parse::ParsedFile,
1755  tok: &str,
1756  catalog: &Catalog,
1757) -> Option<String> {
1758  let pos: usize = u32::from(offset) as usize;
1759  let scopes = dsl_resolve::resolve_with_source(&file.statements, source);
1760  let idx = file.statements.iter().position(|s| {
1761    let lo: u32 = s.range.start().into();
1762    let hi: u32 = s.range.end().into();
1763    pos >= lo as usize && pos <= hi as usize
1764  })?;
1765  let scope = scopes.get(idx)?;
1766
1767  // Qualified form: `alias.col` -- resolve alias, then look up col.
1768  if let Some((left, right)) = tok.split_once('.') {
1769    if right.is_empty() {
1770      return None;
1771    }
1772    // NEW / OLD virtual row aliases inside a CREATE TRIGGER ... WHEN
1773    // predicate or a trigger function body. The bare alias has no
1774    // FROM binding; instead it stands for the trigger's target table
1775    // row. Resolve via the same path as the completion engine: walk
1776    // back to the enclosing `CREATE [OR REPLACE | CONSTRAINT] TRIGGER
1777    // ... ON <tbl>` (or, in a function body, the trigger declared to
1778    // run that function) and render the column card.
1779    let upper_left = left.to_ascii_uppercase();
1780    if upper_left == "NEW" || upper_left == "OLD" {
1781      if let Some(target) = trigger_target_for_hover(source, pos, catalog)
1782        && let Some(t) = catalog.find_table(None, &target)
1783        && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(right))
1784      {
1785        return Some(render::column(t, c));
1786      }
1787      return None;
1788    }
1789    // CTE-qualified column? Render a CTE card showing the alias and
1790    // the projected column name.
1791    if let Some(cte_cols) = scope.cte_columns_of(left)
1792      && cte_cols.iter().any(|c| c.eq_ignore_ascii_case(right))
1793    {
1794      let cols_md = if cte_cols.is_empty() {
1795        String::from("_columns not parsed_")
1796      } else {
1797        cte_cols.iter().map(|c| format!("- `{c}`")).collect::<Vec<_>>().join("\n")
1798      };
1799      return Some(format!("# `{left}.{right}`\n_CTE column_\n\n**`{left}`** projects:\n\n{cols_md}\n"));
1800    }
1801    if let Some(binding) = scope.bindings.iter().find_map(|(k, v)| {
1802      if v.alias.eq_ignore_ascii_case(left) || k.eq_ignore_ascii_case(left) { Some(v) } else { None }
1803    }) && let Some(t) = catalog.find_table(binding.table.schema.as_deref(), &binding.table.name)
1804      && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(right))
1805    {
1806      return Some(render::column(t, c));
1807    }
1808    return None;
1809  }
1810
1811  // Bare column: scan every in-scope table for a unique match.
1812  let mut hit: Option<(&dsl_catalog::Table, &dsl_catalog::Column)> = None;
1813  for b in scope.tables() {
1814    if let Some(t) = catalog.find_table(b.table.schema.as_deref(), &b.table.name)
1815      && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(tok))
1816    {
1817      if hit.is_some() {
1818        // Ambiguous within scope -- let catalog_lookup render
1819        // the multi-table disambiguation card.
1820        return None;
1821      }
1822      hit = Some((t, c));
1823    }
1824  }
1825  hit.map(|(t, c)| render::column(t, c))
1826}
1827
1828/// Run the resolve pipeline against `src`'s pre-parsed `file`, find the
1829/// statement containing `pos`, and return the underlying-table hover
1830/// for `token` when it's an alias in that statement.
1831fn resolve_alias_in(
1832  src: &str,
1833  pos: usize,
1834  file: &dsl_parse::ParsedFile,
1835  token: &str,
1836  catalog: &Catalog,
1837) -> Option<String> {
1838  let scopes = dsl_resolve::resolve_with_source(&file.statements, src);
1839  let idx = file.statements.iter().position(|s| {
1840    let lo: u32 = s.range.start().into();
1841    let hi: u32 = s.range.end().into();
1842    pos >= lo as usize && pos <= hi as usize
1843  })?;
1844  let scope = scopes.get(idx)?;
1845  let binding = scope.bindings.iter().find_map(|(k, v)| {
1846    if v.alias.eq_ignore_ascii_case(token) || k.eq_ignore_ascii_case(token) {
1847      // For real catalog tables, "alias == table name" means the user
1848      // is hovering the table itself (not an alias) -- the catalog
1849      // path handles that. Synthetic bindings (subquery alias / CTE /
1850      // function-call FROM) have table.name == alias by construction,
1851      // so skip this filter for them.
1852      let is_synthetic =
1853        v.table.schema.as_deref().is_some_and(|s| s.starts_with('<')) || scope.cte_columns_of(&v.table.name).is_some();
1854      if !is_synthetic && v.table.name.eq_ignore_ascii_case(token) {
1855        return None;
1856      }
1857      Some(v)
1858    } else {
1859      None
1860    }
1861  })?;
1862  if let Some(t) = catalog.find_table(binding.table.schema.as_deref(), &binding.table.name) {
1863    return Some(render::table(t));
1864  }
1865  // Synthetic bindings: subquery alias (`<subq>`), function-call FROM
1866  // alias (`<func>`), or CTE name -- render a brief card so hovering
1867  // the alias name doesn't silently return None.
1868  if let Some(card) = synthetic_alias_card(scope, binding, token) {
1869    return Some(card);
1870  }
1871  buffer_object(src, &binding.table.name)
1872}
1873
1874fn synthetic_alias_card(
1875  scope: &dsl_resolve::Scope,
1876  binding: &dsl_resolve::binding::Binding,
1877  token: &str,
1878) -> Option<String> {
1879  // CTE: the binding name matches a cte_columns_of entry. Render the
1880  // projected columns so the user can see what `t.<col>` would be.
1881  if let Some(cols) = scope.cte_columns_of(&binding.table.name) {
1882    let cols_md = if cols.is_empty() {
1883      String::from("_columns not parsed_")
1884    } else {
1885      cols.iter().map(|c| format!("- `{c}`")).collect::<Vec<_>>().join("\n")
1886    };
1887    return Some(format!("# `{token}`\n\n_CTE alias_\n\n**Projects:**\n\n{cols_md}\n"));
1888  }
1889  match binding.table.schema.as_deref() {
1890    Some("<subq>") => Some(format!(
1891      "# `{token}`\n\n_Subquery alias_\n\nThe inner SELECT projects its columns through this alias. Hover the column on the right side of `{token}.col` to inspect each one."
1892    )),
1893    Some("<func>") => {
1894      Some(format!("# `{token}`\n\n_Function-call alias_\n\nBound to a set-returning function in the FROM clause."))
1895    },
1896    Some(other) if other.starts_with('<') => {
1897      Some(format!("# `{token}`\n\n_{}_", other.trim_matches(|c| c == '<' || c == '>')))
1898    },
1899    _ => None,
1900  }
1901}
1902
1903/// Return (open_after, close_before) byte offsets when `pos` is inside a
1904/// dollar-quoted `$$ ... $$` block. Used to extract the body for
1905/// re-parsing.
1906fn enclosing_dollar_body(source: &str, pos: usize) -> Option<(usize, usize)> {
1907  let bytes = source.as_bytes();
1908  let n = bytes.len();
1909  let mut i = 0usize;
1910  while i < n {
1911    if bytes[i] == b'$' {
1912      // Read tag.
1913      let tag_start = i;
1914      let mut j = i + 1;
1915      while j < n && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
1916        j += 1;
1917      }
1918      if j < n && bytes[j] == b'$' {
1919        let tag = &source[tag_start..=j];
1920        let body_start = j + 1;
1921        // Find matching close.
1922        let mut k = body_start;
1923        while k + tag.len() <= n {
1924          if &source.as_bytes()[k..k + tag.len()] == tag.as_bytes() {
1925            if pos >= body_start && pos <= k {
1926              return Some((body_start, k));
1927            }
1928            i = k + tag.len();
1929            break;
1930          }
1931          k += 1;
1932        }
1933        if k + tag.len() > n {
1934          if pos >= body_start {
1935            return Some((body_start, n));
1936          }
1937          return None;
1938        }
1939        continue;
1940      }
1941    }
1942    i += 1;
1943  }
1944  None
1945}
1946
1947/// Find the target table for the statement enclosing the cursor when
1948/// it's a CREATE INDEX / UPDATE / DELETE FROM / INSERT INTO -- and look
1949/// up `token` as a column of that single table.
1950fn scoped_column_in_text(
1951  source: &str,
1952  offset: TextSize,
1953  file: &dsl_parse::ParsedFile,
1954  token: &str,
1955  catalog: &Catalog,
1956) -> Option<String> {
1957  let pos: usize = u32::from(offset) as usize;
1958  // Walk back to the last `;` (or start) to bound the current statement.
1959  let stmt_start = source[..pos].rfind(';').map(|i| i + 1).unwrap_or(0);
1960  let slice = &source[stmt_start..pos];
1961  let upper = slice.to_ascii_uppercase();
1962
1963  let table = if upper.contains("CREATE INDEX") || upper.contains("CREATE UNIQUE INDEX") {
1964    // After `ON `.
1965    let on_pos = find_kw(&upper, "ON")?;
1966    read_table_after(slice, on_pos + 2)
1967  } else if upper.starts_with("UPDATE") {
1968    let after = slice["UPDATE".len()..].trim_start();
1969    Some(read_ident(after))
1970  } else if upper.contains("DELETE FROM") {
1971    let p = upper.find("DELETE FROM")?;
1972    let after = slice[p + "DELETE FROM".len()..].trim_start();
1973    Some(read_ident(after))
1974  } else if upper.contains("INSERT INTO") {
1975    let p = upper.find("INSERT INTO")?;
1976    let after = slice[p + "INSERT INTO".len()..].trim_start();
1977    Some(read_ident(after))
1978  } else if upper.contains("ALTER TABLE") {
1979    let p = upper.find("ALTER TABLE")?;
1980    let after = slice[p + "ALTER TABLE".len()..].trim_start();
1981    Some(read_ident(after))
1982  } else {
1983    None
1984  }?;
1985  if table.is_empty() {
1986    return None;
1987  }
1988
1989  if let Some(t) = catalog.find_table(None, &table)
1990    && let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(token))
1991  {
1992    return Some(render::column(t, c));
1993  }
1994  // Buffer-defined fallback (table being declared in same file).
1995  for stmt in &file.statements {
1996    if let dsl_parse::StatementKind::CreateTable(ct) = &stmt.kind
1997      && ct.table.name.eq_ignore_ascii_case(&table)
1998      && let Some(col) = ct.columns.iter().find(|c| c.name.eq_ignore_ascii_case(token))
1999    {
2000      return Some(render::column_decl(&ct.table.name, col));
2001    }
2002  }
2003  None
2004}
2005
2006/// Whole-word search for `kw` in `upper`. Returns the byte offset.
2007fn find_kw(upper: &str, kw: &str) -> Option<usize> {
2008  let bytes = upper.as_bytes();
2009  let n = bytes.len();
2010  let mut from = 0usize;
2011  while let Some(rel) = upper[from..].find(kw) {
2012    let i = from + rel;
2013    let after = i + kw.len();
2014    let prev_ok = i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
2015    let next_ok = after >= n || !(bytes[after].is_ascii_alphanumeric() || bytes[after] == b'_');
2016    if prev_ok && next_ok {
2017      return Some(i);
2018    }
2019    from = after;
2020  }
2021  None
2022}
2023
2024fn read_table_after(src: &str, from: usize) -> Option<String> {
2025  let rest = src[from..].trim_start();
2026  Some(read_ident(rest))
2027}
2028
2029/// Resolve the target table for a `NEW.<col>` / `OLD.<col>` hover.
2030/// Walks the buffer for the enclosing `CREATE [OR REPLACE | CONSTRAINT]
2031/// TRIGGER ... ON <table>` (closest match before the cursor). When the
2032/// cursor sits inside a function body, falls back to finding any
2033/// trigger declared to EXECUTE the surrounding function.
2034fn trigger_target_for_hover(source: &str, pos: usize, catalog: &Catalog) -> Option<String> {
2035  // First try: a CREATE TRIGGER clause in the buffer before the cursor.
2036  let upper = source.to_ascii_uppercase();
2037  let before = &upper[..pos.min(upper.len())];
2038  let idx = ["CREATE OR REPLACE TRIGGER", "CREATE CONSTRAINT TRIGGER", "CREATE TRIGGER"]
2039    .iter()
2040    .filter_map(|kw| before.rfind(kw))
2041    .max();
2042  if let Some(idx) = idx
2043    && let Some(on_idx) = upper[idx..].find(" ON ")
2044  {
2045    let after_on = idx + on_idx + 4;
2046    let tail = &source[after_on..];
2047    let tok: String = tail
2048      .trim_start()
2049      .split(|c: char| c.is_whitespace() || c == '(' || c == ';' || c == ',')
2050      .find(|s| !s.is_empty())
2051      .unwrap_or("")
2052      .to_string();
2053    let tok = if tok.eq_ignore_ascii_case("ONLY") {
2054      tail.trim_start().split_ascii_whitespace().nth(1).unwrap_or("").to_string()
2055    } else {
2056      tok
2057    };
2058    let bare = tok.split('.').next_back().unwrap_or(&tok).trim_matches('"').to_string();
2059    if !bare.is_empty() {
2060      return Some(bare);
2061    }
2062  }
2063  // Fallback: cursor inside a CREATE FUNCTION body whose function is
2064  // wired as a trigger handler -- find that trigger and read its table.
2065  let fn_name = enclosing_create_function_name(source, pos)?;
2066  for f in &catalog.functions {
2067    let _ = f;
2068  }
2069  // Search the buffer's CREATE TRIGGER statements for one that
2070  // EXECUTEs <fn_name>.
2071  let fn_upper = fn_name.to_ascii_uppercase();
2072  let mut from = 0usize;
2073  while let Some(rel) = upper[from..].find("CREATE") {
2074    let at = from + rel;
2075    let chunk = &upper[at..(at + 200).min(upper.len())];
2076    if chunk.contains("TRIGGER")
2077      && let Some(on_idx) = chunk.find(" ON ")
2078    {
2079      // Look for ` EXECUTE ` followed by FUNCTION/PROCEDURE <fn_name>
2080      let stmt_end = upper[at..].find(';').map(|p| at + p).unwrap_or(upper.len());
2081      let stmt_upper = &upper[at..stmt_end];
2082      if stmt_upper.contains(&fn_upper) {
2083        let after_on = at + on_idx + 4;
2084        let tail = &source[after_on..];
2085        let tok: String = tail
2086          .trim_start()
2087          .split(|c: char| c.is_whitespace() || c == '(' || c == ';' || c == ',')
2088          .find(|s| !s.is_empty())
2089          .unwrap_or("")
2090          .to_string();
2091        let bare = tok.split('.').next_back().unwrap_or(&tok).trim_matches('"').to_string();
2092        if !bare.is_empty() {
2093          return Some(bare);
2094        }
2095      }
2096    }
2097    from = at + 6;
2098  }
2099  None
2100}
2101
2102/// Return the name of the CREATE FUNCTION whose body the cursor sits
2103/// in, or None when the cursor isn't inside any function definition.
2104fn enclosing_create_function_name(source: &str, pos: usize) -> Option<String> {
2105  let upper = source.to_ascii_uppercase();
2106  let before = &upper[..pos.min(upper.len())];
2107  let idx = ["CREATE OR REPLACE FUNCTION", "CREATE FUNCTION"].iter().filter_map(|kw| before.rfind(kw)).max()?;
2108  let after = source[idx..].split_once(char::is_whitespace)?.1;
2109  let after = after.trim_start();
2110  // Skip optional `OR REPLACE FUNCTION` head.
2111  let after = if after.to_ascii_uppercase().starts_with("OR REPLACE FUNCTION") {
2112    after.splitn(3, char::is_whitespace).nth(2).unwrap_or(after)
2113  } else if after.to_ascii_uppercase().starts_with("FUNCTION") {
2114    after.split_once(char::is_whitespace).map(|x| x.1).unwrap_or(after)
2115  } else {
2116    after
2117  };
2118  let tok: String = after.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.').collect();
2119  let bare = tok.split('.').next_back().unwrap_or(&tok).to_string();
2120  if bare.is_empty() { None } else { Some(bare) }
2121}
2122
2123fn read_ident(s: &str) -> String {
2124  let name: String = s.chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.').collect();
2125  name.rsplit('.').next().unwrap_or(&name).to_string()
2126}
2127
2128/// Render hover for the NEW / OLD trigger row aliases. If the buffer
2129/// contains a `CREATE TRIGGER ... ON <table>` clause, mention the table
2130/// the alias resolves against; otherwise show generic docs.
2131fn new_old_hover(name: &str, source: &str) -> String {
2132  let target = {
2133    let upper = source.to_ascii_uppercase();
2134    let idx = upper.find("CREATE TRIGGER");
2135    idx.and_then(|i| {
2136      let rest_upper = &upper[i..];
2137      rest_upper.find(" ON ").map(|p| {
2138        let after = &source[i + p + 4..];
2139        let n: String = after.chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.').collect();
2140        n
2141      })
2142    })
2143  };
2144  let desc = if name == "NEW" {
2145    "The row being inserted or updated. Inside an INSERT trigger \
2146         it holds the new tuple; inside UPDATE it holds the new column \
2147         values. NULL inside a DELETE / statement-level trigger."
2148  } else {
2149    "The row before UPDATE / DELETE. NULL inside an INSERT trigger \
2150         or a statement-level trigger."
2151  };
2152  let mut s = format!("# `{name}`\n*Trigger row variable*\n{desc}\n");
2153  if let Some(t) = target.filter(|s| !s.is_empty()) {
2154    s.push_str(&format!("\nResolves to a row of `{t}` (from the enclosing CREATE TRIGGER).\n"));
2155    s.push_str(&format!("```sql\n{name}.<column>\n```\n"));
2156  } else {
2157    s.push_str(
2158      "```sql\nNEW.<column>   -- access a field of the new row\nOLD.<column>   -- access a field of the old row\n```\n",
2159    );
2160  }
2161  s
2162}
2163
2164/// Hover for a PL/pgSQL function parameter or DECLARE'd local. Uses
2165/// the same extraction logic as completion so the two stay in sync.
2166fn plpgsql_local_hover(source: &str, offset: TextSize, token: &str) -> Option<String> {
2167  let pos: usize = u32::from(offset) as usize;
2168  let locals = dsl_completion::plpgsql_locals::extract(source, pos);
2169  if let Some((_, ty)) = locals.params.iter().find(|(n, _)| n.eq_ignore_ascii_case(token)) {
2170    return Some(format!("# `{token}`\n*function parameter*\n```sql\n{token} {ty}\n```\n"));
2171  }
2172  if let Some((_, ty)) = locals.decls.iter().find(|(n, _)| n.eq_ignore_ascii_case(token)) {
2173    return Some(format!("# `{token}`\n*local (DECLARE)*\n```sql\n{token} {ty}\n```\n"));
2174  }
2175  None
2176}
2177
2178/// Like [`db_function`] but biases the lookup by schema when one is
2179/// available -- for `schema.fn` calls the user wants the function
2180/// declared under THAT schema, not an unrelated overload elsewhere.
2181fn db_function_scoped(name: &str, schema: Option<&str>, catalog: &Catalog) -> Option<String> {
2182  let f = catalog
2183    .functions
2184    .iter()
2185    .find(|f| f.name.eq_ignore_ascii_case(name) && schema.is_none_or(|s| f.schema.eq_ignore_ascii_case(s)))?;
2186  let mut s = render::function_full(f);
2187  let (outgoing, incoming) = call_graph(&f.name, catalog);
2188  if !outgoing.is_empty() {
2189    s.push_str("\n**Calls**\n\n");
2190    for callee in outgoing.iter().take(20) {
2191      s.push_str(&format!("- `{callee}`\n"));
2192    }
2193  }
2194  if !incoming.is_empty() {
2195    s.push_str("\n**Called by**\n\n");
2196    for caller in incoming.iter().take(20) {
2197      s.push_str(&format!("- `{caller}`\n"));
2198    }
2199  }
2200  Some(s)
2201}
2202
2203fn db_function(token: &str, catalog: &Catalog) -> Option<String> {
2204  let f = catalog.functions.iter().find(|f| f.name.eq_ignore_ascii_case(token))?;
2205  let mut s = render::function_full(f);
2206  // Append fan-in/fan-out from the workspace catalog. The function
2207  // body lives in f.comment (CREATE OR REPLACE FUNCTION ... $$ ...
2208  // $$); we scan it for other function calls and walk every other
2209  // catalog function's body for calls to this one.
2210  let (outgoing, incoming) = call_graph(&f.name, catalog);
2211  if !outgoing.is_empty() {
2212    s.push_str("\n**Calls**\n\n");
2213    for callee in outgoing.iter().take(20) {
2214      s.push_str(&format!("- `{callee}`\n"));
2215    }
2216    if outgoing.len() > 20 {
2217      s.push_str(&format!("- _… and {} more_\n", outgoing.len() - 20));
2218    }
2219  }
2220  if !incoming.is_empty() {
2221    s.push_str("\n**Called by**\n\n");
2222    for caller in incoming.iter().take(20) {
2223      s.push_str(&format!("- `{caller}`\n"));
2224    }
2225    if incoming.len() > 20 {
2226      s.push_str(&format!("- _… and {} more_\n", incoming.len() - 20));
2227    }
2228  }
2229  Some(s)
2230}
2231
2232fn call_graph(name: &str, catalog: &Catalog) -> (Vec<String>, Vec<String>) {
2233  let mut outgoing = std::collections::BTreeSet::new();
2234  let mut incoming = std::collections::BTreeSet::new();
2235  for f in &catalog.functions {
2236    let Some(body) = f.comment.as_ref() else { continue };
2237    let upper_body = body.to_ascii_uppercase();
2238    if f.name.eq_ignore_ascii_case(name) {
2239      // Outgoing: identifiers in this function's body followed by `(`.
2240      for callee in extract_call_targets(body) {
2241        if !callee.eq_ignore_ascii_case(name) && !is_keyword(&callee) {
2242          outgoing.insert(callee);
2243        }
2244      }
2245    } else if upper_body.contains(&name.to_ascii_uppercase()) {
2246      // Incoming: if some other function's body mentions `name(`.
2247      let needle = format!("{}(", name.to_ascii_lowercase());
2248      if body.to_ascii_lowercase().contains(&needle) {
2249        incoming.insert(f.name.clone());
2250      }
2251    }
2252  }
2253  (outgoing.into_iter().collect(), incoming.into_iter().collect())
2254}
2255
2256fn extract_call_targets(body: &str) -> std::collections::BTreeSet<String> {
2257  let bytes = body.as_bytes();
2258  let n = bytes.len();
2259  let mut out = std::collections::BTreeSet::new();
2260  let mut i = 0;
2261  while i < n {
2262    if !(bytes[i].is_ascii_alphabetic() || bytes[i] == b'_') {
2263      i += 1;
2264      continue;
2265    }
2266    let s = i;
2267    while i < n && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
2268      i += 1;
2269    }
2270    let mut k = i;
2271    while k < n && bytes[k].is_ascii_whitespace() {
2272      k += 1;
2273    }
2274    if k < n && bytes[k] == b'(' {
2275      out.insert(body[s..i].to_string());
2276    }
2277  }
2278  out
2279}
2280
2281fn is_keyword(s: &str) -> bool {
2282  matches!(
2283    s.to_ascii_uppercase().as_str(),
2284    "IF"
2285      | "WHILE"
2286      | "FOR"
2287      | "CASE"
2288      | "WHEN"
2289      | "RETURN"
2290      | "RAISE"
2291      | "SELECT"
2292      | "VALUES"
2293      | "INSERT"
2294      | "UPDATE"
2295      | "DELETE"
2296      | "PERFORM"
2297      | "EXECUTE"
2298      | "DECLARE"
2299      | "BEGIN"
2300      | "EXCEPTION"
2301      | "LOOP"
2302      | "EXIT"
2303      | "CONTINUE"
2304      | "ALL"
2305      | "ANY"
2306      | "OR"
2307      | "AND"
2308      | "NOT"
2309      | "IN"
2310      | "NULLIF"
2311      | "COALESCE"
2312      | "GREATEST"
2313      | "LEAST"
2314      | "CAST"
2315  )
2316}
2317
2318/// Locate a CREATE FUNCTION / CREATE TRIGGER / CREATE INDEX defining
2319/// `token` in the buffer text and render it as a SQL code block. Lets
2320/// hover work before the DB schema has been refreshed.
2321fn buffer_object(source: &str, token: &str) -> Option<String> {
2322  for (heading, kind) in [
2323    ("CREATE OR REPLACE FUNCTION ", "Function"),
2324    ("CREATE FUNCTION ", "Function"),
2325    ("CREATE OR REPLACE PROCEDURE ", "Procedure"),
2326    ("CREATE PROCEDURE ", "Procedure"),
2327    ("CREATE TRIGGER ", "Trigger"),
2328    ("CREATE INDEX ", "Index"),
2329    ("CREATE UNIQUE INDEX ", "Unique index"),
2330    ("CREATE MATERIALIZED VIEW ", "Materialised view"),
2331    ("CREATE VIEW ", "View"),
2332    ("CREATE OR REPLACE VIEW ", "View"),
2333    ("CREATE SEQUENCE ", "Sequence"),
2334    ("CREATE TYPE ", "Type"),
2335    ("CREATE DOMAIN ", "Domain"),
2336    ("CREATE EXTENSION ", "Extension"),
2337    ("CREATE SCHEMA ", "Schema"),
2338    ("CREATE POLICY ", "Policy"),
2339  ] {
2340    if let Some(body) = find_def(source, heading, token) {
2341      return Some(format!(
2342        "# `{token}`\n_{kind} (current buffer)_\n\n```sql\n{}\n```\n",
2343        body.trim_end_matches(|c: char| c.is_whitespace())
2344      ));
2345    }
2346  }
2347  None
2348}
2349
2350/// Walk `source` for `<heading> <token>` and, when found, return the
2351/// statement text up to the next top-level `;` (or EOF). Skips strings
2352/// and dollar-quoted bodies so the terminator is the real statement end.
2353fn find_def(source: &str, heading: &str, token: &str) -> Option<String> {
2354  let upper = source.to_ascii_uppercase();
2355  let mut from = 0usize;
2356  while let Some(rel) = upper[from..].find(heading) {
2357    let start = from + rel;
2358    let after = start + heading.len();
2359    let rest = &source[after..];
2360    let trim_lead = rest.len() - rest.trim_start().len();
2361    let name_start = after + trim_lead;
2362    let name_end = name_start
2363      + source[name_start..]
2364        .chars()
2365        .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.')
2366        .map(|c| c.len_utf8())
2367        .sum::<usize>();
2368    let name = source[name_start..name_end].rsplit('.').next().unwrap_or("");
2369    if name.eq_ignore_ascii_case(token) {
2370      let end = stmt_end(source, name_end);
2371      return Some(source[start..end].to_string());
2372    }
2373    from = after;
2374  }
2375  None
2376}
2377
2378/// Return the byte offset just past the next top-level `;`. Respects
2379/// `$$ ... $$` and single-quoted strings so we don't terminate mid-body.
2380fn stmt_end(source: &str, mut i: usize) -> usize {
2381  let bytes = source.as_bytes();
2382  let n = bytes.len();
2383  while i < n {
2384    match bytes[i] {
2385      b'\'' => {
2386        i += 1;
2387        while i < n {
2388          if bytes[i] == b'\'' {
2389            i += 1;
2390            break;
2391          }
2392          i += 1;
2393        }
2394      },
2395      b'$' => {
2396        // Dollar-quoted body. Read the tag.
2397        let tag_start = i;
2398        let mut j = i + 1;
2399        while j < n && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
2400          j += 1;
2401        }
2402        if j < n && bytes[j] == b'$' {
2403          let tag = &source[tag_start..=j];
2404          i = j + 1;
2405          // Walk until matching tag.
2406          while i + tag.len() <= n {
2407            if &source.as_bytes()[i..i + tag.len()] == tag.as_bytes() {
2408              i += tag.len();
2409              break;
2410            }
2411            i += 1;
2412          }
2413        } else {
2414          i += 1;
2415        }
2416      },
2417      b';' => return i + 1,
2418      _ => i += 1,
2419    }
2420  }
2421  n
2422}
2423
2424/// Cursor on a literal / identifier inside a function-call argument
2425/// list. Walks back to the enclosing `(`, reads the function name,
2426/// looks up the signature in the knowledge base, and renders a card
2427/// pointing at the active parameter slot. Returns None when the
2428/// cursor is not inside a call OR the function is unknown.
2429/// True when the cursor sits on (or just past) an *identifier-shaped*
2430/// token -- one whose first character is `[A-Za-z_]`. Numeric-only
2431/// tokens (`1`, `42`) are NOT treated as identifiers since there's no
2432/// column / alias named after a bare number; that lets the function-
2433/// signature card still fire on numeric literal args. Used as a gate
2434/// so the function-arg card defers to column / alias / table hover
2435/// paths when the cursor is on a real name.
2436fn cursor_on_word_byte(source: &str, pos: usize) -> bool {
2437  let bytes = source.as_bytes();
2438  // Clamp: a caller may pass an offset past EOF (editor sometimes
2439  // sends an end-of-buffer pos that hasn't been re-validated).
2440  let pos = pos.min(bytes.len());
2441  let on = pos < bytes.len() && is_word_byte(bytes[pos]);
2442  let after = pos > 0 && is_word_byte(bytes[pos - 1]);
2443  if !(on || after) {
2444    return false;
2445  }
2446  // Walk back to the start of the word and inspect its first char.
2447  let mut start = pos.min(bytes.len());
2448  while start > 0 && is_word_byte(bytes[start - 1]) {
2449    start -= 1;
2450  }
2451  if start >= bytes.len() {
2452    return false;
2453  }
2454  let first = bytes[start];
2455  first.is_ascii_alphabetic() || first == b'_'
2456}
2457
2458fn is_word_byte(b: u8) -> bool {
2459  b.is_ascii_alphanumeric() || b == b'_'
2460}
2461
2462fn function_arg_at(source: &str, offset: TextSize) -> Option<String> {
2463  let pos: usize = u32::from(offset) as usize;
2464  let bytes = source.as_bytes();
2465  let n = bytes.len();
2466  if pos > n {
2467    return None;
2468  }
2469  // First, determine whether the cursor is currently inside a `'...'`
2470  // string by counting unescaped single-quotes from the start of the
2471  // statement up to `pos`. Odd count = inside a string -- walk back
2472  // past the opening quote before the depth/comma scan.
2473  let mut quotes = 0usize;
2474  let mut j = 0;
2475  while j < pos {
2476    if bytes[j] == b'\'' {
2477      quotes += 1;
2478    }
2479    j += 1;
2480  }
2481  let mut i = pos;
2482  if quotes % 2 == 1 {
2483    while i > 0 && bytes[i - 1] != b'\'' {
2484      i -= 1;
2485    }
2486    i = i.saturating_sub(1); // skip the opening `'`
2487  }
2488  // Now walk back through non-string content, counting commas at the
2489  // enclosing depth and looking for the unmatched `(`.
2490  let mut depth = 0i32;
2491  let mut commas = 0usize;
2492  let mut in_string: Option<u8> = None;
2493  while i > 0 {
2494    i -= 1;
2495    let b = bytes[i];
2496    if let Some(q) = in_string {
2497      if b == q {
2498        in_string = None;
2499      }
2500      continue;
2501    }
2502    match b {
2503      b')' => depth += 1,
2504      b'(' => {
2505        if depth == 0 {
2506          break;
2507        }
2508        depth -= 1;
2509      },
2510      b',' if depth == 0 => commas += 1,
2511      b'\'' => in_string = Some(b'\''),
2512      _ => {},
2513    }
2514  }
2515  if i == 0 && bytes.first() != Some(&b'(') {
2516    return None;
2517  }
2518  // i is at the `(`. Find identifier immediately before it.
2519  let mut end = i;
2520  while end > 0 && bytes[end - 1].is_ascii_whitespace() {
2521    end -= 1;
2522  }
2523  let mut start = end;
2524  while start > 0 {
2525    let c = bytes[start - 1] as char;
2526    if c.is_alphanumeric() || c == '_' || c == '.' {
2527      start -= 1;
2528    } else {
2529      break;
2530    }
2531  }
2532  if start == end {
2533    return None;
2534  }
2535  let name = source[start..end].to_string();
2536  let bare = name.rsplit('.').next().unwrap_or(&name).to_string();
2537  let entry = dsl_knowledge::functions().get(bare.to_ascii_lowercase().as_str())?;
2538  let sig = entry.signature?;
2539  // Parse the signature `fn(p1 t1, p2 t2) -> ret` to surface each
2540  // parameter name on its own line and mark the active one.
2541  let params = parse_signature_params(sig);
2542  let mut lines = Vec::new();
2543  lines.push(format!("-- function call: {bare}"));
2544  lines.push(format!("-- signature: {sig}"));
2545  lines.push(String::new());
2546  for (idx, p) in params.iter().enumerate() {
2547    let marker = if idx == commas { ">>" } else { "  " };
2548    lines.push(format!("{marker} {p}"));
2549  }
2550  Some(format!("```sql\n{}\n```\n", lines.join("\n")))
2551}
2552
2553fn parse_signature_params(sig: &str) -> Vec<String> {
2554  let open = match sig.find('(') {
2555    Some(i) => i + 1,
2556    None => return Vec::new(),
2557  };
2558  let close = match sig.rfind(')') {
2559    Some(i) => i,
2560    None => sig.len(),
2561  };
2562  if close <= open {
2563    return Vec::new();
2564  }
2565  let body = &sig[open..close];
2566  let mut out = Vec::new();
2567  let bytes = body.as_bytes();
2568  let mut depth = 0i32;
2569  let mut start = 0usize;
2570  for (i, &b) in bytes.iter().enumerate() {
2571    match b {
2572      b'(' => depth += 1,
2573      b')' => depth -= 1,
2574      b',' if depth == 0 => {
2575        out.push(body[start..i].trim().to_string());
2576        start = i + 1;
2577      },
2578      _ => {},
2579    }
2580  }
2581  let tail = body[start..].trim();
2582  if !tail.is_empty() {
2583    out.push(tail.to_string());
2584  }
2585  out
2586}
2587
2588/// `nextval('seq')`, `currval('seq')`, `setval('seq', 1)` -- when the
2589/// cursor sits inside the single-quoted sequence-name literal, return
2590/// a sequence card. Returns None when not in such a context.
2591fn sequence_ref_at(source: &str, offset: TextSize) -> Option<String> {
2592  let pos: usize = u32::from(offset) as usize;
2593  let bytes = source.as_bytes();
2594  let n = bytes.len();
2595  if pos >= n {
2596    return None;
2597  }
2598  // Walk back to the opening `'` of the string the cursor is in.
2599  let mut s = pos;
2600  while s > 0 && bytes[s - 1] != b'\'' {
2601    s -= 1;
2602  }
2603  if s == 0 || bytes[s - 1] != b'\'' {
2604    return None;
2605  }
2606  // Walk forward to the closing `'`.
2607  let mut e = pos;
2608  while e < n && bytes[e] != b'\'' {
2609    e += 1;
2610  }
2611  if e == n {
2612    return None;
2613  }
2614  let literal = &source[s..e];
2615  if literal.is_empty() {
2616    return None;
2617  }
2618  // The literal must look like an identifier (sequence name).
2619  if !literal.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '.') {
2620    return None;
2621  }
2622  // Walk back from the opening `'` over whitespace, expect `(`, then
2623  // walk back over whitespace, expect `NEXTVAL` / `CURRVAL` / `SETVAL`.
2624  let mut k = s.saturating_sub(1);
2625  while k > 0 && bytes[k - 1].is_ascii_whitespace() {
2626    k -= 1;
2627  }
2628  if k == 0 || bytes[k - 1] != b'(' {
2629    return None;
2630  }
2631  k -= 1;
2632  let kw_end = k;
2633  while k > 0 && (bytes[k - 1].is_ascii_alphabetic() || bytes[k - 1] == b'_') {
2634    k -= 1;
2635  }
2636  let kw = source[k..kw_end].to_ascii_uppercase();
2637  if !matches!(kw.as_str(), "NEXTVAL" | "CURRVAL" | "SETVAL" | "LASTVAL") {
2638    return None;
2639  }
2640  let qualified = literal;
2641  let bare = qualified.rsplit('.').next().unwrap_or(qualified);
2642  Some(format!(
2643    "```sql\n-- Sequence: {qualified}\n-- referenced by {kw_lc}('{qualified}')\n\nCREATE SEQUENCE {bare};\n```\n",
2644    kw_lc = kw.to_ascii_lowercase(),
2645  ))
2646}