1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use super::jq_functions::{JQ_FUNCTION_METADATA, is_element_context_function};
use super::scan_state::ScanState;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BraceType {
Curly,
Square,
Paren,
}
/// Context for parentheses that changes how autocomplete behaves
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionContext {
/// Function that iterates over elements (map, select, sort_by, etc.)
/// Inner value is the function name for debugging/display.
ElementIterator(&'static str),
}
/// Information about an open brace/bracket/paren
#[derive(Debug, Clone)]
pub struct BraceInfo {
pub pos: usize,
pub brace_type: BraceType,
pub context: Option<FunctionContext>,
}
#[derive(Debug, Clone)]
pub struct BraceTracker {
open_braces: Vec<BraceInfo>,
query_snapshot: String,
}
impl Default for BraceTracker {
fn default() -> Self {
Self::new()
}
}
impl BraceTracker {
pub fn new() -> Self {
Self {
open_braces: Vec::new(),
query_snapshot: String::new(),
}
}
pub fn rebuild(&mut self, query: &str) {
self.open_braces.clear();
self.query_snapshot = query.to_string();
let mut state = ScanState::default();
for (pos, ch) in query.char_indices() {
if !state.is_in_string() {
match ch {
'{' => self.open_braces.push(BraceInfo {
pos,
brace_type: BraceType::Curly,
context: None,
}),
'[' => self.open_braces.push(BraceInfo {
pos,
brace_type: BraceType::Square,
context: None,
}),
'(' => {
let context = Self::detect_function_context(query, pos);
self.open_braces.push(BraceInfo {
pos,
brace_type: BraceType::Paren,
context,
});
}
'}' => {
if let Some(info) = self.open_braces.last()
&& info.brace_type == BraceType::Curly
{
self.open_braces.pop();
}
}
']' => {
if let Some(info) = self.open_braces.last()
&& info.brace_type == BraceType::Square
{
self.open_braces.pop();
}
}
')' => {
if let Some(info) = self.open_braces.last()
&& info.brace_type == BraceType::Paren
{
self.open_braces.pop();
}
}
_ => {}
}
}
state = state.advance(ch);
}
}
/// Detect if the parenthesis at `paren_pos` is preceded by an element-context function.
/// Scans backwards to find a function name, then checks if it's in ELEMENT_CONTEXT_FUNCTIONS.
fn detect_function_context(query: &str, paren_pos: usize) -> Option<FunctionContext> {
let bytes = query.as_bytes();
if paren_pos == 0 {
return None;
}
// Skip whitespace before the paren
let mut end = paren_pos;
while end > 0 && bytes[end - 1].is_ascii_whitespace() {
end -= 1;
}
if end == 0 {
return None;
}
// Check if there's a word character before the paren
if !Self::is_word_char(bytes[end - 1]) {
return None;
}
// Find the start of the word
let mut start = end - 1;
while start > 0 && Self::is_word_char(bytes[start - 1]) {
start -= 1;
}
// Extract the function name
let func_name = &query[start..end];
// Look up in JQ_FUNCTION_METADATA to get static str reference
let static_name = JQ_FUNCTION_METADATA
.iter()
.find(|f| f.name == func_name)
.map(|f| f.name)?;
if is_element_context_function(static_name) {
Some(FunctionContext::ElementIterator(static_name))
} else {
None
}
}
fn is_word_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
pub fn context_at(&self, pos: usize) -> Option<BraceType> {
for info in self.open_braces.iter().rev() {
if info.pos < pos {
return Some(info.brace_type);
}
}
None
}
pub fn is_in_object(&self, pos: usize) -> bool {
self.context_at(pos) == Some(BraceType::Curly)
}
/// Check if the cursor position is inside any element-context function.
/// This checks ALL enclosing parens, not just the innermost one,
/// so `map(limit(5; .` correctly returns true (map provides element context).
pub fn is_in_element_context(&self, pos: usize) -> bool {
self.open_braces.iter().any(|info| {
info.pos < pos
&& info.brace_type == BraceType::Paren
&& matches!(info.context, Some(FunctionContext::ElementIterator(_)))
})
}
/// Check if tracker is stale (test helper)
#[cfg(test)]
pub fn is_stale(&self, current_query: &str) -> bool {
self.query_snapshot != current_query
}
/// Check if the cursor position is in a non-executing context where cache doesn't reflect
/// the expression being typed.
///
/// Non-executing contexts include:
/// - Inside element-iterating functions (map, select, sort_by, etc.)
/// - Inside array builders `[expr, expr]`
/// - Inside object builder values `{key: expr}`
///
/// In these contexts, the cache is stale and we need to extract path and navigate.
pub fn is_in_non_executing_context(&self, pos: usize) -> bool {
// Element-iterating functions (existing check)
if self.is_in_element_context(pos) {
return true;
}
// Check innermost brace context
for info in self.open_braces.iter().rev() {
if info.pos >= pos {
continue;
}
match info.brace_type {
// Array builder: non-executing (but not array iteration `.[]`)
BraceType::Square => {
if self.is_array_builder(info.pos) {
return true;
}
}
// Object builder value position: non-executing
BraceType::Curly => {
if self.is_after_colon_in_object(pos) {
return true;
}
}
// Parentheses: only non-executing if it's an element-context function
// (already handled above by is_in_element_context)
BraceType::Paren => {}
}
}
false
}
/// Get the innermost open brace info at a position.
pub fn innermost_brace_info(&self, pos: usize) -> Option<&BraceInfo> {
self.open_braces.iter().rev().find(|info| info.pos < pos)
}
/// Check if the square bracket at `bracket_pos` is an array builder vs iteration.
///
/// Array iteration: `.[]`, `.[0]`, `.foo[]`
/// Array builder: `[.a, .b]`, `[1, 2, 3]`
fn is_array_builder(&self, bracket_pos: usize) -> bool {
if bracket_pos == 0 {
return true; // `[...]` at start is always builder
}
let before = &self.query_snapshot[..bracket_pos];
let trimmed = before.trim_end();
if trimmed.is_empty() {
return true;
}
let last_char = trimmed.chars().last().unwrap();
// Array iteration follows: `.`, `]`, `?`, identifier chars
// Array builder follows: `|`, `;`, `(`, `[`, `{`, `,`, `:`
matches!(last_char, '|' | ';' | '(' | '[' | '{' | ',' | ':')
}
/// Check if position is after a colon in an object (value position).
fn is_after_colon_in_object(&self, pos: usize) -> bool {
// Find the innermost curly brace
let curly_pos = self
.open_braces
.iter()
.rev()
.find(|info| info.pos < pos && info.brace_type == BraceType::Curly)
.map(|info| info.pos);
if let Some(curly_pos) = curly_pos {
let inside = &self.query_snapshot[curly_pos + 1..pos.min(self.query_snapshot.len())];
// Check if we're after a colon (value position) vs before (key position)
if let Some(last_colon) = inside.rfind(':') {
if let Some(last_comma) = inside.rfind(',') {
return last_colon > last_comma;
}
return true;
}
}
false
}
}
#[cfg(test)]
#[path = "brace_tracker_tests.rs"]
mod brace_tracker_tests;