Skip to content

Commit

Permalink
refactor: change print to log
Browse files Browse the repository at this point in the history
  • Loading branch information
Fumuran committed Nov 13, 2023
1 parent e0ce650 commit c27c5fc
Show file tree
Hide file tree
Showing 14 changed files with 96 additions and 68 deletions.
16 changes: 12 additions & 4 deletions assembly/src/assembler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use super::{
use core::{borrow::Borrow, cell::RefCell};
use vm_core::{utils::group_vector_elements, Decorator, DecoratorList};

#[cfg(feature = "std")]
use std::time::Instant;

mod instruction;

mod module_provider;
Expand Down Expand Up @@ -200,6 +203,9 @@ impl Assembler {
path: Option<&LibraryPath>,
context: &mut AssemblyContext,
) -> Result<Vec<RpoDigest>, AssemblyError> {
#[cfg(feature = "std")]
let now = Instant::now();

// a variable to track MAST roots of all procedures exported from this module
let mut proc_roots = Vec::new();
context.begin_module(path.unwrap_or(&LibraryPath::anon_path()), module)?;
Expand Down Expand Up @@ -264,10 +270,12 @@ impl Assembler {
}
}

// log the completion of the module
log::debug!(
"\n - Module \"{}\" has been compiled",
path.unwrap_or(&LibraryPath::anon_path())
// log the module compilation completion
#[cfg(feature = "std")]
log::trace!(
"\n- Compiled \"{}\" module in {} ms",
path.unwrap_or(&LibraryPath::anon_path()),
now.elapsed().as_millis()
);

Ok(proc_roots)
Expand Down
20 changes: 19 additions & 1 deletion assembly/src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::{
crypto::hash::RpoDigest, BTreeMap, ByteReader, ByteWriter, Deserializable,
DeserializationError, Felt, LabelError, LibraryPath, ParsingError, ProcedureId, ProcedureName,
Serializable, SliceReader, StarkField, String, ToString, Token, TokenStream, Vec,
MAX_LABEL_LEN,
MAX_LABEL_LEN,
};
use core::{fmt, iter, str::from_utf8};
#[cfg(feature = "std")]
Expand Down Expand Up @@ -224,8 +224,12 @@ impl ProgramAst {
return Err(ParsingError::dangling_ops_after_program(token));
}

#[cfg(feature = "std")]
check_unused_imports(context.import_info);

let local_procs = sort_procs_into_vec(context.local_procs);
let (nodes, locations) = body.into_parts();

Ok(Self::new(nodes, local_procs)?
.with_source_locations(locations, start)
.with_import_info(import_info))
Expand Down Expand Up @@ -938,3 +942,17 @@ fn sort_procs_into_vec(proc_map: LocalProcMap) -> Vec<ProcedureAst> {

procedures.into_iter().map(|(_idx, proc)| proc).collect()
}

/// Logging a warning message for every imported but unused module.
#[cfg(feature = "std")]
fn check_unused_imports(import_info: &ModuleImports) {
let import_lib_paths = import_info.import_paths();
let invoked_procs_paths: Vec<&LibraryPath> =
import_info.invoked_procs().iter().map(|(_id, (_name, path))| path).collect();

for lib in import_lib_paths {
if !invoked_procs_paths.contains(&lib) {
log::warn!("\nwarning: unused imports: \"{}\"", lib);
}
}
}
3 changes: 3 additions & 0 deletions miden/examples/logger/logger.inputs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"operand_stack": []
}
Binary file added miden/examples/logger/logger.masl
Binary file not shown.
6 changes: 6 additions & 0 deletions miden/examples/logger/logger.masm
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use.module::path::two
use.bar::baz

begin
exec.two::foo
end
7 changes: 0 additions & 7 deletions miden/examples/merkle_store/merkle_store.masm
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use.std::math::u64

begin
# push the root of the Partial Merkle Tree on the stack
push.0x82bb4d9a8e93582f1387611949703eecd8e4c74b904880f9c9c85f1fc1d7576d
Expand Down Expand Up @@ -35,11 +33,6 @@ begin
push.22.0.0.0
assert_eqw



dropw

push.1.2
exec.u64::checked_add

end
8 changes: 4 additions & 4 deletions miden/src/cli/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ pub struct BundleCmd {

impl BundleCmd {
pub fn execute(&self) -> Result<(), String> {
println!("============================================================");
println!("Build library");
println!("============================================================");
log::info!("============================================================\n");
log::info!("Build library\n");
log::info!("============================================================\n");

let namespace = match &self.namespace {
Some(namespace) => namespace.to_string(),
Expand All @@ -50,7 +50,7 @@ impl BundleCmd {
// write the masl output
stdlib.write_to_dir(self.dir.clone()).map_err(|e| e.to_string())?;

println!("Built library {}", namespace);
log::info!("Built library {}\n", namespace);

Ok(())
}
Expand Down
8 changes: 4 additions & 4 deletions miden/src/cli/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ pub struct CompileCmd {

impl CompileCmd {
pub fn execute(&self) -> Result<(), String> {
println!("============================================================");
println!("Compile program");
println!("============================================================");
log::info!("============================================================\n");
log::info!("Compile program\n");
log::info!("============================================================\n");

// load the program from file and parse it
let program = ProgramFile::read(&self.assembly_file)?;
Expand All @@ -34,7 +34,7 @@ impl CompileCmd {

// report program hash to user
let program_hash: [u8; 32] = compiled_program.hash().into();
println!("program hash is {}", hex::encode(program_hash));
log::info!("program hash is {}\n", hex::encode(program_hash));

// write the compiled file
program.write(self.output_file.clone())
Expand Down
39 changes: 19 additions & 20 deletions miden/src/cli/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use serde_derive::{Deserialize, Serialize};
use std::{
collections::HashMap,
fs,
io::{stdout, Write},
io::Write,
path::{Path, PathBuf},
time::Instant,
};
Expand Down Expand Up @@ -100,7 +100,7 @@ impl InputFile {
None => program_path.with_extension("inputs"),
};

println!("Reading input file `{}`", path.display());
log::info!("Reading input file `{}`\n", path.display());

// read input file to string
let inputs_file = fs::read_to_string(&path)
Expand Down Expand Up @@ -199,15 +199,15 @@ impl InputFile {
let tree = MerkleTree::new(leaves)
.map_err(|e| format!("failed to parse a Merkle tree: {e}"))?;
merkle_store.extend(tree.inner_nodes());
println!("Added Merkle tree with root {} to the Merkle store", tree.root());
log::trace!("Added Merkle tree with root {} to the Merkle store\n", tree.root());
}
MerkleData::SparseMerkleTree(data) => {
let entries = Self::parse_sparse_merkle_tree(data)?;
let tree = SimpleSmt::with_leaves(u64::BITS as u8, entries)
.map_err(|e| format!("failed to parse a Sparse Merkle Tree: {e}"))?;
merkle_store.extend(tree.inner_nodes());
println!(
"Added Sparse Merkle tree with root {} to the Merkle store",
log::trace!(
"Added Sparse Merkle tree with root {} to the Merkle store\n",
tree.root()
);
}
Expand All @@ -216,8 +216,8 @@ impl InputFile {
let tree = PartialMerkleTree::with_leaves(entries)
.map_err(|e| format!("failed to parse a Partial Merkle Tree: {e}"))?;
merkle_store.extend(tree.inner_nodes());
println!(
"Added Partial Merkle tree with root {} to the Merkle store",
log::trace!(
"Added Partial Merkle tree with root {} to the Merkle store\n",
tree.root()
);
}
Expand Down Expand Up @@ -324,7 +324,7 @@ impl OutputFile {
None => program_path.with_extension("outputs"),
};

println!("Reading output file `{}`", path.display());
log::info!("Reading output file `{}`\n", path.display());

// read outputs file to string
let outputs_file = fs::read_to_string(&path)
Expand All @@ -340,13 +340,13 @@ impl OutputFile {
/// Write the output file
pub fn write(stack_outputs: &StackOutputs, path: &PathBuf) -> Result<(), String> {
// if path provided, create output file
println!("Creating output file `{}`", path.display());
log::info!("Creating output file `{}`\n", path.display());

let file = fs::File::create(&path).map_err(|err| {
format!("Failed to create output file `{}` - {}", path.display(), err)
})?;

println!("Writing data to output file");
log::info!("Writing data to output file\n");

// write outputs to output file
serde_json::to_writer_pretty(file, &Self::new(stack_outputs))
Expand Down Expand Up @@ -381,17 +381,17 @@ impl ProgramFile {
/// Reads the masm file at the specified path and parses it into a [ProgramAst].
pub fn read(path: &PathBuf) -> Result<Self, String> {
// read program file to string
println!("Reading program file `{}`", path.display());
log::info!("Reading program file `{}`\n", path.display());
let source = fs::read_to_string(&path)
.map_err(|err| format!("Failed to open program file `{}` - {}", path.display(), err))?;

// parse the program into an AST
print!("Parsing program... ");
log::info!("Parsing program... ");
let now = Instant::now();
let ast = ProgramAst::parse(&source).map_err(|err| {
format!("Failed to parse program file `{}` - {}", path.display(), err)
})?;
println!("done ({} ms)", now.elapsed().as_millis());
log::info!("\ndone ({} ms)\n", now.elapsed().as_millis());

Ok(Self {
ast,
Expand All @@ -405,8 +405,7 @@ impl ProgramFile {
I: IntoIterator<Item = L>,
L: Library,
{
print!("Compiling program... ");
stdout().flush().expect("Couldn't flush stdout");
log::info!("Compiling program... ");
let now = Instant::now();

// compile program
Expand All @@ -423,7 +422,7 @@ impl ProgramFile {
.compile_ast(&self.ast)
.map_err(|err| format!("Failed to compile program - {}", err))?;

println!("done ({} ms)", now.elapsed().as_millis());
log::info!("\ndone ({} ms)\n", now.elapsed().as_millis());

Ok(program)
}
Expand Down Expand Up @@ -462,7 +461,7 @@ impl ProofFile {
None => program_path.with_extension("proof"),
};

println!("Reading proof file `{}`", path.display());
log::info!("Reading proof file `{}`\n", path.display());

// read the file to bytes
let file = fs::read(&path)
Expand All @@ -486,15 +485,15 @@ impl ProofFile {
None => program_path.with_extension("proof"),
};

println!("Creating proof file `{}`", path.display());
log::info!("Creating proof file `{}`\n", path.display());

// create output fille
let mut file = fs::File::create(&path)
.map_err(|err| format!("Failed to create proof file `{}` - {}", path.display(), err))?;

let proof_bytes = proof.to_bytes();

println!("Writing data to proof file - size {} KB", proof_bytes.len() / 1024);
log::info!("Writing data to proof file - size {} KB\n", proof_bytes.len() / 1024);

// write proof bytes to file
file.write_all(&proof_bytes).unwrap();
Expand Down Expand Up @@ -542,7 +541,7 @@ impl Libraries {
let mut libraries = Vec::new();

for path in paths {
println!("Reading library file `{}`", path.as_ref().display());
log::info!("Reading library file `{}`\n", path.as_ref().display());

let library = MaslLibrary::read_from_file(path)
.map_err(|e| format!("Failed to read library: {e}"))?;
Expand Down
12 changes: 6 additions & 6 deletions miden/src/cli/debug/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ pub struct DebugCmd {

impl DebugCmd {
pub fn execute(&self) -> Result<(), String> {
println!("============================================================");
println!("Debug program");
println!("============================================================");
log::info!("============================================================\n");
log::info!("Debug program\n");
log::info!("============================================================\n");

// load libraries from files
let libraries = Libraries::new(&self.library_paths)?;
Expand All @@ -40,7 +40,7 @@ impl DebugCmd {
ProgramFile::read(&self.assembly_file)?.compile(&Debug::On, libraries.libraries)?;

let program_hash: [u8; 32] = program.hash().into();
println!("Debugging program with hash {}... ", hex::encode(program_hash));
log::info!("Debugging program with hash {}... \n", hex::encode(program_hash));

// load input data from file
let input_data = InputFile::read(&self.input_file, &self.assembly_file)?;
Expand All @@ -63,14 +63,14 @@ impl DebugCmd {
let mut rl =
DefaultEditor::with_config(rl_config).expect("Readline couldn't be initialized");

println!("Welcome! Enter `h` for help.");
log::info!("Welcome! Enter `h` for help.\n");

loop {
match rl.readline(">> ") {
Ok(command) => match DebugCommand::parse(&command) {
Ok(Some(command)) => {
if !debug_executor.execute(command) {
println!("Debugging complete");
log::info!("Debugging complete\n");
break;
}
}
Expand Down
14 changes: 7 additions & 7 deletions miden/src/cli/prove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ impl ProveCmd {
}

pub fn execute(&self) -> Result<(), String> {
println!("============================================================");
println!("Prove program");
println!("============================================================");
log::info!("============================================================\n");
log::info!("Prove program\n");
log::info!("============================================================\n");

// load libraries from files
let libraries = Libraries::new(&self.library_paths)?;
Expand All @@ -76,7 +76,7 @@ impl ProveCmd {
let input_data = InputFile::read(&self.input_file, &self.assembly_file)?;

let program_hash: [u8; 32] = program.hash().into();
println!("Proving program with hash {}...", hex::encode(program_hash));
log::info!("Proving program with hash {}...\n", hex::encode(program_hash));
let now = Instant::now();

// fetch the stack and program inputs from the arguments
Expand All @@ -90,8 +90,8 @@ impl ProveCmd {
prover::prove(&program, stack_inputs, host, proving_options)
.map_err(|err| format!("Failed to prove program - {:?}", err))?;

println!(
"Program with hash {} proved in {} ms",
log::info!(
"Program with hash {} proved in {} ms\n",
hex::encode(program_hash),
now.elapsed().as_millis()
);
Expand All @@ -111,7 +111,7 @@ impl ProveCmd {
OutputFile::write(&stack_outputs, &self.assembly_file.with_extension("outputs"))?;

// print stack outputs to screen.
println!("Output: {:?}", stack);
log::info!("Output: {:?}\n", stack);
}

Ok(())
Expand Down
Loading

0 comments on commit c27c5fc

Please sign in to comment.