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
#[cfg(blots_pools)]
mod allocator;
mod cli;
mod commands;
mod highlighter;
use blots_core::ast::{Expr, Spanned};
use blots_core::environment::Environment;
use blots_core::expressions::{
evaluate_statement, evaluate_statement_pairs, pairs_to_expr_with_comments,
validate_portable_value,
};
use blots_core::fast_parser::{Statement, parse_program};
use blots_core::formatter::format_expr;
use blots_core::functions::{
clear_function_call_stats, get_function_call_stats, set_profiling_enabled,
};
use blots_core::heap::Heap;
use blots_core::intern::Symbol;
use blots_core::json::{self, Inputs};
use blots_core::parser::{Rule, get_pairs};
use blots_core::stats::ProfilingSummary;
use blots_core::values::Value;
use clap::CommandFactory;
use clap_complete::{Shell, generate, shells::*};
use cli::Args;
use commands::{CommandResult, exec_command, is_command};
use highlighter::BlotsHighlighter;
use indexmap::IndexMap;
use rustyline::Editor;
use std::cell::RefCell;
use std::fs;
use std::io::{self, BufWriter, IsTerminal, Read, Write};
use std::rc::Rc;
use std::sync::LazyLock;
#[cfg(blots_pools)]
#[global_allocator]
static ALLOCATOR: allocator::Allocator = allocator::Allocator;
static ARGS: LazyLock<Args> = LazyLock::new(Args::from_env);
/// Parse JSON string into an IndexMap of Values
fn parse_json_inputs(
json_str: &str,
heap: &RefCell<Heap>,
source: &str,
unnamed_counter: &mut usize,
) -> Result<IndexMap<String, Value>, String> {
let inputs = json::read_inputs(json_str, &mut heap.borrow_mut())
.map_err(|e| format!("[input error] Failed to parse JSON from {}: {}", source, e))?;
let mut inputs_map: IndexMap<String, Value> = IndexMap::new();
match inputs {
Inputs::Named(entries) => inputs_map.extend(entries),
// If not an object, wrap in a record with a unique key
Inputs::Unnamed(Some(value)) => {
let key = format!("value_{}", *unnamed_counter + 1);
*unnamed_counter += 1;
inputs_map.insert(key, value);
}
Inputs::Unnamed(None) => {}
}
Ok(inputs_map)
}
/// The outputs of a program: the JSON text of each value, under its name, in the order the
/// names were first recorded in.
type Outputs = IndexMap<String, String>;
/// Write `outputs` to `writer` as one JSON object.
fn write_outputs_to(writer: &mut impl Write, outputs: &Outputs) -> io::Result<()> {
writer.write_all(b"{")?;
for (position, (name, json)) in outputs.iter().enumerate() {
if position > 0 {
writer.write_all(b",")?;
}
serde_json::to_writer(&mut *writer, name)?;
writer.write_all(b":")?;
writer.write_all(json.as_bytes())?;
}
writer.write_all(b"}")
}
/// Write outputs to file or stdout
fn write_outputs(outputs: &Outputs, output_path: Option<&String>) {
if let Some(path) = output_path {
// Write to file
match fs::File::create(path) {
Ok(file) => {
let mut writer = BufWriter::new(file);
let written = write_outputs_to(&mut writer, outputs).and_then(|()| writer.flush());
if let Err(e) = written {
eprintln!("[output error] Failed to write to file {}: {}", path, e);
std::process::exit(1);
}
eprintln!("Output saved to {}", path);
}
Err(e) => {
eprintln!("[output error] Failed to create file {}: {}", path, e);
std::process::exit(1);
}
}
} else {
// Write to stdout
let mut writer = BufWriter::new(io::stdout().lock());
let written = write_outputs_to(&mut writer, outputs)
.and_then(|()| writer.write_all(b"\n"))
.and_then(|()| writer.flush());
if let Err(e) = written {
panic!("failed printing to stdout: {}", e);
}
}
}
/// Record `value` as the output called `name`, or exit if it cannot leave the program.
fn record_output(
name: &str,
value: &Value,
heap: &Rc<RefCell<Heap>>,
bindings: &Rc<Environment>,
outputs: &mut Outputs,
) {
if let Err(e) = validate_portable_value(value, &heap.borrow(), bindings) {
eprintln!("[output error] {}", e);
std::process::exit(1);
}
if let Ok(text) = json::to_text(value, &heap.borrow()) {
outputs.insert(name.to_string(), text);
}
}
/// Evaluate the statements of a program that `parse_program` read, in order.
fn evaluate_statements(
statements: Vec<Statement>,
source: &str,
heap: &Rc<RefCell<Heap>>,
bindings: &Rc<Environment>,
outputs: &mut Outputs,
) {
let source: Rc<str> = source.into();
for statement in statements {
match statement {
Statement::Expression(expr) => {
let result = evaluate_statement(
&expr,
Rc::clone(heap),
Rc::clone(bindings),
Rc::clone(&source),
&mut [],
);
if let Err(error) = result {
println!("[evaluation error] {}", error);
std::process::exit(1);
}
}
Statement::Output {
name,
expr,
assigns,
} => {
let result = evaluate_statement(
&expr,
Rc::clone(heap),
Rc::clone(bindings),
Rc::clone(&source),
&mut [],
);
if assigns {
if let Ok(value) = &result {
record_output(name.as_str(), value, heap, bindings, outputs);
}
} else if let Some(value) = bindings.get(name) {
record_output(name.as_str(), &value, heap, bindings, outputs);
}
if let Err(error) = result {
println!("[evaluation error] {}", error);
std::process::exit(1);
}
}
Statement::Comment => {}
}
// Statement boundary: safe point to reclaim heap garbage, since only the root
// bindings (and the pinned constants record) need to survive past this point.
heap.borrow_mut().compact_if_grown(bindings, &mut []);
}
}
/// Evaluate Blots source code and collect outputs
fn evaluate_source(
source: &str,
heap: &Rc<RefCell<Heap>>,
bindings: &Rc<Environment>,
outputs: &mut Outputs,
) -> Result<(), String> {
if let Some(statements) = parse_program(source) {
evaluate_statements(statements, source, heap, bindings, outputs);
return Ok(());
}
let pairs = get_pairs(source).map_err(|e| format!("Parse error: {}", e))?;
pairs.for_each(|pair| match pair.as_rule() {
Rule::statement => {
if let Some(inner_pair) = pair.into_inner().next() {
match inner_pair.as_rule() {
Rule::expression => {
let result = evaluate_statement_pairs(
inner_pair.into_inner(),
Rc::clone(heap),
Rc::clone(bindings),
source,
&mut [],
);
if let Err(error) = result {
println!("[evaluation error] {}", error);
std::process::exit(1);
}
}
Rule::output_declaration => {
let inner_pairs_clone = inner_pair.clone().into_inner();
let result = evaluate_statement_pairs(
inner_pair.clone().into_inner(),
Rc::clone(heap),
Rc::clone(bindings),
source,
&mut [],
);
for pair in inner_pairs_clone {
match pair.as_rule() {
Rule::identifier => {
let identifier = pair.as_str();
if let Some(value) = bindings.get(Symbol::intern(identifier)) {
// Validate that the value is portable
if let Err(e) = validate_portable_value(
&value,
&heap.borrow(),
bindings,
) {
eprintln!("[output error] {}", e);
std::process::exit(1);
} else if let Ok(text) =
json::to_text(&value, &heap.borrow())
{
outputs.insert(identifier.to_string(), text);
}
}
break;
}
Rule::assignment => {
if let Some(ident_pair) = pair.into_inner().next() {
let identifier = ident_pair.as_str();
if let Ok(value) = &result {
if let Err(e) = validate_portable_value(
value,
&heap.borrow(),
bindings,
) {
eprintln!("[output error] {}", e);
std::process::exit(1);
} else if let Ok(text) =
json::to_text(value, &heap.borrow())
{
outputs.insert(identifier.to_string(), text);
}
}
}
break;
}
_ => {}
}
}
if let Err(error) = result {
println!("[evaluation error] {}", error);
std::process::exit(1);
}
}
Rule::comment => {}
_ => unreachable!("unexpected rule: {:?}", inner_pair.as_rule()),
}
// Statement boundary: safe point to reclaim heap garbage, since only the root
// bindings (and the pinned constants record) need to survive past this point.
heap.borrow_mut().compact_if_grown(bindings, &mut []);
}
}
Rule::EOI => {}
rule => unreachable!("unexpected rule: {:?}", rule),
});
Ok(())
}
fn main() -> ! {
// Handle shell completion generation
if let Some(shell) = &ARGS.completions {
let mut cmd = cli::Args::command();
let name = "blots";
match shell {
Shell::Bash => generate(Bash, &mut cmd, name, &mut io::stdout()),
Shell::Zsh => generate(Zsh, &mut cmd, name, &mut io::stdout()),
Shell::Fish => generate(Fish, &mut cmd, name, &mut io::stdout()),
Shell::PowerShell => generate(PowerShell, &mut cmd, name, &mut io::stdout()),
Shell::Elvish => generate(Elvish, &mut cmd, name, &mut io::stdout()),
_ => {
eprintln!("Unsupported shell: {}", shell);
std::process::exit(1);
}
}
std::process::exit(0);
}
// Handle formatting
if !ARGS.format.is_empty() {
if ARGS.format.len() != 2 {
eprintln!("Error: --format requires exactly 2 arguments: INPUT and OUTPUT");
std::process::exit(1);
}
let input_path = &ARGS.format[0];
let output_path = &ARGS.format[1];
// Read input file
let source = match fs::read_to_string(input_path) {
Ok(content) => content,
Err(e) => {
eprintln!("Error reading input file '{}': {}", input_path, e);
std::process::exit(1);
}
};
// Parse the source
let pairs = match get_pairs(&source) {
Ok(pairs) => pairs,
Err(e) => {
eprintln!("Parse error: {}", e);
std::process::exit(1);
}
};
// Format each statement
let mut formatted_output = String::new();
for pair in pairs {
match pair.as_rule() {
Rule::statement => {
if let Some(inner_pair) = pair.into_inner().next() {
match inner_pair.as_rule() {
Rule::expression => {
match pairs_to_expr_with_comments(inner_pair.into_inner()) {
Ok(expr) => {
let formatted = format_expr(&expr, None);
formatted_output.push_str(&formatted);
formatted_output.push('\n');
}
Err(e) => {
eprintln!("Error converting to AST: {}", e);
std::process::exit(1);
}
}
}
Rule::output_declaration => {
match pairs_to_expr_with_comments(inner_pair.into_inner()) {
Ok(inner_expr) => {
// Wrap in Output expression
let output_expr = Spanned::dummy(Expr::Output {
expr: Box::new(inner_expr),
});
let formatted = format_expr(&output_expr, None);
formatted_output.push_str(&formatted);
formatted_output.push('\n');
}
Err(e) => {
eprintln!("Error converting to AST: {}", e);
std::process::exit(1);
}
}
}
Rule::comment => {
// Preserve comments as-is
formatted_output.push_str(inner_pair.as_str());
formatted_output.push('\n');
}
_ => {}
}
}
}
Rule::EOI => {}
_ => {}
}
}
// Write to output file
match fs::write(output_path, formatted_output) {
Ok(_) => {
println!("Formatted {} -> {}", input_path, output_path);
std::process::exit(0);
}
Err(e) => {
eprintln!("Error writing output file '{}': {}", output_path, e);
std::process::exit(1);
}
}
}
// Save output path for REPL mode (before args is moved)
let output_path = ARGS.output.clone();
// Check if stdin is piped or interactive
let is_piped = !io::stdin().is_terminal();
let should_parse_piped_inputs = is_piped && !ARGS.evaluate;
// Track if we've consumed piped input and need to reopen stdin
let mut stdin_consumed = false;
// Set up our memory
let heap = Rc::new(RefCell::new(Heap::new()));
let bindings = Rc::new(Environment::new());
let mut outputs = Outputs::new();
// Turn on per-call stats recording (off by default for performance) and start clean
#[cfg(not(target_arch = "wasm32"))]
if ARGS.profile {
set_profiling_enabled(true);
clear_function_call_stats();
}
// Collect inputs
// Parse inputs from stdin and/or -i flag
let mut inputs_map: IndexMap<String, Value> = IndexMap::new();
let mut unnamed_counter: usize = 0;
// First, read from stdin if available (piped inputs). The text is only needed until the
// inputs are values of the heap, and is given back then: it can be as large as they are.
if should_parse_piped_inputs {
let mut stdin_content = String::new();
let _ = io::stdin().read_to_string(&mut stdin_content);
stdin_consumed = true;
if !stdin_content.trim().is_empty() {
match parse_json_inputs(&stdin_content, &heap, "stdin", &mut unnamed_counter) {
Ok(map) => inputs_map = map,
Err(e) => {
eprintln!("{}", e);
std::process::exit(1);
}
}
}
}
// Then, apply -i flag inputs (which override piped inputs)
// Process each -i flag in order, with later ones overriding earlier ones
for (index, inputs_str) in ARGS.input.iter().enumerate() {
match parse_json_inputs(
inputs_str,
&heap,
&format!("--input #{}", index + 1),
&mut unnamed_counter,
) {
Ok(map) => {
// Merge with existing inputs (later --input override earlier ones)
for (k, v) in map {
inputs_map.insert(k, v);
}
}
Err(e) => {
eprintln!("{}", e);
std::process::exit(1);
}
}
}
let inputs_record = { heap.borrow_mut().insert_record(inputs_map) };
bindings.insert(Symbol::intern("inputs"), inputs_record);
// Check if we should evaluate from stdin with -e flag
if ARGS.evaluate && ARGS.file_or_source.is_none() {
// Read stdin as Blots source code
if io::stdin().is_terminal() {
eprintln!("Error: --evaluate requires piped input");
std::process::exit(1);
}
let mut content = String::new();
io::stdin().read_to_string(&mut content).unwrap();
if let Err(e) = evaluate_source(&content, &heap, &bindings, &mut outputs) {
eprintln!("{}", e);
std::process::exit(1);
}
#[cfg(not(target_arch = "wasm32"))]
if ARGS.profile {
let stats = get_function_call_stats();
if !stats.is_empty() {
let summary = ProfilingSummary::from_stats(&stats);
summary.print_summary();
}
}
write_outputs(&outputs, ARGS.output.as_ref());
std::process::exit(0);
}
if let Some(path_or_source) = &ARGS.file_or_source {
let is_file = std::path::Path::new(path_or_source).exists();
let content = if !is_file {
// Treat the argument as inline Blots code
path_or_source.clone()
} else {
// Treat as a file path
std::fs::read_to_string(path_or_source).unwrap_or_else(|e| {
eprintln!("Error reading file '{}': {}", path_or_source, e);
std::process::exit(1);
})
};
if let Err(e) = evaluate_source(&content, &heap, &bindings, &mut outputs) {
eprintln!("{}", e);
std::process::exit(1);
}
#[cfg(not(target_arch = "wasm32"))]
if ARGS.profile {
let stats = get_function_call_stats();
if !stats.is_empty() {
let summary = ProfilingSummary::from_stats(&stats);
summary.print_summary();
}
}
write_outputs(&outputs, ARGS.output.as_ref());
std::process::exit(0);
}
// REPL mode
// Check if stdin was consumed (piped input) - if so, we can't start an interactive REPL
if stdin_consumed {
eprintln!("Error: Cannot start Interactive Mode after reading piped input.");
eprintln!();
eprintln!(
"When piping JSON data, you must also specify what to do with it, by specifying a .blots file to run:"
);
eprintln!(" echo '{{\"x\": 42}}' | blots myfile.blots");
eprintln!();
eprintln!(
"If you want to provide inputs that you can use in an interactive session, you can use the --input (-i) flag:"
);
eprintln!(" blots --input '{{\"x\": 42, \"y\": \"hello\"}}'");
eprintln!();
eprintln!(
"You can also pipe Blots code with --evaluate (-e). This can be combined with the -i flag:"
);
eprintln!(
" echo -e 'output result = inputs.x + inputs.y' | blots --evaluate -i '{{\"x\": 42, \"y\": \"hello\"}}'"
);
// If outputs were collected, write them before exiting
if !outputs.is_empty() || output_path.is_some() {
write_outputs(&outputs, output_path.as_ref());
}
std::process::exit(1);
}
// Initialize rustyline editor for command history
let mut rl: Option<Editor<BlotsHighlighter, rustyline::history::DefaultHistory>> =
match Editor::with_config(rustyline::Config::builder().build()) {
Ok(mut editor) => {
// Set up syntax highlighting
let highlighter = BlotsHighlighter::new(Rc::clone(&bindings));
editor.set_helper(Some(highlighter));
Some(editor)
}
Err(e) => {
eprintln!("Error: Failed to initialize interactive editor: {}", e);
std::process::exit(1);
}
};
let mut accumulated_input = String::new();
let mut continuation = false;
// REPL loop
loop {
let prompt = if continuation { "... " } else { "> " };
let line = if let Some(ref mut editor) = rl {
// Use rustyline for interactive input with history
match editor.readline(prompt) {
Ok(input) => {
input + "\n" // Add newline to match read_line behavior
}
Err(rustyline::error::ReadlineError::Eof) => {
// EOF - print outputs and exit gracefully
if outputs.is_empty() && output_path.is_none() {
println!("{{}}");
} else {
write_outputs(&outputs, output_path.as_ref());
}
std::process::exit(0);
}
Err(rustyline::error::ReadlineError::Interrupted) => {
// Ctrl+C - print outputs and exit
if outputs.is_empty() && output_path.is_none() {
println!("{{}}");
} else {
write_outputs(&outputs, output_path.as_ref());
}
std::process::exit(0);
}
Err(e) => {
eprintln!("Error: Failed to read line: {}", e);
if stdin_consumed {
eprintln!(
"This may be because the terminal is not accessible after piped input."
);
eprintln!("Try using the -i flag instead: blots -i '{{\"x\": 42}}'");
}
std::process::exit(1);
}
}
} else {
// Fall back to basic stdin just in case
let mut line = String::new();
let bytes_read = std::io::stdin().read_line(&mut line).unwrap();
// If we've reached EOF, exit
if bytes_read == 0 {
// Print outputs before exiting
if outputs.is_empty() && output_path.is_none() {
println!("{{}}");
} else {
write_outputs(&outputs, output_path.as_ref());
}
std::process::exit(0);
}
line
};
// Check for commands only on first line
if !continuation && is_command(line.trim()) {
match exec_command(line.trim()) {
CommandResult::Quit => {
// Print outputs before exiting
if outputs.is_empty() && output_path.is_none() {
println!("{{}}");
} else {
write_outputs(&outputs, output_path.as_ref());
}
std::process::exit(0);
}
CommandResult::Continue => continue,
}
}
// Accumulate the input
accumulated_input.push_str(&line);
// Try to parse the accumulated input
let parse_result = get_pairs(&accumulated_input);
// Check for continuation (unmatched brackets)
if parse_result.is_err()
&& (accumulated_input.matches('(').count() > accumulated_input.matches(')').count()
|| accumulated_input.matches('[').count() > accumulated_input.matches(']').count()
|| accumulated_input.matches('{').count() > accumulated_input.matches('}').count())
{
continuation = true;
continue;
}
// Add to history (for both successful and failed commands)
if let Some(ref mut editor) = rl
&& !accumulated_input.trim().is_empty()
{
let _ = editor.add_history_entry(accumulated_input.trim());
}
let pairs = match parse_result {
Ok(pairs) => pairs,
Err(error) => {
println!("[parse error] {}", error);
accumulated_input.clear();
continuation = false;
continue;
}
};
pairs.for_each(|pair| match pair.as_rule() {
Rule::statement => {
if let Some(inner_pair) = pair.into_inner().next() {
match inner_pair.as_rule() {
Rule::expression => {
let result = evaluate_statement_pairs(
inner_pair.into_inner(),
Rc::clone(&heap),
Rc::clone(&bindings),
&accumulated_input,
&mut [],
);
match result {
Ok(value) => {
let value_str = value.stringify_external(&heap.borrow());
println!(
"{}",
rl.as_ref()
.unwrap()
.helper()
.unwrap()
.highlight_result(&value_str)
);
}
Err(error) => println!("[evaluation error] {}", error),
}
}
Rule::output_declaration => {
// Handle output declarations in REPL
let inner_pairs_clone = inner_pair.clone().into_inner();
// Evaluate the entire output declaration
let result = evaluate_statement_pairs(
inner_pair.clone().into_inner(),
Rc::clone(&heap),
Rc::clone(&bindings),
&accumulated_input,
&mut [],
);
// Extract the output name from the declaration
for pair in inner_pairs_clone {
match pair.as_rule() {
Rule::identifier => {
// output x - reference existing binding
let identifier = pair.as_str();
if let Some(value) =
bindings.get(Symbol::intern(identifier))
{
// Validate that the value is portable
if let Err(e) = validate_portable_value(
&value,
&heap.borrow(),
&bindings,
) {
eprintln!("[output error] {}", e);
} else if let Ok(text) =
json::to_text(&value, &heap.borrow())
{
outputs.insert(identifier.to_string(), text);
println!("[output '{}' recorded]", identifier);
}
}
break;
}
Rule::assignment => {
// output x = expr - get the identifier from the assignment
if let Some(ident_pair) = pair.into_inner().next() {
let identifier = ident_pair.as_str();
if let Ok(value) = &result {
// Validate that the value is portable
if let Err(e) = validate_portable_value(
value,
&heap.borrow(),
&bindings,
) {
eprintln!("[output error] {}", e);
} else if let Ok(text) =
json::to_text(value, &heap.borrow())
{
outputs.insert(identifier.to_string(), text);
// Show value and confirmation in REPL
let value_str =
value.stringify_external(&heap.borrow());
println!(
"{}",
rl.as_ref()
.unwrap()
.helper()
.unwrap()
.highlight_result(&value_str)
);
println!("[output '{}' recorded]", identifier);
}
}
}
break;
}
_ => {}
}
}
// Check for errors in evaluation
if let Err(error) = result {
println!("[evaluation error] {}", error);
}
}
Rule::comment => {} // Ignore comments
_ => unreachable!("unexpected rule: {:?}", inner_pair.as_rule()),
}
}
}
Rule::EOI => {}
rule => unreachable!("unexpected rule: {:?}", rule),
});
// Input boundary: reclaim heap garbage between REPL entries. Recorded outputs are
// already serialized, so the root bindings are the only values that must survive.
heap.borrow_mut().compact_if_grown(&bindings, &mut []);
// Reset for next input
accumulated_input.clear();
continuation = false;
}
}