refactor(tvix): split binary (REPL etc.) out from evaluator library

The tvix-eval project is independent from any *uses* of the evaluator,
such as the tvix-repl.

This functionality has been split out into a separate "tvix-cli"
crate. Note that this doesn't have to mean that this CLI crate is the
"final" CLI crate for tvix, the point of this is not "getting the CLI
structure right" but rather "getting the evaluator structure right".

This reshuffling is part of restructuring the way that functionality
like store communication is injected into language evaluation.

Note that at this commit the new CLI crate is not at feature-parity.

Change-Id: Id0af03dc8e07ef09a9f882a89612ad555eca8f93
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7541
Autosubmit: tazjin <tazjin@tvl.su>
Reviewed-by: grfn <grfn@gws.fyi>
Tested-by: BuildkiteCI
This commit is contained in:
Vincent Ambo 2022-12-09 00:19:22 +03:00 committed by clbot
parent 1138fbcaad
commit d9e2bec953
9 changed files with 105 additions and 198 deletions

12
tvix/Cargo.lock generated
View file

@ -1487,12 +1487,21 @@ dependencies = [
"serde_json", "serde_json",
] ]
[[package]]
name = "tvix-cli"
version = "0.1.0"
dependencies = [
"clap 3.2.23",
"dirs",
"rustyline",
"tvix-eval",
]
[[package]] [[package]]
name = "tvix-eval" name = "tvix-eval"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"backtrace-on-stack-overflow", "backtrace-on-stack-overflow",
"clap 3.2.23",
"codemap", "codemap",
"codemap-diagnostic", "codemap-diagnostic",
"criterion", "criterion",
@ -1504,7 +1513,6 @@ dependencies = [
"regex", "regex",
"rnix", "rnix",
"rowan", "rowan",
"rustyline",
"serde", "serde",
"serde_json", "serde_json",
"smol_str", "smol_str",

View file

@ -47,6 +47,16 @@ rec {
# File a bug if you depend on any for non-debug work! # File a bug if you depend on any for non-debug work!
debug = internal.debugCrate { inherit packageId; }; debug = internal.debugCrate { inherit packageId; };
}; };
"tvix-cli" = rec {
packageId = "tvix-cli";
build = internal.buildRustCrateWithFeatures {
packageId = "tvix-cli";
};
# Debug support which might change between releases.
# File a bug if you depend on any for non-debug work!
debug = internal.debugCrate { inherit packageId; };
};
"tvix-eval" = rec { "tvix-eval" = rec {
packageId = "tvix-eval"; packageId = "tvix-eval";
build = internal.buildRustCrateWithFeatures { build = internal.buildRustCrateWithFeatures {
@ -4175,14 +4185,40 @@ rec {
} }
]; ];
};
"tvix-cli" = rec {
crateName = "tvix-cli";
version = "0.1.0";
edition = "2021";
crateBin = [
{ name = "tvix-cli"; path = "src/main.rs"; }
];
src = lib.cleanSourceWith { filter = sourceFilter; src = ./cli; };
dependencies = [
{
name = "clap";
packageId = "clap 3.2.23";
features = [ "derive" "env" ];
}
{
name = "dirs";
packageId = "dirs";
}
{
name = "rustyline";
packageId = "rustyline";
}
{
name = "tvix-eval";
packageId = "tvix-eval";
}
];
}; };
"tvix-eval" = rec { "tvix-eval" = rec {
crateName = "tvix-eval"; crateName = "tvix-eval";
version = "0.1.0"; version = "0.1.0";
edition = "2021"; edition = "2021";
crateBin = [
{ name = "tvix-eval"; path = "src/main.rs"; }
];
src = lib.cleanSourceWith { filter = sourceFilter; src = ./eval; }; src = lib.cleanSourceWith { filter = sourceFilter; src = ./eval; };
libName = "tvix_eval"; libName = "tvix_eval";
dependencies = [ dependencies = [
@ -4191,12 +4227,6 @@ rec {
packageId = "backtrace-on-stack-overflow"; packageId = "backtrace-on-stack-overflow";
optional = true; optional = true;
} }
{
name = "clap";
packageId = "clap 3.2.23";
optional = true;
features = [ "derive" "env" ];
}
{ {
name = "codemap"; name = "codemap";
packageId = "codemap"; packageId = "codemap";
@ -4232,11 +4262,6 @@ rec {
name = "rowan"; name = "rowan";
packageId = "rowan"; packageId = "rowan";
} }
{
name = "rustyline";
packageId = "rustyline";
optional = true;
}
{ {
name = "serde"; name = "serde";
packageId = "serde"; packageId = "serde";
@ -4290,14 +4315,11 @@ rec {
"arbitrary" = [ "proptest" "test-strategy" ]; "arbitrary" = [ "proptest" "test-strategy" ];
"backtrace-on-stack-overflow" = [ "dep:backtrace-on-stack-overflow" ]; "backtrace-on-stack-overflow" = [ "dep:backtrace-on-stack-overflow" ];
"backtrace_overflow" = [ "backtrace-on-stack-overflow" ]; "backtrace_overflow" = [ "backtrace-on-stack-overflow" ];
"clap" = [ "dep:clap" ]; "default" = [ "impure" "arbitrary" "nix_tests" "backtrace_overflow" ];
"default" = [ "repl" "impure" "arbitrary" "nix_tests" "backtrace_overflow" ];
"proptest" = [ "dep:proptest" ]; "proptest" = [ "dep:proptest" ];
"repl" = [ "rustyline" "clap" ];
"rustyline" = [ "dep:rustyline" ];
"test-strategy" = [ "dep:test-strategy" ]; "test-strategy" = [ "dep:test-strategy" ];
}; };
resolvedDefaultFeatures = [ "arbitrary" "backtrace-on-stack-overflow" "backtrace_overflow" "clap" "default" "impure" "nix_tests" "proptest" "repl" "rustyline" "test-strategy" ]; resolvedDefaultFeatures = [ "arbitrary" "backtrace-on-stack-overflow" "backtrace_overflow" "default" "impure" "nix_tests" "proptest" "test-strategy" ];
}; };
"tvix-eval-builtin-macros" = rec { "tvix-eval-builtin-macros" = rec {
crateName = "tvix-eval-builtin-macros"; crateName = "tvix-eval-builtin-macros";

View file

@ -18,6 +18,7 @@
[workspace] [workspace]
members = [ members = [
"cli",
"eval", "eval",
"eval/builtin-macros", "eval/builtin-macros",
"nix_cli", "nix_cli",

10
tvix/cli/Cargo.toml Normal file
View file

@ -0,0 +1,10 @@
[package]
name = "tvix-cli"
version = "0.1.0"
edition = "2021"
[dependencies]
tvix-eval = { path = "../eval" }
rustyline = "10.0.0"
clap = { version = "3.2.22", features = ["derive", "env"] }
dirs = "4.0.0"

5
tvix/cli/default.nix Normal file
View file

@ -0,0 +1,5 @@
{ depot, pkgs, lib, ... }:
depot.tvix.crates.workspaceMembers.tvix-cli.build.override {
runTests = true;
}

View file

@ -2,7 +2,7 @@ use std::{fs, path::PathBuf};
use clap::Parser; use clap::Parser;
use rustyline::{error::ReadlineError, Editor}; use rustyline::{error::ReadlineError, Editor};
use tvix_eval::Value; use tvix_eval::Value; //{Error, EvalWarning, Evaluation, Value};
#[derive(Parser)] #[derive(Parser)]
struct Args { struct Args {
@ -11,35 +11,57 @@ struct Args {
#[clap(long, short = 'E')] #[clap(long, short = 'E')]
expr: Option<String>, expr: Option<String>,
// TODO: port these options here directly
// #[clap(flatten)]
// eval_options: tvix_eval::Options,
}
#[clap(flatten)] /// Interprets the given code snippet, printing out warnings, errors
eval_options: tvix_eval::Options, /// and the result itself. The return value indicates whether
/// evaluation succeeded.
fn interpret(code: &str, path: Option<PathBuf>) -> bool {
let mut eval = tvix_eval::Evaluation::new(code, path);
let result = eval.evaluate();
let source_map = eval.source_map();
for error in &result.errors {
error.fancy_format_stderr(&source_map);
}
for warning in &result.warnings {
warning.fancy_format_stderr(&source_map);
}
if let Some(value) = result.value.as_ref() {
println_result(value, /* TODO raw = */ false);
}
// inform the caller about any errors
result.errors.is_empty()
} }
fn main() { fn main() {
let args = Args::parse(); let args = Args::parse();
if let Some(file) = args.script { if let Some(file) = args.script {
run_file(file, args.eval_options) run_file(file /* TODO, args.eval_options*/)
} else if let Some(expr) = args.expr { } else if let Some(expr) = args.expr {
let raw = args.eval_options.raw; if !interpret(&expr, None) {
if let Ok(result) = tvix_eval::interpret(&expr, None, args.eval_options) { std::process::exit(1);
println_result(&result, raw);
} }
} else { } else {
run_prompt(args.eval_options) run_prompt(/* TODO args.eval_options */)
} }
} }
fn run_file(mut path: PathBuf, eval_options: tvix_eval::Options) { fn run_file(mut path: PathBuf /* TODO: , eval_options: tvix_eval::Options */) {
if path.is_dir() { if path.is_dir() {
path.push("default.nix"); path.push("default.nix");
} }
let contents = fs::read_to_string(&path).expect("failed to read the input file"); let contents = fs::read_to_string(&path).expect("failed to read the input file");
let raw = eval_options.raw;
match tvix_eval::interpret(&contents, Some(path), eval_options) { if !interpret(&contents, Some(path)) {
Ok(result) => println_result(&result, raw), std::process::exit(1);
Err(err) => eprintln!("{}", err),
} }
} }
@ -59,7 +81,7 @@ fn state_dir() -> Option<PathBuf> {
path path
} }
fn run_prompt(eval_options: tvix_eval::Options) { fn run_prompt(/* TODO eval_options: tvix_eval::Options */) {
let mut rl = Editor::<()>::new().expect("should be able to launch rustyline"); let mut rl = Editor::<()>::new().expect("should be able to launch rustyline");
let history_path = match state_dir() { let history_path = match state_dir() {
@ -84,12 +106,7 @@ fn run_prompt(eval_options: tvix_eval::Options) {
} }
rl.add_history_entry(&line); rl.add_history_entry(&line);
match tvix_eval::interpret(&line, None, eval_options.clone()) { interpret(&line, None);
Ok(result) => {
println!("=> {} :: {}", result, result.type_of());
}
Err(_) => { /* interpret takes care of error formatting */ }
}
} }
Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break, Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break,

View file

@ -8,13 +8,8 @@ edition = "2021"
[lib] [lib]
name = "tvix_eval" name = "tvix_eval"
[[bin]]
name = "tvix-eval"
required-features = [ "repl" ]
[dependencies] [dependencies]
smol_str = "0.1" smol_str = "0.1"
rustyline = { version = "10.0.0", optional = true }
dirs = "4.0.0" dirs = "4.0.0"
path-clean = "0.1" path-clean = "0.1"
tabwriter = "1.2" tabwriter = "1.2"
@ -23,7 +18,6 @@ codemap = "0.1.3"
codemap-diagnostic = "0.1.1" codemap-diagnostic = "0.1.1"
proptest = { version = "1.0.0", default_features = false, features = ["std", "alloc", "break-dead-code", "tempfile"], optional = true } proptest = { version = "1.0.0", default_features = false, features = ["std", "alloc", "break-dead-code", "tempfile"], optional = true }
test-strategy = { version = "0.2.1", optional = true } test-strategy = { version = "0.2.1", optional = true }
clap = { version = "3.2.22", optional = true, features = ["derive", "env"] }
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
regex = "1.6.0" regex = "1.6.0"
@ -39,15 +33,12 @@ itertools = "0.10.3"
tempdir = "0.3.7" tempdir = "0.3.7"
[features] [features]
default = [ "repl", "impure", "arbitrary", "nix_tests", "backtrace_overflow" ] default = [ "impure", "arbitrary", "nix_tests", "backtrace_overflow" ]
# Enables running the Nix language test suite from the original C++ # Enables running the Nix language test suite from the original C++
# Nix implementation (at version 2.3) against Tvix. # Nix implementation (at version 2.3) against Tvix.
nix_tests = [] nix_tests = []
# Enables building the binary (tvix-eval REPL)
repl = [ "rustyline", "clap" ]
# Enables operations in the VM which depend on the ability to perform I/O # Enables operations in the VM which depend on the ability to perform I/O
impure = [] impure = []

View file

@ -1,145 +0,0 @@
use std::path::PathBuf;
use crate::{
builtins::global_builtins,
errors::{Error, ErrorKind, EvalResult},
nix_search_path::NixSearchPath,
observer::{DisassemblingObserver, NoOpObserver, TracingObserver},
pretty_ast::pretty_print_expr,
value::Value,
SourceCode,
};
/// Runtime options for the Tvix interpreter
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "repl", derive(clap::Parser))]
pub struct Options {
/// Dump the raw AST to stdout before interpreting
#[cfg_attr(feature = "repl", clap(long, env = "TVIX_DISPLAY_AST"))]
display_ast: bool,
/// Dump the bytecode to stdout before evaluating
#[cfg_attr(feature = "repl", clap(long, env = "TVIX_DUMP_BYTECODE"))]
dump_bytecode: bool,
/// Trace the runtime of the VM
#[cfg_attr(feature = "repl", clap(long, env = "TVIX_TRACE_RUNTIME"))]
trace_runtime: bool,
/// Print warnings
#[cfg_attr(
feature = "repl",
clap(long, env = "TVIX_WARNINGS", default_value = "true")
)]
warnings: bool,
/// A colon-separated list of directories to use to resolve `<...>`-style paths
#[cfg_attr(feature = "repl", clap(long, short = 'I', env = "NIX_PATH"))]
nix_search_path: Option<NixSearchPath>,
#[cfg_attr(feature = "repl", clap(long))]
pub raw: bool,
}
impl Options {
#[cfg(test)]
pub(crate) fn test_options() -> Options {
Options {
warnings: false,
..Options::default()
}
}
}
pub fn interpret(code: &str, location: Option<PathBuf>, options: Options) -> EvalResult<Value> {
let source = SourceCode::new();
let file = source.add_file(
location
.as_ref()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "[tvix-repl]".into()),
code.into(),
);
let parsed = rnix::ast::Root::parse(code);
let errors = parsed.errors();
if !errors.is_empty() {
let err = Error {
kind: ErrorKind::ParseErrors(errors.to_vec()),
span: file.span,
};
err.fancy_format_stderr(&source);
return Err(err);
}
// If we've reached this point, there are no errors.
let root_expr = parsed
.tree()
.expr()
.expect("expression should exist if no errors occured");
if options.display_ast {
println!("{}", pretty_print_expr(&root_expr));
}
let builtins = crate::compiler::prepare_globals(Box::new(global_builtins(source.clone())));
let result = if options.dump_bytecode {
crate::compiler::compile(
&root_expr,
location,
file.clone(),
builtins,
&mut DisassemblingObserver::new(source.clone(), std::io::stderr()),
)
} else {
crate::compiler::compile(
&root_expr,
location,
file.clone(),
builtins,
&mut NoOpObserver::default(),
)
}?;
if options.warnings {
for warning in result.warnings {
warning.fancy_format_stderr(&source);
}
}
for error in &result.errors {
error.fancy_format_stderr(&source);
}
if let Some(err) = result.errors.last() {
return Err(err.clone());
}
let result = if options.trace_runtime {
crate::vm::run_lambda(
options.nix_search_path.unwrap_or_default(),
&mut TracingObserver::new(std::io::stderr()),
result.lambda,
)
} else {
crate::vm::run_lambda(
options.nix_search_path.unwrap_or_default(),
&mut NoOpObserver::default(),
result.lambda,
)
};
if let Err(err) = &result {
err.fancy_format_stderr(&source);
}
result.map(|r| {
if options.warnings {
for warning in r.warnings {
warning.fancy_format_stderr(&source);
}
}
r.value
})
}

View file

@ -16,7 +16,6 @@ mod builtins;
mod chunk; mod chunk;
mod compiler; mod compiler;
mod errors; mod errors;
mod eval;
pub mod observer; pub mod observer;
mod opcode; mod opcode;
mod pretty_ast; mod pretty_ast;
@ -44,7 +43,6 @@ use std::sync::Arc;
pub use crate::builtins::global_builtins; pub use crate::builtins::global_builtins;
pub use crate::compiler::{compile, prepare_globals}; pub use crate::compiler::{compile, prepare_globals};
pub use crate::errors::{Error, ErrorKind, EvalResult}; pub use crate::errors::{Error, ErrorKind, EvalResult};
pub use crate::eval::{interpret, Options};
pub use crate::pretty_ast::pretty_print_expr; pub use crate::pretty_ast::pretty_print_expr;
pub use crate::source::SourceCode; pub use crate::source::SourceCode;
pub use crate::value::Value; pub use crate::value::Value;