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
|
mod nix_compat;
use std::{fs, path::PathBuf};
use clap::Parser;
use rustyline::{error::ReadlineError, Editor};
use tvix_eval::observer::{DisassemblingObserver, TracingObserver};
use tvix_eval::Value;
#[derive(Parser)]
struct Args {
/// Path to a script to evaluate
script: Option<PathBuf>,
#[clap(long, short = 'E')]
expr: Option<String>,
/// Dump the raw AST to stdout before interpreting
#[clap(long, env = "TVIX_DISPLAY_AST")]
display_ast: bool,
/// Dump the bytecode to stdout before evaluating
#[clap(long, env = "TVIX_DUMP_BYTECODE")]
dump_bytecode: bool,
/// Trace the runtime of the VM
#[clap(long, env = "TVIX_TRACE_RUNTIME")]
trace_runtime: bool,
/// Only compile, but do not execute code. This will make Tvix act
/// sort of like a linter.
#[clap(long)]
compile_only: bool,
/// A colon-separated list of directories to use to resolve `<...>`-style paths
#[clap(long, short = 'I', env = "NIX_PATH")]
nix_search_path: Option<String>,
/// Print "raw" (unquoted) output.
#[clap(long)]
raw: bool,
}
/// Interprets the given code snippet, printing out warnings, errors
/// and the result itself. The return value indicates whether
/// evaluation succeeded.
fn interpret(code: &str, path: Option<PathBuf>, args: &Args, explain: bool) -> bool {
let mut eval = tvix_eval::Evaluation::new_impure(code, path);
eval.io_handle = Box::new(nix_compat::NixCompatIO::new());
eval.nix_path = args.nix_search_path.clone();
let source_map = eval.source_map();
let result = {
let mut compiler_observer =
DisassemblingObserver::new(source_map.clone(), std::io::stderr());
if args.dump_bytecode {
eval.compiler_observer = Some(&mut compiler_observer);
}
let mut runtime_observer = TracingObserver::new(std::io::stderr());
if args.trace_runtime {
eval.runtime_observer = Some(&mut runtime_observer);
}
eval.evaluate()
};
if args.display_ast {
if let Some(ref expr) = result.expr {
eprintln!("AST: {}", tvix_eval::pretty_print_expr(expr));
}
}
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() {
if explain {
println!("=> {}", value.explain());
} else {
println_result(value, args.raw);
}
}
// inform the caller about any errors
result.errors.is_empty()
}
/// Interpret the given code snippet, but only run the Tvix compiler
/// on it and return errors and warnings.
fn lint(code: &str, path: Option<PathBuf>, args: &Args) -> bool {
let mut eval = tvix_eval::Evaluation::new_impure(code, path);
let source_map = eval.source_map();
let mut compiler_observer = DisassemblingObserver::new(source_map.clone(), std::io::stderr());
if args.dump_bytecode {
eval.compiler_observer = Some(&mut compiler_observer);
}
if args.trace_runtime {
eprintln!("warning: --trace-runtime has no effect with --compile-only!");
}
let result = eval.compile_only();
if args.display_ast {
if let Some(ref expr) = result.expr {
eprintln!("AST: {}", tvix_eval::pretty_print_expr(expr));
}
}
for error in &result.errors {
error.fancy_format_stderr(&source_map);
}
for warning in &result.warnings {
warning.fancy_format_stderr(&source_map);
}
// inform the caller about any errors
result.errors.is_empty()
}
fn main() {
let args = Args::parse();
if let Some(file) = &args.script {
run_file(file.clone(), &args)
} else if let Some(expr) = &args.expr {
if !interpret(expr, None, &args, false) {
std::process::exit(1);
}
} else {
run_prompt(&args)
}
}
fn run_file(mut path: PathBuf, args: &Args) {
if path.is_dir() {
path.push("default.nix");
}
let contents = fs::read_to_string(&path).expect("failed to read the input file");
let success = if args.compile_only {
lint(&contents, Some(path), args)
} else {
interpret(&contents, Some(path), args, false)
};
if !success {
std::process::exit(1);
}
}
fn println_result(result: &Value, raw: bool) {
if raw {
println!("{}", result.to_str().unwrap().as_str())
} else {
println!("=> {} :: {}", result, result.type_of())
}
}
fn state_dir() -> Option<PathBuf> {
let mut path = dirs::data_dir();
if let Some(p) = path.as_mut() {
p.push("tvix")
}
path
}
fn run_prompt(args: &Args) {
let mut rl = Editor::<()>::new().expect("should be able to launch rustyline");
if args.compile_only {
eprintln!("warning: `--compile-only` has no effect on REPL usage!");
}
let history_path = match state_dir() {
// Attempt to set up these paths, but do not hard fail if it
// doesn't work.
Some(mut path) => {
let _ = std::fs::create_dir_all(&path);
path.push("history.txt");
let _ = rl.load_history(&path);
Some(path)
}
None => None,
};
loop {
let readline = rl.readline("tvix-repl> ");
match readline {
Ok(line) => {
if line.is_empty() {
continue;
}
rl.add_history_entry(&line);
if let Some(without_prefix) = line.strip_prefix(":d ") {
interpret(without_prefix, None, args, true);
} else {
interpret(&line, None, args, false);
}
}
Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break,
Err(err) => {
eprintln!("error: {}", err);
break;
}
}
}
if let Some(path) = history_path {
rl.save_history(&path).unwrap();
}
}
|