liblevenshtein 0.9.1

Levenshtein/Universal Automata for approximate string matching using various dictionary backends
Documentation
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! REPL state machine
//!
//! Provides a structured state machine for managing REPL execution flow,
//! inspired by The Elm Architecture (TEA) and functional state management patterns.

use super::command::{Command, CommandResult};
use anyhow::Result;
use colored::Colorize;

/// REPL execution phase
///
/// Represents the current state of the REPL's execution cycle.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ReplPhase {
    /// Ready to accept new input
    #[default]
    Ready,

    /// Accepting multi-line input (continuation)
    Continuation {
        /// Buffer containing accumulated input
        buffer: String,
    },

    /// Executing a command
    Executing {
        /// The command being executed
        command: Command,
    },

    /// Displaying query results
    DisplayingResults {
        /// Results to display
        output: String,
    },

    /// Error state
    Error {
        /// Error message
        message: String,
        /// Whether the error is recoverable
        recoverable: bool,
    },

    /// Exiting the REPL
    Exiting,
}

impl ReplPhase {
    /// Check if the phase is terminal (requires exit)
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Exiting
                | Self::Error {
                    recoverable: false,
                    ..
                }
        )
    }

    /// Check if the phase is recoverable from error
    pub fn is_recoverable(&self) -> bool {
        !matches!(
            self,
            Self::Error {
                recoverable: false,
                ..
            }
        )
    }

    /// Get a status indicator string for display
    pub fn status_indicator(&self) -> String {
        match self {
            Self::Ready => "🔵".to_string(),
            Self::Continuation { .. } => "🟡".to_string(),
            Self::Executing { .. } => "🟢".to_string(),
            Self::DisplayingResults { .. } => "✓".green().to_string(),
            Self::Error {
                recoverable: true, ..
            } => "âš ".yellow().to_string(),
            Self::Error {
                recoverable: false, ..
            } => "✗".red().to_string(),
            Self::Exiting => "👋".to_string(),
        }
    }
}

/// REPL event
///
/// Represents events that trigger state transitions in the REPL.
#[derive(Debug, Clone)]
pub enum ReplEvent {
    /// User submitted a line of input
    LineSubmitted {
        /// The input line
        line: String,
    },

    /// Command was successfully parsed
    CommandParsed {
        /// The parsed command
        command: Command,
    },

    /// Command execution completed
    CommandExecuted {
        /// The execution result
        result: CommandResult,
    },

    /// User interrupted (Ctrl+C)
    Interrupted,

    /// End of file (Ctrl+D)
    Eof,

    /// Parse error occurred
    ParseError {
        /// Error message
        message: String,
    },

    /// Execution error occurred
    ExecutionError {
        /// Error message
        message: String,
        /// Whether the error is recoverable
        recoverable: bool,
    },

    /// Continuation line needed
    ContinuationNeeded {
        /// Current buffer
        buffer: String,
    },

    /// Results ready to display
    ResultsReady {
        /// Output to display
        output: String,
    },
}

/// State transition result
#[derive(Debug)]
pub struct Transition {
    /// New phase after transition
    pub new_phase: ReplPhase,
    /// Optional output message
    pub output: Option<String>,
    /// Optional follow-up event to process
    pub follow_up: Option<ReplEvent>,
}

impl Transition {
    /// Create a simple transition with no output or follow-up
    pub fn to(phase: ReplPhase) -> Self {
        Self {
            new_phase: phase,
            output: None,
            follow_up: None,
        }
    }

    /// Create a transition with output
    pub fn to_with_output(phase: ReplPhase, output: String) -> Self {
        Self {
            new_phase: phase,
            output: Some(output),
            follow_up: None,
        }
    }

    /// Create a transition with a follow-up event
    pub fn to_with_follow_up(phase: ReplPhase, follow_up: ReplEvent) -> Self {
        Self {
            new_phase: phase,
            output: None,
            follow_up: Some(follow_up),
        }
    }

    /// Create a transition with both output and follow-up
    pub fn to_with_both(phase: ReplPhase, output: String, follow_up: ReplEvent) -> Self {
        Self {
            new_phase: phase,
            output: Some(output),
            follow_up: Some(follow_up),
        }
    }
}

/// State machine for REPL execution
pub struct ReplStateMachine {
    /// Current phase
    phase: ReplPhase,
}

impl ReplStateMachine {
    /// Create a new state machine in Ready phase
    pub fn new() -> Self {
        Self {
            phase: ReplPhase::Ready,
        }
    }

    /// Get the current phase
    pub fn phase(&self) -> &ReplPhase {
        &self.phase
    }

    /// Check if the state machine is in a terminal state
    pub fn is_terminal(&self) -> bool {
        self.phase.is_terminal()
    }

    /// Process an event and transition to a new state
    pub fn process_event(&mut self, event: ReplEvent) -> Result<Transition> {
        let transition = match (&self.phase, &event) {
            // Ready state transitions
            (ReplPhase::Ready, ReplEvent::LineSubmitted { line }) => {
                if line.is_empty() {
                    // Empty line, stay in Ready
                    Transition::to(ReplPhase::Ready)
                } else if line.ends_with('\\') {
                    // Continuation needed
                    let buffer = line.trim_end_matches('\\').to_string();
                    Transition::to(ReplPhase::Continuation { buffer })
                } else {
                    // Try to parse command
                    match Command::parse(line) {
                        Ok(command) => Transition::to_with_follow_up(
                            ReplPhase::Executing {
                                command: command.clone(),
                            },
                            ReplEvent::CommandParsed { command },
                        ),
                        Err(e) => Transition::to_with_output(
                            ReplPhase::Ready,
                            format!("{}: {}", "Parse error".red().bold(), e),
                        ),
                    }
                }
            }

            (ReplPhase::Ready, ReplEvent::Interrupted) => Transition::to_with_output(
                ReplPhase::Ready,
                "^C (Use 'exit' or Ctrl+D to quit)".yellow().to_string(),
            ),

            (ReplPhase::Ready, ReplEvent::Eof) => {
                Transition::to_with_output(ReplPhase::Exiting, "Goodbye!".green().to_string())
            }

            // Continuation state transitions
            (ReplPhase::Continuation { buffer }, ReplEvent::LineSubmitted { line }) => {
                let mut new_buffer = buffer.clone();
                new_buffer.push(' ');
                new_buffer.push_str(line);

                if line.ends_with('\\') {
                    // Still continuing
                    let trimmed = new_buffer.trim_end_matches('\\').to_string();
                    Transition::to(ReplPhase::Continuation { buffer: trimmed })
                } else {
                    // Try to parse complete command
                    match Command::parse(&new_buffer) {
                        Ok(command) => Transition::to_with_follow_up(
                            ReplPhase::Executing {
                                command: command.clone(),
                            },
                            ReplEvent::CommandParsed { command },
                        ),
                        Err(e) => Transition::to_with_output(
                            ReplPhase::Ready,
                            format!("{}: {}", "Parse error".red().bold(), e),
                        ),
                    }
                }
            }

            (ReplPhase::Continuation { .. }, ReplEvent::Interrupted) => Transition::to_with_output(
                ReplPhase::Ready,
                "Continuation cancelled".yellow().to_string(),
            ),

            // Executing state transitions
            (ReplPhase::Executing { .. }, ReplEvent::CommandExecuted { result }) => match result {
                CommandResult::Continue(output) => {
                    if output.is_empty() {
                        Transition::to(ReplPhase::Ready)
                    } else {
                        Transition::to_with_output(ReplPhase::Ready, output.clone())
                    }
                }
                CommandResult::Exit => {
                    Transition::to_with_output(ReplPhase::Exiting, "Goodbye!".green().to_string())
                }
                CommandResult::Silent => Transition::to(ReplPhase::Ready),
            },

            (
                ReplPhase::Executing { .. },
                ReplEvent::ExecutionError {
                    message,
                    recoverable,
                },
            ) => {
                if *recoverable {
                    Transition::to_with_output(
                        ReplPhase::Ready,
                        format!("{}: {}", "Error".red().bold(), message),
                    )
                } else {
                    Transition::to(ReplPhase::Error {
                        message: message.clone(),
                        recoverable: false,
                    })
                }
            }

            // Error state transitions
            (
                ReplPhase::Error {
                    recoverable: true, ..
                },
                ReplEvent::LineSubmitted { .. },
            ) => {
                // Recoverable error, go back to Ready
                Transition::to(ReplPhase::Ready)
            }

            // Exiting state (terminal)
            (ReplPhase::Exiting, _) => {
                // Already exiting, ignore events
                Transition::to(ReplPhase::Exiting)
            }

            // Catch-all for unexpected transitions
            (current, event) => {
                eprintln!(
                    "{}: Unexpected event {:?} in phase {:?}",
                    "Warning".yellow(),
                    event,
                    current
                );
                Transition::to(ReplPhase::Ready)
            }
        };

        // Update internal state
        self.phase = transition.new_phase.clone();

        Ok(transition)
    }

    /// Reset to Ready phase
    pub fn reset(&mut self) {
        self.phase = ReplPhase::Ready;
    }
}

impl Default for ReplStateMachine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ready_to_executing() {
        let mut sm = ReplStateMachine::new();
        assert!(matches!(sm.phase(), ReplPhase::Ready));

        let result = sm.process_event(ReplEvent::LineSubmitted {
            line: "help".to_string(),
        });
        assert!(result.is_ok());
        assert!(matches!(sm.phase(), ReplPhase::Executing { .. }));
    }

    #[test]
    fn test_continuation() {
        let mut sm = ReplStateMachine::new();

        // Submit line ending with backslash
        let result = sm.process_event(ReplEvent::LineSubmitted {
            line: "query test\\".to_string(),
        });
        assert!(result.is_ok());
        assert!(matches!(sm.phase(), ReplPhase::Continuation { .. }));
    }

    #[test]
    fn test_interrupt_recovery() {
        let mut sm = ReplStateMachine::new();

        // Interrupt in Ready state
        let result = sm.process_event(ReplEvent::Interrupted);
        assert!(result.is_ok());
        assert!(matches!(sm.phase(), ReplPhase::Ready));
    }

    #[test]
    fn test_eof_exits() {
        let mut sm = ReplStateMachine::new();

        let result = sm.process_event(ReplEvent::Eof);
        assert!(result.is_ok());
        assert!(matches!(sm.phase(), ReplPhase::Exiting));
        assert!(sm.is_terminal());
    }
}