fmt fixes, realized they have to be in that format for outputs

This commit is contained in:
gluaxspeed 2021-07-08 04:05:00 -07:00
parent d6c3aec431
commit 0bd580e3d1
15 changed files with 89 additions and 29 deletions

5
.gitignore vendored
View File

@ -8,3 +8,8 @@
**/.crates.toml **/.crates.toml
**/.crates2.json **/.crates2.json
**/bin/ **/bin/
# Emacs gitignore files
*~
\#*\#
.\#*

4
Cargo.lock generated
View File

@ -2800,9 +2800,9 @@ dependencies = [
[[package]] [[package]]
name = "tracing-subscriber" name = "tracing-subscriber"
version = "0.2.18" version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa5553bf0883ba7c9cbe493b085c29926bd41b66afc31ff72cf17ff4fb60dcd5" checksum = "ab69019741fca4d98be3c62d2b75254528b5432233fd8a4d2739fec20278de48"
dependencies = [ dependencies = [
"ansi_term 0.12.1", "ansi_term 0.12.1",
"chrono", "chrono",

View File

@ -145,7 +145,7 @@ version = "0.5"
version = "0.1" version = "0.1"
[dependencies.tracing-subscriber] [dependencies.tracing-subscriber]
version = "0.2" version = "0.2.19"
features = [ "fmt" ] features = [ "fmt" ]
[dependencies.zip] [dependencies.zip]

View File

@ -21,6 +21,9 @@ use snarkvm_r1cs::SynthesisError;
pub enum GroupError { pub enum GroupError {
#[error("{}", _0)] #[error("{}", _0)]
Error(#[from] FormattedError), Error(#[from] FormattedError),
#[error("Failed to represent group as log string.")]
LogError,
} }
impl LeoError for GroupError {} impl LeoError for GroupError {}
@ -30,6 +33,10 @@ impl GroupError {
GroupError::Error(FormattedError::new_from_span(message, span)) GroupError::Error(FormattedError::new_from_span(message, span))
} }
pub fn failed_to_create_log_string() -> Self {
GroupError::LogError
}
pub fn negate_operation(error: SynthesisError, span: &Span) -> Self { pub fn negate_operation(error: SynthesisError, span: &Span) -> Self {
let message = format!("group negation failed due to the synthesis error `{:?}`", error,); let message = format!("group negation failed due to the synthesis error `{:?}`", error,);

View File

@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>. // along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_ast::{FormattedError, IntegerType, LeoError, Span}; use leo_ast::{FormattedError, LeoError, Span};
use snarkvm_gadgets::errors::{SignedIntegerError, UnsignedIntegerError}; use snarkvm_gadgets::errors::{SignedIntegerError, UnsignedIntegerError};
use snarkvm_r1cs::SynthesisError; use snarkvm_r1cs::SynthesisError;
@ -68,7 +68,7 @@ impl IntegerError {
Self::new_from_span(message, span) Self::new_from_span(message, span)
} }
pub fn integer_type_mismatch(expected: &IntegerType, received: IntegerType, span: &Span) -> Self { pub fn integer_type_mismatch(expected: String, received: String, span: &Span) -> Self {
let message = format!("expected data type `{}`, found `{}`", expected, received); let message = format!("expected data type `{}`, found `{}`", expected, received);
Self::new_from_span(message, span) Self::new_from_span(message, span)

View File

@ -18,7 +18,7 @@
use crate::{ use crate::{
address::Address, address::Address,
errors::FunctionError, errors::{FunctionError, IntegerError},
program::ConstrainedProgram, program::ConstrainedProgram,
value::{ value::{
boolean::input::bool_from_input, boolean::input::bool_from_input,
@ -101,9 +101,19 @@ impl<'a, F: PrimeField, G: GroupType<F>> ConstrainedProgram<'a, F, G> {
Ok(ConstrainedValue::Field(FieldType::constant(cs, value, span)?)) Ok(ConstrainedValue::Field(FieldType::constant(cs, value, span)?))
} }
(Type::Group, InputValue::Group(value)) => Ok(ConstrainedValue::Group(G::constant(&value.into(), span)?)), (Type::Group, InputValue::Group(value)) => Ok(ConstrainedValue::Group(G::constant(&value.into(), span)?)),
(Type::Integer(integer_type), InputValue::Integer(_, value)) => Ok(ConstrainedValue::Integer( (Type::Integer(integer_type), InputValue::Integer(input_type, value)) => {
Integer::new(&ConstInt::parse(integer_type, &value, span)?), let parsed = ConstInt::parse(integer_type, &value, span)?;
)), let parsed_type = parsed.get_int_type();
let input_type = input_type.into();
if std::mem::discriminant(&parsed_type) != std::mem::discriminant(&input_type) {
return Err(FunctionError::from(IntegerError::integer_type_mismatch(
input_type.to_string(),
parsed_type.to_string(),
span,
)));
}
Ok(ConstrainedValue::Integer(Integer::new(&parsed)))
}
(Type::Array(type_, arr_len), InputValue::Array(values)) => { (Type::Array(type_, arr_len), InputValue::Array(values)) => {
if *arr_len != values.len() { if *arr_len != values.len() {
return Err(FunctionError::invalid_input_array_dimensions( return Err(FunctionError::invalid_input_array_dimensions(

View File

@ -155,6 +155,8 @@ impl Output {
format!("({})", values) format!("({})", values)
} }
ConstrainedValue::Field(field) => format!("{:?}", field),
ConstrainedValue::Group(group) => format!("{:?}", group),
_ => value.to_string(), _ => value.to_string(),
}; };

View File

@ -45,6 +45,8 @@ pub trait GroupType<F: Field>:
+ ToBitsBEGadget<F> + ToBitsBEGadget<F>
+ ToBytesGadget<F> + ToBytesGadget<F>
{ {
fn log_string(&self) -> Result<String, GroupError>;
fn constant(value: &GroupValue, span: &Span) -> Result<Self, GroupError>; fn constant(value: &GroupValue, span: &Span) -> Result<Self, GroupError>;
fn to_allocated<CS: ConstraintSystem<F>>(&self, cs: CS, span: &Span) -> Result<Self, GroupError>; fn to_allocated<CS: ConstraintSystem<F>>(&self, cs: CS, span: &Span) -> Result<Self, GroupError>;

View File

@ -52,6 +52,16 @@ pub enum EdwardsGroupType {
} }
impl GroupType<Fq> for EdwardsGroupType { impl GroupType<Fq> for EdwardsGroupType {
fn log_string(&self) -> Result<String, GroupError> {
match self {
EdwardsGroupType::Constant(constant) => Ok(format!("({}, {})group", constant.x, constant.y)),
EdwardsGroupType::Allocated(allocated) => match (allocated.x.get_value(), allocated.y.get_value()) {
(Some(x), Some(y)) => Ok(format!("({}, {})group", x, y)),
_ => Err(GroupError::failed_to_create_log_string()),
},
}
}
fn constant(group: &GroupValue, span: &Span) -> Result<Self, GroupError> { fn constant(group: &GroupValue, span: &Span) -> Result<Self, GroupError> {
let value = Self::edwards_affine_from_value(group, span)?; let value = Self::edwards_affine_from_value(group, span)?;

View File

@ -160,7 +160,11 @@ impl Integer {
if let InputValue::Integer(type_, number) = input { if let InputValue::Integer(type_, number) = input {
let asg_type = IntegerType::from(type_); let asg_type = IntegerType::from(type_);
if std::mem::discriminant(&asg_type) != std::mem::discriminant(integer_type) { if std::mem::discriminant(&asg_type) != std::mem::discriminant(integer_type) {
return Err(IntegerError::integer_type_mismatch(integer_type, asg_type, span)); return Err(IntegerError::integer_type_mismatch(
integer_type.to_string(),
asg_type.to_string(),
span,
));
} }
Some(number) Some(number)
} else { } else {

View File

@ -96,8 +96,14 @@ impl<'a, F: PrimeField, G: GroupType<F>> fmt::Display for ConstrainedValue<'a, F
.unwrap_or_else(|| "[allocated]".to_string()) .unwrap_or_else(|| "[allocated]".to_string())
), ),
ConstrainedValue::Char(ref value) => write!(f, "{}", value), ConstrainedValue::Char(ref value) => write!(f, "{}", value),
ConstrainedValue::Field(ref value) => write!(f, "{:?}", value), ConstrainedValue::Field(ref value) => {
ConstrainedValue::Group(ref value) => write!(f, "{:?}", value), if let Some(value) = value.get_value() {
write!(f, "{}", value)
} else {
Err(std::fmt::Error)
}
}
ConstrainedValue::Group(ref value) => write!(f, "{}", value.log_string().unwrap_or_else(|e| e.to_string())),
ConstrainedValue::Integer(ref value) => write!(f, "{}", value), ConstrainedValue::Integer(ref value) => write!(f, "{}", value),
// Data type wrappers // Data type wrappers

View File

@ -16,6 +16,7 @@
use std::{fmt, sync::Once}; use std::{fmt, sync::Once};
use anyhow::{anyhow, Result};
use colored::Colorize; use colored::Colorize;
use tracing::{event::Event, subscriber::Subscriber}; use tracing::{event::Event, subscriber::Subscriber};
use tracing_subscriber::{ use tracing_subscriber::{
@ -181,17 +182,23 @@ where
let mut message = "".to_string(); let mut message = "".to_string();
let scope = context.scope(); match context.lookup_current() {
for span in scope { Some(span_ref) => {
message += span.metadata().name(); let scope = span_ref.scope();
let ext = span.extensions(); for span in scope {
let fields = &ext message += span.metadata().name();
.get::<FormattedFields<N>>()
.expect("Unable to find FormattedFields in extensions; this is a bug"); let ext = span.extensions();
if !fields.is_empty() { let fields = &ext
message += &format!("{{{}}}", fields); .get::<FormattedFields<N>>()
.expect("Unable to find FormattedFields in extensions; this is a bug");
if !fields.is_empty() {
message += &format!("{{{}}}", fields);
}
}
} }
None => return Err(std::fmt::Error),
} }
write!(writer, "{:>10} ", colored_string(meta.level(), &message)).expect("Error writing event"); write!(writer, "{:>10} ", colored_string(meta.level(), &message)).expect("Error writing event");
@ -203,10 +210,16 @@ where
} }
/// Initialize logger with custom format and verbosity. /// Initialize logger with custom format and verbosity.
pub fn init_logger(_app_name: &'static str, verbosity: usize) { pub fn init_logger(_app_name: &'static str, verbosity: usize) -> Result<()> {
// This line enables Windows 10 ANSI coloring API. // This line enables Windows 10 ANSI coloring API.
#[cfg(target_family = "windows")] #[cfg(target_family = "windows")]
ansi_term::enable_ansi_support(); match ansi_term::enable_ansi_support() {
Ok(_) => {}
Err(_) => {
println!("YOTE");
return Err(anyhow!("Error: Failedto enable ansi_support"));
}
};
let subscriber = FmtSubscriber::builder() let subscriber = FmtSubscriber::builder()
// all spans/events with a level higher than TRACE (e.g, debug, info, warn, etc.) // all spans/events with a level higher than TRACE (e.g, debug, info, warn, etc.)
@ -226,4 +239,5 @@ pub fn init_logger(_app_name: &'static str, verbosity: usize) {
START.call_once(|| { START.call_once(|| {
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
}); });
Ok(())
} }

View File

@ -38,7 +38,7 @@ use commands::{
Watch, Watch,
}; };
use anyhow::Error; use anyhow::Result;
use std::{path::PathBuf, process::exit}; use std::{path::PathBuf, process::exit};
use structopt::{clap::AppSettings, StructOpt}; use structopt::{clap::AppSettings, StructOpt};
@ -185,13 +185,13 @@ fn main() {
} }
/// Run command with custom build arguments. /// Run command with custom build arguments.
fn run_with_args(opt: Opt) -> Result<(), Error> { fn run_with_args(opt: Opt) -> Result<()> {
if !opt.quiet { if !opt.quiet {
// Init logger with optional debug flag. // Init logger with optional debug flag.
logger::init_logger("leo", match opt.debug { logger::init_logger("leo", match opt.debug {
false => 1, false => 1,
true => 2, true => 2,
}); })?;
} }
// Get custom root folder and create context for it. // Get custom root folder and create context for it.
@ -225,7 +225,7 @@ fn run_with_args(opt: Opt) -> Result<(), Error> {
} }
} }
fn handle_error<T>(res: Result<T, Error>) -> T { fn handle_error<T>(res: Result<T>) -> T {
match res { match res {
Ok(t) => t, Ok(t) => t,
Err(err) => { Err(err) => {
@ -239,13 +239,13 @@ fn handle_error<T>(res: Result<T, Error>) -> T {
mod cli_tests { mod cli_tests {
use crate::{run_with_args, Opt}; use crate::{run_with_args, Opt};
use anyhow::Error; use anyhow::Result;
use std::path::PathBuf; use std::path::PathBuf;
use structopt::StructOpt; use structopt::StructOpt;
use test_dir::{DirBuilder, FileType, TestDir}; use test_dir::{DirBuilder, FileType, TestDir};
// Runs Command from cmd-like argument "leo run --arg1 --arg2". // Runs Command from cmd-like argument "leo run --arg1 --arg2".
fn run_cmd(args: &str, path: &Option<PathBuf>) -> Result<(), Error> { fn run_cmd(args: &str, path: &Option<PathBuf>) -> Result<()> {
let args = args.split(' ').collect::<Vec<&str>>(); let args = args.split(' ').collect::<Vec<&str>>();
let mut opts = Opt::from_iter_safe(args)?; let mut opts = Opt::from_iter_safe(args)?;