feat: json output for uplc eval

This commit is contained in:
rvcas
2023-03-08 01:10:56 -05:00
committed by KtorZ
parent bd7b8792bf
commit f8545854fc
4 changed files with 103 additions and 52 deletions

View File

@@ -144,7 +144,7 @@ pub fn exec(
eprintln!("\n");
println!(
"{}",
serde_json::to_string(&total_budget_used)
serde_json::to_string_pretty(&total_budget_used)
.map_err(|_| fmt::Error)
.into_diagnostic()?
);

View File

@@ -1,5 +1,6 @@
use miette::IntoDiagnostic;
use std::path::PathBuf;
use serde_json::json;
use std::{path::PathBuf, process};
use uplc::{
ast::{FakeNamedDeBruijn, Name, NamedDeBruijn, Program, Term},
machine::cost_model::ExBudget,
@@ -63,32 +64,38 @@ pub fn exec(
let budget = ExBudget::default();
let (term, cost, logs) = program.eval(budget);
let mut eval_result = program.eval(budget);
match term {
let cost = eval_result.cost();
let logs = eval_result.logs();
match eval_result.result() {
Ok(term) => {
let term: Term<Name> = term.try_into().into_diagnostic()?;
println!("\nResult\n------\n\n{}\n", term.to_pretty());
let output = json!({
"result": term.to_pretty(),
"cpu": cost.cpu,
"mem": cost.mem,
});
println!(
"{}",
serde_json::to_string_pretty(&output).into_diagnostic()?
);
Ok(())
}
Err(err) => {
eprintln!("\nError\n-----\n\n{err}\n");
eprintln!("\nCosts\n-----\ncpu: {}\nmemory: {}", cost.cpu, cost.mem);
if !logs.is_empty() {
eprintln!("\nLogs\n----\n{}", logs.join("\n"))
}
process::exit(1)
}
}
println!(
"\nCosts\n-----\ncpu: {}\nmemory: {}",
budget.cpu - cost.cpu,
budget.mem - cost.mem
);
println!(
"\nBudget\n------\ncpu: {}\nmemory: {}\n",
cost.cpu, cost.mem
);
if !logs.is_empty() {
println!("\nLogs\n----\n{}", logs.join("\n"))
}
Ok(())
}

View File

@@ -0,0 +1,44 @@
use crate::ast::{Constant, NamedDeBruijn, Term};
use super::{cost_model::ExBudget, Error};
pub struct EvalResult {
result: Result<Term<NamedDeBruijn>, Error>,
remaining_budget: ExBudget,
initial_budget: ExBudget,
logs: Vec<String>,
}
impl EvalResult {
pub fn new(
result: Result<Term<NamedDeBruijn>, Error>,
remaining_budget: ExBudget,
initial_budget: ExBudget,
logs: Vec<String>,
) -> EvalResult {
EvalResult {
result,
remaining_budget,
initial_budget,
logs,
}
}
pub fn cost(&self) -> ExBudget {
self.initial_budget - self.remaining_budget
}
pub fn logs(&mut self) -> Vec<String> {
std::mem::take(&mut self.logs)
}
pub fn failed(&self) -> bool {
matches!(self.result, Err(_))
|| matches!(self.result, Ok(Term::Error))
|| matches!(self.result, Ok(Term::Constant(ref con)) if matches!(con.as_ref(), Constant::Bool(false)))
}
pub fn result(self) -> Result<Term<NamedDeBruijn>, Error> {
self.result
}
}