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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! Finite State Machine for completion context determination
//!
//! This module implements a simple FSM that walks through tokens to determine
//! what kind of completion should be provided. The FSM is designed to be:
//! - Simple and predictable
//! - Error-tolerant (handles incomplete input)
//! - Fast (O(n) single pass through tokens)
//! - Context-aware (tracks parentheses to avoid completing inside function arguments)
use super::context::CompletionContext;
use super::token_stream::{TokenStream, UnifiedToken};
/// FSM states representing different positions in a command
#[derive(Debug, Clone, PartialEq)]
pub enum CompletionState {
/// Initial state
Start,
// === Mongo Shell States ===
/// After "db" keyword
AfterDb,
/// After "db." - should complete collection names
AfterDbDot,
/// After "db.collection"
AfterCollection,
/// After "db.collection." - should complete operation names
AfterCollectionDot,
/// Inside parentheses - no completion to avoid suggesting when typing function arguments
/// Example: `db.users.findOne(find` should NOT complete "find" to "findOne"
InsideParentheses,
// === SQL States ===
/// After "FROM" keyword - should complete collection/table names
SqlFrom,
/// After "JOIN" keyword - should complete collection/table names
SqlJoin,
/// After "WHERE" keyword
SqlWhere,
/// After table name in FROM/JOIN - expect WHERE, JOIN, ORDER, LIMIT, etc. - no completion
SqlAfterTableName,
/// After LIMIT/OFFSET - expect numbers - no completion
SqlAfterLimit,
/// After ORDER BY - expect column names
SqlOrderBy,
/// After semicolon or complete statement - no completion
SqlComplete,
// === Shell Command States ===
/// After "show" command - should complete subcommands
ShowCommand,
/// After "use" command - should complete database names
UseCommand,
}
impl CompletionState {
/// Perform state transition based on current state and token
pub fn next(self, token: &UnifiedToken) -> Self {
use CompletionState::*;
match (self, token) {
// === Check for parentheses first (highest priority) ===
// If we encounter an opening parenthesis, enter InsideParentheses state
(_, t) if t.is_open_paren() => InsideParentheses,
// If we're inside parentheses and see a closing paren, return to Start
(InsideParentheses, t) if t.is_close_paren() => Start,
// Stay inside parentheses for any other token
(InsideParentheses, _) => InsideParentheses,
// === Check for semicolon (statement terminator) ===
(_, t) if t.is_semicolon() => SqlComplete,
// After semicolon, any keyword starts a new statement
(SqlComplete, t) if t.is_sql_keyword("SELECT") => Start,
(SqlComplete, t) if t.is_sql_keyword("INSERT") => Start,
(SqlComplete, t) if t.is_sql_keyword("UPDATE") => Start,
(SqlComplete, t) if t.is_sql_keyword("DELETE") => Start,
// Stay in SqlComplete for whitespace/identifiers after semicolon
(SqlComplete, _) => SqlComplete,
// === Mongo Shell Transitions ===
(Start, t) if t.is_db() => AfterDb,
(AfterDb, t) if t.is_dot() => AfterDbDot,
(AfterDbDot, t) if t.is_ident() => AfterCollection,
(AfterCollection, t) if t.is_dot() => AfterCollectionDot,
// === SQL Transitions ===
(Start, t) if t.is_sql_keyword("SELECT") => Start, // Stay in Start after SELECT
(_, t) if t.is_sql_keyword("FROM") => SqlFrom,
// After FROM, when we see an identifier (table name), transition to SqlAfterTableName
(SqlFrom, t) if t.is_ident() => SqlAfterTableName,
// JOIN keywords can come from various states
(SqlAfterTableName, t)
if t.is_sql_keyword("JOIN")
|| t.is_sql_keyword("INNER")
|| t.is_sql_keyword("LEFT")
|| t.is_sql_keyword("RIGHT") =>
{
SqlJoin
}
(_, t)
if t.is_sql_keyword("JOIN")
|| t.is_sql_keyword("INNER")
|| t.is_sql_keyword("LEFT")
|| t.is_sql_keyword("RIGHT") =>
{
SqlJoin
}
// After JOIN, when we see an identifier (table name), transition to SqlAfterTableName
(SqlJoin, t) if t.is_ident() => SqlAfterTableName,
// WHERE can come after table name
(SqlAfterTableName, t) if t.is_sql_keyword("WHERE") => SqlWhere,
(SqlFrom, t) if t.is_sql_keyword("WHERE") => SqlWhere,
(SqlWhere, t) if t.is_ident() => SqlWhere, // Stay in WHERE for column names, etc.
// LIMIT/OFFSET expect numbers - no completion
(_, t) if t.is_sql_keyword("LIMIT") || t.is_sql_keyword("OFFSET") => SqlAfterLimit,
(SqlAfterLimit, t) if t.is_number() => SqlAfterLimit, // Stay after seeing number
// ORDER BY for column names
(_, t) if t.is_sql_keyword("ORDER") => Start, // Wait for BY
(Start, t) if t.is_sql_keyword("BY") => SqlOrderBy,
(SqlAfterTableName, t) if t.is_sql_keyword("ORDER") => Start,
(SqlOrderBy, t) if t.is_ident() => SqlOrderBy, // Column names
// GROUP BY similar to ORDER BY
(_, t) if t.is_sql_keyword("GROUP") => Start,
(SqlAfterTableName, t) if t.is_sql_keyword("GROUP") => Start,
// === Shell Command Transitions ===
(Start, t) if t.ident_value() == Some("show".to_string()) => ShowCommand,
(Start, t) if t.ident_value() == Some("use".to_string()) => UseCommand,
// === Stay in current state for identifiers after certain states ===
(ShowCommand, t) if t.is_ident() => ShowCommand,
(UseCommand, t) if t.is_ident() => UseCommand,
// === Default: maintain current state ===
(state, _) => state,
}
}
/// Run the FSM on a sequence of tokens
pub fn run(tokens: &[UnifiedToken]) -> Self {
let mut state = CompletionState::Start;
for token in tokens {
state = state.next(token);
}
state
}
/// Convert state to completion context
pub fn to_context(&self, stream: &TokenStream) -> CompletionContext {
use CompletionState::*;
let prefix = stream.current_prefix();
let has_prefix = !prefix.is_empty();
match self {
// Need to complete collection names
AfterDbDot | SqlFrom | SqlJoin => CompletionContext::collection(prefix),
// If we're in AfterCollection state but have a prefix, user is still typing collection name
AfterCollection if has_prefix => CompletionContext::collection(prefix),
// If we're in SqlAfterTableName but have a prefix, user is still typing table name
SqlAfterTableName if has_prefix => CompletionContext::collection(prefix),
// Need to complete operation names
AfterCollectionDot => CompletionContext::operation(prefix),
// Need to complete "show" subcommands
ShowCommand => CompletionContext::show_subcommand(prefix),
// Need to complete database names
UseCommand => CompletionContext::database(prefix),
// At the start, complete top-level commands
Start if has_prefix => CompletionContext::command(prefix),
// No completion for these states (even with prefix)
// - SqlAfterLimit: expects numbers, not identifiers
// - SqlWhere: would need column name completion (not implemented)
// - SqlOrderBy: would need column name completion (not implemented)
// - SqlComplete: statement has ended with semicolon
SqlAfterLimit | SqlWhere | SqlOrderBy | SqlComplete => CompletionContext::None,
// No completion for terminal states without prefix
SqlAfterTableName | AfterCollection => CompletionContext::None,
// No completion
_ => CompletionContext::None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::{MongoLexer, SqlLexer};
#[test]
fn test_state_mongo_db() {
let tokens = MongoLexer::tokenize("db");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::MongoTokenKind::EOF))
.map(UnifiedToken::Mongo)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::AfterDb);
}
#[test]
fn test_state_mongo_db_dot() {
let tokens = MongoLexer::tokenize("db.");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::MongoTokenKind::EOF))
.map(UnifiedToken::Mongo)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::AfterDbDot);
}
#[test]
fn test_state_mongo_db_collection() {
let tokens = MongoLexer::tokenize("db.users");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::MongoTokenKind::EOF))
.map(UnifiedToken::Mongo)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::AfterCollection);
}
#[test]
fn test_state_mongo_db_collection_dot() {
let tokens = MongoLexer::tokenize("db.users.");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::MongoTokenKind::EOF))
.map(UnifiedToken::Mongo)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::AfterCollectionDot);
}
#[test]
fn test_state_sql_from() {
let tokens = SqlLexer::tokenize("SELECT * FROM");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::SqlTokenKind::EOF))
.map(UnifiedToken::Sql)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::SqlFrom);
}
#[test]
fn test_state_show_command() {
let tokens = MongoLexer::tokenize("show");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::MongoTokenKind::EOF))
.map(UnifiedToken::Mongo)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::ShowCommand);
}
#[test]
fn test_state_use_command() {
let tokens = MongoLexer::tokenize("use");
let unified: Vec<UnifiedToken> = tokens
.into_iter()
.take_while(|t| !matches!(t.kind, crate::parser::MongoTokenKind::EOF))
.map(UnifiedToken::Mongo)
.collect();
let state = CompletionState::run(&unified);
assert_eq!(state, CompletionState::UseCommand);
}
#[test]
fn test_context_collection() {
// Test "db." with cursor after the dot - should complete collections
let tokens = MongoLexer::tokenize("db.");
let stream = TokenStream::from_mongo(tokens, 3);
let state = CompletionState::run(stream.tokens_before_cursor());
let context = state.to_context(&stream);
assert_eq!(context, CompletionContext::collection(""));
}
#[test]
fn test_context_operation() {
// Test "db.users." with cursor after second dot - should complete operations
let tokens = MongoLexer::tokenize("db.users.");
let stream = TokenStream::from_mongo(tokens, 9);
let state = CompletionState::run(stream.tokens_before_cursor());
let context = state.to_context(&stream);
assert_eq!(context, CompletionContext::operation(""));
}
#[test]
fn test_context_show_subcommand() {
// Test "show " with cursor after space - should complete show subcommands
let tokens = MongoLexer::tokenize("show ");
let stream = TokenStream::from_mongo(tokens, 5);
let state = CompletionState::run(stream.tokens_before_cursor());
let context = state.to_context(&stream);
assert_eq!(context, CompletionContext::show_subcommand(""));
}
#[test]
fn test_context_sql_from() {
// Test "SELECT * FROM " with cursor after FROM - should complete collections
let tokens = SqlLexer::tokenize("SELECT * FROM ");
let stream = TokenStream::from_sql(tokens, 14);
let state = CompletionState::run(stream.tokens_before_cursor());
let context = state.to_context(&stream);
assert_eq!(context, CompletionContext::collection(""));
}
#[test]
fn test_no_completion_inside_parentheses() {
// Test "db.users.findOne(find" - should NOT complete inside parentheses
let tokens = MongoLexer::tokenize("db.users.findOne(find");
let stream = TokenStream::from_mongo(tokens, 21);
let state = CompletionState::run(stream.tokens_before_cursor());
assert_eq!(state, CompletionState::InsideParentheses);
let context = state.to_context(&stream);
assert_eq!(context, CompletionContext::None);
}
#[test]
fn test_completion_after_closing_parenthesis() {
// Test "db.users.find()." - should complete after closing parenthesis
let tokens = MongoLexer::tokenize("db.users.find().");
let stream = TokenStream::from_mongo(tokens, 16);
let state = CompletionState::run(stream.tokens_before_cursor());
// After closing paren and dot, we're not in a clear completion state
// This is acceptable - the important part is we don't complete INSIDE parens
let context = state.to_context(&stream);
// Either None or some completion is fine - just not crashing
assert!(matches!(
context,
CompletionContext::None | CompletionContext::Operation { .. }
));
}
}