numbat-cli 1.23.0

A statically typed programming language for scientific computations with first class support for physical dimensions and units.
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
mod ansi_formatter;
mod completer;
mod config;
mod highlighter;

use ansi_formatter::ansi_format;
use colored::control::SHOULD_COLORIZE;
use completer::NumbatCompleter;
use config::{
    ColorMode, Config, EditMode, ExchangeRateFetchingPolicy, IntroBanner, PrettyPrintMode,
};
use highlighter::NumbatHighlighter;

use itertools::Itertools;
use numbat::command::{CommandControlFlow, CommandRunner};
use numbat::diagnostic::{ErrorDiagnostic, ResolverDiagnostic};
use numbat::module_importer::{BuiltinModuleImporter, ChainedImporter, FileSystemImporter};
use numbat::pretty_print::PrettyPrint;
use numbat::resolver::CodeSource;
use numbat::session_history::{ParseEvaluationResult, SessionHistory};
use numbat::{Context, NumbatError};
use numbat::{InterpreterSettings, NameResolutionError};
use numbat::{RuntimeErrorKind, markup as m};

use anyhow::{Context as AnyhowContext, Result, bail};
use clap::Parser;
use rustyline::config::Configurer;
use rustyline::{
    Completer, Editor, Helper, Hinter, Validator, error::ReadlineError, history::DefaultHistory,
};
use rustyline::{EventHandler, Highlighter, KeyCode, KeyEvent, Modifiers};

use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fs, thread};

#[derive(Debug, PartialEq, Eq)]
pub enum ExitStatus {
    Success,
    Error,
}

type ControlFlow = std::ops::ControlFlow<ExitStatus>;

#[derive(Parser, Debug)]
#[command(
    version,
    about,
    name("numbat"),
    max_term_width = 90,
    trailing_var_arg = true
)]
struct Args {
    /// Path to source file with Numbat code. If none is given, an interactive
    /// session is started.
    file: Option<PathBuf>,

    /// Command-line arguments passed to the Numbat program
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    script_args: Vec<String>,

    /// Evaluate a single expression. Can be specified multiple times to evaluate several expressions in sequence.
    #[arg(
        short,
        long,
        value_name = "CODE",
        action = clap::ArgAction::Append
    )]
    expression: Option<Vec<String>>,

    /// Enter interactive session after running a numbat script or expression
    #[arg(short, long)]
    inspect_interactively: bool,

    /// Do not load the user configuration file.
    #[arg(long, hide_short_help = true)]
    no_config: bool,

    /// Do not load the prelude with predefined physical dimensions and units. This implies --no-init.
    #[arg(short = 'N', long, hide_short_help = true)]
    no_prelude: bool,

    /// Do not load the user init file.
    #[arg(long, hide_short_help = true)]
    no_init: bool,

    /// Whether or not to pretty-print every input expression.
    #[arg(long, value_name = "WHEN")]
    pretty_print: Option<PrettyPrintMode>,

    /// Whether or not coloring should occur.
    #[arg(long, value_name = "WHEN")]
    color: Option<ColorMode>,

    /// What kind of intro banner to show (if any).
    #[arg(long, value_name = "MODE")]
    intro_banner: Option<IntroBanner>,

    /// Generate a default configuration file
    #[arg(long, hide_short_help = true)]
    generate_config: bool,

    /// Turn on debug mode and print disassembler output (hidden, mainly for development)
    #[arg(long, short, hide = true)]
    debug: bool,
}

struct ParseEvaluationOutcome {
    control_flow: ControlFlow,
    result: ParseEvaluationResult,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum ExecutionMode {
    Normal,
    Interactive,
}

impl ExecutionMode {
    fn exit_status_in_case_of_error(self) -> ControlFlow {
        if matches!(self, ExecutionMode::Normal) {
            ControlFlow::Break(ExitStatus::Error)
        } else {
            ControlFlow::Continue(())
        }
    }
}

#[derive(Completer, Helper, Hinter, Validator, Highlighter)]
struct NumbatHelper {
    #[rustyline(Completer)]
    completer: NumbatCompleter,
    #[rustyline(Highlighter)]
    highlighter: NumbatHighlighter,
}

struct Cli {
    config: Config,
    context: Arc<Mutex<Context>>,
    file: Option<PathBuf>,
    expression: Option<Vec<String>>,
}

impl Cli {
    fn make_fresh_context() -> Context {
        let mut fs_importer = FileSystemImporter::default();
        for path in Self::get_modules_paths() {
            fs_importer.add_path(path);
        }

        let importer = ChainedImporter::new(
            Box::new(fs_importer),
            Box::<BuiltinModuleImporter>::default(),
        );

        let mut context = Context::new(importer);

        context.set_terminal_width(
            terminal_size::terminal_size().map(|(terminal_size::Width(w), _)| w as usize),
        );

        context
    }

    fn initialize_context(&mut self) -> Result<()> {
        if self.config.load_prelude {
            let result = self.parse_and_evaluate(
                "use prelude",
                CodeSource::Internal,
                ExecutionMode::Normal,
                PrettyPrintMode::Never,
            );
            if result.control_flow.is_break() {
                bail!("Interpreter error in Prelude code")
            }
        }

        if self.config.load_user_init {
            let user_init_path = Self::get_config_path().join("init.nbt");

            if let Ok(user_init_code) = fs::read_to_string(&user_init_path) {
                let result = self.parse_and_evaluate(
                    &user_init_code,
                    CodeSource::File(user_init_path),
                    ExecutionMode::Normal,
                    PrettyPrintMode::Never,
                );
                if result.control_flow.is_break() {
                    bail!("Interpreter error in user initialization code")
                }
            }
        }

        if self.config.load_prelude
            && self.config.exchange_rates.fetching_policy != ExchangeRateFetchingPolicy::Never
        {
            self.context
                .lock()
                .unwrap()
                .load_currency_module_on_demand(true);
        }

        Ok(())
    }

    fn new(args: Args) -> Result<Self> {
        let user_config_path = Self::get_config_path().join("config.toml");

        let mut config = if args.no_config {
            Config::default()
        } else if let Ok(contents) = fs::read_to_string(&user_config_path) {
            toml::from_str(&contents).context(format!(
                "Error while loading {}",
                user_config_path.to_string_lossy()
            ))?
        } else {
            Config::default()
        };

        config.load_prelude &= !args.no_prelude;
        config.load_user_init &= !(args.no_prelude || args.no_init);

        config.intro_banner = args.intro_banner.unwrap_or(config.intro_banner);
        config.pretty_print = args.pretty_print.unwrap_or(config.pretty_print);
        config.color = args.color.unwrap_or(config.color);

        config.enter_repl =
            (args.file.is_none() && args.expression.is_none()) || args.inspect_interactively;

        let mut context = Self::make_fresh_context();
        context.set_debug(args.debug);

        Ok(Self {
            context: Arc::new(Mutex::new(context)),
            config,
            file: args.file,
            expression: args.expression,
        })
    }

    fn run(&mut self) -> Result<()> {
        // Enabled ANSI colors on Windows 10
        #[cfg(windows)]
        colored::control::set_virtual_terminal(true).unwrap();

        match self.config.color {
            ColorMode::Never => SHOULD_COLORIZE.set_override(false),
            ColorMode::Always => SHOULD_COLORIZE.set_override(true),
            ColorMode::Auto => (), // Let colored itself decide whether coloring should occur or not
        }

        self.initialize_context()?;

        let mut code_and_source = Vec::new();

        if let Some(ref path) = self.file {
            code_and_source.push((
                (fs::read_to_string(path).context(format!(
                    "Could not load source file '{}'",
                    path.to_string_lossy()
                ))?),
                CodeSource::File(path.clone()),
            ));
        };

        if let Some(expressions) = &self.expression {
            code_and_source.push((expressions.iter().join("\n"), CodeSource::Text));
        }

        let mut run_result = Ok(());

        if !code_and_source.is_empty() {
            for (code, code_source) in code_and_source {
                let result = self.parse_and_evaluate(
                    &code,
                    code_source,
                    ExecutionMode::Normal,
                    self.config.pretty_print,
                );

                let result_status = match result.control_flow {
                    std::ops::ControlFlow::Continue(()) => Ok(()),
                    std::ops::ControlFlow::Break(_) => {
                        bail!("Interpreter stopped")
                    }
                };

                run_result = run_result.and(result_status);
            }
        }

        if self.config.enter_repl {
            let mut currency_fetch_thread = if self.config.load_prelude
                && self.config.exchange_rates.fetching_policy
                    == ExchangeRateFetchingPolicy::OnStartup
            {
                Some(thread::spawn(move || {
                    numbat::Context::prefetch_exchange_rates();
                }))
            } else {
                None
            };

            let repl_result = self.repl();
            if let Some(thread) = currency_fetch_thread.take() {
                let _ = thread.join();
            }
            run_result = run_result.and(repl_result);
        }

        run_result
    }

    fn repl(&mut self) -> Result<()> {
        let interactive = std::io::stdin().is_terminal();
        let history_path = self.get_history_path()?;

        let mut rl = Editor::<NumbatHelper, DefaultHistory>::new()?;
        rl.set_edit_mode(match self.config.edit_mode {
            EditMode::Emacs => rustyline::EditMode::Emacs,
            EditMode::Vi => rustyline::EditMode::Vi,
        });
        rl.set_max_history_size(1000)
            .context("Error while configuring history size")?;
        rl.set_completion_type(rustyline::CompletionType::List);
        rl.set_helper(Some(NumbatHelper {
            completer: NumbatCompleter {
                context: self.context.clone(),
                modules: self.context.lock().unwrap().list_modules().collect(),
                all_timezones: jiff::tz::db()
                    .available()
                    .map(|name| name.as_str().into())
                    .collect(),
            },
            highlighter: NumbatHighlighter {
                context: self.context.clone(),
            },
        }));
        rl.bind_sequence(
            KeyEvent(KeyCode::Enter, Modifiers::ALT),
            EventHandler::Simple(rustyline::Cmd::Newline),
        );
        rl.load_history(&history_path).ok();

        if interactive {
            match self.config.intro_banner {
                IntroBanner::Long => {
                    println!();
                    println!(
                        "  █▄░█ █░█ █▀▄▀█ █▄▄ ▄▀█ ▀█▀    Numbat {}",
                        env!("CARGO_PKG_VERSION")
                    );
                    println!(
                        "  █░▀█ █▄█ █░▀░█ █▄█ █▀█ ░█░    {}",
                        env!("CARGO_PKG_HOMEPAGE")
                    );
                    println!();
                }
                IntroBanner::Short => {
                    println!("Numbat {}", env!("CARGO_PKG_VERSION"));
                }
                IntroBanner::Off => {}
            }
        }

        let result = self.repl_loop(&mut rl, interactive, &history_path);

        if interactive {
            rl.save_history(&history_path).context(format!(
                "Error while saving history to '{}'",
                history_path.to_string_lossy()
            ))?;
        }

        result
    }

    fn repl_loop(
        &mut self,
        rl: &mut Editor<NumbatHelper, DefaultHistory>,
        interactive: bool,
        history_path: &Path,
    ) -> Result<()> {
        let mut cmd_runner = CommandRunner::<Editor<NumbatHelper, DefaultHistory>>::new()
            .print_with(|m| println!("{}", ansi_format(m, true)))
            .enable_clear(|rl| match rl.clear_screen() {
                Ok(_) => CommandControlFlow::Continue,
                Err(_) => CommandControlFlow::Return,
            })
            .enable_save(SessionHistory::default())
            .enable_reset()
            .enable_quit();

        loop {
            let readline = rl.readline(&self.config.prompt);
            match readline {
                Ok(line) => {
                    if line.trim().is_empty() {
                        continue;
                    }

                    rl.add_history_entry(&line)?;
                    let mut ctx = self.context.lock().unwrap();

                    if interactive && rl.append_history(history_path).is_err() {
                        ctx.print_diagnostic(
                            ResolverDiagnostic {
                                resolver: ctx.resolver(),
                                error: &ctx.runtime_error(RuntimeErrorKind::HistoryWrite(
                                    history_path.to_owned(),
                                )),
                            },
                            colored::control::SHOULD_COLORIZE.should_colorize(),
                        );
                    }

                    match cmd_runner.try_run_command(&line, &mut ctx, rl) {
                        Ok(cf) => match cf {
                            CommandControlFlow::Continue => continue,
                            CommandControlFlow::Return => return Ok(()),
                            CommandControlFlow::Reset => {
                                *ctx = Self::make_fresh_context();
                                drop(ctx);
                                let _ = self.initialize_context();
                                continue;
                            }
                            CommandControlFlow::NotACommand => {}
                        },
                        Err(err) => {
                            ctx.print_diagnostic(
                                ResolverDiagnostic {
                                    resolver: ctx.resolver(),
                                    error: &*err,
                                },
                                colored::control::SHOULD_COLORIZE.should_colorize(),
                            );
                            continue;
                        }
                    }
                    drop(ctx);

                    let ParseEvaluationOutcome {
                        control_flow,
                        result,
                    } = self.parse_and_evaluate(
                        &line,
                        CodeSource::Text,
                        if interactive {
                            ExecutionMode::Interactive
                        } else {
                            ExecutionMode::Normal
                        },
                        self.config.pretty_print,
                    );

                    match control_flow {
                        std::ops::ControlFlow::Continue(()) => {}
                        std::ops::ControlFlow::Break(ExitStatus::Success) => {
                            return Ok(());
                        }
                        std::ops::ControlFlow::Break(ExitStatus::Error) => {
                            bail!("Interpreter stopped due to error")
                        }
                    }

                    cmd_runner.push_to_history(&line, result);
                }
                Err(ReadlineError::Interrupted) => {}
                Err(ReadlineError::Eof) => {
                    return Ok(());
                }
                Err(err) => {
                    bail!(err);
                }
            }
        }
    }

    #[must_use]
    fn parse_and_evaluate(
        &mut self,
        input: &str,
        code_source: CodeSource,
        execution_mode: ExecutionMode,
        pretty_print_mode: PrettyPrintMode,
    ) -> ParseEvaluationOutcome {
        let to_be_printed: Arc<Mutex<Vec<m::Markup>>> = Arc::new(Mutex::new(vec![]));
        let to_be_printed_c = to_be_printed.clone();
        let mut settings = InterpreterSettings {
            print_fn: Box::new(move |s: &m::Markup| {
                to_be_printed_c.lock().unwrap().push(s.clone());
            }),
        };

        let interpretation_result =
            self.context
                .lock()
                .unwrap()
                .interpret_with_settings(&mut settings, input, code_source);

        let interactive = execution_mode == ExecutionMode::Interactive;

        let pretty_print = match pretty_print_mode {
            PrettyPrintMode::Always => true,
            PrettyPrintMode::Never => false,
            PrettyPrintMode::Auto => interactive,
        };

        let parse_eval_result = match &interpretation_result {
            Ok(_) => Ok(()),
            Err(_) => Err(()),
        };

        let control_flow = match interpretation_result.map_err(|b| *b) {
            Ok((statements, interpreter_result)) => {
                if interactive || pretty_print {
                    println!();
                }

                if pretty_print {
                    for statement in &statements {
                        let repr = ansi_format(&statement.pretty_print(), true);
                        println!("{repr}");
                        println!();
                    }
                }

                let to_be_printed = to_be_printed.lock().unwrap();
                for s in to_be_printed.iter() {
                    println!("{}", ansi_format(s, interactive));
                }
                if interactive && !to_be_printed.is_empty() {
                    println!();
                }

                let ctx = self.context.lock().unwrap();
                let registry = ctx.dimension_registry();
                let format_options = self.config.formatting.to_format_options();
                let result_markup = interpreter_result.to_markup(
                    statements.last(),
                    registry,
                    interactive || pretty_print,
                    interactive || pretty_print,
                    &format_options,
                );
                print!("{}", ansi_format(&result_markup, false));

                if (interactive || pretty_print) && interpreter_result.is_value() {
                    println!();
                }

                ControlFlow::Continue(())
            }
            Err(NumbatError::ResolverError(e)) => {
                self.print_diagnostic(e);
                execution_mode.exit_status_in_case_of_error()
            }
            Err(NumbatError::NameResolutionError(
                e @ (NameResolutionError::IdentifierClash { .. }
                | NameResolutionError::ReservedIdentifier(_)),
            )) => {
                self.print_diagnostic(e);
                execution_mode.exit_status_in_case_of_error()
            }
            Err(NumbatError::TypeCheckError(e)) => {
                self.print_diagnostic(e);
                execution_mode.exit_status_in_case_of_error()
            }
            Err(NumbatError::RuntimeError(e)) => {
                let ctx = self.context.lock().unwrap();
                ctx.print_diagnostic(
                    ResolverDiagnostic {
                        resolver: ctx.resolver(),
                        error: &e,
                    },
                    colored::control::SHOULD_COLORIZE.should_colorize(),
                );
                execution_mode.exit_status_in_case_of_error()
            }
        };

        ParseEvaluationOutcome {
            control_flow,
            result: parse_eval_result,
        }
    }

    fn print_diagnostic(&mut self, error: impl ErrorDiagnostic) {
        self.context
            .lock()
            .unwrap()
            .print_diagnostic(error, colored::control::SHOULD_COLORIZE.should_colorize())
    }

    fn get_config_path() -> PathBuf {
        let config_dir = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
        config_dir.join("numbat")
    }

    fn get_modules_paths() -> Vec<PathBuf> {
        let mut paths = vec![];

        if let Some(modules_path) = std::env::var_os("NUMBAT_MODULES_PATH") {
            for path in modules_path.to_string_lossy().split(':') {
                paths.push(path.into());
            }
        }

        paths.push(Self::get_config_path().join("modules"));

        // We read the value of this environment variable at compile time to
        // allow package maintainers to control the system-wide module path
        // for Numbat.
        if let Some(system_module_path) = option_env!("NUMBAT_SYSTEM_MODULE_PATH") {
            if !system_module_path.is_empty() {
                paths.push(system_module_path.into());
            }
        } else if cfg!(unix) {
            paths.push("/usr/share/numbat/modules".into());
        } else {
            paths.push("C:\\Program Files\\numbat\\modules".into());
        }
        paths
    }

    fn get_history_path(&self) -> Result<PathBuf> {
        if let Ok(history) = env::var("NUMBAT_HISTORY") {
            let history_path = PathBuf::from(history);
            if let Some(parent) = history_path.parent() {
                fs::create_dir_all(parent).ok();
            }
            return Ok(history_path);
        }

        let data_dir = dirs::data_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("numbat");
        fs::create_dir_all(&data_dir).ok();
        Ok(data_dir.join("history"))
    }
}

fn generate_config() -> Result<()> {
    let config_folder_path = Cli::get_config_path();
    let config_file_path = config_folder_path.join("config.toml");

    if config_file_path.exists() {
        bail!(
            "The file '{}' exists already.",
            config_file_path.to_string_lossy()
        );
    }

    std::fs::create_dir_all(&config_folder_path).context(format!(
        "Error while creating folder '{}'",
        config_folder_path.to_string_lossy()
    ))?;

    let config = Config::default();
    let content = toml::to_string(&config).context("Error while creating TOML from config")?;

    std::fs::write(&config_file_path, content)?;

    println!(
        "A default configuration has been written to '{}'.",
        config_file_path.to_string_lossy()
    );
    println!(
        "Open the file in a text editor. Modify whatever you want to change and remove the other fields"
    );

    Ok(())
}

fn main() {
    let args = Args::parse();

    if args.generate_config {
        if let Err(e) = generate_config() {
            eprintln!("{e:#}");
            std::process::exit(1);
        }
        std::process::exit(0);
    }

    if let Err(e) = Cli::new(args).and_then(|mut cli| cli.run()) {
        let mut stdout = termcolor::StandardStream::stderr(termcolor::ColorChoice::Never);
        writeln!(stdout, "{e:#}").unwrap();
        std::process::exit(1);
    }
}