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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
//! TUI Application
//!
//! Main application state and event loop using crossterm.
//! Integrates all widgets and handles Vi mode editing via vim-line.
//!
//! Session file management is ported from the original REPL (crates/repl/src/main.rs).
//! Expressions accumulate in a temp file with `stack.dump` to show values.
use crate::completion::CompletionManager;
use crate::engine::{AnalysisResult, analyze, analyze_expression};
use crate::ir::stack_art::{Stack, StackEffect, render_transition};
use crate::keys::convert_key;
use crate::run::{RunResult, run_with_timeout};
use crate::text_utils::floor_char_boundary;
use crate::ui::ir_pane::{IrContent, IrPane, IrViewMode};
use crate::ui::layout::{ComputedLayout, LayoutConfig, StatusContent};
use crate::ui::repl_pane::{HistoryEntry, ReplPane, ReplState};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
Frame,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph},
};
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use tempfile::NamedTempFile;
use vim_line::{Action, LineEditor, TextEdit, VimLineEditor};
/// REPL template for new sessions (same as original REPL)
const REPL_TEMPLATE: &str = r#"# Seq REPL session
# Expressions are auto-printed via stack.dump
# --- includes ---
# --- definitions ---
# --- main ---
: main ( -- )
"#;
/// Closing for the main word
const MAIN_CLOSE: &str = " stack.dump\n;\n";
/// Marker for includes section
const INCLUDES_MARKER: &str = "# --- includes ---";
/// Marker for main section
const MAIN_MARKER: &str = "# --- main ---";
/// Lines shown by the `:help` command in the IR pane.
const HELP_LINES: &[&str] = &[
"â•─────────────────────────────────────╮",
"│ Seq TUI REPL │",
"╰─────────────────────────────────────╯",
"",
"COMMANDS",
" :q, :quit Exit the REPL",
" :version, :v Show version",
" :clear Clear session and history",
" :pop Remove last expression",
" :stack, :s Show current stack",
" :show Show session file",
" :edit, :e Open in $EDITOR",
" :ir Toggle IR pane",
" :ir stack Show stack effects",
" :ir ast Show typed AST",
" :ir llvm Show LLVM IR",
" :include <m> Include module",
" :help, :h Show this help",
"",
"VI MODE",
" i, a, A, I Enter insert mode",
" Esc Return to normal mode",
" h, l Move cursor left/right",
" j, k History down/up",
" w, b Word forward/backward",
" 0, $ Line start/end",
" x Delete character",
" d Clear line",
" / Search history",
"",
"KEYS",
" F1 Toggle Stack Effects",
" F2 Toggle Typed AST",
" F3 Toggle LLVM IR",
" Tab Show completions",
" Ctrl+N Cycle IR views",
" Ctrl+D Exit REPL",
" Enter Execute expression",
" Up/Down History navigation",
"",
"SEARCH MODE (after /)",
" Type Filter history",
" Tab/Shift+Tab Cycle matches",
" Enter Accept match",
" Esc Cancel search",
];
/// Main application state
pub(crate) struct App {
/// REPL state (history, input, cursor)
pub(crate) repl_state: ReplState,
/// IR content for visualization
pub(crate) ir_content: IrContent,
/// Current IR view mode
pub(crate) ir_mode: IrViewMode,
/// Vim-style line editor
pub(crate) editor: VimLineEditor,
/// Layout configuration
pub(crate) layout_config: LayoutConfig,
/// Current filename (display name)
pub(crate) filename: String,
/// Whether the IR pane is visible
pub(crate) show_ir_pane: bool,
/// Whether the app should quit
pub(crate) should_quit: bool,
/// Whether the app should open editor
pub(crate) should_edit: bool,
/// Status message (clears after next action)
pub(crate) status_message: Option<String>,
/// Session file path (temp file or user-provided file)
pub(crate) session_path: PathBuf,
/// Temp file handle (kept alive to prevent deletion)
_temp_file: Option<NamedTempFile>,
/// Completion manager (handles LSP and builtin completions)
completions: CompletionManager,
/// Whether in search mode (vim `/` search)
search_mode: bool,
/// Current search pattern
search_pattern: String,
/// Indices of history entries matching search pattern
search_matches: Vec<usize>,
/// Current match index (into search_matches)
search_match_index: usize,
/// Original input before search started (for cancellation)
search_original_input: String,
}
// Note: App intentionally does not implement Default because App::new() can fail
// (temp file creation, file I/O). Use App::new() directly and handle the Result.
/// Maximum history entries to keep in memory
const MAX_HISTORY_IN_MEMORY: usize = 1000;
impl App {
/// Create a new application with a temp session file
pub(crate) fn new() -> Result<Self, String> {
// Create temp file for session
let temp_file = NamedTempFile::with_suffix(".seq")
.map_err(|e| format!("Failed to create temp file: {}", e))?;
let session_path = temp_file.path().to_path_buf();
// Initialize with template
let initial_content = format!("{}{}", REPL_TEMPLATE, MAIN_CLOSE);
fs::write(&session_path, &initial_content)
.map_err(|e| format!("Failed to write session file: {}", e))?;
// Create completion manager with LSP if available
let completions = CompletionManager::try_with_lsp(&session_path, &initial_content);
let mut app = Self {
repl_state: ReplState::new(),
ir_content: IrContent::new(),
ir_mode: IrViewMode::default(),
editor: VimLineEditor::new(),
layout_config: LayoutConfig::default(),
filename: "(scratch)".to_string(),
show_ir_pane: false,
should_quit: false,
should_edit: false,
status_message: None,
session_path,
_temp_file: Some(temp_file),
completions,
search_mode: false,
search_pattern: String::new(),
search_matches: Vec::new(),
search_match_index: 0,
search_original_input: String::new(),
};
app.load_history();
Ok(app)
}
/// Create application with an existing file
pub(crate) fn with_file(path: PathBuf) -> Result<Self, String> {
let filename = path.display().to_string();
// Check if file exists, create if not
let content = if !path.exists() {
let c = format!("{}{}", REPL_TEMPLATE, MAIN_CLOSE);
fs::write(&path, &c).map_err(|e| format!("Failed to create session file: {}", e))?;
c
} else {
match fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => {
eprintln!(
"Warning: Could not read session file '{}': {}",
path.display(),
e
);
eprintln!("Starting with empty session.");
String::new()
}
}
};
// Create completion manager with LSP if available
let completions = CompletionManager::try_with_lsp(&path, &content);
let mut app = Self {
repl_state: ReplState::new(),
ir_content: IrContent::new(),
ir_mode: IrViewMode::default(),
editor: VimLineEditor::new(),
layout_config: LayoutConfig::default(),
filename,
show_ir_pane: false,
should_quit: false,
should_edit: false,
status_message: None,
session_path: path,
_temp_file: None,
completions,
search_mode: false,
search_pattern: String::new(),
search_matches: Vec::new(),
search_match_index: 0,
search_original_input: String::new(),
};
app.load_history();
Ok(app)
}
/// Get the history file path (shared with original REPL)
fn history_file_path() -> Option<PathBuf> {
home::home_dir().map(|d| d.join(".local/share/seqr_history"))
}
/// Load history from file
fn load_history(&mut self) {
if let Some(path) = Self::history_file_path()
&& path.exists()
&& let Ok(file) = fs::File::open(&path)
{
let reader = BufReader::new(file);
// Collect lines, then take only the last MAX_HISTORY_IN_MEMORY entries
let lines: Vec<String> = reader
.lines()
.map_while(Result::ok)
.filter(|line| !line.is_empty())
.collect();
// Only load the most recent entries to prevent memory exhaustion
let start = lines.len().saturating_sub(MAX_HISTORY_IN_MEMORY);
for line in &lines[start..] {
// Add as history entry (no output - it's from a previous session)
self.repl_state
.add_entry(HistoryEntry::new(line.clone()).with_output("(previous session)"));
}
}
}
/// Save history to file
pub(crate) fn save_history(&self) {
if let Some(path) = Self::history_file_path() {
// Ensure parent directory exists
if let Some(parent) = path.parent()
&& let Err(e) = fs::create_dir_all(parent)
{
eprintln!("Warning: could not create history directory: {e}");
return;
}
match fs::File::create(&path) {
Ok(mut file) => {
// Save the last 1000 entries
let start = self.repl_state.history.len().saturating_sub(1000);
for entry in &self.repl_state.history[start..] {
if let Err(e) = writeln!(file, "{}", entry.input) {
eprintln!("Warning: could not write history entry: {e}");
return;
}
}
}
Err(e) => {
eprintln!("Warning: could not create history file: {e}");
}
}
}
}
/// Check if editor is in normal mode (for completion navigation)
fn is_normal_mode(&self) -> bool {
self.editor.status() == "NORMAL"
}
/// Restore the session file to `original` content; surface a warning via
/// the status bar if that write fails.
fn rollback_session(&mut self, original: &str) {
if let Err(rollback_err) = fs::write(&self.session_path, original) {
self.status_message = Some(format!(
"Warning: Could not rollback session file: {}",
rollback_err
));
}
}
/// Sync the vim-line editor and `repl_state.cursor` to the current
/// `repl_state.input`, placing the cursor at end-of-input.
fn sync_editor_to_input(&mut self) {
self.editor.reset();
self.editor
.set_cursor(self.repl_state.input.len(), &self.repl_state.input);
self.repl_state.cursor = self.editor.cursor();
}
/// Handle a key event
pub(crate) fn handle_key(&mut self, key: KeyEvent) {
// Clear status message on any key
self.status_message = None;
// Handle completion popup navigation first
if self.completions.is_visible() {
match key.code {
KeyCode::Esc => {
self.completions.hide();
return;
}
KeyCode::Up | KeyCode::Char('k') if self.is_normal_mode() => {
self.completions.up();
return;
}
KeyCode::Down | KeyCode::Char('j') if self.is_normal_mode() => {
self.completions.down();
return;
}
KeyCode::Up => {
self.completions.up();
return;
}
KeyCode::Down => {
self.completions.down();
return;
}
KeyCode::Tab => {
self.completions.down();
return;
}
KeyCode::Enter => {
self.accept_completion();
return;
}
_ => {
// Any other key hides completions and continues
self.completions.hide();
}
}
}
// Handle search mode (vim `/` search)
if self.search_mode {
match key.code {
KeyCode::Esc => {
// Cancel search - restore original input
self.repl_state.input = self.search_original_input.clone();
self.sync_editor_to_input();
self.search_mode = false;
self.search_pattern.clear();
self.search_matches.clear();
self.status_message = None;
return;
}
KeyCode::Enter => {
// Accept current match (input already shows preview)
self.search_mode = false;
self.search_pattern.clear();
self.search_matches.clear();
return;
}
KeyCode::Backspace => {
// Delete from search pattern
self.search_pattern.pop();
self.update_search_matches();
self.preview_current_match();
self.update_search_status();
return;
}
KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => {
// Previous match (Shift+Tab)
if !self.search_matches.is_empty() {
self.search_match_index = if self.search_match_index == 0 {
self.search_matches.len() - 1
} else {
self.search_match_index - 1
};
self.preview_current_match();
self.update_search_status();
}
return;
}
KeyCode::Tab | KeyCode::BackTab => {
// Next match (Tab) or previous (BackTab for terminals that send it)
if !self.search_matches.is_empty() {
if key.code == KeyCode::BackTab {
self.search_match_index = if self.search_match_index == 0 {
self.search_matches.len() - 1
} else {
self.search_match_index - 1
};
} else {
self.search_match_index =
(self.search_match_index + 1) % self.search_matches.len();
}
self.preview_current_match();
self.update_search_status();
}
return;
}
KeyCode::Char(c) => {
// Add to search pattern
self.search_pattern.push(c);
self.update_search_matches();
self.preview_current_match();
self.update_search_status();
return;
}
_ => return,
}
}
// Enter search mode with `/` in normal mode
if key.code == KeyCode::Char('/') && self.is_normal_mode() {
self.search_mode = true;
self.search_original_input = self.repl_state.input.clone();
self.search_pattern.clear();
self.search_matches.clear();
self.search_match_index = 0;
self.update_search_status();
return;
}
// Global shortcuts (work in any mode)
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('c') | KeyCode::Char('d') | KeyCode::Char('q') => {
// Ctrl+C, Ctrl+D (EOF), Ctrl+Q all quit
self.should_quit = true;
return;
}
KeyCode::Char('l') => {
// Clear screen / refresh
return;
}
KeyCode::Char('n') => {
// Cycle IR view modes (when visible)
if self.show_ir_pane {
self.ir_mode = self.ir_mode.next();
}
return;
}
_ => {}
}
}
// Function keys toggle IR pane views (F1=Stack, F2=AST, F3=LLVM)
match key.code {
KeyCode::F(1) => {
self.toggle_ir_view(IrViewMode::StackArt);
return;
}
KeyCode::F(2) => {
self.toggle_ir_view(IrViewMode::TypedAst);
return;
}
KeyCode::F(3) => {
self.toggle_ir_view(IrViewMode::LlvmIr);
return;
}
_ => {}
}
// Tab triggers completion (before vim-line, which doesn't handle Tab)
if key.code == KeyCode::Tab {
self.request_completions();
return;
}
// Shift+Enter in Insert mode inserts a newline
// Terminals report Shift+Enter differently:
// - Some as Enter with SHIFT modifier
// - Some as Enter with ALT modifier (e.g., macOS Terminal/iTerm)
// - Some as Char('\n')
let is_modified_enter = key.code == KeyCode::Enter
&& (key.modifiers.contains(KeyModifiers::SHIFT)
|| key.modifiers.contains(KeyModifiers::ALT));
let is_newline_char = key.code == KeyCode::Char('\n');
if (is_modified_enter || is_newline_char) && self.editor.status() == "INSERT" {
let cursor = self.editor.cursor();
self.repl_state.input.insert(cursor, '\n');
self.editor.set_cursor(cursor + 1, &self.repl_state.input);
self.repl_state.cursor = self.editor.cursor();
return;
}
// Enter in Insert mode submits (REPL behavior, not vim's newline insertion)
if key.code == KeyCode::Enter && self.editor.status() == "INSERT" {
self.execute_input();
return;
}
// Context-aware j/k in Normal mode: navigate history when at buffer boundaries
// This makes j/k intuitive for single-line inputs (the common case) while
// still supporting multi-line navigation when there are multiple lines
if self.editor.status() == "NORMAL" {
let input = &self.repl_state.input;
let cursor = floor_char_boundary(input, self.editor.cursor());
match key.code {
KeyCode::Char('k') => {
// k at top line (or single line) → history prev
let on_first_line = !input[..cursor].contains('\n');
if on_first_line {
self.navigate_history_prev();
return;
}
}
KeyCode::Char('j') => {
// j at bottom line (or single line) → history next
let on_last_line = !input[cursor..].contains('\n');
if on_last_line {
self.navigate_history_next();
return;
}
}
_ => {}
}
}
// Convert to vim-line key and process
let vl_key = convert_key(key);
let result = self.editor.handle_key(vl_key, &self.repl_state.input);
// Apply text edits (in reverse order to preserve offsets)
let had_edits = !result.edits.is_empty();
for edit in result.edits.into_iter().rev() {
match edit {
TextEdit::Delete { start, end } => {
self.repl_state.input.replace_range(start..end, "");
}
TextEdit::Insert { at, text } => {
self.repl_state.input.insert_str(at, &text);
}
}
}
// Sync cursor from editor
self.repl_state.cursor = self.editor.cursor();
// Handle actions
if let Some(action) = result.action {
match action {
Action::Submit => {
self.execute_input();
}
Action::HistoryPrev => {
self.navigate_history_prev();
}
Action::HistoryNext => {
self.navigate_history_next();
}
Action::Cancel => {
self.should_quit = true;
}
}
}
// Update IR preview if text changed
if had_edits {
self.update_ir_preview();
}
}
/// Execute the current input
fn execute_input(&mut self) {
let input = self.repl_state.current_input().to_string();
if input.trim().is_empty() {
return;
}
// Handle REPL commands (start with : but not ": " which is a word definition)
let trimmed = input.trim_start();
if trimmed.starts_with(':') && !trimmed.starts_with(": ") && !trimmed.starts_with(":\t") {
let cmd = input.clone();
self.handle_command(&cmd);
return;
}
// Check if this is a word definition
if trimmed.starts_with(": ") || trimmed.starts_with(":\t") {
self.try_definition(&input);
return;
}
// It's an expression - append to session and run
self.try_expression(&input);
}
/// Try adding a word definition to the session file
fn try_definition(&mut self, def: &str) {
// Save current content for rollback
let original = match fs::read_to_string(&self.session_path) {
Ok(c) => c,
Err(e) => {
self.add_error_entry(def, &format!("Error reading file: {}", e));
return;
}
};
// Add definition before main marker
if !self.add_definition(def) {
return;
}
// Try to compile
let output_path = self.session_path.with_extension("");
match seqc::compile_file(&self.session_path, &output_path, false) {
Ok(_) => {
let _ = fs::remove_file(&output_path);
self.repl_state
.add_entry(HistoryEntry::new(def).with_output("Defined."));
self.repl_state.clear_input();
}
Err(e) => {
// Rollback
self.rollback_session(&original);
self.add_error_entry(def, &e.to_string());
}
}
}
/// Add a definition to the definitions section
fn add_definition(&mut self, def: &str) -> bool {
let Ok(content) = fs::read_to_string(&self.session_path) else {
return false;
};
// Find the main marker
let Some(main_pos) = content.find(MAIN_MARKER) else {
return false;
};
// Insert definition before the main marker
let mut new_content = String::new();
new_content.push_str(&content[..main_pos]);
new_content.push_str(def);
new_content.push_str("\n\n");
new_content.push_str(&content[main_pos..]);
fs::write(&self.session_path, new_content).is_ok()
}
/// Try an expression: append to session, compile, run, show output
fn try_expression(&mut self, expr: &str) {
// Save current content for rollback
let original = match fs::read_to_string(&self.session_path) {
Ok(c) => c,
Err(e) => {
self.add_error_entry(expr, &format!("Error reading file: {}", e));
return;
}
};
// Append the expression
if !self.append_expression(expr) {
self.add_error_entry(expr, "Failed to append expression");
return;
}
// Try to compile and run
let output_path = self.session_path.with_extension("");
match seqc::compile_file(&self.session_path, &output_path, false) {
Ok(_) => {
// Run with timeout to prevent hanging on blocked operations
let result = run_with_timeout(&output_path);
let _ = fs::remove_file(&output_path);
match result {
RunResult::Success { stdout } => {
// Update IR from the session file - only on success
self.update_ir_from_session(expr);
let output_text = stdout.trim();
if output_text.is_empty() {
self.repl_state
.add_entry(HistoryEntry::new(expr).with_output("ok"));
} else {
self.repl_state
.add_entry(HistoryEntry::new(expr).with_output(output_text));
}
}
RunResult::Failed { stderr, status } => {
// Rollback on runtime error - don't keep failed expression in session
self.rollback_session(&original);
let err = if stderr.is_empty() {
format!("exit: {:?}", status.code())
} else {
stderr.trim().to_string()
};
self.repl_state
.add_entry(HistoryEntry::new(expr).with_error(&err));
}
RunResult::Timeout { timeout_secs } => {
// Rollback on timeout - the expression caused blocking
self.rollback_session(&original);
self.repl_state
.add_entry(HistoryEntry::new(expr).with_error(format!(
"Timeout after {}s (SEQ_REPL_TIMEOUT to adjust)",
timeout_secs
)));
}
RunResult::Error(e) => {
// Rollback on run error - don't keep failed expression in session
self.rollback_session(&original);
self.add_error_entry(expr, &format!("Run error: {}", e));
}
}
self.repl_state.clear_input();
}
Err(e) => {
// Rollback
self.rollback_session(&original);
self.add_error_entry(expr, &e.to_string());
}
}
}
/// Append an expression to main (before stack.dump)
fn append_expression(&mut self, expr: &str) -> bool {
// Don't persist stack.dump - it's an introspection command that should only
// run once. The auto-appended stack.dump at the end of main will show the
// current stack state. This fixes issue #193 where user-typed stack.dump
// accumulated in the session file, causing multiple "stack:" lines.
if expr.trim() == "stack.dump" {
return true; // Skip appending but allow compile/run to proceed
}
let Ok(content) = fs::read_to_string(&self.session_path) else {
return false;
};
// Find "stack.dump" which marks the end of user code
let Some(dump_pos) = content.find(" stack.dump") else {
return false;
};
// Insert new expression before stack.dump
let mut new_content = String::new();
new_content.push_str(&content[..dump_pos]);
new_content.push_str(" ");
new_content.push_str(expr);
new_content.push('\n');
new_content.push_str(&content[dump_pos..]);
fs::write(&self.session_path, new_content).is_ok()
}
/// Pop the last expression from main
fn pop_last_expression(&mut self) -> bool {
let Ok(content) = fs::read_to_string(&self.session_path) else {
return false;
};
// Find ": main ( -- )" line end
let Some(main_pos) = content.find(": main") else {
return false;
};
let Some(newline_offset) = content[main_pos..].find('\n') else {
return false;
};
let main_line_end = main_pos + newline_offset + 1;
// Find " stack.dump"
let Some(dump_pos) = content.find(" stack.dump") else {
return false;
};
// Get the expressions section
let expr_section = &content[main_line_end..dump_pos];
let lines: Vec<&str> = expr_section.lines().collect();
// Find last non-empty line
let mut last_expr_idx = None;
for (i, line) in lines.iter().enumerate().rev() {
if !line.trim().is_empty() {
last_expr_idx = Some(i);
break;
}
}
let last_expr_idx = match last_expr_idx {
Some(i) => i,
None => return false, // Nothing to pop
};
// Rebuild without the last expression
let mut new_content = String::new();
new_content.push_str(&content[..main_line_end]);
for (i, line) in lines.iter().enumerate() {
if i != last_expr_idx {
new_content.push_str(line);
new_content.push('\n');
}
}
new_content.push_str(&content[dump_pos..]);
fs::write(&self.session_path, new_content).is_ok()
}
/// Clear the session (reset to template)
fn clear_session(&mut self) {
if let Err(e) = fs::write(
&self.session_path,
format!("{}{}", REPL_TEMPLATE, MAIN_CLOSE),
) {
self.status_message = Some(format!("Warning: Could not clear session file: {}", e));
return;
}
self.repl_state = ReplState::new();
self.ir_content = IrContent::new();
}
/// Add an include to the includes section
fn add_include(&mut self, module: &str) -> bool {
let Ok(content) = fs::read_to_string(&self.session_path) else {
return false;
};
// Check if already included
let include_stmt = format!("include {}", module);
if content.contains(&include_stmt) {
self.status_message = Some(format!("'{}' is already included.", module));
return false;
}
// Find the includes marker
let Some(includes_pos) = content.find(INCLUDES_MARKER) else {
return false;
};
// Find end of marker line
let marker_end = includes_pos + INCLUDES_MARKER.len();
let after_marker = &content[marker_end..];
let newline_pos = after_marker.find('\n').unwrap_or(0);
let insert_pos = marker_end + newline_pos + 1;
// Insert include after marker
let mut new_content = String::new();
new_content.push_str(&content[..insert_pos]);
new_content.push_str("include ");
new_content.push_str(module);
new_content.push('\n');
new_content.push_str(&content[insert_pos..]);
fs::write(&self.session_path, new_content).is_ok()
}
/// Try including a module
fn try_include(&mut self, module: &str) {
let Ok(original) = fs::read_to_string(&self.session_path) else {
return;
};
if !self.add_include(module) {
return;
}
// Try to compile
let output_path = self.session_path.with_extension("");
match seqc::compile_file(&self.session_path, &output_path, false) {
Ok(_) => {
let _ = fs::remove_file(&output_path);
self.status_message = Some(format!("Included '{}'.", module));
}
Err(e) => {
if let Err(rollback_err) = fs::write(&self.session_path, &original) {
self.status_message = Some(format!(
"Include error: {} (also failed to rollback: {})",
e, rollback_err
));
} else {
self.status_message = Some(format!("Include error: {}", e));
}
}
}
self.repl_state.clear_input();
}
/// Update IR from the current session file
fn update_ir_from_session(&mut self, expr: &str) {
if let Ok(source) = fs::read_to_string(&self.session_path) {
let result = analyze(&source);
if result.errors.is_empty() {
self.update_ir_from_result(&result, expr);
}
}
}
/// Helper to add an error entry
fn add_error_entry(&mut self, input: &str, error: &str) {
self.repl_state
.add_entry(HistoryEntry::new(input).with_error(error));
self.repl_state.clear_input();
}
/// Handle a REPL command
fn handle_command(&mut self, cmd: &str) {
let cmd = cmd.trim();
match cmd {
":q" | ":quit" => {
self.should_quit = true;
}
":version" | ":v" => {
let version = env!("CARGO_PKG_VERSION");
self.repl_state
.add_entry(HistoryEntry::new(cmd).with_output(format!("seqr {version}")));
self.status_message = Some(format!("seqr {}", version));
}
":clear" => {
self.clear_session();
self.repl_state.add_entry(HistoryEntry::new(":clear"));
self.status_message = Some("Session cleared.".to_string());
}
":pop" => {
if self.pop_last_expression() {
// Add :pop to history
self.repl_state.add_entry(HistoryEntry::new(":pop"));
// Show new stack state in IR pane (informational, not in history)
self.show_stack_in_ir_pane();
self.status_message = Some("Popped last expression.".to_string());
} else {
self.status_message = Some("Nothing to pop.".to_string());
}
}
":stack" | ":s" => {
// Show current stack state
self.compile_and_show_stack(":stack");
}
":show" => {
// Show session file contents in IR pane
self.repl_state.add_entry(HistoryEntry::new(":show"));
if let Ok(content) = fs::read_to_string(&self.session_path) {
self.ir_content = IrContent {
stack_art: content.lines().map(String::from).collect(),
typed_ast: vec!["(session file contents)".to_string()],
llvm_ir: vec![],
errors: vec![],
};
self.ir_mode = IrViewMode::StackArt;
}
}
":ir" => {
// Toggle IR pane visibility
self.repl_state.add_entry(HistoryEntry::new(":ir"));
self.show_ir_pane = !self.show_ir_pane;
if self.show_ir_pane {
self.status_message =
Some(format!("IR: {} (Ctrl+N to cycle)", self.ir_mode.name()));
} else {
self.status_message = Some("IR pane hidden".to_string());
}
}
":ir stack" => {
self.repl_state.add_entry(HistoryEntry::new(":ir stack"));
self.show_ir_pane = true;
self.ir_mode = IrViewMode::StackArt;
self.status_message = Some("IR: Stack Effects".to_string());
}
":ir ast" => {
self.repl_state.add_entry(HistoryEntry::new(":ir ast"));
self.show_ir_pane = true;
self.ir_mode = IrViewMode::TypedAst;
self.status_message = Some("IR: Typed AST".to_string());
}
":ir llvm" => {
self.repl_state.add_entry(HistoryEntry::new(":ir llvm"));
self.show_ir_pane = true;
self.ir_mode = IrViewMode::LlvmIr;
self.status_message = Some("IR: LLVM IR".to_string());
}
":edit" | ":e" => {
// Signal that we need to open editor (handled by run loop)
self.repl_state.add_entry(HistoryEntry::new(cmd));
self.should_edit = true;
}
":help" | ":h" => {
// Show help in the IR pane
self.repl_state.add_entry(HistoryEntry::new(cmd));
self.ir_content = IrContent {
stack_art: HELP_LINES.iter().map(|s| s.to_string()).collect(),
typed_ast: vec![],
llvm_ir: vec![],
errors: vec![],
};
self.ir_mode = IrViewMode::StackArt;
self.show_ir_pane = true;
}
_ if cmd.starts_with(":include ") => {
// Safe: we just verified the prefix exists
let module = &cmd[":include ".len()..].trim();
if module.is_empty() {
self.status_message = Some("Usage: :include <module>".to_string());
} else {
self.repl_state.add_entry(HistoryEntry::new(cmd));
self.try_include(module);
return; // try_include clears input
}
}
_ => {
self.status_message = Some(format!("Unknown command: {}", cmd));
}
}
self.repl_state.clear_input();
}
/// Compile session and show current stack (used by :stack command)
/// The command parameter is the actual command string (e.g., ":stack") for history
fn compile_and_show_stack(&mut self, command: &str) {
let output_path = self.session_path.with_extension("");
match seqc::compile_file(&self.session_path, &output_path, false) {
Ok(_) => {
let result = run_with_timeout(&output_path);
let _ = fs::remove_file(&output_path);
match result {
RunResult::Success { stdout } => {
let output_text = stdout.trim();
// Add command to history with stack output
if !output_text.is_empty() {
self.repl_state
.add_entry(HistoryEntry::new(command).with_output(output_text));
} else {
self.repl_state
.add_entry(HistoryEntry::new(command).with_output("(empty)"));
}
}
RunResult::Timeout { timeout_secs } => {
self.status_message = Some(format!(
"Timeout after {}s while showing stack",
timeout_secs
));
}
_ => {
// Failed or Error - just ignore for stack display
}
}
}
Err(e) => {
self.status_message = Some(format!("Compile error: {}", e));
}
}
}
/// Show current stack in IR pane without adding to history (for informational display)
fn show_stack_in_ir_pane(&mut self) {
let output_path = self.session_path.with_extension("");
match seqc::compile_file(&self.session_path, &output_path, false) {
Ok(_) => {
let result = run_with_timeout(&output_path);
let _ = fs::remove_file(&output_path);
match result {
RunResult::Success { stdout } => {
let output_text = stdout.trim();
let mut lines = vec!["Stack:".to_string()];
if !output_text.is_empty() {
lines.extend(output_text.lines().map(String::from));
} else {
lines.push("(empty)".to_string());
}
self.ir_content = IrContent {
stack_art: lines,
typed_ast: vec![],
llvm_ir: vec![],
errors: vec![],
};
self.ir_mode = IrViewMode::StackArt;
self.show_ir_pane = true;
}
_ => {
// Timeout or error - ignore for display
}
}
}
Err(_) => {
// Compile error - ignore for display
}
}
}
/// Update search matches based on current search pattern
fn update_search_matches(&mut self) {
self.search_matches.clear();
self.search_match_index = 0;
if self.search_pattern.is_empty() {
return;
}
let pattern = self.search_pattern.to_lowercase();
// Search in reverse order (most recent first)
for (i, entry) in self.repl_state.history.iter().enumerate().rev() {
if entry.input.to_lowercase().contains(&pattern) {
self.search_matches.push(i);
}
}
}
/// Preview the current search match in the input line
fn preview_current_match(&mut self) {
if self.search_matches.is_empty() {
// No matches - show original input
self.repl_state.input = self.search_original_input.clone();
} else {
// Show current match
let idx = self.search_matches[self.search_match_index];
if let Some(entry) = self.repl_state.history.get(idx) {
self.repl_state.input = entry.input.clone();
}
}
self.sync_editor_to_input();
}
/// Update status message to show search state
fn update_search_status(&mut self) {
if self.search_matches.is_empty() {
if self.search_pattern.is_empty() {
self.status_message = Some("/".to_string());
} else {
self.status_message = Some(format!("/{} (no matches)", self.search_pattern));
}
} else {
let match_num = self.search_match_index + 1;
let total = self.search_matches.len();
self.status_message = Some(format!(
"/{} ({}/{})",
self.search_pattern, match_num, total
));
}
}
/// Update IR preview as user types
fn update_ir_preview(&mut self) {
let input = self.repl_state.current_input().to_string();
if input.trim().is_empty() {
self.ir_content = IrContent::new();
return;
}
// For live preview, just show stack art for known words
// Don't run full analysis on every keystroke - too noisy with errors
self.ir_content = IrContent {
stack_art: self.generate_stack_art(&input),
typed_ast: vec![format!("Expression: {}", input)],
llvm_ir: vec!["(compile with Enter to see LLVM IR)".to_string()],
errors: vec![],
};
}
/// Navigate to previous history entry (older)
fn navigate_history_prev(&mut self) {
self.repl_state.history_up();
self.sync_editor_to_input();
}
/// Navigate to next history entry (newer)
fn navigate_history_next(&mut self) {
self.repl_state.history_down();
self.sync_editor_to_input();
}
/// Toggle IR pane to a specific view mode
/// If already showing this mode, hide the pane. Otherwise show/switch to it.
fn toggle_ir_view(&mut self, mode: IrViewMode) {
if self.show_ir_pane && self.ir_mode == mode {
// Same view - toggle off
self.show_ir_pane = false;
self.status_message = Some("IR pane hidden".to_string());
} else {
// Different view or hidden - show this view
self.show_ir_pane = true;
self.ir_mode = mode;
self.status_message = Some(format!("IR: {}", mode.name()));
}
}
/// Update IR content from analysis result
fn update_ir_from_result(&mut self, _result: &AnalysisResult, input: &str) {
// Generate stack art for the expression
let stack_art = self.generate_stack_art(input);
// Typed AST placeholder
let typed_ast = vec![
format!("Expression: {}", input),
String::new(),
"Types inferred successfully".to_string(),
];
// LLVM IR - compile the expression standalone for clean, focused IR
let llvm_ir = analyze_expression(input)
.unwrap_or_else(|| vec!["(expression could not be compiled standalone)".to_string()]);
self.ir_content = IrContent {
stack_art,
typed_ast,
llvm_ir,
errors: vec![],
};
}
/// Generate stack art for an expression
fn generate_stack_art(&self, input: &str) -> Vec<String> {
// Parse the expression into words and generate stack transitions
let words: Vec<&str> = input.split_whitespace().collect();
if words.is_empty() {
return vec![];
}
let mut lines = vec![format!("Expression: {}", input), String::new()];
// For now, show individual word effects
for word in &words {
if let Some(effect) = self.get_word_effect(word) {
let before = Stack::with_rest("s");
let after = Stack::with_rest("s");
let transition = render_transition(&effect, &before, &after);
lines.extend(transition);
lines.push(String::new());
}
}
if lines.len() <= 2 {
lines.push("(no stack effects to display)".to_string());
}
lines
}
/// Get the stack effect for a word or literal
fn get_word_effect(&self, word: &str) -> Option<StackEffect> {
// Check for literals first
if word.parse::<i64>().is_ok() {
return Some(StackEffect::literal(word));
}
if word.parse::<f64>().is_ok() && word.contains('.') {
return Some(StackEffect::literal(word));
}
if word == "true" || word == "false" {
return Some(StackEffect::literal(word));
}
// Look up in static effects table
crate::ir::stack_effects::get_effect(word).cloned()
}
/// Request completions from LSP or builtins
fn request_completions(&mut self) {
let input = &self.repl_state.input;
let cursor = self.repl_state.cursor;
if let Some(msg) = self.completions.request(input, cursor, &self.session_path) {
self.status_message = Some(msg);
} else if self.completions.items().is_empty() {
self.status_message = Some("No completions".to_string());
}
}
/// Accept the current completion
fn accept_completion(&mut self) {
let input = &self.repl_state.input;
let cursor = self.repl_state.cursor;
if let Some((word_start, completion)) = self.completions.accept(input, cursor) {
let before = &input[..word_start];
let after = &input[cursor..];
self.repl_state.input = format!("{}{}{}", before, completion, after);
self.repl_state.cursor = word_start + completion.len();
self.update_ir_preview();
}
}
/// Render the application to a frame
pub(crate) fn render(&self, frame: &mut Frame) {
let area = frame.area();
let layout = ComputedLayout::compute(area, &self.layout_config, self.show_ir_pane);
// Render REPL pane (always focused, no border)
// Cursor should always be visible in both Normal and Insert modes
let repl_pane = ReplPane::new(&self.repl_state).focused(true).prompt(
if self.editor.status() == "INSERT" {
"seq> "
} else {
"seq: "
},
);
frame.render_widget(&repl_pane, layout.repl);
// Render IR pane (if enabled and space available)
if self.show_ir_pane && layout.ir_visible() {
let ir_pane = IrPane::new(&self.ir_content).mode(self.ir_mode);
frame.render_widget(&ir_pane, layout.ir);
}
// Render status bar
self.render_status_bar(frame, layout.status);
// Render completion popup (on top of everything)
if self.completions.is_visible() && !self.completions.items().is_empty() {
self.render_completions(frame, layout.repl);
}
}
/// Render the status bar
fn render_status_bar(&self, frame: &mut Frame, area: Rect) {
let status = StatusContent::new()
.filename(&self.filename)
.mode(self.editor.status())
.ir_view(self.ir_mode.name());
let status_text = if let Some(msg) = &self.status_message {
msg.clone()
} else {
status.format(area.width)
};
let style = Style::default().bg(Color::DarkGray).fg(Color::White);
let paragraph = Paragraph::new(Line::from(Span::styled(status_text, style)));
frame.render_widget(paragraph, area);
}
/// Render the completion popup
fn render_completions(&self, frame: &mut Frame, repl_area: Rect) {
let items = self.completions.items();
let selected_index = self.completions.index();
// Calculate popup position (above the input line)
let popup_height = (items.len() + 2) as u16; // +2 for border
let popup_width = items.iter().map(|c| c.label.len()).max().unwrap_or(10) as u16 + 4; // +4 for padding and border
// Position popup near the cursor
let prompt_len = 5; // "seq> " or "seq: "
let x = repl_area.x + prompt_len + self.repl_state.cursor as u16;
let x = x.min(repl_area.right().saturating_sub(popup_width));
// Put it above the current line if possible
let y = if repl_area.bottom() > popup_height + 1 {
repl_area.bottom() - popup_height - 1
} else {
repl_area.y
};
let popup_area = Rect::new(x, y, popup_width, popup_height);
// Clear the area first
frame.render_widget(Clear, popup_area);
// Build completion lines
let lines: Vec<Line> = items
.iter()
.enumerate()
.map(|(i, item)| {
let style = if i == selected_index {
Style::default()
.bg(Color::Blue)
.fg(Color::White)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Color::White)
};
Line::from(Span::styled(format!(" {} ", item.label), style))
})
.collect();
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Cyan))
.style(Style::default().bg(Color::Black));
let paragraph = Paragraph::new(lines).block(block);
frame.render_widget(paragraph, popup_area);
}
}
#[cfg(test)]
mod tests;