1use super::{DataSlice, Instruction, IrBlock, Literal, RedirectMode};
2use crate::{DeclId, VarId, ast::Pattern, engine::EngineState};
3use std::fmt::{self};
4
5pub struct FmtIrBlock<'a> {
6 pub(super) engine_state: &'a EngineState,
7 pub(super) ir_block: &'a IrBlock,
8}
9
10impl fmt::Display for FmtIrBlock<'_> {
11 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12 let plural = |count| if count == 1 { "" } else { "s" };
13 writeln!(
14 f,
15 "# {} register{}, {} instruction{}, {} byte{} of data",
16 self.ir_block.register_count,
17 plural(self.ir_block.register_count as usize),
18 self.ir_block.instructions.len(),
19 plural(self.ir_block.instructions.len()),
20 self.ir_block.data.len(),
21 plural(self.ir_block.data.len()),
22 )?;
23 if self.ir_block.file_count > 0 {
24 writeln!(
25 f,
26 "# {} file{} used for redirection",
27 self.ir_block.file_count,
28 plural(self.ir_block.file_count as usize)
29 )?;
30 }
31 for (index, instruction) in self.ir_block.instructions.iter().enumerate() {
32 let formatted = format!(
33 "{:-4}: {}",
34 index,
35 FmtInstruction {
36 engine_state: self.engine_state,
37 instruction,
38 data: &self.ir_block.data,
39 }
40 );
41 let comment = &self.ir_block.comments[index];
42 if comment.is_empty() {
43 writeln!(f, "{formatted}")?;
44 } else {
45 writeln!(f, "{formatted:40} # {comment}")?;
46 }
47 }
48 Ok(())
49 }
50}
51
52pub struct FmtInstruction<'a> {
53 pub(super) engine_state: &'a EngineState,
54 pub(super) instruction: &'a Instruction,
55 pub(super) data: &'a [u8],
56}
57
58impl fmt::Display for FmtInstruction<'_> {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 const WIDTH: usize = 22;
61
62 match self.instruction {
63 Instruction::Unreachable => {
64 write!(f, "{:WIDTH$}", "unreachable")
65 }
66 Instruction::LoadLiteral { dst, lit } => {
67 let lit = FmtLiteral {
68 literal: lit,
69 data: self.data,
70 };
71 write!(f, "{:WIDTH$} {dst}, {lit}", "load-literal")
72 }
73 Instruction::LoadValue { dst, val } => {
74 let val = val.to_debug_string();
75 write!(f, "{:WIDTH$} {dst}, {val}", "load-value")
76 }
77 Instruction::Move { dst, src } => {
78 write!(f, "{:WIDTH$} {dst}, {src}", "move")
79 }
80 Instruction::Clone { dst, src } => {
81 write!(f, "{:WIDTH$} {dst}, {src}", "clone")
82 }
83 Instruction::Collect { src_dst } => {
84 write!(f, "{:WIDTH$} {src_dst}", "collect")
85 }
86 Instruction::TryCollect { src_dst } => {
87 write!(f, "{:WIDTH$} {src_dst}", "try-collect")
88 }
89 Instruction::Span { src_dst } => {
90 write!(f, "{:WIDTH$} {src_dst}", "span")
91 }
92 Instruction::Drop { src } => {
93 write!(f, "{:WIDTH$} {src}", "drop")
94 }
95 Instruction::Drain { src } => {
96 write!(f, "{:WIDTH$} {src}", "drain")
97 }
98 Instruction::DrainIfEnd { src } => {
99 write!(f, "{:WIDTH$} {src}", "drain-if-end")
100 }
101 Instruction::LoadVariable { dst, var_id } => {
102 let var = FmtVar::new(self.engine_state, *var_id);
103 write!(f, "{:WIDTH$} {dst}, {var}", "load-variable")
104 }
105 Instruction::StoreVariable { var_id, src } => {
106 let var = FmtVar::new(self.engine_state, *var_id);
107 write!(f, "{:WIDTH$} {var}, {src}", "store-variable")
108 }
109 Instruction::DropVariable { var_id } => {
110 let var = FmtVar::new(self.engine_state, *var_id);
111 write!(f, "{:WIDTH$} {var}", "drop-variable")
112 }
113 Instruction::LoadEnv { dst, key } => {
114 let key = FmtData(self.data, *key);
115 write!(f, "{:WIDTH$} {dst}, {key}", "load-env")
116 }
117 Instruction::LoadEnvOpt { dst, key } => {
118 let key = FmtData(self.data, *key);
119 write!(f, "{:WIDTH$} {dst}, {key}", "load-env-opt")
120 }
121 Instruction::StoreEnv { key, src } => {
122 let key = FmtData(self.data, *key);
123 write!(f, "{:WIDTH$} {key}, {src}", "store-env")
124 }
125 Instruction::PushPositional { src } => {
126 write!(f, "{:WIDTH$} {src}", "push-positional")
127 }
128 Instruction::AppendRest { src } => {
129 write!(f, "{:WIDTH$} {src}", "append-rest")
130 }
131 Instruction::PushFlag { name } => {
132 let name = FmtData(self.data, *name);
133 write!(f, "{:WIDTH$} {name}", "push-flag")
134 }
135 Instruction::PushShortFlag { short } => {
136 let short = FmtData(self.data, *short);
137 write!(f, "{:WIDTH$} {short}", "push-short-flag")
138 }
139 Instruction::PushNamed { name, src } => {
140 let name = FmtData(self.data, *name);
141 write!(f, "{:WIDTH$} {name}, {src}", "push-named")
142 }
143 Instruction::PushShortNamed { short, src } => {
144 let short = FmtData(self.data, *short);
145 write!(f, "{:WIDTH$} {short}, {src}", "push-short-named")
146 }
147 Instruction::PushParserInfo { name, info } => {
148 let name = FmtData(self.data, *name);
149 write!(f, "{:WIDTH$} {name}, {info:?}", "push-parser-info")
150 }
151 Instruction::RedirectOut { mode } => {
152 write!(f, "{:WIDTH$} {mode}", "redirect-out")
153 }
154 Instruction::RedirectErr { mode } => {
155 write!(f, "{:WIDTH$} {mode}", "redirect-err")
156 }
157 Instruction::CheckErrRedirected { src } => {
158 write!(f, "{:WIDTH$} {src}", "check-err-redirected")
159 }
160 Instruction::OpenFile {
161 file_num,
162 path,
163 append,
164 } => {
165 write!(
166 f,
167 "{:WIDTH$} file({file_num}), {path}, append = {append:?}",
168 "open-file"
169 )
170 }
171 Instruction::WriteFile { file_num, src } => {
172 write!(f, "{:WIDTH$} file({file_num}), {src}", "write-file")
173 }
174 Instruction::CloseFile { file_num } => {
175 write!(f, "{:WIDTH$} file({file_num})", "close-file")
176 }
177 Instruction::Call { decl_id, src_dst } => {
178 let decl = FmtDecl::new(self.engine_state, *decl_id);
179 write!(f, "{:WIDTH$} {decl}, {src_dst}", "call")
180 }
181 Instruction::StringAppend { src_dst, val } => {
182 write!(f, "{:WIDTH$} {src_dst}, {val}", "string-append")
183 }
184 Instruction::GlobFrom { src_dst, no_expand } => {
185 let no_expand = if *no_expand { "no-expand" } else { "expand" };
186 write!(f, "{:WIDTH$} {src_dst}, {no_expand}", "glob-from",)
187 }
188 Instruction::ListPush { src_dst, item } => {
189 write!(f, "{:WIDTH$} {src_dst}, {item}", "list-push")
190 }
191 Instruction::ListSpread { src_dst, items } => {
192 write!(f, "{:WIDTH$} {src_dst}, {items}", "list-spread")
193 }
194 Instruction::RecordInsert { src_dst, key, val } => {
195 write!(f, "{:WIDTH$} {src_dst}, {key}, {val}", "record-insert")
196 }
197 Instruction::RecordSpread { src_dst, items } => {
198 write!(f, "{:WIDTH$} {src_dst}, {items}", "record-spread")
199 }
200 Instruction::Not { src_dst } => {
201 write!(f, "{:WIDTH$} {src_dst}", "not")
202 }
203 Instruction::BinaryOp { lhs_dst, op, rhs } => {
204 write!(f, "{:WIDTH$} {lhs_dst}, {op:?}, {rhs}", "binary-op")
205 }
206 Instruction::FollowCellPath { src_dst, path } => {
207 write!(f, "{:WIDTH$} {src_dst}, {path}", "follow-cell-path")
208 }
209 Instruction::CloneCellPath { dst, src, path } => {
210 write!(f, "{:WIDTH$} {dst}, {src}, {path}", "clone-cell-path")
211 }
212 Instruction::UpsertCellPath {
213 src_dst,
214 path,
215 new_value,
216 } => {
217 write!(
218 f,
219 "{:WIDTH$} {src_dst}, {path}, {new_value}",
220 "upsert-cell-path"
221 )
222 }
223 Instruction::UpdateVarCellPath {
224 var_id,
225 cell_path,
226 new_value,
227 } => {
228 let var = FmtVar::new(self.engine_state, *var_id);
229 write!(
230 f,
231 "{:WIDTH$} {var}, {cell_path}, {new_value}",
232 "update-var-cell-path"
233 )
234 }
235 Instruction::Jump { index } => {
236 write!(f, "{:WIDTH$} {index}", "jump")
237 }
238 Instruction::BranchIf { cond, index } => {
239 write!(f, "{:WIDTH$} {cond}, {index}", "branch-if")
240 }
241 Instruction::BranchIfEmpty { src, index } => {
242 write!(f, "{:WIDTH$} {src}, {index}", "branch-if-empty")
243 }
244 Instruction::Match {
245 pattern,
246 src,
247 index,
248 } => {
249 let pattern = FmtPattern {
250 engine_state: self.engine_state,
251 pattern,
252 };
253 write!(f, "{:WIDTH$} ({pattern}), {src}, {index}", "match")
254 }
255 Instruction::CheckMatchGuard { src } => {
256 write!(f, "{:WIDTH$} {src}", "check-match-guard")
257 }
258 Instruction::Iterate {
259 dst,
260 stream,
261 end_index,
262 } => {
263 write!(f, "{:WIDTH$} {dst}, {stream}, end {end_index}", "iterate")
264 }
265 Instruction::OnError { index } => {
266 write!(f, "{:WIDTH$} {index}", "on-error")
267 }
268 Instruction::Finally { index } => {
269 write!(f, "{:WIDTH$} {index}", "finally")
270 }
271 Instruction::FinallyInto { index, dst } => {
272 write!(f, "{:WIDTH$} {index}, {dst}", "finally-into")
273 }
274 Instruction::OnErrorInto { index, dst } => {
275 write!(f, "{:WIDTH$} {index}, {dst}", "on-error-into")
276 }
277 Instruction::PopErrorHandler => {
278 write!(f, "{:WIDTH$}", "pop-error-handler")
279 }
280 Instruction::PopFinallyRun => {
281 write!(f, "{:WIDTH$}", "pop-finally")
282 }
283 Instruction::ReturnEarly { src } => {
284 write!(f, "{:WIDTH$} {src}", "return-early")
285 }
286 Instruction::Return { src } => {
287 write!(f, "{:WIDTH$} {src}", "return")
288 }
289 }
290 }
291}
292
293struct FmtDecl<'a>(DeclId, &'a str);
294
295impl<'a> FmtDecl<'a> {
296 fn new(engine_state: &'a EngineState, decl_id: DeclId) -> Self {
297 FmtDecl(decl_id, engine_state.get_decl(decl_id).name())
298 }
299}
300
301impl fmt::Display for FmtDecl<'_> {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 write!(f, "decl {} {:?}", self.0.get(), self.1)
304 }
305}
306
307struct FmtVar<'a>(VarId, Option<&'a str>);
308
309impl<'a> FmtVar<'a> {
310 fn new(engine_state: &'a EngineState, var_id: VarId) -> Self {
311 let name: Option<&str> = engine_state
313 .active_overlays(&[])
314 .flat_map(|overlay| overlay.vars.iter())
315 .find(|(_, v)| **v == var_id)
316 .map(|(k, _)| std::str::from_utf8(k).unwrap_or("<utf-8 error>"));
317 FmtVar(var_id, name)
318 }
319}
320
321impl fmt::Display for FmtVar<'_> {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 if let Some(name) = self.1 {
324 write!(f, "var {} {:?}", self.0.get(), name)
325 } else {
326 write!(f, "var {}", self.0.get())
327 }
328 }
329}
330
331impl fmt::Display for RedirectMode {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 match self {
334 RedirectMode::Pipe => write!(f, "pipe"),
335 RedirectMode::PipeSeparate => write!(f, "pipe separate"),
336 RedirectMode::Value => write!(f, "value"),
337 RedirectMode::Null => write!(f, "null"),
338 RedirectMode::Inherit => write!(f, "inherit"),
339 RedirectMode::Print => write!(f, "print"),
340 RedirectMode::File { file_num } => write!(f, "file({file_num})"),
341 RedirectMode::Caller => write!(f, "caller"),
342 }
343 }
344}
345
346struct FmtData<'a>(&'a [u8], DataSlice);
347
348impl fmt::Display for FmtData<'_> {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 if let Ok(s) = std::str::from_utf8(&self.0[self.1]) {
351 write!(f, "{s:?}")
353 } else {
354 write!(f, "0x{:x?}", self.0)
356 }
357 }
358}
359
360struct FmtLiteral<'a> {
361 literal: &'a Literal,
362 data: &'a [u8],
363}
364
365impl fmt::Display for FmtLiteral<'_> {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 match self.literal {
368 Literal::Bool(b) => write!(f, "bool({b:?})"),
369 Literal::Int(i) => write!(f, "int({i:?})"),
370 Literal::Float(fl) => write!(f, "float({fl:?})"),
371 Literal::Filesize(q) => write!(f, "filesize({q}b)"),
372 Literal::Duration(q) => write!(f, "duration({q}ns)"),
373 Literal::Binary(b) => write!(f, "binary({})", FmtData(self.data, *b)),
374 Literal::Block(id) => write!(f, "block({})", id.get()),
375 Literal::Closure(id) => write!(f, "closure({})", id.get()),
376 Literal::RowCondition(id) => write!(f, "row_condition({})", id.get()),
377 Literal::Range {
378 start,
379 step,
380 end,
381 inclusion,
382 } => write!(f, "range({start}, {step}, {end}, {inclusion:?})"),
383 Literal::List { capacity } => write!(f, "list(capacity = {capacity})"),
384 Literal::Record { capacity } => write!(f, "record(capacity = {capacity})"),
385 Literal::Filepath { val, no_expand } => write!(
386 f,
387 "filepath({}, no_expand = {no_expand:?})",
388 FmtData(self.data, *val)
389 ),
390 Literal::Directory { val, no_expand } => write!(
391 f,
392 "directory({}, no_expand = {no_expand:?})",
393 FmtData(self.data, *val)
394 ),
395 Literal::GlobPattern { val, no_expand } => write!(
396 f,
397 "glob-pattern({}, no_expand = {no_expand:?})",
398 FmtData(self.data, *val)
399 ),
400 Literal::String(s) => write!(f, "string({})", FmtData(self.data, *s)),
401 Literal::RawString(rs) => write!(f, "raw-string({})", FmtData(self.data, *rs)),
402 Literal::CellPath(p) => write!(f, "cell-path({p})"),
403 Literal::Date(dt) => write!(f, "date({dt})"),
404 Literal::Nothing => write!(f, "nothing"),
405 Literal::Empty => write!(f, "empty"),
406 }
407 }
408}
409
410struct FmtPattern<'a> {
411 engine_state: &'a EngineState,
412 pattern: &'a Pattern,
413}
414
415impl fmt::Display for FmtPattern<'_> {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 match self.pattern {
418 Pattern::Record(bindings) => {
419 f.write_str("{")?;
420 for (name, pattern) in bindings {
421 write!(
422 f,
423 "{}: {}",
424 name,
425 FmtPattern {
426 engine_state: self.engine_state,
427 pattern: &pattern.pattern,
428 }
429 )?;
430 }
431 f.write_str("}")
432 }
433 Pattern::List(bindings) => {
434 f.write_str("[")?;
435 for pattern in bindings {
436 write!(
437 f,
438 "{}",
439 FmtPattern {
440 engine_state: self.engine_state,
441 pattern: &pattern.pattern
442 }
443 )?;
444 }
445 f.write_str("]")
446 }
447 Pattern::Expression(expr) => {
448 let string =
449 String::from_utf8_lossy(self.engine_state.get_span_contents(expr.span));
450 f.write_str(&string)
451 }
452 Pattern::Value(value) => {
453 f.write_str(&value.to_parsable_string(", ", &self.engine_state.config))
454 }
455 Pattern::Variable(var_id) => {
456 let variable = FmtVar::new(self.engine_state, *var_id);
457 write!(f, "{variable}")
458 }
459 Pattern::Or(patterns) => {
460 for (index, pattern) in patterns.iter().enumerate() {
461 if index > 0 {
462 f.write_str(" | ")?;
463 }
464 write!(
465 f,
466 "{}",
467 FmtPattern {
468 engine_state: self.engine_state,
469 pattern: &pattern.pattern
470 }
471 )?;
472 }
473 Ok(())
474 }
475 Pattern::Rest(var_id) => {
476 let variable = FmtVar::new(self.engine_state, *var_id);
477 write!(f, "..{variable}")
478 }
479 Pattern::IgnoreRest => f.write_str(".."),
480 Pattern::IgnoreValue => f.write_str("_"),
481 Pattern::Garbage => f.write_str("<garbage>"),
482 }
483 }
484}