Skip to main content

dsl_completion/
json_path.rs

1//! JSON key completion for `col->'<cursor>'` / `col->>'<cursor>'`
2//! chains.
3//!
4//! Two sources of keys: same-buffer jsonb literal examples (harvested
5//! by a cheap non-parsing scanner), and -- when a live catalog is
6//! available -- `Column.json_keys` recorded for the resolved column.
7//! Extracted from `engine.rs` (was inline there) -- pure code motion,
8//! no behavior change.
9
10use text_size::TextSize;
11
12/// When the cursor sits inside the literal of `<expr>->'<cursor>` or
13/// `<expr>->>'<cursor>`, return the JSON keys observed in same-buffer
14/// jsonb literals (`'{"key":...}'`) so the user can autocomplete
15/// instead of guessing. Handles chained paths: `col->'a'->'b'->'<cursor>'`
16/// walks into nested objects of the harvested literals and surfaces
17/// only the keys present at depth a.b. Returns None outside this
18/// context.
19pub fn json_path_keys_at(source: &str, offset: TextSize) -> Option<Vec<String>> {
20  let pos: usize = u32::from(offset) as usize;
21  let bytes = source.as_bytes();
22  let n = bytes.len().min(source.len());
23  if pos > n {
24    return None;
25  }
26  // Walk back to the opening `'` of the string the cursor is in.
27  let mut s = pos;
28  while s > 0 && bytes[s - 1] != b'\'' {
29    s -= 1;
30  }
31  if s == 0 || bytes[s - 1] != b'\'' {
32    return None;
33  }
34  // The string must be preceded by `->` or `->>`. Skip whitespace.
35  let mut k = s - 1; // points at the `'`
36  while k > 0 && bytes[k - 1].is_ascii_whitespace() {
37    k -= 1;
38  }
39  if k < 2 {
40    return None;
41  }
42  // `->>` form: bytes[k-3]='-', bytes[k-2]='>', bytes[k-1]='>'.
43  // `->`  form: bytes[k-2]='-', bytes[k-1]='>'.
44  let has_double = k >= 3 && bytes[k - 1] == b'>' && bytes[k - 2] == b'>' && bytes[k - 3] == b'-';
45  let has_single = bytes[k - 1] == b'>' && bytes[k - 2] == b'-';
46  if !has_double && !has_single {
47    return None;
48  }
49  // Walk further back to harvest the chain of preceding `->'KEY'`
50  // segments so we know what depth to look up in the JSON blobs.
51  let chain_end = if has_double { k - 3 } else { k - 2 };
52  let chain = collect_json_path_chain(source, chain_end);
53
54  // Harvest jsonb keys from same-buffer literals -- at the requested depth.
55  let mut keys: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
56  let mut i = 0;
57  while i < n {
58    if bytes[i] == b'\'' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'[') {
59      let lit_start = i + 1;
60      let mut j = lit_start;
61      while j < n && bytes[j] != b'\'' {
62        j += 1;
63      }
64      if j < n {
65        let blob = &source[lit_start..j];
66        let nested = navigate_json(blob, &chain).unwrap_or(blob);
67        harvest_json_keys(nested, &mut keys);
68        i = j + 1;
69        continue;
70      }
71    }
72    i += 1;
73  }
74  if keys.is_empty() {
75    return None;
76  }
77  Some(keys.into_iter().collect())
78}
79
80/// Like [`json_path_keys_at`] but also consults `Column.json_keys` from
81/// the catalog. When the cursor sits on a `col->'...'` chain whose head
82/// resolves to a known jsonb column with stored top-level keys, surface
83/// those even when the buffer has no example literal to harvest.
84pub fn json_path_keys_at_with_catalog(
85  source: &str,
86  offset: TextSize,
87  catalog: &dsl_catalog::Catalog,
88) -> Option<Vec<String>> {
89  if let Some(keys) = json_path_keys_at(source, offset) {
90    return Some(keys);
91  }
92  // Walk back to the column name at the head of the `->'k'` chain.
93  let pos: usize = u32::from(offset) as usize;
94  let bytes = source.as_bytes();
95  if pos > bytes.len() {
96    return None;
97  }
98  let mut s = pos;
99  while s > 0 && bytes[s - 1] != b'\'' {
100    s -= 1
101  }
102  if s == 0 {
103    return None;
104  }
105  let mut k = s - 1;
106  while k > 0 && bytes[k - 1].is_ascii_whitespace() {
107    k -= 1
108  }
109  let has_double = k >= 3 && bytes[k - 1] == b'>' && bytes[k - 2] == b'>' && bytes[k - 3] == b'-';
110  let has_single = bytes[k - 1] == b'>' && bytes[k - 2] == b'-';
111  if !has_double && !has_single {
112    return None;
113  }
114  let arrow_at = if has_double { k - 3 } else { k - 2 };
115  // Identifier just before the first arrow.
116  let mut j = arrow_at;
117  while j > 0 && bytes[j - 1].is_ascii_whitespace() {
118    j -= 1
119  }
120  let id_end = j;
121  while j > 0
122    && (bytes[j - 1].is_ascii_alphanumeric() || bytes[j - 1] == b'_' || bytes[j - 1] == b'.' || bytes[j - 1] == b'"')
123  {
124    j -= 1;
125  }
126  if j == id_end {
127    return None;
128  }
129  let col_full = &source[j..id_end];
130  let col_bare = col_full.rsplit('.').next().unwrap_or(col_full).trim_matches('"');
131  for t in catalog.tables() {
132    if let Some(c) = t.columns.iter().find(|c| c.name.eq_ignore_ascii_case(col_bare))
133      && let Some(keys) = &c.json_keys
134      && !keys.is_empty()
135    {
136      return Some(keys.clone());
137    }
138  }
139  None
140}
141
142/// Walk backwards from `end` collecting `->'KEY'` (or `->>'KEY'`)
143/// segments in left-to-right order. Stops at the first non-segment
144/// token. Whitespace between segments is tolerated.
145fn collect_json_path_chain(source: &str, end: usize) -> Vec<String> {
146  let bytes = source.as_bytes();
147  let mut chain: Vec<String> = Vec::new();
148  let mut k = end;
149  loop {
150    // Skip trailing whitespace.
151    while k > 0 && bytes[k - 1].is_ascii_whitespace() {
152      k -= 1;
153    }
154    // Need a closing `'`.
155    if k == 0 || bytes[k - 1] != b'\'' {
156      break;
157    }
158    let close = k - 1;
159    // Walk back to the opening `'`.
160    let mut open = close;
161    while open > 0 && bytes[open - 1] != b'\'' {
162      open -= 1;
163    }
164    if open == 0 {
165      break;
166    }
167    let key = &source[open..close];
168    let preceded_by_arrow = {
169      let mut p = open.saturating_sub(1); // points at the opening `'`
170      while p > 0 && bytes[p - 1].is_ascii_whitespace() {
171        p -= 1;
172      }
173      let double = p >= 3 && bytes[p - 1] == b'>' && bytes[p - 2] == b'>' && bytes[p - 3] == b'-';
174      let single = p >= 2 && bytes[p - 1] == b'>' && bytes[p - 2] == b'-';
175      if double || single { Some(if double { p - 3 } else { p - 2 }) } else { None }
176    };
177    if let Some(next_end) = preceded_by_arrow {
178      chain.push(key.to_string());
179      k = next_end;
180    } else {
181      break;
182    }
183  }
184  chain.reverse();
185  chain
186}
187
188/// Given a JSON object literal (no surrounding quotes), navigate down
189/// the `keys` path and return a sub-blob that the caller can re-scan
190/// for keys. Returns None when the path doesn't resolve.
191fn navigate_json<'a>(blob: &'a str, keys: &[String]) -> Option<&'a str> {
192  if keys.is_empty() {
193    return Some(blob);
194  }
195  let mut current = blob;
196  for key in keys {
197    current = find_value_for_key(current, key)?;
198  }
199  Some(current)
200}
201
202/// Locate `"key":` in `blob` and return the slice starting at the
203/// value's first byte and ending at the matching close (`}` for
204/// objects, `]` for arrays, or the next top-level `,`).
205fn find_value_for_key<'a>(blob: &'a str, key: &str) -> Option<&'a str> {
206  let needle = format!("\"{key}\"");
207  let bytes = blob.as_bytes();
208  let n = bytes.len();
209  let mut i = 0;
210  while i + needle.len() <= n {
211    if blob[i..i + needle.len()] == needle {
212      let mut j = i + needle.len();
213      while j < n && bytes[j].is_ascii_whitespace() {
214        j += 1;
215      }
216      if j >= n || bytes[j] != b':' {
217        i += 1;
218        continue;
219      }
220      j += 1;
221      while j < n && bytes[j].is_ascii_whitespace() {
222        j += 1;
223      }
224      if j >= n {
225        return None;
226      }
227      let value_start = j;
228      let value_end = scan_value_end(bytes, value_start);
229      return Some(&blob[value_start..value_end]);
230    }
231    i += 1;
232  }
233  None
234}
235
236fn scan_value_end(bytes: &[u8], start: usize) -> usize {
237  let n = bytes.len();
238  if start >= n {
239    return n;
240  }
241  match bytes[start] {
242    b'{' | b'[' => {
243      let open = bytes[start];
244      let close = if open == b'{' { b'}' } else { b']' };
245      let mut depth = 1i32;
246      let mut i = start + 1;
247      while i < n && depth > 0 {
248        match bytes[i] {
249          b'"' => {
250            i += 1;
251            while i < n && bytes[i] != b'"' {
252              if bytes[i] == b'\\' && i + 1 < n {
253                i += 2;
254              } else {
255                i += 1;
256              }
257            }
258          },
259          c if c == open => depth += 1,
260          c if c == close => depth -= 1,
261          _ => {},
262        }
263        i += 1;
264      }
265      i.min(n)
266    },
267    b'"' => {
268      let mut i = start + 1;
269      while i < n && bytes[i] != b'"' {
270        if bytes[i] == b'\\' && i + 1 < n {
271          i += 2;
272        } else {
273          i += 1;
274        }
275      }
276      (i + 1).min(n)
277    },
278    _ => {
279      let mut i = start;
280      while i < n && bytes[i] != b',' && bytes[i] != b'}' && bytes[i] != b']' {
281        i += 1;
282      }
283      i
284    },
285  }
286}
287
288fn harvest_json_keys(blob: &str, out: &mut std::collections::BTreeSet<String>) {
289  // Cheap key-scanner: find each `"<key>":` pair without a real JSON
290  // parser. Good enough for completion -- if the blob is malformed,
291  // we miss a key or two, no harm done.
292  let b = blob.as_bytes();
293  let n = b.len();
294  let mut i = 0;
295  while i < n {
296    if b[i] == b'"' {
297      let key_start = i + 1;
298      let mut j = key_start;
299      while j < n && b[j] != b'"' {
300        j += 1;
301      }
302      if j >= n {
303        return;
304      }
305      let key = &blob[key_start..j];
306      // Look forward for `:`.
307      let mut k = j + 1;
308      while k < n && b[k].is_ascii_whitespace() {
309        k += 1;
310      }
311      if k < n && b[k] == b':' && !key.is_empty() && key.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') {
312        out.insert(key.to_string());
313      }
314      i = j + 1;
315      continue;
316    }
317    i += 1;
318  }
319}