forked from noir-lang/noir
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepl.rs
More file actions
568 lines (515 loc) · 19.1 KB
/
repl.rs
File metadata and controls
568 lines (515 loc) · 19.1 KB
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
use crate::context::{DebugCommandResult, DebugContext};
use acvm::acir::circuit::{Circuit, Opcode, OpcodeLocation};
use acvm::acir::native_types::{Witness, WitnessMap};
use acvm::{BlackBoxFunctionSolver, FieldElement};
use nargo::artifacts::debug::DebugArtifact;
use nargo::NargoError;
use easy_repl::{command, CommandStatus, Repl};
use std::cell::RefCell;
use codespan_reporting::files::Files;
use noirc_errors::Location;
use owo_colors::OwoColorize;
use std::ops::Range;
pub struct ReplDebugger<'a, B: BlackBoxFunctionSolver> {
context: DebugContext<'a, B>,
blackbox_solver: &'a B,
circuit: &'a Circuit,
debug_artifact: &'a DebugArtifact,
initial_witness: WitnessMap,
last_result: DebugCommandResult,
}
impl<'a, B: BlackBoxFunctionSolver> ReplDebugger<'a, B> {
pub fn new(
blackbox_solver: &'a B,
circuit: &'a Circuit,
debug_artifact: &'a DebugArtifact,
initial_witness: WitnessMap,
) -> Self {
let context =
DebugContext::new(blackbox_solver, circuit, debug_artifact, initial_witness.clone());
Self {
context,
blackbox_solver,
circuit,
debug_artifact,
initial_witness,
last_result: DebugCommandResult::Ok,
}
}
pub fn show_current_vm_status(&self) {
let location = self.context.get_current_opcode_location();
let opcodes = self.context.get_opcodes();
match location {
None => println!("Finished execution"),
Some(location) => {
match location {
OpcodeLocation::Acir(ip) => {
println!("At opcode {}: {}", ip, opcodes[ip])
}
OpcodeLocation::Brillig { acir_index, brillig_index } => {
let Opcode::Brillig(ref brillig) = opcodes[acir_index] else {
unreachable!("Brillig location does not contain a Brillig block");
};
println!(
"At opcode {}.{}: {:?}",
acir_index, brillig_index, brillig.bytecode[brillig_index]
);
}
}
self.show_source_code_location(&location);
}
}
}
fn print_location_path(&self, loc: Location) {
let line_number = self.debug_artifact.location_line_number(loc).unwrap();
let column_number = self.debug_artifact.location_column_number(loc).unwrap();
println!(
"At {}:{line_number}:{column_number}",
self.debug_artifact.name(loc.file).unwrap()
);
}
fn show_source_code_location(&self, location: &OpcodeLocation) {
let locations = self.debug_artifact.debug_symbols[0].opcode_location(location);
let Some(locations) = locations else { return };
for loc in locations {
self.print_location_path(loc);
let loc_line_index = self.debug_artifact.location_line_index(loc).unwrap();
// How many lines before or after the location's line we
// print
let context_lines = 5;
let first_line_to_print =
if loc_line_index < context_lines { 0 } else { loc_line_index - context_lines };
let last_line_index = self.debug_artifact.last_line_index(loc).unwrap();
let last_line_to_print = std::cmp::min(loc_line_index + context_lines, last_line_index);
let source = self.debug_artifact.location_source_code(loc).unwrap();
for (current_line_index, line) in source.lines().enumerate() {
let current_line_number = current_line_index + 1;
if current_line_index < first_line_to_print {
// Ignore lines before range starts
continue;
} else if current_line_index == first_line_to_print && current_line_index > 0 {
// Denote that there's more lines before but we're not showing them
print_line_of_ellipsis(current_line_index);
}
if current_line_index > last_line_to_print {
// Denote that there's more lines after but we're not showing them,
// and stop printing
print_line_of_ellipsis(current_line_number);
break;
}
if current_line_index == loc_line_index {
// Highlight current location
let Range { start: loc_start, end: loc_end } =
self.debug_artifact.location_in_line(loc).unwrap();
println!(
"{:>3} {:2} {}{}{}",
current_line_number,
"->",
&line[0..loc_start].to_string().dimmed(),
&line[loc_start..loc_end],
&line[loc_end..].to_string().dimmed()
);
} else {
print_dimmed_line(current_line_number, line);
}
}
}
}
fn display_opcodes(&self) {
let opcodes = self.context.get_opcodes();
let current_opcode_location = self.context.get_current_opcode_location();
let current_acir_index = match current_opcode_location {
Some(OpcodeLocation::Acir(ip)) => Some(ip),
Some(OpcodeLocation::Brillig { acir_index, .. }) => Some(acir_index),
None => None,
};
let current_brillig_index = match current_opcode_location {
Some(OpcodeLocation::Brillig { brillig_index, .. }) => brillig_index,
_ => 0,
};
let outer_marker = |acir_index| {
if current_acir_index == Some(acir_index) {
"->"
} else if self.context.is_breakpoint_set(&OpcodeLocation::Acir(acir_index)) {
" *"
} else {
""
}
};
let brillig_marker = |acir_index, brillig_index| {
if current_acir_index == Some(acir_index) && brillig_index == current_brillig_index {
"->"
} else if self
.context
.is_breakpoint_set(&OpcodeLocation::Brillig { acir_index, brillig_index })
{
" *"
} else {
""
}
};
for (acir_index, opcode) in opcodes.iter().enumerate() {
let marker = outer_marker(acir_index);
if let Opcode::Brillig(brillig) = opcode {
println!("{:>3} {:2} BRILLIG inputs={:?}", acir_index, marker, brillig.inputs);
println!(" | outputs={:?}", brillig.outputs);
for (brillig_index, brillig_opcode) in brillig.bytecode.iter().enumerate() {
println!(
"{:>3}.{:<2} |{:2} {:?}",
acir_index,
brillig_index,
brillig_marker(acir_index, brillig_index),
brillig_opcode
);
}
} else {
println!("{:>3} {:2} {:?}", acir_index, marker, opcode);
}
}
}
fn add_breakpoint_at(&mut self, location: OpcodeLocation) {
if !self.context.is_valid_opcode_location(&location) {
println!("Invalid opcode location {location}");
} else if self.context.add_breakpoint(location) {
println!("Added breakpoint at opcode {location}");
} else {
println!("Breakpoint at opcode {location} already set");
}
}
fn delete_breakpoint_at(&mut self, location: OpcodeLocation) {
if self.context.delete_breakpoint(&location) {
println!("Breakpoint at opcode {location} deleted");
} else {
println!("Breakpoint at opcode {location} not set");
}
}
fn validate_in_progress(&self) -> bool {
match self.last_result {
DebugCommandResult::Ok | DebugCommandResult::BreakpointReached(..) => true,
DebugCommandResult::Done => {
println!("Execution finished");
false
}
DebugCommandResult::Error(ref error) => {
println!("ERROR: {}", error);
self.show_current_vm_status();
false
}
}
}
fn handle_debug_command_result(&mut self, result: DebugCommandResult) {
match &result {
DebugCommandResult::BreakpointReached(location) => {
println!("Stopped at breakpoint in opcode {}", location);
}
DebugCommandResult::Error(error) => {
println!("ERROR: {}", error);
}
_ => (),
}
self.last_result = result;
self.show_current_vm_status();
}
fn step_acir_opcode(&mut self) {
if self.validate_in_progress() {
let result = self.context.step_acir_opcode();
self.handle_debug_command_result(result);
}
}
fn step_into_opcode(&mut self) {
if self.validate_in_progress() {
let result = self.context.step_into_opcode();
self.handle_debug_command_result(result);
}
}
fn next(&mut self) {
if self.validate_in_progress() {
let result = self.context.next();
self.handle_debug_command_result(result);
}
}
fn cont(&mut self) {
if self.validate_in_progress() {
println!("(Continuing execution...)");
let result = self.context.cont();
self.handle_debug_command_result(result);
}
}
fn restart_session(&mut self) {
let breakpoints: Vec<OpcodeLocation> =
self.context.iterate_breakpoints().copied().collect();
self.context = DebugContext::new(
self.blackbox_solver,
self.circuit,
self.debug_artifact,
self.initial_witness.clone(),
);
for opcode_location in breakpoints {
self.context.add_breakpoint(opcode_location);
}
self.last_result = DebugCommandResult::Ok;
println!("Restarted debugging session.");
self.show_current_vm_status();
}
pub fn show_witness_map(&self) {
let witness_map = self.context.get_witness_map();
// NOTE: we need to clone() here to get the iterator
for (witness, value) in witness_map.clone().into_iter() {
println!("_{} = {value}", witness.witness_index());
}
}
pub fn show_witness(&self, index: u32) {
if let Some(value) = self.context.get_witness_map().get_index(index) {
println!("_{} = {value}", index);
}
}
pub fn update_witness(&mut self, index: u32, value: String) {
let Some(field_value) = FieldElement::try_from_str(&value) else {
println!("Invalid witness value: {value}");
return;
};
let witness = Witness::from(index);
_ = self.context.overwrite_witness(witness, field_value);
println!("_{} = {value}", index);
}
pub fn show_brillig_registers(&self) {
if !self.context.is_executing_brillig() {
println!("Not executing a Brillig block");
return;
}
let Some(registers) = self.context.get_brillig_registers() else {
// this can happen when just entering the Brillig block since ACVM
// would have not initialized the Brillig VM yet; in fact, the
// Brillig code may be skipped altogether
println!("Brillig VM registers not available");
return;
};
for (index, value) in registers.inner.iter().enumerate() {
println!("{index} = {}", value.to_field());
}
}
pub fn set_brillig_register(&mut self, index: usize, value: String) {
let Some(field_value) = FieldElement::try_from_str(&value) else {
println!("Invalid value: {value}");
return;
};
if !self.context.is_executing_brillig() {
println!("Not executing a Brillig block");
return;
}
self.context.set_brillig_register(index, field_value);
}
pub fn show_brillig_memory(&self) {
if !self.context.is_executing_brillig() {
println!("Not executing a Brillig block");
return;
}
let Some(memory) = self.context.get_brillig_memory() else {
// this can happen when just entering the Brillig block since ACVM
// would have not initialized the Brillig VM yet; in fact, the
// Brillig code may be skipped altogether
println!("Brillig VM memory not available");
return;
};
for (index, value) in memory.iter().enumerate() {
println!("{index} = {}", value.to_field());
}
}
pub fn write_brillig_memory(&mut self, index: usize, value: String) {
let Some(field_value) = FieldElement::try_from_str(&value) else {
println!("Invalid value: {value}");
return;
};
if !self.context.is_executing_brillig() {
println!("Not executing a Brillig block");
return;
}
self.context.write_brillig_memory(index, field_value);
}
fn is_solved(&self) -> bool {
self.context.is_solved()
}
fn finalize(self) -> WitnessMap {
self.context.finalize()
}
}
fn print_line_of_ellipsis(line_number: usize) {
println!("{}", format!("{:>3} {}", line_number, "...").dimmed());
}
fn print_dimmed_line(line_number: usize, line: &str) {
println!("{}", format!("{:>3} {:2} {}", line_number, "", line).dimmed());
}
pub fn run<B: BlackBoxFunctionSolver>(
blackbox_solver: &B,
circuit: &Circuit,
debug_artifact: &DebugArtifact,
initial_witness: WitnessMap,
) -> Result<Option<WitnessMap>, NargoError> {
let context =
RefCell::new(ReplDebugger::new(blackbox_solver, circuit, debug_artifact, initial_witness));
let ref_context = &context;
ref_context.borrow().show_current_vm_status();
let mut repl = Repl::builder()
.add(
"step",
command! {
"step to the next ACIR opcode",
() => || {
ref_context.borrow_mut().step_acir_opcode();
Ok(CommandStatus::Done)
}
},
)
.add(
"into",
command! {
"step into to the next opcode",
() => || {
ref_context.borrow_mut().step_into_opcode();
Ok(CommandStatus::Done)
}
},
)
.add(
"next",
command! {
"step until a new source location is reached",
() => || {
ref_context.borrow_mut().next();
Ok(CommandStatus::Done)
}
},
)
.add(
"continue",
command! {
"continue execution until the end of the program",
() => || {
ref_context.borrow_mut().cont();
Ok(CommandStatus::Done)
}
},
)
.add(
"restart",
command! {
"restart the debugging session",
() => || {
ref_context.borrow_mut().restart_session();
Ok(CommandStatus::Done)
}
},
)
.add(
"opcodes",
command! {
"display ACIR opcodes",
() => || {
ref_context.borrow().display_opcodes();
Ok(CommandStatus::Done)
}
},
)
.add(
"break",
command! {
"add a breakpoint at an opcode location",
(LOCATION:OpcodeLocation) => |location| {
ref_context.borrow_mut().add_breakpoint_at(location);
Ok(CommandStatus::Done)
}
},
)
.add(
"delete",
command! {
"delete breakpoint at an opcode location",
(LOCATION:OpcodeLocation) => |location| {
ref_context.borrow_mut().delete_breakpoint_at(location);
Ok(CommandStatus::Done)
}
},
)
.add(
"witness",
command! {
"show witness map",
() => || {
ref_context.borrow().show_witness_map();
Ok(CommandStatus::Done)
}
},
)
.add(
"witness",
command! {
"display a single witness from the witness map",
(index: u32) => |index| {
ref_context.borrow().show_witness(index);
Ok(CommandStatus::Done)
}
},
)
.add(
"witness",
command! {
"update a witness with the given value",
(index: u32, value: String) => |index, value| {
ref_context.borrow_mut().update_witness(index, value);
Ok(CommandStatus::Done)
}
},
)
.add(
"registers",
command! {
"show Brillig registers (valid when executing a Brillig block)",
() => || {
ref_context.borrow().show_brillig_registers();
Ok(CommandStatus::Done)
}
},
)
.add(
"regset",
command! {
"update a Brillig register with the given value",
(index: usize, value: String) => |index, value| {
ref_context.borrow_mut().set_brillig_register(index, value);
Ok(CommandStatus::Done)
}
},
)
.add(
"memory",
command! {
"show Brillig memory (valid when executing a Brillig block)",
() => || {
ref_context.borrow().show_brillig_memory();
Ok(CommandStatus::Done)
}
},
)
.add(
"memset",
command! {
"update a Brillig memory cell with the given value",
(index: usize, value: String) => |index, value| {
ref_context.borrow_mut().write_brillig_memory(index, value);
Ok(CommandStatus::Done)
}
},
)
.build()
.expect("Failed to initialize debugger repl");
repl.run().expect("Debugger error");
// REPL execution has finished.
// Drop it so that we can move fields out from `context` again.
drop(repl);
if context.borrow().is_solved() {
let solved_witness = context.into_inner().finalize();
Ok(Some(solved_witness))
} else {
Ok(None)
}
}