Compiler wip

This commit is contained in:
howardwu 2020-04-23 23:57:05 -07:00
parent 0a49dd1ec3
commit 8c5be763ff
21 changed files with 606 additions and 153 deletions

125
Cargo.lock generated
View File

@ -233,6 +233,17 @@ dependencies = [
"bitflags",
]
[[package]]
name = "colored"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4ffc801dacf156c5854b9df4f425a626539c3a6ef7893cc0c5084a23f0b6c59"
dependencies = [
"atty",
"lazy_static",
"winapi",
]
[[package]]
name = "constant_time_eq"
version = "0.1.5"
@ -507,6 +518,15 @@ dependencies = [
"winapi",
]
[[package]]
name = "heck"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "hermit-abi"
version = "0.1.8"
@ -591,17 +611,21 @@ checksum = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f"
name = "leo"
version = "0.1.0"
dependencies = [
"clap",
"colored",
"failure",
"from-pest",
"lazy_static",
"pest",
"pest-ast",
"pest_derive",
"rand 0.7.3",
"rand_core 0.5.1",
"serde",
"serde_json",
"snarkos-algorithms",
"snarkos-curves",
"snarkos-errors",
"snarkos-gadgets",
"snarkos-models",
"structopt",
"toml",
]
[[package]]
@ -618,20 +642,6 @@ dependencies = [
"snarkos-models",
]
[[package]]
name = "leo-compiler"
version = "0.1.0"
dependencies = [
"from-pest",
"leo-program",
"rand 0.7.3",
"snarkos-algorithms",
"snarkos-curves",
"snarkos-errors",
"snarkos-gadgets",
"snarkos-models",
]
[[package]]
name = "leo-program"
version = "0.1.0"
@ -807,6 +817,32 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b"
[[package]]
name = "proc-macro-error"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98e9e4b82e0ef281812565ea4751049f1bdcdfccda7d3f459f2e138a40c08678"
dependencies = [
"proc-macro-error-attr",
"proc-macro2 1.0.9",
"quote 1.0.3",
"syn 1.0.16",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f5444ead4e9935abd7f27dc51f7e852a0569ac888096d5ec2499470794e2e53"
dependencies = [
"proc-macro2 1.0.9",
"quote 1.0.3",
"syn 1.0.16",
"syn-mid",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "0.4.30"
@ -1159,6 +1195,9 @@ name = "serde"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
@ -1312,6 +1351,30 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "structopt"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863246aaf5ddd0d6928dfeb1a9ca65f505599e4e1b399935ef7e75107516b4ef"
dependencies = [
"clap",
"lazy_static",
"structopt-derive",
]
[[package]]
name = "structopt-derive"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d239ca4b13aee7a2142e6795cbd69e457665ff8037aed33b3effdc430d2f927a"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2 1.0.9",
"quote 1.0.3",
"syn 1.0.16",
]
[[package]]
name = "subtle"
version = "1.0.0"
@ -1340,6 +1403,17 @@ dependencies = [
"unicode-xid 0.2.0",
]
[[package]]
name = "syn-mid"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7be3539f6c128a931cf19dcee741c1af532c7fd387baa739c03dd2e96479338a"
dependencies = [
"proc-macro2 1.0.9",
"quote 1.0.3",
"syn 1.0.16",
]
[[package]]
name = "synstructure"
version = "0.12.3"
@ -1388,6 +1462,15 @@ dependencies = [
"crunchy 0.2.2",
]
[[package]]
name = "toml"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffc92d160b1eef40665be3a05630d003936a3bc7da7421277846c2613e92c71a"
dependencies = [
"serde",
]
[[package]]
name = "typenum"
version = "1.11.2"
@ -1412,6 +1495,12 @@ dependencies = [
"rustc-hex",
]
[[package]]
name = "unicode-segmentation"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
[[package]]
name = "unicode-width"
version = "0.1.7"

View File

@ -6,14 +6,14 @@ edition = "2018"
[lib]
name = "leo"
path = "program/src/lib.rs"
path = "leo/lib.rs"
[[bin]]
name = "leo"
path = "benchmark/src/main.rs"
path = "leo/main.rs"
[workspace]
members = [ "benchmark", "compiler", "program" ]
members = [ "benchmark", "program" ]
[dependencies]
snarkos-algorithms = { path = "../snarkOS/algorithms", version = "0.8.0" }
@ -22,9 +22,13 @@ snarkos-errors = { path = "../snarkOS/errors", version = "0.8.0" }
snarkos-gadgets = { path = "../snarkOS/gadgets", version = "0.8.0" }
snarkos-models = { path = "../snarkOS/models", version = "0.8.0" }
clap = { version = "2.33.0" }
colored = { version = "1.9" }
failure = { version = "0.1.5" }
from-pest = { version = "0.3.1" }
lazy_static = { version = "1.3.0" }
pest = { version = "2.0" }
pest-ast = { version = "0.3.3" }
pest_derive = { version = "2.0" }
rand = { version = "0.7" }
rand_core = { version = "0.5.1" }
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
structopt = { version = "0.3.14" }
toml = { version = "0.5" }

View File

@ -1,17 +0,0 @@
[package]
name = "leo-compiler"
version = "0.1.0"
authors = ["The Aleo Team <hello@aleo.org>"]
edition = "2018"
[dependencies]
leo-program = { path = "../program", version = "0.1.0" }
snarkos-algorithms = { path = "../../snarkOS/algorithms", version = "0.8.0" }
snarkos-curves = { path = "../../snarkOS/curves", version = "0.8.0" }
snarkos-errors = { path = "../../snarkOS/errors", version = "0.8.0" }
snarkos-gadgets = { path = "../../snarkOS/gadgets", version = "0.8.0" }
snarkos-models = { path = "../../snarkOS/models", version = "0.8.0" }
from-pest = { version = "0.3.1" }
rand = { version = "0.7" }

View File

View File

@ -1,111 +0,0 @@
use leo_program::{self, ast};
use snarkos_algorithms::snark::{
create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof,
};
use snarkos_curves::bls12_377::{Bls12_377, Fr};
use snarkos_errors::gadgets::SynthesisError;
use snarkos_models::{
curves::{Field, PrimeField},
gadgets::r1cs::{ConstraintSynthesizer, ConstraintSystem},
};
use from_pest::FromPest;
use rand::thread_rng;
use std::{
fs,
marker::PhantomData,
time::{Duration, Instant},
};
pub struct Benchmark<F: Field + PrimeField> {
_engine: PhantomData<F>,
}
impl<F: Field + PrimeField> Benchmark<F> {
pub fn new() -> Self {
Self {
_engine: PhantomData,
}
}
}
impl<F: Field + PrimeField> ConstraintSynthesizer<F> for Benchmark<F> {
fn generate_constraints<CS: ConstraintSystem<F>>(
self,
cs: &mut CS,
) -> Result<(), SynthesisError> {
// Read in file as string
let unparsed_file = fs::read_to_string("simple.leo").expect("cannot read file");
// Parse the file using leo.pest
let mut file = ast::parse(&unparsed_file).expect("unsuccessful parse");
// Build the abstract syntax tree
let syntax_tree = ast::File::from_pest(&mut file).expect("infallible");
// println!("{:#?}", syntax_tree);
let program = leo_program::Program::<'_, F>::from(syntax_tree);
println!(" compiled: {:#?}", program);
let program = program.name("simple".into());
leo_program::ResolvedProgram::generate_constraints(cs, program);
Ok(())
}
}
fn main() {
let mut setup = Duration::new(0, 0);
let mut proving = Duration::new(0, 0);
let mut verifying = Duration::new(0, 0);
let rng = &mut thread_rng();
let start = Instant::now();
let params = {
let circuit = Benchmark::<Fr>::new();
generate_random_parameters::<Bls12_377, _, _>(circuit, rng).unwrap()
};
let prepared_verifying_key = prepare_verifying_key::<Bls12_377>(&params.vk);
setup += start.elapsed();
let start = Instant::now();
let proof = {
let c = Benchmark::new();
create_random_proof(c, &params, rng).unwrap()
};
proving += start.elapsed();
// let _inputs: Vec<_> = [1u32; 1].to_vec();
let start = Instant::now();
let is_success = verify_proof(&prepared_verifying_key, &proof, &[]).unwrap();
verifying += start.elapsed();
println!(" ");
println!(" Setup time : {:?} milliseconds", setup.as_millis());
println!(" Prover time : {:?} milliseconds", proving.as_millis());
println!(
" Verifier time : {:?} milliseconds",
verifying.as_millis()
);
println!(" Verifier output : {}", is_success);
println!(" ");
// let mut cs = TestConstraintSystem::<Fr>::new();
//
// println!("\n satisfied: {:?}", cs.is_satisfied());
//
// println!(
// "\n number of constraints for input: {}",
// cs.num_constraints()
// );
//
}

6
hello_world/Leo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "hello_world"
version = "0.1.0"
authors = "Satoshi Nakamoto"
license = "Apache/MIT"

68
leo/commands/cli.rs Normal file
View File

@ -0,0 +1,68 @@
use crate::commands::cli_types::*;
use crate::errors::CLIError;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
pub trait CLI {
type Options;
const NAME: NameType;
const ABOUT: AboutType;
const FLAGS: &'static [FlagType];
const OPTIONS: &'static [OptionType];
const SUBCOMMANDS: &'static [SubCommandType];
#[cfg_attr(tarpaulin, skip)]
fn new<'a, 'b>() -> App<'a, 'b> {
let flags = &Self::FLAGS
.iter()
.map(|a| Arg::from_usage(a).global(true))
.collect::<Vec<Arg<'static, 'static>>>();
let options = &Self::OPTIONS
.iter()
.map(|a| match a.2.len() > 0 {
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>>>();
let subcommands = Self::SUBCOMMANDS
.iter()
.map(|s| {
SubCommand::with_name(s.0)
.about(s.1)
.args(
&s.2.iter()
.map(|a| match a.2.len() > 0 {
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.3)
})
.collect::<Vec<App<'static, 'static>>>();
SubCommand::with_name(Self::NAME)
.about(Self::ABOUT)
.settings(&[
AppSettings::ColoredHelp,
AppSettings::DisableHelpSubcommand,
AppSettings::DisableVersion,
])
.args(flags)
.args(options)
.subcommands(subcommands)
}
#[cfg_attr(tarpaulin, skip)]
fn parse(arguments: &ArgMatches) -> Result<Self::Options, CLIError>;
#[cfg_attr(tarpaulin, skip)]
fn output(&mut self, options: Self::Options) -> Result<(), CLIError>;
}

12
leo/commands/cli_types.rs Normal file
View File

@ -0,0 +1,12 @@
use clap::AppSettings;
pub type NameType = &'static str;
pub type AboutType = &'static str;
pub type FlagType = &'static str;
pub type OptionType = (
&'static str,
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
);
pub type SubCommandType = (NameType, AboutType, &'static [OptionType], &'static [AppSettings]);

6
leo/commands/mod.rs Normal file
View File

@ -0,0 +1,6 @@
#[cfg_attr(tarpaulin, skip)]
pub mod cli;
pub mod cli_types;
pub mod new;
pub use self::new::*;

2
leo/commands/new/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod new;
pub use self::new::*;

66
leo/commands/new/new.rs Normal file
View File

@ -0,0 +1,66 @@
use crate::commands::{cli::*, cli_types::*};
use crate::errors::{CLIError, ManifestError, NewError};
use crate::manifest::Manifest;
use clap::{ArgMatches, Values};
use colored::*;
use rand::{rngs::StdRng, Rng};
use rand_core::SeedableRng;
use serde::{Deserialize, Serialize};
use serde_json::from_str;
use std::{fmt, fmt::Display, fs, str::FromStr};
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct NewCommand {
#[structopt(parse(from_os_str))]
path: PathBuf,
}
impl CLI for NewCommand {
type Options = ();
const NAME: NameType = "new";
const ABOUT: AboutType = "Creates a new Leo package (include -h for more options)";
const FLAGS: &'static [FlagType] = &[];
const OPTIONS: &'static [OptionType] = &[];
const SUBCOMMANDS: &'static [SubCommandType] = &[];
#[cfg_attr(tarpaulin, skip)]
fn parse(arguments: &ArgMatches) -> Result<Self::Options, CLIError> {
let mut options = ();
// options.parse(arguments, &["count", "format", "json", "network"]);
//
// match arguments.subcommand() {
// ("hd", Some(arguments)) => {
// options.subcommand = Some("hd".into());
// options.parse(arguments, &["count", "json", "network"]);
// options.parse(arguments, &["derivation", "language", "password", "word count"]);
// }
// _ => {}
// };
Ok(options)
}
#[cfg_attr(tarpaulin, skip)]
fn output(&mut self, options: Self::Options) -> Result<(), CLIError> {
let package_name = self.path
.file_stem()
.ok_or_else(|| NewError::ProjectNameInvalid(self.path.as_os_str().to_owned()))?
.to_string_lossy()
.to_string();
if self.path.exists() {
return Err(NewError::DirectoryAlreadyExists(self.path.as_os_str().to_owned()).into());
}
fs::create_dir_all(&self.path).map_err(|error| {
NewError::CreatingRootDirectory(self.path.as_os_str().to_owned(), error)
})?;
Manifest::new(&package_name).write_to(&self.path).map_err(NewError::ManifestError)?;
Ok(())
}
}

31
leo/errors/cli.rs Normal file
View File

@ -0,0 +1,31 @@
use crate::errors::{ManifestError, NewError};
#[derive(Debug, Fail)]
pub enum CLIError {
#[fail(display = "{}: {}", _0, _1)]
Crate(&'static str, String),
#[fail(display = "{}", _0)]
ManifestError(ManifestError),
#[fail(display = "{}", _0)]
NewError(NewError),
}
impl From<ManifestError> for CLIError {
fn from(error: ManifestError) -> Self {
CLIError::ManifestError(error)
}
}
impl From<NewError> for CLIError {
fn from(error: NewError) -> Self {
CLIError::NewError(error)
}
}
impl From<serde_json::error::Error> for CLIError {
fn from(error: serde_json::error::Error) -> Self {
CLIError::Crate("serde_json", format!("{:?}", error))
}
}

View File

@ -0,0 +1,2 @@
pub mod new;
pub use self::new::*;

View File

@ -0,0 +1,27 @@
use crate::errors::ManifestError;
use std::ffi::OsString;
use std::io;
#[derive(Debug, Fail)]
pub enum NewError {
#[fail(display = "root directory {:?} creating: {}", _0, _1)]
CreatingRootDirectory(OsString, io::Error),
#[fail(display = "directory {:?} already exists", _0)]
DirectoryAlreadyExists(OsString),
#[fail(display = "{}", _0)]
ManifestError(ManifestError),
#[fail(display = "package name is missing - {:?}", _0)]
ProjectNameInvalid(OsString),
}
impl From<ManifestError> for NewError {
fn from(error: ManifestError) -> Self {
NewError::ManifestError(error)
}
}

24
leo/errors/manifest.rs Normal file
View File

@ -0,0 +1,24 @@
use std::io;
#[derive(Debug, Fail)]
pub enum ManifestError {
#[fail(display = "`{}` creating: {}", _0, _1)]
Creating(&'static str, io::Error),
#[fail(display = "`{}` metadata: {}", _0, _1)]
Metadata(&'static str, io::Error),
#[fail(display = "`{}` opening: {}", _0, _1)]
Opening(&'static str, io::Error),
#[fail(display = "`{}` parsing: {}", _0, _1)]
Parsing(&'static str, toml::de::Error),
#[fail(display = "`{}` reading: {}", _0, _1)]
Reading(&'static str, io::Error),
#[fail(display = "`{}` writing: {}", _0, _1)]
Writing(&'static str, io::Error),
}

8
leo/errors/mod.rs Normal file
View File

@ -0,0 +1,8 @@
pub mod cli;
pub use self::cli::*;
pub mod commands;
pub use self::commands::*;
pub mod manifest;
pub use self::manifest::*;

6
leo/lib.rs Normal file
View File

@ -0,0 +1,6 @@
#[macro_use]
extern crate failure;
pub mod commands;
pub mod errors;
pub mod manifest;

143
leo/main.rs Normal file
View File

@ -0,0 +1,143 @@
// use leo_program::{self, ast};
//
// use snarkos_algorithms::snark::{
// create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof,
// };
// use snarkos_curves::bls12_377::{Bls12_377, Fr};
// use snarkos_errors::gadgets::SynthesisError;
// use snarkos_models::{
// curves::{Field, PrimeField},
// gadgets::r1cs::{ConstraintSynthesizer, ConstraintSystem},
// };
//
// use from_pest::FromPest;
// use rand::thread_rng;
// use std::{
// fs,
// marker::PhantomData,
// time::{Duration, Instant},
// };
//
// pub struct Benchmark<F: Field + PrimeField> {
// _engine: PhantomData<F>,
// }
//
// impl<F: Field + PrimeField> Benchmark<F> {
// pub fn new() -> Self {
// Self {
// _engine: PhantomData,
// }
// }
// }
//
// impl<F: Field + PrimeField> ConstraintSynthesizer<F> for Benchmark<F> {
// fn generate_constraints<CS: ConstraintSystem<F>>(
// self,
// cs: &mut CS,
// ) -> Result<(), SynthesisError> {
// // Read in file as string
// let unparsed_file = fs::read_to_string("simple.leo").expect("cannot read file");
//
// // Parse the file using leo.pest
// let mut file = ast::parse(&unparsed_file).expect("unsuccessful parse");
//
// // Build the abstract syntax tree
// let syntax_tree = ast::File::from_pest(&mut file).expect("infallible");
// // println!("{:#?}", syntax_tree);
//
// let program = leo_program::Program::<'_, F>::from(syntax_tree);
// println!(" compiled: {:#?}", program);
//
// let program = program.name("simple".into());
// leo_program::ResolvedProgram::generate_constraints(cs, program);
//
// Ok(())
// }
// }
//
// fn main() {
// let mut setup = Duration::new(0, 0);
// let mut proving = Duration::new(0, 0);
// let mut verifying = Duration::new(0, 0);
//
// let rng = &mut thread_rng();
//
// let start = Instant::now();
//
// let params = {
// let circuit = Benchmark::<Fr>::new();
// generate_random_parameters::<Bls12_377, _, _>(circuit, rng).unwrap()
// };
//
// let prepared_verifying_key = prepare_verifying_key::<Bls12_377>(&params.vk);
//
// setup += start.elapsed();
//
// let start = Instant::now();
// let proof = {
// let c = Benchmark::new();
// create_random_proof(c, &params, rng).unwrap()
// };
//
// proving += start.elapsed();
//
// // let _inputs: Vec<_> = [1u32; 1].to_vec();
//
// let start = Instant::now();
//
// let is_success = verify_proof(&prepared_verifying_key, &proof, &[]).unwrap();
//
// verifying += start.elapsed();
//
// println!(" ");
// println!(" Setup time : {:?} milliseconds", setup.as_millis());
// println!(" Prover time : {:?} milliseconds", proving.as_millis());
// println!(
// " Verifier time : {:?} milliseconds",
// verifying.as_millis()
// );
// println!(" Verifier output : {}", is_success);
// println!(" ");
//
// // let mut cs = TestConstraintSystem::<Fr>::new();
// //
// // println!("\n satisfied: {:?}", cs.is_satisfied());
// //
// // println!(
// // "\n number of constraints for input: {}",
// // cs.num_constraints()
// // );
// //
// }
use leo::commands::{cli::*, NewCommand};
use leo::errors::CLIError;
use clap::{App, AppSettings};
#[cfg_attr(tarpaulin, skip)]
fn main() -> Result<(), CLIError> {
let arguments = App::new("leo")
.version("v0.1.0")
.about("Leo compiler and package manager")
.author("The Aleo Team <hello@aleo.org>")
.settings(&[
AppSettings::ColoredHelp,
AppSettings::DisableHelpSubcommand,
AppSettings::DisableVersion,
AppSettings::SubcommandRequiredElseHelp,
])
.subcommands(vec![
NewCommand::new(),
])
.set_term_width(0)
.get_matches();
match arguments.subcommand() {
// ("new", Some(arguments)) => {
// NewCommand::().output(NewCommand::parse(arguments)?)
// },
_ => unreachable!(),
}
}

87
leo/manifest.rs Normal file
View File

@ -0,0 +1,87 @@
use crate::errors::ManifestError;
use failure::Fail;
use serde::Deserialize;
use std::convert::TryFrom;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
pub static FILE_NAME_DEFAULT: &str = "Leo.toml";
#[derive(Deserialize)]
pub struct Package {
pub name: String,
pub version: String,
}
#[derive(Deserialize)]
pub struct Manifest {
pub package: Package,
}
impl Manifest {
pub fn new(package_name: &str) -> Self {
Self {
package: Package {
name: package_name.to_owned(),
version: "0.1.0".to_owned(),
},
}
}
pub fn exists_at(path: &PathBuf) -> bool {
let mut path = path.to_owned();
if path.is_dir() {
path.push(PathBuf::from(FILE_NAME_DEFAULT));
}
path.exists()
}
pub fn write_to(self, path: &PathBuf) -> Result<(), ManifestError> {
let mut path = path.to_owned();
if path.is_dir() {
path.push(PathBuf::from(FILE_NAME_DEFAULT));
}
let mut file =
File::create(&path).map_err(|error| ManifestError::Creating(FILE_NAME_DEFAULT, error))?;
file.write_all(self.template().as_bytes())
.map_err(|error| ManifestError::Writing(FILE_NAME_DEFAULT, error))
}
fn template(&self) -> String {
format!(
r#"[package]
name = "{}"
version = "0.1.0"
"#,
self.package.name
)
}
}
impl TryFrom<&PathBuf> for Manifest {
type Error = ManifestError;
fn try_from(path: &PathBuf) -> Result<Self, Self::Error> {
let mut path = path.to_owned();
if path.is_dir() {
path.push(PathBuf::from(FILE_NAME_DEFAULT));
}
let mut file =
File::open(path).map_err(|error| ManifestError::Opening(FILE_NAME_DEFAULT, error))?;
let size = file
.metadata()
.map_err(|error| ManifestError::Metadata(FILE_NAME_DEFAULT, error))?
.len() as usize;
let mut buffer = String::with_capacity(size);
file.read_to_string(&mut buffer)
.map_err(|error| ManifestError::Reading(FILE_NAME_DEFAULT, error))?;
Ok(toml::from_str(&buffer).map_err(|error| ManifestError::Parsing(FILE_NAME_DEFAULT, error))?)
}
}