This commit is contained in:
collin 2022-07-06 20:49:05 -07:00
parent 0e5ad5e385
commit 95c2f66c5a
11 changed files with 33 additions and 29 deletions

View File

@ -43,7 +43,8 @@ fn compare_license_text(path: &Path, expected_lines: &[&str]) {
let reader = BufReader::new(file); let reader = BufReader::new(file);
for (i, (file_line, expected_line)) in reader.lines().zip(expected_lines).enumerate() { for (i, (file_line, expected_line)) in reader.lines().zip(expected_lines).enumerate() {
let file_line = file_line.expect(&format!("Can't read line {} in file \"{}\"!", i + 1, path.display())); let file_line =
file_line.unwrap_or_else(|_| panic!("Can't read line {} in file \"{}\"!", i + 1, path.display()));
assert!( assert!(
&file_line == expected_line, &file_line == expected_line,
@ -75,7 +76,7 @@ fn check_file_licenses<P: AsRef<Path>>(path: P) {
// Check all files with the ".rs" extension. // Check all files with the ".rs" extension.
if entry_type.is_file() && entry.file_name().to_str().unwrap_or("").ends_with(".rs") { if entry_type.is_file() && entry.file_name().to_str().unwrap_or("").ends_with(".rs") {
compare_license_text(&entry.path(), &license_lines); compare_license_text(entry.path(), &license_lines);
} }
} }

View File

@ -174,7 +174,7 @@ impl<'a> Compiler<'a> {
self.parse_program()?; self.parse_program()?;
let symbol_table = self.compiler_stages()?; let symbol_table = self.compiler_stages()?;
let bytecode = CodeGenerator::do_pass((&self.ast, &self.handler))?; let bytecode = CodeGenerator::do_pass((&self.ast, self.handler))?;
Ok((symbol_table, bytecode)) Ok((symbol_table, bytecode))
} }

View File

@ -20,7 +20,6 @@
//! separated by whitespace. //! separated by whitespace.
pub(crate) mod token; pub(crate) mod token;
use std::iter;
pub use self::token::KEYWORD_TOKENS; pub use self::token::KEYWORD_TOKENS;
pub(crate) use self::token::*; pub(crate) use self::token::*;
@ -31,6 +30,8 @@ pub(crate) use self::lexer::*;
use leo_errors::Result; use leo_errors::Result;
use leo_span::span::{BytePos, Pos, Span}; use leo_span::span::{BytePos, Pos, Span};
use std::iter;
/// Creates a new vector of spanned tokens from a given file path and source code text. /// Creates a new vector of spanned tokens from a given file path and source code text.
pub(crate) fn tokenize(input: &str, start_pos: BytePos) -> Result<Vec<SpannedToken>> { pub(crate) fn tokenize(input: &str, start_pos: BytePos) -> Result<Vec<SpannedToken>> {
tokenize_iter(input, start_pos).collect() tokenize_iter(input, start_pos).collect()
@ -65,6 +66,7 @@ pub(crate) fn tokenize_iter(mut input: &str, mut lo: BytePos) -> impl '_ + Itera
mod tests { mod tests {
use super::*; use super::*;
use leo_span::{source_map::FileName, symbol::create_session_if_not_set_then}; use leo_span::{source_map::FileName, symbol::create_session_if_not_set_then};
use std::fmt::Write as _;
#[test] #[test]
fn test_tokenizer() { fn test_tokenizer() {
@ -147,7 +149,7 @@ mod tests {
let tokens = tokenize(&sf.src, sf.start_pos).unwrap(); let tokens = tokenize(&sf.src, sf.start_pos).unwrap();
let mut output = String::new(); let mut output = String::new();
for SpannedToken { token, .. } in tokens.iter() { for SpannedToken { token, .. } in tokens.iter() {
output += &format!("{} ", token); write!(output, "{} ", token).expect("failed to write to string");
} }
assert_eq!( assert_eq!(

View File

@ -15,12 +15,13 @@
// 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 crate::CodeGenerator; use crate::CodeGenerator;
use leo_ast::{ use leo_ast::{
AccessExpression, BinaryExpression, BinaryOperation, CallExpression, CircuitInitExpression, ErrExpression, AccessExpression, BinaryExpression, BinaryOperation, CallExpression, CircuitInitExpression, ErrExpression,
Expression, Identifier, LiteralExpression, MemberAccess, TernaryExpression, UnaryExpression, UnaryOperation, Expression, Identifier, LiteralExpression, MemberAccess, TernaryExpression, UnaryExpression, UnaryOperation,
}; };
use std::fmt::Write as _;
/// Implement the necessary methods to visit nodes in the AST. /// Implement the necessary methods to visit nodes in the AST.
// Note: We opt for this option instead of using `Visitor` and `Director` because this pass requires // Note: We opt for this option instead of using `Visitor` and `Director` because this pass requires
// a post-order traversal of the AST. This is sufficient since this implementation is intended to be // a post-order traversal of the AST. This is sufficient since this implementation is intended to be
@ -171,12 +172,12 @@ impl<'a> CodeGenerator<'a> {
}; };
// Push operand name to circuit init instruction. // Push operand name to circuit init instruction.
circuit_init_instruction.push_str(&format!("{} ", operand)) write!(circuit_init_instruction, "{} ", operand).expect("failed to write to string");
} }
// Push destination register to circuit init instruction. // Push destination register to circuit init instruction.
let destination_register = format!("r{}", self.next_register); let destination_register = format!("r{}", self.next_register);
circuit_init_instruction.push_str(&format!("into {};\n", destination_register)); writeln!(circuit_init_instruction, "into {};", destination_register).expect("failed to write to string");
instructions.push_str(&circuit_init_instruction); instructions.push_str(&circuit_init_instruction);
// Increment the register counter. // Increment the register counter.
@ -205,14 +206,14 @@ impl<'a> CodeGenerator<'a> {
let mut instructions = String::new(); let mut instructions = String::new();
for argument in input.arguments.iter() { for argument in input.arguments.iter() {
let (argument, argument_instructions) = self.visit_expression(&argument); let (argument, argument_instructions) = self.visit_expression(argument);
call_instruction.push_str(&format!("{} ", argument)); write!(call_instruction, "{} ", argument).expect("failed to write to string");
instructions.push_str(&argument_instructions); instructions.push_str(&argument_instructions);
} }
// Push destination register to call instruction. // Push destination register to call instruction.
let destination_register = format!("r{}", self.next_register); let destination_register = format!("r{}", self.next_register);
call_instruction.push_str(&format!("into {};\n", destination_register)); writeln!(call_instruction, "into {};", destination_register).expect("failed to write to string");
instructions.push_str(&call_instruction); instructions.push_str(&call_instruction);
// Increment the register counter. // Increment the register counter.

View File

@ -19,7 +19,7 @@ use crate::CodeGenerator;
use leo_ast::{Circuit, CircuitMember, Function, Program}; use leo_ast::{Circuit, CircuitMember, Function, Program};
use itertools::Itertools; use itertools::Itertools;
use std::collections::HashMap; use std::{collections::HashMap, fmt::Write as _};
impl<'a> CodeGenerator<'a> { impl<'a> CodeGenerator<'a> {
pub(crate) fn visit_program(&mut self, input: &'a Program) -> String { pub(crate) fn visit_program(&mut self, input: &'a Program) -> String {
@ -34,7 +34,7 @@ impl<'a> CodeGenerator<'a> {
.join("\n"), .join("\n"),
); );
program_string.push_str("\n"); program_string.push('\n');
// Visit each `Function` in the Leo AST and produce a bytecode function. // Visit each `Function` in the Leo AST and produce a bytecode function.
program_string.push_str( program_string.push_str(
@ -69,7 +69,7 @@ impl<'a> CodeGenerator<'a> {
CircuitMember::CircuitVariable(name, type_) => (name, type_), CircuitMember::CircuitVariable(name, type_) => (name, type_),
}; };
output_string.push_str(&format!(" {} as {};\n", name, type_,)) writeln!(output_string, " {} as {};", name, type_,).expect("failed to write to string");
} }
output_string output_string
@ -80,7 +80,8 @@ impl<'a> CodeGenerator<'a> {
let mut output_string = String::from("record"); let mut output_string = String::from("record");
self.composite_mapping self.composite_mapping
.insert(&record.identifier.name, output_string.clone()); .insert(&record.identifier.name, output_string.clone());
output_string.push_str(&format!(" {}:\n", record.identifier.to_string().to_lowercase())); // todo: check if this is safe from name conflicts. writeln!(output_string, " {}:", record.identifier.to_string().to_lowercase())
.expect("failed to write to string"); // todo: check if this is safe from name conflicts.
// Construct and append the record variables. // Construct and append the record variables.
for var in record.members.iter() { for var in record.members.iter() {
@ -88,10 +89,12 @@ impl<'a> CodeGenerator<'a> {
CircuitMember::CircuitVariable(name, type_) => (name, type_), CircuitMember::CircuitVariable(name, type_) => (name, type_),
}; };
output_string.push_str(&format!( writeln!(
" {} as {}.private;\n", // todo: CAUTION private record variables only. output_string,
" {} as {}.private;", // todo: CAUTION private record variables only.
name, type_, name, type_,
)) )
.expect("failed to write to string");
} }
output_string output_string
@ -116,7 +119,8 @@ impl<'a> CodeGenerator<'a> {
let type_string = let type_string =
self.visit_type_with_visibility(&input.get_variable().type_, Some(input.get_variable().mode())); self.visit_type_with_visibility(&input.get_variable().type_, Some(input.get_variable().mode()));
function_string.push_str(&format!(" input {} as {};\n", register_string, type_string,)) writeln!(function_string, " input {} as {};", register_string, type_string,)
.expect("failed to write to string");
} }
// Construct and append the function body. // Construct and append the function body.

View File

@ -55,7 +55,7 @@ impl<'a> CodeGenerator<'a> {
true => { true => {
let (operand, expression_instructions) = self.visit_expression(&input.value); let (operand, expression_instructions) = self.visit_expression(&input.value);
self.variable_mapping self.variable_mapping
.insert(&input.variable_names[0].identifier.name, operand.clone()); .insert(&input.variable_names[0].identifier.name, operand);
expression_instructions expression_instructions
} }
} }

View File

@ -17,6 +17,7 @@
use crate::CodeGenerator; use crate::CodeGenerator;
use leo_ast::{ParamMode, Type}; use leo_ast::{ParamMode, Type};
use std::fmt::Write as _;
impl<'a> CodeGenerator<'a> { impl<'a> CodeGenerator<'a> {
pub(crate) fn visit_type(&mut self, input: &'a Type) -> String { pub(crate) fn visit_type(&mut self, input: &'a Type) -> String {
@ -47,7 +48,7 @@ impl<'a> CodeGenerator<'a> {
} else { } else {
// Append `.private` to return type. // Append `.private` to return type.
// todo: CAUTION private by default. // todo: CAUTION private by default.
return_type.push_str(&format!(".{}", visibility.unwrap_or(ParamMode::Private).to_string())); write!(return_type, ".{}", visibility.unwrap_or(ParamMode::Private)).expect("failed to write to string");
} }
return_type return_type

View File

@ -86,10 +86,6 @@ impl Api {
} }
} }
pub fn host(&self) -> &str {
&*self.host
}
/// Returns the token for bearer auth, otherwise None. /// Returns the token for bearer auth, otherwise None.
/// The [`auth_token`] should be passed into the Api through Context. /// The [`auth_token`] should be passed into the Api through Context.
pub fn auth_token(&self) -> Option<String> { pub fn auth_token(&self) -> Option<String> {

View File

@ -25,7 +25,6 @@ use leo_package::{
source::{MainFile, MAIN_FILENAME, SOURCE_DIRECTORY_NAME}, source::{MainFile, MAIN_FILENAME, SOURCE_DIRECTORY_NAME},
}; };
use snarkvm::prelude::*;
use snarkvm_circuit::prelude::*; use snarkvm_circuit::prelude::*;
use clap::StructOpt; use clap::StructOpt;
@ -159,7 +158,7 @@ impl Command for Build {
&handler, &handler,
main_file_path, main_file_path,
output_directory, output_directory,
Some(self.compiler_options.clone().into()), Some(self.compiler_options.into()),
); );
program.parse_input(input_path.to_path_buf())?; program.parse_input(input_path.to_path_buf())?;

View File

@ -299,7 +299,7 @@ mod tests {
}); });
assert_eq!(count_err(res.unwrap_err().to_string()), 2); assert_eq!(count_err(res.unwrap_err().to_string()), 2);
let () = Handler::with(|_| Ok(())).unwrap(); Handler::with(|_| Ok(())).unwrap();
}) })
} }
} }

View File

@ -429,7 +429,7 @@ fn analyze_source_file(src: &str, source_file_start_pos: BytePos) -> (Vec<BytePo
// The slow path: // The slow path:
// This is either ASCII control character "DEL" or the beginning of // This is either ASCII control character "DEL" or the beginning of
// a multibyte char. Just decode to `char`. // a multibyte char. Just decode to `char`.
let c = (&src[i..]).chars().next().unwrap(); let c = (src[i..]).chars().next().unwrap();
char_len = c.len_utf8(); char_len = c.len_utf8();
if char_len > 1 { if char_len > 1 {