Skip to main content

dsl_completion/
plpgsql_locals.rs

1//! Extract PL/pgSQL function parameters and DECLARE'd locals from the
2//! buffer text so completion can surface them inside a function body.
3//!
4//! Approach: walk backwards from `offset` to the most recent
5//! `CREATE [OR REPLACE] FUNCTION|PROCEDURE <name> (...)` header. Parse
6//! its parameter list, then continue forward to find any `DECLARE ... BEGIN`
7//! blocks before the cursor. Both contribute completion items.
8
9use crate::item::{Item, ItemKind};
10
11#[derive(Debug, Default, Clone)]
12pub struct Locals {
13  pub params: Vec<(String, String)>, // (name, type)
14  pub decls: Vec<(String, String)>,  // (name, type)
15}
16
17/// Scan the buffer for the function header that encloses `offset`. When
18/// the cursor sits outside any function the returned struct is empty.
19pub fn extract(source: &str, offset: usize) -> Locals {
20  let bytes = source.as_bytes();
21  let cursor = offset.min(bytes.len());
22  let mut out = Locals::default();
23
24  // Find the most recent CREATE FUNCTION / PROCEDURE header at or
25  // before the cursor. Case-insensitive, whole-word.
26  let upper = source.to_ascii_uppercase();
27  let mut header_start: Option<usize> = None;
28  for needle in ["CREATE OR REPLACE FUNCTION ", "CREATE OR REPLACE PROCEDURE ", "CREATE FUNCTION ", "CREATE PROCEDURE "]
29  {
30    let mut from = 0usize;
31    while let Some(rel) = upper[from..].find(needle) {
32      let pos = from + rel;
33      if pos > cursor {
34        break;
35      }
36      // Boundary check on preceding char.
37      let prev_ok = pos == 0 || !(bytes[pos - 1].is_ascii_alphanumeric() || bytes[pos - 1] == b'_');
38      if prev_ok {
39        header_start = Some(pos);
40      }
41      from = pos + needle.len();
42    }
43  }
44  let Some(start) = header_start else { return out };
45
46  // The header parameter list lives between the first `(` after start
47  // and its matching `)`. Read it.
48  if let Some(open) = source[start..].find('(') {
49    let open_abs = start + open;
50    if let Some(close_abs) = match_paren(bytes, open_abs) {
51      let params_text = &source[open_abs + 1..close_abs];
52      out.params = parse_param_list(params_text);
53      // Now look for DECLARE ... BEGIN between close_abs and cursor.
54      out.decls = scan_decls(&source[close_abs..cursor.max(close_abs)]);
55    }
56  }
57  out
58}
59
60/// Match the closing `)` for the `(` at `open`. Returns None on mismatch.
61fn match_paren(bytes: &[u8], open: usize) -> Option<usize> {
62  if open >= bytes.len() || bytes[open] != b'(' {
63    return None;
64  }
65  let mut depth = 0i32;
66  let mut i = open;
67  let n = bytes.len();
68  while i < n {
69    match bytes[i] {
70      b'(' => depth += 1,
71      b')' => {
72        depth -= 1;
73        if depth == 0 {
74          return Some(i);
75        }
76      },
77      b'\'' => {
78        i += 1;
79        while i < n {
80          if bytes[i] == b'\'' {
81            i += 1;
82            break;
83          }
84          i += 1;
85        }
86        continue;
87      },
88      _ => {},
89    }
90    i += 1;
91  }
92  None
93}
94
95/// Parse a parameter list like `p_user_id UUID, p_email text DEFAULT ''`.
96/// Skips arg modes (IN / OUT / INOUT / VARIADIC).
97fn parse_param_list(s: &str) -> Vec<(String, String)> {
98  let mut out = Vec::new();
99  for part in split_top_level(s, ',') {
100    let trimmed = part.trim();
101    if trimmed.is_empty() {
102      continue;
103    }
104    // Strip any trailing `DEFAULT <expr>` / `= <expr>` so we keep just
105    // the name + type.
106    let head = trimmed.split_once(" DEFAULT ").map(|(h, _)| h).unwrap_or(trimmed);
107    let head = head.split_once(" default ").map(|(h, _)| h).unwrap_or(head);
108    let head = head.split_once(" = ").map(|(h, _)| h).unwrap_or(head);
109    let mut tokens = head.split_whitespace().peekable();
110    // Skip arg mode prefix
111    if let Some(first) = tokens.peek() {
112      let up = first.to_ascii_uppercase();
113      if matches!(up.as_str(), "IN" | "OUT" | "INOUT" | "VARIADIC") {
114        tokens.next();
115      }
116    }
117    let Some(name) = tokens.next() else {
118      continue;
119    };
120    let ty: String = tokens.collect::<Vec<_>>().join(" ");
121    if !ty.is_empty() {
122      out.push((name.to_string(), ty));
123    }
124  }
125  out
126}
127
128/// Walk forward from `body` (the text between the closing param `)` and
129/// the cursor) collecting DECLARE'd variables. Multiple DECLARE blocks
130/// inside nested BEGIN/END are accumulated.
131fn scan_decls(body: &str) -> Vec<(String, String)> {
132  let bytes = body.as_bytes();
133  let n = bytes.len();
134  let upper = body.to_ascii_uppercase();
135  let mut out = Vec::new();
136  let mut from = 0usize;
137  while let Some(rel) = upper[from..].find("DECLARE") {
138    let s = from + rel;
139    // Boundary check.
140    let prev_ok = s == 0 || !(bytes[s - 1].is_ascii_alphanumeric() || bytes[s - 1] == b'_');
141    let after = s + "DECLARE".len();
142    let next_ok = after >= n || !(bytes[after].is_ascii_alphanumeric() || bytes[after] == b'_');
143    if !prev_ok || !next_ok {
144      from = after;
145      continue;
146    }
147    // Find the matching BEGIN that ends this DECLARE block (case-insensitive).
148    let block_end = upper[after..].find("BEGIN").map(|p| after + p).unwrap_or(n);
149    let decl_body = &body[after..block_end];
150    out.extend(parse_decl_body(decl_body));
151    from = block_end;
152  }
153  out
154}
155
156/// Each declaration ends with `;`. Pattern: `<name> [CONSTANT] <type> [DEFAULT|:= expr]`.
157fn parse_decl_body(s: &str) -> Vec<(String, String)> {
158  let mut out = Vec::new();
159  for stmt in s.split(';') {
160    let trimmed = stmt.trim();
161    if trimmed.is_empty() {
162      continue;
163    }
164    // Strip default expression: anything after `:=` or `DEFAULT`.
165    let head = trimmed
166      .split_once(":=")
167      .map(|(h, _)| h)
168      .or_else(|| trimmed.split_once(" DEFAULT ").map(|(h, _)| h))
169      .or_else(|| trimmed.split_once(" default ").map(|(h, _)| h))
170      .unwrap_or(trimmed);
171    let mut tokens = head.split_whitespace().peekable();
172    let Some(name) = tokens.next() else {
173      continue;
174    };
175    // Skip CONSTANT keyword.
176    if let Some(t) = tokens.peek()
177      && t.eq_ignore_ascii_case("CONSTANT")
178    {
179      tokens.next();
180    }
181    let ty: String = tokens.collect::<Vec<_>>().join(" ");
182    if !ty.is_empty() {
183      out.push((name.to_string(), ty));
184    }
185  }
186  out
187}
188
189/// Split `s` on `sep` at parenthesis depth 0, respecting single-quoted
190/// strings. Used by `parse_param_list`.
191fn split_top_level(s: &str, sep: char) -> Vec<String> {
192  let bytes = s.as_bytes();
193  let n = bytes.len();
194  let mut out = Vec::new();
195  let mut depth = 0i32;
196  let mut start = 0usize;
197  let mut i = 0usize;
198  while i < n {
199    let c = bytes[i] as char;
200    match c {
201      '(' => depth += 1,
202      ')' => depth -= 1,
203      '\'' => {
204        i += 1;
205        while i < n {
206          if bytes[i] == b'\'' {
207            i += 1;
208            break;
209          }
210          i += 1;
211        }
212        continue;
213      },
214      _ if c == sep && depth == 0 => {
215        out.push(s[start..i].to_string());
216        start = i + 1;
217      },
218      _ => {},
219    }
220    i += 1;
221  }
222  out.push(s[start..].to_string());
223  out
224}
225
226/// Look up the declared type of a PL/pgSQL local by name. Searches
227/// parameters first, then DECLARE'd locals. Case-insensitive match.
228/// Returns the raw type string (`users`, `INT`, `promo_codes%ROWTYPE`,
229/// etc.) so callers can decide what to do with it.
230pub fn type_of(locals: &Locals, name: &str) -> Option<String> {
231  for (n, t) in locals.params.iter().chain(locals.decls.iter()) {
232    if n.eq_ignore_ascii_case(name) {
233      return Some(t.clone());
234    }
235  }
236  None
237}
238
239/// Push `Locals` as completion items.
240pub fn push_items(locals: &Locals, out: &mut Vec<Item>) {
241  for (name, ty) in &locals.params {
242    out.push(Item {
243      label: name.clone(),
244      kind: ItemKind::Parameter,
245      detail: Some(ty.clone()),
246      description: Some("parameter".into()),
247      documentation_md: Some(format!("**{name}**\n\nfunction parameter — `{ty}`")),
248      insert_text: name.clone(),
249      is_snippet: false,
250      kb_entry: None,
251      sort_priority: 5,
252    });
253  }
254  for (name, ty) in &locals.decls {
255    out.push(Item {
256      label: name.clone(),
257      kind: ItemKind::Variable,
258      detail: Some(ty.clone()),
259      description: Some("local".into()),
260      documentation_md: Some(format!("**{name}**\n\nlocal — `{ty}` (declared in this function)")),
261      insert_text: name.clone(),
262      is_snippet: false,
263      kb_entry: None,
264      sort_priority: 5,
265    });
266  }
267}