Merge pull request #396 from ljedrz/alloc_hunting

Further memory-handling improvements
This commit is contained in:
Collin Chin 2020-10-21 01:54:34 -07:00 committed by GitHub
commit 0850da64b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
99 changed files with 450 additions and 448 deletions

View File

@ -16,11 +16,12 @@
use leo_ast::LeoAst;
use criterion::{criterion_group, criterion_main, Criterion};
use std::path::{Path, PathBuf};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use std::path::Path;
fn leo_ast<'ast>(filepath: &'ast PathBuf, program_string: &'ast str) -> LeoAst<'ast> {
LeoAst::<'ast>::new(filepath, program_string).unwrap()
fn leo_ast<'ast>(filepath: &'ast Path, program_string: &'ast str) {
let result = LeoAst::<'ast>::new(filepath, program_string).unwrap();
black_box(result);
}
fn criterion_benchmark(c: &mut Criterion) {

View File

@ -34,8 +34,16 @@ impl<'ast> fmt::Display for RangeOrExpression<'ast> {
RangeOrExpression::Range(ref range) => write!(
f,
"{}..{}",
range.from.as_ref().map(|v| format!("{}", v)).unwrap_or(format!("")),
range.to.as_ref().map(|v| format!("{}", v)).unwrap_or(format!("")),
range
.from
.as_ref()
.map(|v| v.to_string())
.unwrap_or_else(|| "".to_string()),
range
.to
.as_ref()
.map(|v| v.to_string())
.unwrap_or_else(|| "".to_string()),
),
}
}

View File

@ -38,12 +38,7 @@ impl<'ast> fmt::Display for Variables<'ast> {
write!(f, "{}", self.names[0])?;
} else {
// (a, mut b)
let names = self
.names
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join(",");
let names = self.names.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");
write!(f, "({})", names)?;
}

View File

@ -17,7 +17,7 @@
use crate::{ast::Rule, errors::SyntaxError};
use pest::error::Error;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
#[derive(Debug, Error)]
pub enum ParserError {
@ -38,7 +38,7 @@ pub enum ParserError {
}
impl ParserError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
if let ParserError::SyntaxError(error) = self {
let new_error: Error<Rule> = match error {
SyntaxError::Error(error) => {
@ -62,6 +62,6 @@ impl From<Error<Rule>> for ParserError {
impl From<std::io::Error> for ParserError {
fn from(error: std::io::Error) -> Self {
ParserError::Crate("std::io", format!("{}", error))
ParserError::Crate("std::io", error.to_string())
}
}

View File

@ -45,7 +45,7 @@ pub(crate) mod span;
pub(crate) use span::*;
use from_pest::FromPest;
use std::{fs, path::PathBuf};
use std::{fs, path::Path};
pub struct LeoAst<'ast> {
ast: files::File<'ast>,
@ -53,7 +53,7 @@ pub struct LeoAst<'ast> {
impl<'ast> LeoAst<'ast> {
/// Creates a new abstract syntax tree given the file path.
pub fn new(file_path: &'ast PathBuf, program_string: &'ast str) -> Result<Self, ParserError> {
pub fn new(file_path: &'ast Path, program_string: &'ast str) -> Result<Self, ParserError> {
// TODO (howardwu): Turn this check back on after fixing the testing module.
// assert_eq!(program_string, fs::read_to_string(file_path).map_err(|_| ParserError::FileReadError(file_path.clone()))?);
@ -71,8 +71,8 @@ impl<'ast> LeoAst<'ast> {
// TODO (howardwu): Remove this in favor of a dedicated file loader to verify checksums
// and maintain a global cache of program strings during the compilation process.
/// Loads the Leo code as a string from the given file path.
pub fn load_file(file_path: &'ast PathBuf) -> Result<String, ParserError> {
Ok(fs::read_to_string(file_path).map_err(|_| ParserError::FileReadError(file_path.clone()))?)
pub fn load_file(file_path: &'ast Path) -> Result<String, ParserError> {
Ok(fs::read_to_string(file_path).map_err(|_| ParserError::FileReadError(file_path.to_owned()))?)
}
/// Returns a reference to the inner abstract syntax tree representation.

View File

@ -43,7 +43,7 @@ impl<'ast> fmt::Display for DefinitionStatement<'ast> {
let expressions = self
.expressions
.iter()
.map(|x| format!("{}", x))
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",");

View File

@ -38,7 +38,11 @@ use snarkos_models::{
};
use sha2::{Digest, Sha256};
use std::{fs, marker::PhantomData, path::PathBuf};
use std::{
fs,
marker::PhantomData,
path::{Path, PathBuf},
};
#[derive(Clone)]
pub struct Compiler<F: Field + PrimeField, G: GroupType<F>> {
@ -71,17 +75,17 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
pub fn parse_input(
&mut self,
input_string: &str,
input_path: PathBuf,
input_path: &Path,
state_string: &str,
state_path: PathBuf,
state_path: &Path,
) -> Result<(), CompilerError> {
let input_syntax_tree = LeoInputParser::parse_file(&input_string).map_err(|mut e| {
e.set_path(input_path.clone());
e.set_path(input_path);
e
})?;
let state_syntax_tree = LeoInputParser::parse_file(&state_string).map_err(|mut e| {
e.set_path(state_path.clone());
e.set_path(state_path);
e
})?;
@ -121,9 +125,9 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
main_file_path: PathBuf,
output_directory: PathBuf,
input_string: &str,
input_path: PathBuf,
input_path: &Path,
state_string: &str,
state_path: PathBuf,
state_path: &Path,
) -> Result<Self, CompilerError> {
let mut compiler = Self::new(package_name, main_file_path, output_directory);
@ -149,7 +153,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
pub fn parse_program_from_string(&mut self, program_string: &str) -> Result<(), CompilerError> {
// Use the given bytes to construct the abstract syntax tree.
let ast = LeoAst::new(&self.main_file_path, &program_string).map_err(|mut e| {
e.set_path(self.main_file_path.clone());
e.set_path(&self.main_file_path);
e
})?;
@ -202,7 +206,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
generate_constraints::<F, G, CS>(cs, self.program, self.program_input, &self.imported_programs).map_err(
|mut error| {
error.set_path(path);
error.set_path(&path);
error
},
@ -228,7 +232,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> Compiler<F, G> {
let path = self.main_file_path;
generate_constraints::<_, G, _>(cs, self.program, self.program_input, &self.imported_programs).map_err(
|mut error| {
error.set_path(path);
error.set_path(&path);
error
},
)

View File

@ -46,8 +46,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
string = string.trim_start_matches('\"');
// Trim everything after the ending double quote `"`
let parts: Vec<&str> = string.split('\"').collect();
string = parts[0];
let string = string.split('\"').next().unwrap();
// Insert the parameter for each container `{}`
let mut result = string.to_string();

View File

@ -34,7 +34,7 @@ use snarkos_models::{
curves::{Field, PrimeField},
gadgets::r1cs::{ConstraintSystem, TestConstraintSystem},
};
use std::path::PathBuf;
use std::path::Path;
pub fn generate_constraints<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
cs: &mut CS,
@ -65,8 +65,8 @@ pub fn generate_test_constraints<F: Field + PrimeField, G: GroupType<F>>(
program: Program,
input: InputPairs,
imported_programs: &ImportParser,
main_file_path: &PathBuf,
output_directory: &PathBuf,
main_file_path: &Path,
output_directory: &Path,
) -> Result<(u32, u32), CompilerError> {
let mut resolved_program = ConstrainedProgram::<F, G>::new();
let program_name = program.get_name();
@ -87,7 +87,7 @@ pub fn generate_test_constraints<F: Field + PrimeField, G: GroupType<F>>(
for (test_name, test) in tests.into_iter() {
let cs = &mut TestConstraintSystem::<F>::new();
let full_test_name = format!("{}::{}", program_name, test_name);
let full_test_name = format!("{}::{}", program_name.clone(), test_name);
let mut output_file_name = program_name.clone();
// get input file name from annotation or use test_name
@ -147,7 +147,7 @@ pub fn generate_test_constraints<F: Field + PrimeField, G: GroupType<F>>(
(false, _) => {
// Set file location of error
let mut error = result.unwrap_err();
error.set_path(main_file_path.clone());
error.set_path(main_file_path);
tracing::error!("{} failed due to error\n\n{}\n", full_test_name, error);

View File

@ -20,7 +20,7 @@ use leo_input::InputParserError;
use leo_state::LocalDataVerificationError;
use bincode::Error as SerdeError;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
#[derive(Debug, Error)]
pub enum CompilerError {
@ -65,7 +65,7 @@ pub enum CompilerError {
}
impl CompilerError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
CompilerError::InputParserError(error) => error.set_path(path),
CompilerError::FunctionError(error) => error.set_path(path),

View File

@ -17,7 +17,7 @@
use crate::errors::ExpressionError;
use leo_typed::{Error as FormattedError, Span};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum ConsoleError {
@ -29,7 +29,7 @@ pub enum ConsoleError {
}
impl ConsoleError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
ConsoleError::Expression(error) => error.set_path(path),
ConsoleError::Error(error) => error.set_path(path),

View File

@ -19,7 +19,7 @@ use leo_core::LeoCoreError;
use leo_typed::{Error as FormattedError, Identifier, Span};
use snarkos_errors::gadgets::SynthesisError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum ExpressionError {
@ -52,7 +52,7 @@ pub enum ExpressionError {
}
impl ExpressionError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
ExpressionError::AddressError(error) => error.set_path(path),
ExpressionError::BooleanError(error) => error.set_path(path),

View File

@ -27,7 +27,7 @@ use crate::errors::{
};
use leo_typed::{Error as FormattedError, Span};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum FunctionError {
@ -63,7 +63,7 @@ pub enum FunctionError {
}
impl FunctionError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
FunctionError::AddressError(error) => error.set_path(path),
FunctionError::BooleanError(error) => error.set_path(path),

View File

@ -18,7 +18,7 @@ use leo_ast::ParserError;
use leo_typed::{Error as FormattedError, Identifier, ImportSymbol, Span};
use leo_core::LeoCoreError;
use std::{io, path::PathBuf};
use std::{io, path::Path};
#[derive(Debug, Error)]
pub enum ImportError {
@ -37,7 +37,7 @@ impl ImportError {
ImportError::Error(FormattedError::new_from_span(message, span))
}
fn new_from_span_with_path(message: String, span: Span, path: PathBuf) -> Self {
fn new_from_span_with_path(message: String, span: Span, path: &Path) -> Self {
ImportError::Error(FormattedError::new_from_span_with_path(message, span, path))
}
@ -65,13 +65,13 @@ impl ImportError {
Self::new_from_span(message, span)
}
pub fn directory_error(error: io::Error, span: Span, path: PathBuf) -> Self {
pub fn directory_error(error: io::Error, span: Span, path: &Path) -> Self {
let message = format!("compilation failed due to directory error - {:?}", error);
Self::new_from_span_with_path(message, span, path)
}
pub fn star(path: PathBuf, span: Span) -> Self {
pub fn star(path: &Path, span: Span) -> Self {
let message = format!("cannot import `*` from path `{:?}`", path);
Self::new_from_span(message, span)

View File

@ -16,7 +16,7 @@
use leo_typed::{Error as FormattedError, Span};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum OutputBytesError {
@ -25,7 +25,7 @@ pub enum OutputBytesError {
}
impl OutputBytesError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
OutputBytesError::Error(error) => error.set_path(path),
}

View File

@ -36,6 +36,6 @@ pub enum OutputFileError {
impl From<std::io::Error> for OutputFileError {
fn from(error: std::io::Error) -> Self {
OutputFileError::Crate("std::io", format!("{}", error))
OutputFileError::Crate("std::io", error.to_string())
}
}

View File

@ -17,7 +17,7 @@
use crate::errors::{AddressError, BooleanError, ConsoleError, ExpressionError, IntegerError, ValueError};
use leo_typed::{Error as FormattedError, Span, Type};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum StatementError {
@ -44,7 +44,7 @@ pub enum StatementError {
}
impl StatementError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
StatementError::AddressError(error) => error.set_path(path),
StatementError::BooleanError(error) => error.set_path(path),

View File

@ -17,7 +17,7 @@
use leo_typed::{Error as FormattedError, Span};
use snarkos_errors::{gadgets::SynthesisError, objects::account::AccountError};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum AddressError {
@ -26,7 +26,7 @@ pub enum AddressError {
}
impl AddressError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
AddressError::Error(error) => error.set_path(path),
}

View File

@ -17,7 +17,7 @@
use leo_typed::{Error as FormattedError, Span};
use snarkos_errors::gadgets::SynthesisError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum BooleanError {
@ -26,7 +26,7 @@ pub enum BooleanError {
}
impl BooleanError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
BooleanError::Error(error) => error.set_path(path),
}

View File

@ -17,7 +17,7 @@
use leo_typed::{Error as FormattedError, Span};
use snarkos_errors::gadgets::SynthesisError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum FieldError {
@ -26,7 +26,7 @@ pub enum FieldError {
}
impl FieldError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
FieldError::Error(error) => error.set_path(path),
}

View File

@ -17,7 +17,7 @@
use leo_typed::{Error as FormattedError, Span};
use snarkos_errors::gadgets::SynthesisError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum GroupError {
@ -26,7 +26,7 @@ pub enum GroupError {
}
impl GroupError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
GroupError::Error(error) => error.set_path(path),
}

View File

@ -18,7 +18,7 @@ use leo_gadgets::errors::SignedIntegerError;
use leo_typed::{error::Error as FormattedError, Span};
use snarkos_errors::gadgets::SynthesisError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum IntegerError {
@ -27,7 +27,7 @@ pub enum IntegerError {
}
impl IntegerError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
IntegerError::Error(error) => error.set_path(path),
}

View File

@ -17,7 +17,7 @@
use crate::errors::{AddressError, BooleanError, FieldError, GroupError, IntegerError};
use leo_typed::{Error as FormattedError, Span};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum ValueError {
@ -41,7 +41,7 @@ pub enum ValueError {
}
impl ValueError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
ValueError::AddressError(error) => error.set_path(path),
ValueError::BooleanError(error) => error.set_path(path),

View File

@ -40,8 +40,9 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
span: Span,
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
// Circuit definitions are located at the minimum file scope
let scopes: Vec<&str> = file_scope.split('_').collect();
let mut program_identifier = new_scope(scopes[0], &identifier.name);
let minimum_scope = file_scope.split('_').next().unwrap();
let identifier_string = identifier.to_string();
let mut program_identifier = new_scope(minimum_scope, &identifier_string);
if identifier.is_self() {
program_identifier = file_scope.to_string();

View File

@ -42,7 +42,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
// Save a reference to the circuit we are mutating.
let circuit_id_string = circuit_identifier.to_string();
let declared_circuit_reference = new_scope(&function_scope, &circuit_id_string);
let declared_circuit_reference = new_scope(function_scope.clone(), &circuit_id_string);
(
declared_circuit_reference,

View File

@ -69,9 +69,9 @@ impl ImportParser {
}
let entries = fs::read_dir(path)
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), error_path.clone()))?
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), &error_path))?
.collect::<Result<Vec<_>, std::io::Error>>()
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), error_path.clone()))?;
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), &error_path))?;
let matched_source_entry = entries.into_iter().find(|entry| {
entry
@ -87,9 +87,9 @@ impl ImportParser {
self.parse_core_package(&package)
} else if imports_directory.exists() {
let entries = fs::read_dir(imports_directory)
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), error_path.clone()))?
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), &error_path))?
.collect::<Result<Vec<_>, std::io::Error>>()
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), error_path.clone()))?;
.map_err(|error| ImportError::directory_error(error, package_name.span.clone(), &error_path))?;
let matched_import_entry = entries
.into_iter()

View File

@ -27,7 +27,7 @@ fn parse_import_file(entry: &DirEntry, span: &Span) -> Result<Program, ImportErr
// make sure the given entry is file
let file_type = entry
.file_type()
.map_err(|error| ImportError::directory_error(error, span.clone(), entry.path()))?;
.map_err(|error| ImportError::directory_error(error, span.clone(), &entry.path()))?;
let file_name = entry
.file_name()
.into_string()
@ -92,7 +92,7 @@ impl ImportParser {
Ok(())
} else {
// importing * from a directory or non-leo file in `package/src/` is illegal
Err(ImportError::star(entry.path(), span.clone()))
Err(ImportError::star(&entry.path(), span.clone()))
}
}

View File

@ -19,9 +19,10 @@
use crate::errors::OutputFileError;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static OUTPUTS_DIRECTORY_NAME: &str = "outputs/";
@ -38,21 +39,21 @@ impl OutputFile {
}
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the output register variables from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<String, OutputFileError> {
pub fn read_from(&self, path: &Path) -> Result<String, OutputFileError> {
let path = self.setup_file_path(path);
let output = fs::read_to_string(&path).map_err(|_| OutputFileError::FileReadError(path.clone()))?;
let output = fs::read_to_string(&path).map_err(|_| OutputFileError::FileReadError(path.into_owned()))?;
Ok(output)
}
/// Writes output to a file.
pub fn write(&self, path: &PathBuf, bytes: &[u8]) -> Result<(), OutputFileError> {
pub fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), OutputFileError> {
// create output file
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -62,23 +63,24 @@ impl OutputFile {
/// Removes the output file at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, OutputFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, OutputFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| OutputFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| OutputFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!("{}{}", self.package_name, OUTPUT_FILE_EXTENSION)));
path.to_mut()
.push(format!("{}{}", self.package_name, OUTPUT_FILE_EXTENSION));
}
path
}

View File

@ -268,7 +268,7 @@ impl EdwardsGroupType {
if element.is_on_curve() {
Ok(element)
} else {
Err(GroupError::not_on_curve(format!("{}", element), element_span))
Err(GroupError::not_on_curve(element.to_string(), element_span))
}
}

View File

@ -355,7 +355,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<F
write!(f, "]")
}
ConstrainedValue::Tuple(ref tuple) => {
let values = tuple.iter().map(|x| format!("{}", x)).collect::<Vec<_>>().join(", ");
let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", values)
}

View File

@ -78,7 +78,7 @@ pub(crate) fn parse_input(bytes: &[u8]) -> Result<EdwardsTestCompiler, CompilerE
let input_string = String::from_utf8_lossy(bytes);
let path = PathBuf::new();
compiler.parse_input(&input_string, path.clone(), EMPTY_FILE, path)?;
compiler.parse_input(&input_string, &path, EMPTY_FILE, &path)?;
Ok(compiler)
}
@ -88,7 +88,7 @@ pub(crate) fn parse_state(bytes: &[u8]) -> Result<EdwardsTestCompiler, CompilerE
let state_string = String::from_utf8_lossy(bytes);
let path = PathBuf::new();
compiler.parse_input(EMPTY_FILE, path.clone(), &state_string, path)?;
compiler.parse_input(EMPTY_FILE, &path, &state_string, &path)?;
Ok(compiler)
}
@ -102,7 +102,7 @@ pub(crate) fn parse_input_and_state(
let state_string = String::from_utf8_lossy(state_bytes);
let path = PathBuf::new();
compiler.parse_input(&input_string, path.clone(), &state_string, path)?;
compiler.parse_input(&input_string, &path, &state_string, &path)?;
Ok(compiler)
}
@ -117,7 +117,7 @@ pub fn parse_program_with_input(
let input_string = String::from_utf8_lossy(input_bytes);
let path = PathBuf::new();
compiler.parse_input(&input_string, path.clone(), EMPTY_FILE, path)?;
compiler.parse_input(&input_string, &path, EMPTY_FILE, &path)?;
compiler.parse_program_from_string(&program_string)?;
Ok(compiler)
@ -133,7 +133,7 @@ pub fn parse_program_with_state(
let state_string = String::from_utf8_lossy(state_bytes);
let path = PathBuf::new();
compiler.parse_input(EMPTY_FILE, path.clone(), &state_string, path)?;
compiler.parse_input(EMPTY_FILE, &path, &state_string, &path)?;
compiler.parse_program_from_string(&program_string)?;
Ok(compiler)
@ -151,7 +151,7 @@ pub fn parse_program_with_input_and_state(
let state_string = String::from_utf8_lossy(state_bytes);
let path = PathBuf::new();
compiler.parse_input(&input_string, path.clone(), &state_string, path)?;
compiler.parse_input(&input_string, &path, &state_string, &path)?;
compiler.parse_program_from_string(&program_string)?;
Ok(compiler)

View File

@ -45,7 +45,7 @@ fn test_undefined() {
ExpressionError::Error(error),
))) => {
assert_eq!(
format!("{}", error),
error.to_string(),
vec![
" --> \"/test/src/main.leo\": 2:12",
" |",

View File

@ -19,7 +19,7 @@ use leo_typed::{Error as FormattedError, Span};
use snarkos_errors::gadgets::SynthesisError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error, Eq, PartialEq)]
pub enum CoreCircuitError {
@ -28,7 +28,7 @@ pub enum CoreCircuitError {
}
impl CoreCircuitError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
CoreCircuitError::Error(error) => error.set_path(path),
}

View File

@ -15,7 +15,7 @@
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_typed::{Error as FormattedError, Span};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum CorePackageError {
@ -24,7 +24,7 @@ pub enum CorePackageError {
}
impl CorePackageError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
CorePackageError::Error(error) => error.set_path(path),
}

View File

@ -17,7 +17,7 @@
use leo_typed::{Error as FormattedError, ImportSymbol, Span};
use crate::CorePackageError;
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum CorePackageListError {
@ -29,7 +29,7 @@ pub enum CorePackageListError {
}
impl CorePackageListError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
CorePackageListError::CorePackageError(error) => error.set_path(path),
CorePackageListError::Error(error) => error.set_path(path),

View File

@ -17,7 +17,7 @@
use crate::{CoreCircuitError, CorePackageListError};
use leo_typed::{Error as FormattedError, Span};
use std::path::PathBuf;
use std::path::Path;
#[derive(Debug, Error)]
pub enum LeoCoreError {
@ -32,7 +32,7 @@ pub enum LeoCoreError {
}
impl LeoCoreError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
match self {
LeoCoreError::CoreCircuitError(error) => error.set_path(path),
LeoCoreError::CorePackageListError(error) => error.set_path(path),

View File

@ -56,14 +56,14 @@ impl fmt::Display for Value {
Value::I64(value) => value.value.map(|v| v.to_string()),
Value::I128(value) => value.value.map(|v| v.to_string()),
Value::Array(values) => {
let string = values.iter().map(|v| format!("{}", v)).collect::<Vec<_>>().join(", ");
let string = values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "[{}]", string)?;
Some("".to_owned())
}
Value::Tuple(values) => {
let string = values.iter().map(|v| format!("{}", v)).collect::<Vec<_>>().join(", ");
let string = values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "[{}]", string)?;

View File

@ -28,7 +28,11 @@ use pest::{
error::{Error, ErrorVariant},
Span,
};
use std::{num::ParseIntError, path::PathBuf, str::ParseBoolError};
use std::{
num::ParseIntError,
path::{Path, PathBuf},
str::ParseBoolError,
};
#[derive(Debug, Error)]
pub enum InputParserError {
@ -52,7 +56,7 @@ pub enum InputParserError {
}
impl InputParserError {
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
if let InputParserError::SyntaxError(error) = self {
let new_error: Error<Rule> = match error {
InputSyntaxError::Error(error) => {
@ -74,7 +78,7 @@ impl InputParserError {
}
pub fn implicit_type(data_type: DataType, implicit: NumberValue) -> Self {
let message = format!("expected `{}`, found `{}`", data_type.to_string(), implicit.to_string());
let message = format!("expected `{}`, found `{}`", data_type, implicit);
Self::new_from_span(message, implicit.span().clone())
}
@ -86,22 +90,14 @@ impl InputParserError {
}
pub fn data_type_mismatch(data_type: DataType, value: Value) -> Self {
let message = format!(
"expected data type `{}`, found `{}`",
data_type.to_string(),
value.to_string()
);
let message = format!("expected data type `{}`, found `{}`", data_type, value);
let span = value.span().to_owned();
Self::new_from_span(message, span)
}
pub fn expression_type_mismatch(type_: Type, expression: Expression) -> Self {
let message = format!(
"expected expression type `{}`, found `{}`",
type_.to_string(),
expression.to_string()
);
let message = format!("expected expression type `{}`, found `{}`", type_, expression);
let span = expression.span().to_owned();
Self::new_from_span(message, span)

View File

@ -50,7 +50,7 @@ impl<'ast> fmt::Display for Expression<'ast> {
let values = array
.expressions
.iter()
.map(|x| format!("{}", x))
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ");
@ -60,7 +60,7 @@ impl<'ast> fmt::Display for Expression<'ast> {
let values = tuple
.expressions
.iter()
.map(|x| format!("{}", x))
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ");

View File

@ -34,14 +34,14 @@ pub mod types;
pub mod values;
use from_pest::FromPest;
use std::{fs, path::PathBuf};
use std::{fs, path::Path};
pub struct LeoInputParser;
impl LeoInputParser {
/// Reads in the given file path into a string.
pub fn load_file(file_path: &PathBuf) -> Result<String, InputParserError> {
Ok(fs::read_to_string(file_path).map_err(|_| InputParserError::FileReadError(file_path.clone()))?)
pub fn load_file(file_path: &Path) -> Result<String, InputParserError> {
Ok(fs::read_to_string(file_path).map_err(|_| InputParserError::FileReadError(file_path.to_owned()))?)
}
/// Parses the input file and constructs a syntax tree.

View File

@ -29,6 +29,6 @@ pub struct Private<'ast> {
impl<'ast> fmt::Display for Private<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.span.as_str().to_string())
write!(f, "{}", self.span.as_str())
}
}

View File

@ -29,6 +29,6 @@ pub struct Public<'ast> {
impl<'ast> fmt::Display for Public<'ast> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.span.as_str().to_string())
write!(f, "{}", self.span.as_str())
}
}

View File

@ -50,7 +50,7 @@ impl<'ast> ArrayDimensions<'ast> {
span: single.span.clone(),
}),
ArrayDimensions::Multiple(multiple) => {
let old_dimension = multiple.numbers.clone();
let old_dimension = &multiple.numbers;
ArrayDimensions::Multiple(Multiple {
numbers: old_dimension[1..].to_vec(),

View File

@ -29,12 +29,7 @@ pub struct TupleType<'ast> {
impl<'ast> std::fmt::Display for TupleType<'ast> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let tuple = self
.types_
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join(", ");
let tuple = self.types_.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", tuple)
}

View File

@ -55,41 +55,38 @@ pub trait CLI {
false => Arg::from_usage(a.0).conflicts_with_all(a.1).requires_all(a.3),
})
.collect::<Vec<Arg<'static, 'static>>>();
let subcommands = Self::SUBCOMMANDS
.iter()
.map(|s| {
SubCommand::with_name(s.0)
.about(s.1)
.args(
&s.2.iter()
.map(|a| {
let mut args = Arg::with_name(a.0).help(a.1).required(a.3).index(a.4);
if !a.2.is_empty() {
args = args.possible_values(a.2);
}
args
})
.collect::<Vec<Arg<'static, 'static>>>(),
)
.args(
&s.3.iter()
.map(|a| Arg::from_usage(a))
.collect::<Vec<Arg<'static, 'static>>>(),
)
.args(
&s.4.iter()
.map(|a| match !a.2.is_empty() {
true => Arg::from_usage(a.0)
.conflicts_with_all(a.1)
.possible_values(a.2)
.requires_all(a.3),
false => Arg::from_usage(a.0).conflicts_with_all(a.1).requires_all(a.3),
})
.collect::<Vec<Arg<'static, 'static>>>(),
)
.settings(s.5)
})
.collect::<Vec<App<'static, 'static>>>();
let subcommands = Self::SUBCOMMANDS.iter().map(|s| {
SubCommand::with_name(s.0)
.about(s.1)
.args(
&s.2.iter()
.map(|a| {
let mut args = Arg::with_name(a.0).help(a.1).required(a.3).index(a.4);
if !a.2.is_empty() {
args = args.possible_values(a.2);
}
args
})
.collect::<Vec<Arg<'static, 'static>>>(),
)
.args(
&s.3.iter()
.map(|a| Arg::from_usage(a))
.collect::<Vec<Arg<'static, 'static>>>(),
)
.args(
&s.4.iter()
.map(|a| match !a.2.is_empty() {
true => Arg::from_usage(a.0)
.conflicts_with_all(a.1)
.possible_values(a.2)
.requires_all(a.3),
false => Arg::from_usage(a.0).conflicts_with_all(a.1).requires_all(a.3),
})
.collect::<Vec<Arg<'static, 'static>>>(),
)
.settings(s.5)
});
SubCommand::with_name(Self::NAME)
.about(Self::ABOUT)

View File

@ -114,7 +114,7 @@ impl CLI for AddCommand {
let path = current_dir()?;
// Enforce that the current directory is a leo package
Manifest::try_from(&path)?;
Manifest::try_from(path.as_path())?;
let (response, package_name) = match options {
(Some(author), Some(package_name), version) => {

View File

@ -62,7 +62,7 @@ impl CLI for BuildCommand {
let path = current_dir()?;
// Get the package name
let manifest = Manifest::try_from(&path)?;
let manifest = Manifest::try_from(path.as_path())?;
let package_name = manifest.get_package_name();
// Sanitize the package path to the root directory
@ -124,9 +124,9 @@ impl CLI for BuildCommand {
main_file_path,
output_directory,
&input_string,
input_path,
&input_path,
&state_string,
state_path,
&state_path,
)?;
// Compute the current program checksum

View File

@ -52,7 +52,7 @@ impl CLI for CleanCommand {
// Get the package name
let path = current_dir()?;
let package_name = Manifest::try_from(&path)?.get_package_name();
let package_name = Manifest::try_from(path.as_path())?.get_package_name();
// Remove the checksum from the output directory
ChecksumFile::new(&package_name).remove(&path)?;

View File

@ -58,7 +58,7 @@ impl CLI for DeployCommand {
match BuildCommand::output(options)? {
Some((_program, _checksum_differs)) => {
// Get the package name
let _package_name = Manifest::try_from(&path)?.get_package_name();
let _package_name = Manifest::try_from(path.as_path())?.get_package_name();
tracing::error!("Unimplemented - `leo deploy`");

View File

@ -58,7 +58,7 @@ impl CLI for LintCommand {
match BuildCommand::output(options)? {
Some((_program, _checksum_differs)) => {
// Get the package name
let _package_name = Manifest::try_from(&path)?.get_package_name();
let _package_name = Manifest::try_from(path.as_path())?.get_package_name();
tracing::error!("Unimplemented - `leo lint`");

View File

@ -54,7 +54,7 @@ impl CLI for ProveCommand {
// Get the package name
let path = current_dir()?;
let package_name = Manifest::try_from(&path)?.get_package_name();
let package_name = Manifest::try_from(path.as_path())?.get_package_name();
tracing::info!("Starting...");

View File

@ -75,7 +75,7 @@ impl CLI for PublishCommand {
// Get the package manifest
let path = current_dir()?;
let package_manifest = Manifest::try_from(&path)?;
let package_manifest = Manifest::try_from(path.as_path())?;
let package_name = package_manifest.get_package_name();
let package_version = package_manifest.get_package_version();

View File

@ -62,7 +62,7 @@ impl CLI for SetupCommand {
fn output(options: Self::Options) -> Result<Self::Output, CLIError> {
// Get the package name
let path = current_dir()?;
let package_name = Manifest::try_from(&path)?.get_package_name();
let package_name = Manifest::try_from(path.as_path())?.get_package_name();
match BuildCommand::output(options)? {
Some((program, checksum_differs)) => {

View File

@ -56,7 +56,7 @@ impl CLI for TestCommand {
let path = current_dir()?;
// Get the package name
let manifest = Manifest::try_from(&path)?;
let manifest = Manifest::try_from(path.as_path())?;
let package_name = manifest.get_package_name();
// Sanitize the package path to the root directory
@ -96,7 +96,7 @@ impl CLI for TestCommand {
Compiler::<Fq, EdwardsGroupType>::parse_program_without_input(package_name, file_path, output_directory)?;
// Parse all inputs as input pairs
let pairs = InputPairs::try_from(&package_path)?;
let pairs = InputPairs::try_from(package_path.as_path())?;
// Run tests
let temporary_program = program;

View File

@ -159,7 +159,7 @@ impl_cli_error!(
impl From<clap::Error> for CLIError {
fn from(error: clap::Error) -> Self {
tracing::error!("{}\n", error);
CLIError::Crate("clap", format!("{}", error))
CLIError::Crate("clap", error.to_string())
}
}
@ -180,34 +180,34 @@ impl From<leo_input::errors::InputParserError> for CLIError {
impl From<reqwest::Error> for CLIError {
fn from(error: reqwest::Error) -> Self {
tracing::error!("{}\n", error);
CLIError::Crate("rewquest", format!("{}", error))
CLIError::Crate("rewquest", error.to_string())
}
}
impl From<snarkos_errors::algorithms::snark::SNARKError> for CLIError {
fn from(error: snarkos_errors::algorithms::snark::SNARKError) -> Self {
tracing::error!("{}\n", error);
CLIError::Crate("snarkos_errors", format!("{}", error))
CLIError::Crate("snarkos_errors", error.to_string())
}
}
impl From<snarkos_errors::gadgets::SynthesisError> for CLIError {
fn from(error: snarkos_errors::gadgets::SynthesisError) -> Self {
tracing::error!("{}\n", error);
CLIError::Crate("snarkos_errors", format!("{}", error))
CLIError::Crate("snarkos_errors", error.to_string())
}
}
impl From<serde_json::error::Error> for CLIError {
fn from(error: serde_json::error::Error) -> Self {
tracing::error!("{}\n", error);
CLIError::Crate("serde_json", format!("{}", error))
CLIError::Crate("serde_json", error.to_string())
}
}
impl From<std::io::Error> for CLIError {
fn from(error: std::io::Error) -> Self {
tracing::error!("{}\n", error);
CLIError::Crate("std::io", format!("{}", error))
CLIError::Crate("std::io", error.to_string())
}
}

View File

@ -75,9 +75,9 @@ impl Updater {
} else {
// If the auto update configuration is off, notify the user to update leo.
if let Some(latest_version) = Self::update_available().unwrap() {
let mut message = format!("{}", "🟢 A new version is available! Run".bold().green());
message += &format!("{}", " `leo update` ".bold().white());
message += &format!("{}", &(format!("to update to v{}.", latest_version)).bold().green());
let mut message = "🟢 A new version is available! Run".bold().green().to_string();
message += &" `leo update` ".bold().white();
message += &format!("to update to v{}.", latest_version).bold().green();
tracing::info!("\n{}\n", message);
}

View File

@ -33,6 +33,6 @@ pub enum InputFileError {
impl From<std::io::Error> for InputFileError {
fn from(error: std::io::Error) -> Self {
InputFileError::Crate("std::io", format!("{}", error))
InputFileError::Crate("std::io", error.to_string())
}
}

View File

@ -33,6 +33,6 @@ pub enum StateFileError {
impl From<std::io::Error> for StateFileError {
fn from(error: std::io::Error) -> Self {
StateFileError::Crate("std::io", format!("{}", error))
StateFileError::Crate("std::io", error.to_string())
}
}

View File

@ -36,6 +36,6 @@ pub enum ChecksumFileError {
impl From<std::io::Error> for ChecksumFileError {
fn from(error: std::io::Error) -> Self {
ChecksumFileError::Crate("std::io", format!("{}", error))
ChecksumFileError::Crate("std::io", error.to_string())
}
}

View File

@ -36,6 +36,6 @@ pub enum CircuitFileError {
impl From<std::io::Error> for CircuitFileError {
fn from(error: std::io::Error) -> Self {
CircuitFileError::Crate("std::io", format!("{}", error))
CircuitFileError::Crate("std::io", error.to_string())
}
}

View File

@ -36,6 +36,6 @@ pub enum ProofFileError {
impl From<std::io::Error> for ProofFileError {
fn from(error: std::io::Error) -> Self {
ProofFileError::Crate("std::io", format!("{}", error))
ProofFileError::Crate("std::io", error.to_string())
}
}

View File

@ -36,6 +36,6 @@ pub enum ProvingKeyFileError {
impl From<std::io::Error> for ProvingKeyFileError {
fn from(error: std::io::Error) -> Self {
ProvingKeyFileError::Crate("std::io", format!("{}", error))
ProvingKeyFileError::Crate("std::io", error.to_string())
}
}

View File

@ -39,6 +39,6 @@ pub enum VerificationKeyFileError {
impl From<std::io::Error> for VerificationKeyFileError {
fn from(error: std::io::Error) -> Self {
VerificationKeyFileError::Crate("std::io", format!("{}", error))
VerificationKeyFileError::Crate("std::io", error.to_string())
}
}

View File

@ -17,72 +17,72 @@ pub enum PackageError {
impl From<std::io::Error> for PackageError {
fn from(error: std::io::Error) -> Self {
PackageError::Crate("std::io", format!("{}", error))
PackageError::Crate("std::io", error.to_string())
}
}
impl From<crate::errors::GitignoreError> for PackageError {
fn from(error: crate::errors::GitignoreError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::InputFileError> for PackageError {
fn from(error: crate::errors::InputFileError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::InputsDirectoryError> for PackageError {
fn from(error: crate::errors::InputsDirectoryError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::ImportsDirectoryError> for PackageError {
fn from(error: crate::errors::ImportsDirectoryError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::OutputsDirectoryError> for PackageError {
fn from(error: crate::errors::OutputsDirectoryError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::READMEError> for PackageError {
fn from(error: crate::errors::READMEError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::SourceDirectoryError> for PackageError {
fn from(error: crate::errors::SourceDirectoryError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::StateFileError> for PackageError {
fn from(error: crate::errors::StateFileError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::LibraryFileError> for PackageError {
fn from(error: crate::errors::LibraryFileError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::ManifestError> for PackageError {
fn from(error: crate::errors::ManifestError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}
impl From<crate::errors::MainFileError> for PackageError {
fn from(error: crate::errors::MainFileError) -> Self {
PackageError::Crate("leo-package", format!("{}", error))
PackageError::Crate("leo-package", error.to_string())
}
}

View File

@ -30,6 +30,6 @@ pub enum GitignoreError {
impl From<std::io::Error> for GitignoreError {
fn from(error: std::io::Error) -> Self {
GitignoreError::Crate("std::io", format!("{}", error))
GitignoreError::Crate("std::io", error.to_string())
}
}

View File

@ -30,6 +30,6 @@ pub enum READMEError {
impl From<std::io::Error> for READMEError {
fn from(error: std::io::Error) -> Self {
READMEError::Crate("std::io", format!("{}", error))
READMEError::Crate("std::io", error.to_string())
}
}

View File

@ -44,6 +44,6 @@ pub enum ZipFileError {
impl From<std::io::Error> for ZipFileError {
fn from(error: std::io::Error) -> Self {
ZipFileError::Crate("std::io", format!("{}", error))
ZipFileError::Crate("std::io", error.to_string())
}
}

View File

@ -30,6 +30,6 @@ pub enum LibraryFileError {
impl From<std::io::Error> for LibraryFileError {
fn from(error: std::io::Error) -> Self {
LibraryFileError::Crate("std::io", format!("{}", error))
LibraryFileError::Crate("std::io", error.to_string())
}
}

View File

@ -30,6 +30,6 @@ pub enum MainFileError {
impl From<std::io::Error> for MainFileError {
fn from(error: std::io::Error) -> Self {
MainFileError::Crate("std::io", format!("{}", error))
MainFileError::Crate("std::io", error.to_string())
}
}

View File

@ -16,7 +16,7 @@
use crate::errors::ImportsDirectoryError;
use std::{fs, path::PathBuf};
use std::{borrow::Cow, fs, path::Path};
pub static IMPORTS_DIRECTORY_NAME: &str = "imports/";
@ -24,20 +24,20 @@ pub struct ImportsDirectory;
impl ImportsDirectory {
/// Creates a directory at the provided path with the default directory name.
pub fn create(path: &PathBuf) -> Result<(), ImportsDirectoryError> {
let mut path = path.to_owned();
pub fn create(path: &Path) -> Result<(), ImportsDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(IMPORTS_DIRECTORY_NAME) {
path.push(PathBuf::from(IMPORTS_DIRECTORY_NAME));
path.to_mut().push(IMPORTS_DIRECTORY_NAME);
}
fs::create_dir_all(&path).map_err(ImportsDirectoryError::Creating)
}
/// Removes the directory at the provided path.
pub fn remove(path: &PathBuf) -> Result<(), ImportsDirectoryError> {
let mut path = path.to_owned();
pub fn remove(path: &Path) -> Result<(), ImportsDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(IMPORTS_DIRECTORY_NAME) {
path.push(PathBuf::from(IMPORTS_DIRECTORY_NAME));
path.to_mut().push(IMPORTS_DIRECTORY_NAME);
}
if path.exists() {
@ -48,13 +48,13 @@ impl ImportsDirectory {
}
/// Removes an imported package in the imports directory at the provided path.
pub fn remove_import(path: &PathBuf, package_name: &str) -> Result<(), ImportsDirectoryError> {
let mut path = path.to_owned();
pub fn remove_import(path: &Path, package_name: &str) -> Result<(), ImportsDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(IMPORTS_DIRECTORY_NAME) {
path.push(PathBuf::from(IMPORTS_DIRECTORY_NAME));
path.to_mut().push(IMPORTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(package_name));
path.to_mut().push(package_name);
if !path.exists() || !path.is_dir() {
return Err(ImportsDirectoryError::ImportDoesNotExist(package_name.into()));

View File

@ -16,7 +16,12 @@
use crate::errors::InputsDirectoryError;
use std::{fs, fs::ReadDir, path::PathBuf};
use std::{
borrow::Cow,
fs,
fs::ReadDir,
path::{Path, PathBuf},
};
pub static INPUTS_DIRECTORY_NAME: &str = "inputs/";
@ -24,19 +29,19 @@ pub struct InputsDirectory;
impl InputsDirectory {
/// Creates a directory at the provided path with the default directory name.
pub fn create(path: &PathBuf) -> Result<(), InputsDirectoryError> {
let mut path = path.to_owned();
pub fn create(path: &Path) -> Result<(), InputsDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(INPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(INPUTS_DIRECTORY_NAME));
path.to_mut().push(INPUTS_DIRECTORY_NAME);
}
fs::create_dir_all(&path).map_err(InputsDirectoryError::Creating)
}
/// Returns a list of files in the input directory.
pub fn files(path: &PathBuf) -> Result<Vec<PathBuf>, InputsDirectoryError> {
pub fn files(path: &Path) -> Result<Vec<PathBuf>, InputsDirectoryError> {
let mut path = path.to_owned();
path.push(PathBuf::from(INPUTS_DIRECTORY_NAME));
path.push(INPUTS_DIRECTORY_NAME);
let directory = fs::read_dir(&path).map_err(InputsDirectoryError::Reading)?;
let mut file_paths = Vec::new();

View File

@ -20,9 +20,10 @@ use crate::{errors::InputFileError, inputs::INPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static INPUT_FILE_EXTENSION: &str = ".in";
@ -43,21 +44,23 @@ impl InputFile {
format!("{}{}{}", INPUTS_DIRECTORY_NAME, self.package_name, INPUT_FILE_EXTENSION)
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the program input variables from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<(String, PathBuf), InputFileError> {
pub fn read_from<'a>(&self, path: &'a Path) -> Result<(String, Cow<'a, Path>), InputFileError> {
let path = self.setup_file_path(path);
let input = fs::read_to_string(&path).map_err(|_| InputFileError::FileReadError(path.clone()))?;
Ok((input, path))
match fs::read_to_string(&path) {
Ok(input) => Ok((input, path)),
Err(_) => Err(InputFileError::FileReadError(path.into_owned())),
}
}
/// Writes the standard input format to a file.
pub fn write_to(self, path: &PathBuf) -> Result<(), InputFileError> {
pub fn write_to(self, path: &Path) -> Result<(), InputFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -78,13 +81,14 @@ r0: u32 = 0;
)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(INPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(INPUTS_DIRECTORY_NAME));
path.to_mut().push(INPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!("{}{}", self.package_name, INPUT_FILE_EXTENSION)));
path.to_mut()
.push(format!("{}{}", self.package_name, INPUT_FILE_EXTENSION));
}
path
}

View File

@ -19,7 +19,7 @@ use crate::{
InputsDirectoryError,
};
use std::{collections::HashMap, convert::TryFrom, path::PathBuf};
use std::{collections::HashMap, convert::TryFrom, path::Path};
#[derive(Default)]
pub struct InputPairs {
@ -38,10 +38,10 @@ impl InputPairs {
}
}
impl TryFrom<&PathBuf> for InputPairs {
impl TryFrom<&Path> for InputPairs {
type Error = InputsDirectoryError;
fn try_from(directory: &PathBuf) -> Result<Self, Self::Error> {
fn try_from(directory: &Path) -> Result<Self, Self::Error> {
let files = InputsDirectory::files(directory)?;
let mut pairs = HashMap::<String, InputPair>::new();

View File

@ -20,9 +20,10 @@ use crate::{errors::StateFileError, inputs::INPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static STATE_FILE_EXTENSION: &str = ".state";
@ -43,21 +44,23 @@ impl StateFile {
format!("{}{}{}", INPUTS_DIRECTORY_NAME, self.package_name, STATE_FILE_EXTENSION)
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the state input variables from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<(String, PathBuf), StateFileError> {
pub fn read_from<'a>(&self, path: &'a Path) -> Result<(String, Cow<'a, Path>), StateFileError> {
let path = self.setup_file_path(path);
let input = fs::read_to_string(&path).map_err(|_| StateFileError::FileReadError(path.clone()))?;
Ok((input, path))
match fs::read_to_string(&path) {
Ok(input) => Ok((input, path)),
Err(_) => Err(StateFileError::FileReadError(path.into_owned())),
}
}
/// Writes the standard input format to a file.
pub fn write_to(self, path: &PathBuf) -> Result<(), StateFileError> {
pub fn write_to(self, path: &Path) -> Result<(), StateFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -97,13 +100,14 @@ leaf_randomness: [u8; 32] = [0; 32];
)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(INPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(INPUTS_DIRECTORY_NAME));
path.to_mut().push(INPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!("{}{}", self.package_name, STATE_FILE_EXTENSION)));
path.to_mut()
.push(format!("{}{}", self.package_name, STATE_FILE_EXTENSION));
}
path
}

View File

@ -27,18 +27,18 @@ pub mod package;
pub mod root;
pub mod source;
use std::path::PathBuf;
use std::path::Path;
pub struct LeoPackage;
impl LeoPackage {
/// Initializes a Leo package at the given path.
pub fn initialize(package_name: &str, is_lib: bool, path: &PathBuf) -> Result<(), PackageError> {
pub fn initialize(package_name: &str, is_lib: bool, path: &Path) -> Result<(), PackageError> {
package::Package::initialize(package_name, is_lib, path)
}
/// Removes an imported Leo package
pub fn remove_imported_package(package_name: &str, path: &PathBuf) -> Result<(), PackageError> {
pub fn remove_imported_package(package_name: &str, path: &Path) -> Result<(), PackageError> {
package::Package::remove_imported_package(package_name, path)
}
}

View File

@ -20,9 +20,10 @@ use crate::{errors::ChecksumFileError, outputs::OUTPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static CHECKSUM_FILE_EXTENSION: &str = ".sum";
@ -39,20 +40,20 @@ impl ChecksumFile {
}
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the checksum from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<String, ChecksumFileError> {
pub fn read_from(&self, path: &Path) -> Result<String, ChecksumFileError> {
let path = self.setup_file_path(path);
Ok(fs::read_to_string(&path).map_err(|_| ChecksumFileError::FileReadError(path.clone()))?)
Ok(fs::read_to_string(&path).map_err(|_| ChecksumFileError::FileReadError(path.into_owned()))?)
}
/// Writes the given checksum to a file.
pub fn write_to(&self, path: &PathBuf, checksum: String) -> Result<(), ChecksumFileError> {
pub fn write_to(&self, path: &Path, checksum: String) -> Result<(), ChecksumFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -63,26 +64,24 @@ impl ChecksumFile {
/// Removes the checksum at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, ChecksumFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, ChecksumFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| ChecksumFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| ChecksumFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!(
"{}{}",
self.package_name, CHECKSUM_FILE_EXTENSION
)));
path.to_mut()
.push(format!("{}{}", self.package_name, CHECKSUM_FILE_EXTENSION));
}
path
}

View File

@ -20,9 +20,10 @@ use crate::{errors::CircuitFileError, outputs::OUTPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static CIRCUIT_FILE_EXTENSION: &str = ".json";
@ -39,20 +40,20 @@ impl CircuitFile {
}
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the serialized circuit from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<String, CircuitFileError> {
pub fn read_from(&self, path: &Path) -> Result<String, CircuitFileError> {
let path = self.setup_file_path(path);
Ok(fs::read_to_string(&path).map_err(|_| CircuitFileError::FileReadError(path.clone()))?)
Ok(fs::read_to_string(&path).map_err(|_| CircuitFileError::FileReadError(path.into_owned()))?)
}
/// Writes the given serialized circuit to a file.
pub fn write_to(&self, path: &PathBuf, circuit: String) -> Result<(), CircuitFileError> {
pub fn write_to(&self, path: &Path, circuit: String) -> Result<(), CircuitFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -63,26 +64,24 @@ impl CircuitFile {
/// Removes the serialized circuit at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, CircuitFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, CircuitFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| CircuitFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| CircuitFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!(
"{}{}",
self.package_name, CIRCUIT_FILE_EXTENSION
)));
path.to_mut()
.push(format!("{}{}", self.package_name, CIRCUIT_FILE_EXTENSION));
}
path
}

View File

@ -16,7 +16,7 @@
use crate::errors::OutputsDirectoryError;
use std::{fs, path::PathBuf};
use std::{borrow::Cow, fs, path::Path};
pub static OUTPUTS_DIRECTORY_NAME: &str = "outputs/";
@ -24,20 +24,20 @@ pub struct OutputsDirectory;
impl OutputsDirectory {
/// Creates a directory at the provided path with the default directory name.
pub fn create(path: &PathBuf) -> Result<(), OutputsDirectoryError> {
let mut path = path.to_owned();
pub fn create(path: &Path) -> Result<(), OutputsDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
fs::create_dir_all(&path).map_err(OutputsDirectoryError::Creating)
}
/// Removes the directory at the provided path.
pub fn remove(path: &PathBuf) -> Result<(), OutputsDirectoryError> {
let mut path = path.to_owned();
pub fn remove(path: &Path) -> Result<(), OutputsDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
if path.exists() {

View File

@ -20,9 +20,10 @@ use crate::{errors::ProofFileError, outputs::OUTPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static PROOF_FILE_EXTENSION: &str = ".proof";
@ -39,21 +40,21 @@ impl ProofFile {
}
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the proof from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<String, ProofFileError> {
pub fn read_from(&self, path: &Path) -> Result<String, ProofFileError> {
let path = self.setup_file_path(path);
let proof = fs::read_to_string(&path).map_err(|_| ProofFileError::FileReadError(path.clone()))?;
let proof = fs::read_to_string(&path).map_err(|_| ProofFileError::FileReadError(path.into_owned()))?;
Ok(proof)
}
/// Writes the given proof to a file.
pub fn write_to(&self, path: &PathBuf, proof: &[u8]) -> Result<(), ProofFileError> {
pub fn write_to(&self, path: &Path, proof: &[u8]) -> Result<(), ProofFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -66,23 +67,24 @@ impl ProofFile {
/// Removes the proof at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, ProofFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, ProofFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| ProofFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| ProofFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!("{}{}", self.package_name, PROOF_FILE_EXTENSION)));
path.to_mut()
.push(format!("{}{}", self.package_name, PROOF_FILE_EXTENSION));
}
path
}

View File

@ -20,9 +20,10 @@ use crate::{errors::ProvingKeyFileError, outputs::OUTPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static PROVING_KEY_FILE_EXTENSION: &str = ".lpk";
@ -39,24 +40,24 @@ impl ProvingKeyFile {
}
}
pub fn full_path(&self, path: &PathBuf) -> PathBuf {
pub fn full_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
self.setup_file_path(path)
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the proving key from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<Vec<u8>, ProvingKeyFileError> {
pub fn read_from(&self, path: &Path) -> Result<Vec<u8>, ProvingKeyFileError> {
let path = self.setup_file_path(path);
Ok(fs::read(&path).map_err(|_| ProvingKeyFileError::FileReadError(path.clone()))?)
Ok(fs::read(&path).map_err(|_| ProvingKeyFileError::FileReadError(path.into_owned()))?)
}
/// Writes the given proving key to a file.
pub fn write_to(&self, path: &PathBuf, proving_key: &[u8]) -> Result<PathBuf, ProvingKeyFileError> {
pub fn write_to<'a>(&self, path: &'a Path, proving_key: &[u8]) -> Result<Cow<'a, Path>, ProvingKeyFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -67,26 +68,24 @@ impl ProvingKeyFile {
/// Removes the proving key at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, ProvingKeyFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, ProvingKeyFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| ProvingKeyFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| ProvingKeyFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!(
"{}{}",
self.package_name, PROVING_KEY_FILE_EXTENSION
)));
path.to_mut()
.push(format!("{}{}", self.package_name, PROVING_KEY_FILE_EXTENSION));
}
path
}

View File

@ -20,9 +20,10 @@ use crate::{errors::VerificationKeyFileError, outputs::OUTPUTS_DIRECTORY_NAME};
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::Write,
path::PathBuf,
path::Path,
};
pub static VERIFICATION_KEY_FILE_EXTENSION: &str = ".lvk";
@ -39,24 +40,28 @@ impl VerificationKeyFile {
}
}
pub fn full_path(&self, path: &PathBuf) -> PathBuf {
pub fn full_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
self.setup_file_path(path)
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
/// Reads the verification key from the given file path if it exists.
pub fn read_from(&self, path: &PathBuf) -> Result<Vec<u8>, VerificationKeyFileError> {
pub fn read_from(&self, path: &Path) -> Result<Vec<u8>, VerificationKeyFileError> {
let path = self.setup_file_path(path);
Ok(fs::read(&path).map_err(|_| VerificationKeyFileError::FileReadError(path.clone()))?)
Ok(fs::read(&path).map_err(|_| VerificationKeyFileError::FileReadError(path.into_owned()))?)
}
/// Writes the given verification key to a file.
pub fn write_to(&self, path: &PathBuf, verification_key: &[u8]) -> Result<PathBuf, VerificationKeyFileError> {
pub fn write_to<'a>(
&self,
path: &'a Path,
verification_key: &[u8],
) -> Result<Cow<'a, Path>, VerificationKeyFileError> {
let path = self.setup_file_path(path);
let mut file = File::create(&path)?;
@ -67,26 +72,24 @@ impl VerificationKeyFile {
/// Removes the verification key at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, VerificationKeyFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, VerificationKeyFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| VerificationKeyFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| VerificationKeyFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!(
"{}{}",
self.package_name, VERIFICATION_KEY_FILE_EXTENSION
)));
path.to_mut()
.push(format!("{}{}", self.package_name, VERIFICATION_KEY_FILE_EXTENSION));
}
path
}

View File

@ -23,7 +23,7 @@ use crate::{
};
use serde::Deserialize;
use std::path::PathBuf;
use std::path::Path;
#[derive(Deserialize)]
pub struct Package {
@ -44,39 +44,39 @@ impl Package {
}
/// Returns `true` if a package is can be initialized at a given path.
pub fn can_initialize(package_name: &str, is_lib: bool, path: &PathBuf) -> bool {
pub fn can_initialize(package_name: &str, is_lib: bool, path: &Path) -> bool {
let mut result = true;
let mut existing_files = vec![];
// Check if the manifest file already exists.
if Manifest::exists_at(&path) {
if Manifest::exists_at(path) {
existing_files.push(Manifest::filename());
result = false;
}
if is_lib {
// Check if the library file already exists.
if LibraryFile::exists_at(&path) {
if LibraryFile::exists_at(path) {
existing_files.push(LibraryFile::filename());
result = false;
}
} else {
// Check if the input file already exists.
let input_file = InputFile::new(&package_name);
if input_file.exists_at(&path) {
if input_file.exists_at(path) {
existing_files.push(input_file.filename());
result = false;
}
// Check if the state file already exists.
let state_file = StateFile::new(&package_name);
if state_file.exists_at(&path) {
if state_file.exists_at(path) {
existing_files.push(state_file.filename());
result = false;
}
// Check if the main file already exists.
if MainFile::exists_at(&path) {
if MainFile::exists_at(path) {
existing_files.push(MainFile::filename());
result = false;
}
@ -90,7 +90,7 @@ impl Package {
}
/// Returns `true` if a package is initialized at the given path
pub fn is_initialized(package_name: &str, is_lib: bool, path: &PathBuf) -> bool {
pub fn is_initialized(package_name: &str, is_lib: bool, path: &Path) -> bool {
// Check if the manifest file exists.
if !Manifest::exists_at(&path) {
return false;
@ -124,7 +124,7 @@ impl Package {
}
/// Creates a package at the given path
pub fn initialize(package_name: &str, is_lib: bool, path: &PathBuf) -> Result<(), PackageError> {
pub fn initialize(package_name: &str, is_lib: bool, path: &Path) -> Result<(), PackageError> {
// First, verify that this directory is not already initialized as a Leo package.
{
if !Self::can_initialize(package_name, is_lib, path) {
@ -186,7 +186,7 @@ impl Package {
}
/// Removes the package at the given path
pub fn remove_imported_package(package_name: &str, path: &PathBuf) -> Result<(), PackageError> {
pub fn remove_imported_package(package_name: &str, path: &Path) -> Result<(), PackageError> {
Ok(ImportsDirectory::remove_import(path, package_name)?)
}
}

View File

@ -19,7 +19,7 @@
use crate::errors::GitignoreError;
use serde::Deserialize;
use std::{fs::File, io::Write, path::PathBuf};
use std::{borrow::Cow, fs::File, io::Write, path::Path};
pub static GITIGNORE_FILENAME: &str = ".gitignore";
@ -31,18 +31,18 @@ impl Gitignore {
Self::default()
}
pub fn exists_at(path: &PathBuf) -> bool {
let mut path = path.to_owned();
pub fn exists_at(path: &Path) -> bool {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(GITIGNORE_FILENAME));
path.to_mut().push(GITIGNORE_FILENAME);
}
path.exists()
}
pub fn write_to(self, path: &PathBuf) -> Result<(), GitignoreError> {
let mut path = path.to_owned();
pub fn write_to(self, path: &Path) -> Result<(), GitignoreError> {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(GITIGNORE_FILENAME));
path.to_mut().push(GITIGNORE_FILENAME);
}
let mut file = File::create(&path)?;

View File

@ -18,10 +18,11 @@ use crate::{errors::ManifestError, package::Package};
use serde::Deserialize;
use std::{
borrow::Cow,
convert::TryFrom,
fs::File,
io::{Read, Write},
path::PathBuf,
path::Path,
};
pub const MANIFEST_FILENAME: &str = "Leo.toml";
@ -49,10 +50,10 @@ impl Manifest {
MANIFEST_FILENAME.to_string()
}
pub fn exists_at(path: &PathBuf) -> bool {
let mut path = path.to_owned();
pub fn exists_at(path: &Path) -> bool {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(MANIFEST_FILENAME));
path.to_mut().push(MANIFEST_FILENAME);
}
path.exists()
}
@ -77,10 +78,10 @@ impl Manifest {
self.remote.clone()
}
pub fn write_to(self, path: &PathBuf) -> Result<(), ManifestError> {
let mut path = path.to_owned();
pub fn write_to(self, path: &Path) -> Result<(), ManifestError> {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(MANIFEST_FILENAME));
path.to_mut().push(MANIFEST_FILENAME);
}
let mut file = File::create(&path).map_err(|error| ManifestError::Creating(MANIFEST_FILENAME, error))?;
@ -104,13 +105,13 @@ author = "[AUTHOR]" # Add your Aleo Package Manager username, team's name, or or
}
}
impl TryFrom<&PathBuf> for Manifest {
impl TryFrom<&Path> for Manifest {
type Error = ManifestError;
fn try_from(path: &PathBuf) -> Result<Self, Self::Error> {
let mut path = path.to_owned();
fn try_from(path: &Path) -> Result<Self, Self::Error> {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(MANIFEST_FILENAME));
path.to_mut().push(MANIFEST_FILENAME);
}
let mut file = File::open(path.clone()).map_err(|error| ManifestError::Opening(MANIFEST_FILENAME, error))?;

View File

@ -19,7 +19,7 @@
use crate::errors::READMEError;
use serde::Deserialize;
use std::{fs::File, io::Write, path::PathBuf};
use std::{borrow::Cow, fs::File, io::Write, path::Path};
pub static README_FILENAME: &str = "README.md";
@ -39,18 +39,18 @@ impl README {
self.package_name.clone()
}
pub fn exists_at(path: &PathBuf) -> bool {
let mut path = path.to_owned();
pub fn exists_at(path: &Path) -> bool {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(README_FILENAME));
path.to_mut().push(README_FILENAME);
}
path.exists()
}
pub fn write_to(self, path: &PathBuf) -> Result<(), READMEError> {
let mut path = path.to_owned();
pub fn write_to(self, path: &Path) -> Result<(), READMEError> {
let mut path = Cow::from(path);
if path.is_dir() {
path.push(PathBuf::from(README_FILENAME));
path.to_mut().push(README_FILENAME);
}
let mut file = File::create(&path)?;

View File

@ -34,9 +34,10 @@ use crate::{
use serde::Deserialize;
use std::{
borrow::Cow,
fs::{self, File},
io::{Read, Write},
path::{Path, PathBuf},
path::Path,
};
use walkdir::WalkDir;
use zip::write::{FileOptions, ZipWriter};
@ -55,26 +56,26 @@ impl ZipFile {
}
}
pub fn exists_at(&self, path: &PathBuf) -> bool {
pub fn exists_at(&self, path: &Path) -> bool {
let path = self.setup_file_path(path);
path.exists()
}
pub fn get_file_path(&self, current_dir: &PathBuf) -> PathBuf {
pub fn get_file_path<'a>(&self, current_dir: &'a Path) -> Cow<'a, Path> {
self.setup_file_path(current_dir)
}
// /// Reads the program bytes from the given file path if it exists.
// pub fn read_from(&self, path: &PathBuf) -> Result<Vec<u8>, ZipFileError> {
// pub fn read_from(&self, path: &Path) -> Result<Vec<u8>, ZipFileError> {
// let path = self.setup_file_path(path);
//
// Ok(fs::read(&path).map_err(|_| ZipFileError::FileReadError(path.clone()))?)
// }
/// Writes the current package contents to a zip file.
pub fn write(&self, src_dir: &PathBuf) -> Result<(), ZipFileError> {
pub fn write(&self, src_dir: &Path) -> Result<(), ZipFileError> {
// Build walkdir iterator from current package
let walkdir = WalkDir::new(src_dir.clone());
let walkdir = WalkDir::new(src_dir);
// Create zip file
let path = self.setup_file_path(src_dir);
@ -89,7 +90,7 @@ impl ZipFile {
let mut buffer = Vec::new();
for entry in walkdir.into_iter().filter_map(|e| e.ok()) {
let path = entry.path();
let name = path.strip_prefix(src_dir.as_path()).unwrap();
let name = path.strip_prefix(src_dir).unwrap();
// Add file/directory exclusion
@ -125,23 +126,24 @@ impl ZipFile {
/// Removes the zip file at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, ZipFileError> {
pub fn remove(&self, path: &Path) -> Result<bool, ZipFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| ZipFileError::FileRemovalError(path.clone()))?;
fs::remove_file(&path).map_err(|_| ZipFileError::FileRemovalError(path.into_owned()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
fn setup_file_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(OUTPUTS_DIRECTORY_NAME) {
path.push(PathBuf::from(OUTPUTS_DIRECTORY_NAME));
path.to_mut().push(OUTPUTS_DIRECTORY_NAME);
}
path.push(PathBuf::from(format!("{}{}", self.package_name, ZIP_FILE_EXTENSION)));
path.to_mut()
.push(format!("{}{}", self.package_name, ZIP_FILE_EXTENSION));
}
path
}

View File

@ -16,7 +16,11 @@
use crate::errors::SourceDirectoryError;
use std::{fs, path::PathBuf};
use std::{
borrow::Cow,
fs,
path::{Path, PathBuf},
};
pub static SOURCE_DIRECTORY_NAME: &str = "src/";
@ -26,19 +30,19 @@ pub struct SourceDirectory;
impl SourceDirectory {
/// Creates a directory at the provided path with the default directory name.
pub fn create(path: &PathBuf) -> Result<(), SourceDirectoryError> {
let mut path = path.to_owned();
pub fn create(path: &Path) -> Result<(), SourceDirectoryError> {
let mut path = Cow::from(path);
if path.is_dir() && !path.ends_with(SOURCE_DIRECTORY_NAME) {
path.push(PathBuf::from(SOURCE_DIRECTORY_NAME));
path.to_mut().push(SOURCE_DIRECTORY_NAME);
}
fs::create_dir_all(&path).map_err(SourceDirectoryError::Creating)
}
/// Returns a list of files in the source directory.
pub fn files(path: &PathBuf) -> Result<Vec<PathBuf>, SourceDirectoryError> {
let mut path = path.to_owned();
path.push(PathBuf::from(SOURCE_DIRECTORY_NAME));
pub fn files(path: &Path) -> Result<Vec<PathBuf>, SourceDirectoryError> {
let mut path = Cow::from(path);
path.to_mut().push(SOURCE_DIRECTORY_NAME);
let directory = fs::read_dir(&path).map_err(SourceDirectoryError::Reading)?;
let mut file_paths = Vec::new();

View File

@ -19,7 +19,7 @@
use crate::{errors::LibraryFileError, source::directory::SOURCE_DIRECTORY_NAME};
use serde::Deserialize;
use std::{fs::File, io::Write, path::PathBuf};
use std::{borrow::Cow, fs::File, io::Write, path::Path};
pub static LIBRARY_FILENAME: &str = "lib.leo";
@ -39,24 +39,24 @@ impl LibraryFile {
format!("{}{}", SOURCE_DIRECTORY_NAME, LIBRARY_FILENAME)
}
pub fn exists_at(path: &PathBuf) -> bool {
let mut path = path.to_owned();
pub fn exists_at(path: &Path) -> bool {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(SOURCE_DIRECTORY_NAME) {
path.push(PathBuf::from(SOURCE_DIRECTORY_NAME));
path.to_mut().push(SOURCE_DIRECTORY_NAME);
}
path.push(PathBuf::from(LIBRARY_FILENAME));
path.to_mut().push(LIBRARY_FILENAME);
}
path.exists()
}
pub fn write_to(self, path: &PathBuf) -> Result<(), LibraryFileError> {
let mut path = path.to_owned();
pub fn write_to(self, path: &Path) -> Result<(), LibraryFileError> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(SOURCE_DIRECTORY_NAME) {
path.push(PathBuf::from(SOURCE_DIRECTORY_NAME));
path.to_mut().push(SOURCE_DIRECTORY_NAME);
}
path.push(PathBuf::from(LIBRARY_FILENAME));
path.to_mut().push(LIBRARY_FILENAME);
}
let mut file = File::create(&path)?;

View File

@ -19,7 +19,7 @@
use crate::{errors::MainFileError, source::directory::SOURCE_DIRECTORY_NAME};
use serde::Deserialize;
use std::{fs::File, io::Write, path::PathBuf};
use std::{borrow::Cow, fs::File, io::Write, path::Path};
pub static MAIN_FILENAME: &str = "main.leo";
@ -39,24 +39,24 @@ impl MainFile {
format!("{}{}", SOURCE_DIRECTORY_NAME, MAIN_FILENAME)
}
pub fn exists_at(path: &PathBuf) -> bool {
let mut path = path.to_owned();
pub fn exists_at(path: &Path) -> bool {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(SOURCE_DIRECTORY_NAME) {
path.push(PathBuf::from(SOURCE_DIRECTORY_NAME));
path.to_mut().push(SOURCE_DIRECTORY_NAME);
}
path.push(PathBuf::from(MAIN_FILENAME));
path.to_mut().push(MAIN_FILENAME);
}
path.exists()
}
pub fn write_to(self, path: &PathBuf) -> Result<(), MainFileError> {
let mut path = path.to_owned();
pub fn write_to(self, path: &Path) -> Result<(), MainFileError> {
let mut path = Cow::from(path);
if path.is_dir() {
if !path.ends_with(SOURCE_DIRECTORY_NAME) {
path.push(PathBuf::from(SOURCE_DIRECTORY_NAME));
path.to_mut().push(SOURCE_DIRECTORY_NAME);
}
path.push(PathBuf::from(MAIN_FILENAME));
path.to_mut().push(MAIN_FILENAME);
}
let mut file = File::create(&path)?;

View File

@ -23,7 +23,7 @@ use std::{
convert::TryFrom,
fs::File,
io::{Read, Write},
path::PathBuf,
path::{Path, PathBuf},
};
const OLD_MANIFEST_FORMAT: &str = r#"[package]
@ -46,7 +46,7 @@ const NEW_PROJECT_FORMAT: &str = "[project]";
fn create_outdated_manifest_file(path: PathBuf) -> PathBuf {
let mut path = path;
if path.is_dir() {
path.push(PathBuf::from(MANIFEST_FILENAME));
path.push(MANIFEST_FILENAME);
}
let mut file = File::create(&path).unwrap();
@ -56,8 +56,8 @@ fn create_outdated_manifest_file(path: PathBuf) -> PathBuf {
}
/// Read the manifest file into a string.
fn read_manifest_file(path: &PathBuf) -> String {
let mut file = File::open(path.clone()).unwrap();
fn read_manifest_file(path: &Path) -> String {
let mut file = File::open(path).unwrap();
let size = file.metadata().unwrap().len() as usize;
let mut buffer = String::with_capacity(size);
@ -67,7 +67,7 @@ fn read_manifest_file(path: &PathBuf) -> String {
}
/// Read the manifest file and check that the remote format is updated.
fn remote_is_updated(path: &PathBuf) -> bool {
fn remote_is_updated(path: &Path) -> bool {
let manifest_string = read_manifest_file(&path);
for line in manifest_string.lines() {
if line.starts_with("remote") {
@ -79,7 +79,7 @@ fn remote_is_updated(path: &PathBuf) -> bool {
}
/// Read the manifest file and check that the project format is updated.
fn project_is_updated(path: &PathBuf) -> bool {
fn project_is_updated(path: &Path) -> bool {
let manifest_string = read_manifest_file(&path);
!manifest_string.contains(OLD_PROJECT_FORMAT) && manifest_string.contains(NEW_PROJECT_FORMAT)
@ -96,7 +96,7 @@ fn test_manifest_no_refactors() {
let manifest_path = create_outdated_manifest_file(test_directory);
// Load the manifest file, and discard the new struct.
let _manifest = Manifest::try_from(&manifest_path).unwrap();
let _manifest = Manifest::try_from(manifest_path.as_path()).unwrap();
// Check that the manifest file project has NOT been updated.
assert!(!project_is_updated(&manifest_path));
@ -116,7 +116,7 @@ fn test_manifest_refactor_remote() {
let manifest_path = create_outdated_manifest_file(test_directory);
// Load the manifest file, and discard the new struct.
let _manifest = Manifest::try_from(&manifest_path).unwrap();
let _manifest = Manifest::try_from(manifest_path.as_path()).unwrap();
// Check that the manifest file project has NOT been updated.
assert!(!project_is_updated(&manifest_path));
@ -136,7 +136,7 @@ fn test_manifest_refactor_project() {
let manifest_path = create_outdated_manifest_file(test_directory);
// Load the manifest file, and discard the new struct.
let _manifest = Manifest::try_from(&manifest_path).unwrap();
let _manifest = Manifest::try_from(manifest_path.as_path()).unwrap();
// Check that the manifest file project has been updated.
assert!(project_is_updated(&manifest_path));
@ -159,7 +159,7 @@ fn test_manifest_refactors() {
let manifest_path = create_outdated_manifest_file(test_directory);
// Load the manifest file, and discard the new struct.
let _manifest = Manifest::try_from(&manifest_path).unwrap();
let _manifest = Manifest::try_from(manifest_path.as_path()).unwrap();
// Check that the manifest file project has been updated.
assert!(project_is_updated(&manifest_path));

View File

@ -58,7 +58,7 @@ impl TryFrom<&TypedRecord> for DPCRecordValues {
// Lookup record owner
let owner_value = find_input(OWNER_PARAMETER_STRING.to_owned(), &parameters)?;
let owner = AccountAddress::<Components>::from_str(&format!("{}", owner_value))?;
let owner = AccountAddress::<Components>::from_str(&owner_value.to_string())?;
// Lookup record is_dummy
let is_dummy_value = find_input(IS_DUMMY_PARAMETER_STRING.to_owned(), &parameters)?;

View File

@ -44,12 +44,7 @@ impl fmt::Display for Variables {
write!(f, "{}", self.names[0])?;
} else {
// (a, mut b)
let names = self
.names
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join(",");
let names = self.names.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");
write!(f, "({})", names)?;
}

View File

@ -16,7 +16,7 @@
use crate::Span;
use std::{fmt, path::PathBuf};
use std::{fmt, path::Path};
pub const INDENT: &str = " ";
@ -55,7 +55,7 @@ impl Error {
}
}
pub fn new_from_span_with_path(message: String, span: Span, path: PathBuf) -> Self {
pub fn new_from_span_with_path(message: String, span: Span, path: &Path) -> Self {
Self {
path: Some(format!("{:?}", path)),
line: span.line,
@ -66,7 +66,7 @@ impl Error {
}
}
pub fn set_path(&mut self, path: PathBuf) {
pub fn set_path(&mut self, path: &Path) {
self.path = Some(format!("{:?}", path));
}
@ -136,7 +136,7 @@ fn test_error() {
};
assert_eq!(
format!("{}", err),
err.to_string(),
vec![
" --> file.leo: 2:8",
" |",

View File

@ -242,7 +242,7 @@ impl<'ast> fmt::Display for Expression {
// Tuples
Expression::Tuple(ref tuple, ref _span) => {
let values = tuple.iter().map(|x| format!("{}", x)).collect::<Vec<_>>().join(", ");
let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", values)
}

View File

@ -61,13 +61,8 @@ impl Function {
fn format(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "function {}", self.identifier)?;
let parameters = self
.input
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join(",");
let returns = self.returns.as_ref().map(|type_| format!("{}", type_));
let parameters = self.input.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");
let returns = self.returns.as_ref().map(|type_| type_.to_string());
let statements = self
.statements
.iter()

View File

@ -260,12 +260,12 @@ impl fmt::Display for InputValue {
InputValue::Field(ref field) => write!(f, "{}", field),
InputValue::Integer(ref type_, ref number) => write!(f, "{}{:?}", number, type_),
InputValue::Array(ref array) => {
let values = array.iter().map(|x| format!("{}", x)).collect::<Vec<_>>().join(", ");
let values = array.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "array [{}]", values)
}
InputValue::Tuple(ref tuple) => {
let values = tuple.iter().map(|x| format!("{}", x)).collect::<Vec<_>>().join(", ");
let values = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", values)
}

View File

@ -189,11 +189,7 @@ impl fmt::Display for Statement {
match *self {
Statement::Return(ref expression, ref _span) => write!(f, "return {}", expression),
Statement::Definition(ref declare, ref variable, ref expressions, ref _span) => {
let formatted_expressions = expressions
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join(",");
let formatted_expressions = expressions.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");
write!(f, "{} {} = {};", declare, variable, formatted_expressions)
}

View File

@ -217,15 +217,11 @@ impl fmt::Display for Type {
Type::Circuit(ref variable) => write!(f, "circuit {}", variable),
Type::SelfType => write!(f, "SelfType"),
Type::Array(ref array, ref dimensions) => {
let dimensions = dimensions
.iter()
.map(|x| format!("{}", x))
.collect::<Vec<_>>()
.join(", ");
let dimensions = dimensions.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "[{}; ({})]", *array, dimensions)
}
Type::Tuple(ref tuple) => {
let types = tuple.iter().map(|x| format!("{}", x)).collect::<Vec<_>>().join(", ");
let types = tuple.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ");
write!(f, "({})", types)
}

View File

@ -17,9 +17,9 @@
use leo_ast::LeoAst;
use leo_typed::LeoTypedAst;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
fn to_typed_ast(program_filepath: &PathBuf) -> LeoTypedAst {
fn to_typed_ast(program_filepath: &Path) -> LeoTypedAst {
// Loads the Leo code as a string from the given file path.
let program_string = LeoAst::load_file(program_filepath).unwrap();