Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] leo fmt #28333

Draft
wants to merge 4 commits into
base: mainnet
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ members = [
"leo/package",
"tests/test-framework",
"utils/disassembler",
"utils/linter",
"utils/retriever"
]

Expand Down
133 changes: 133 additions & 0 deletions compiler/ast/src/cst/functions/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (C) 2019-2024 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// 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/>.


use crate::{FunctionStub, Identifier, Node, NodeID, TupleType, Type, Annotation, Variant, Input, Output};
use crate::cst::Block;
use leo_span::{Span, Symbol};
use serde::{Deserialize, Serialize};
use std::fmt;

/// A function definition.
#[derive(Clone, Serialize, Deserialize)]
pub struct Function {
/// Annotations on the function.
pub annotations: Vec<Annotation>,
/// Is this function a transition, inlined, or a regular function?.
pub variant: Variant,
/// The function identifier, e.g., `foo` in `function foo(...) { ... }`.
pub identifier: Identifier,
/// The function's input parameters.
pub input: Vec<Input>,
/// The function's output declarations.
pub output: Vec<Output>,
/// The function's output type.
pub output_type: Type,
/// The body of the function.
pub block: Block,
/// The entire span of the function definition.
pub span: Span,
/// The ID of the node.
pub id: NodeID,
}

impl PartialEq for Function {
fn eq(&self, other: &Self) -> bool {
self.identifier == other.identifier
}
}

impl Eq for Function {}

impl Function {
/// Initialize a new function.
#[allow(clippy::too_many_arguments)]
pub fn new(
annotations: Vec<Annotation>,
variant: Variant,
identifier: Identifier,
input: Vec<Input>,
output: Vec<Output>,
block: Block,
span: Span,
id: NodeID,
) -> Self {
let output_type = match output.len() {
0 => Type::Unit,
1 => output[0].type_.clone(),
_ => Type::Tuple(TupleType::new(output.iter().map(|o| o.type_.clone()).collect())),
};

Function { annotations, variant, identifier, input, output, output_type, block, span, id }
}

/// Returns function name.
pub fn name(&self) -> Symbol {
self.identifier.name
}

///
/// Private formatting method used for optimizing [fmt::Debug] and [fmt::Display] implementations.
///
fn format(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.variant {
Variant::Inline => write!(f, "inline ")?,
Variant::Function | Variant::AsyncFunction => write!(f, "function ")?,
Variant::Transition | Variant::AsyncTransition => write!(f, "transition ")?,
}
write!(f, "{}", self.identifier)?;

let parameters = self.input.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");
let returns = match self.output.len() {
0 => "()".to_string(),
1 => self.output[0].to_string(),
_ => self.output.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(","),
};
write!(f, "({parameters}) -> {returns} {}", self.block)?;

Ok(())
}
}

impl From<FunctionStub> for Function {
fn from(function: FunctionStub) -> Self {
Self {
annotations: function.annotations,
variant: function.variant,
identifier: function.identifier,
input: function.input,
output: function.output,
output_type: function.output_type,
block: Block::default(),
span: function.span,
id: function.id,
}
}
}

impl fmt::Debug for Function {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.format(f)
}
}

impl fmt::Display for Function {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.format(f)
}
}

crate::simple_node_impl!(Function);
59 changes: 59 additions & 0 deletions compiler/ast/src/cst/mapping/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (C) 2019-2024 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// 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/>.

use crate::{Identifier, NodeID, Type};
use crate::cst::Comment;
use leo_span::Span;
use serde::{Deserialize, Serialize};
use snarkvm::prelude::{Mapping as MappingCore, Network};
use std::fmt;

/// A mapping declaration, e.g `mapping balances: address => u128`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Mapping {
/// The name of the mapping.
pub identifier: Identifier,
/// The type of the key.
pub key_type: Type,
/// The type of the value.
pub value_type: Type,
/// The entire span of the mapping declaration.
pub span: Span,
/// The ID of the node.
pub id: NodeID,
///The comment of the mapping
pub comment: Comment
}

impl Mapping {
pub fn from_snarkvm<N: Network>(mapping: &MappingCore<N>) -> Self {
Self {
identifier: Identifier::from(mapping.name()),
key_type: Type::from_snarkvm(mapping.key().plaintext_type(), None),
value_type: Type::from_snarkvm(mapping.value().plaintext_type(), None),
span: Default::default(),
id: Default::default(),
comment: Comment::None
}
}
}
impl fmt::Display for Mapping {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "mapping {}: {} => {}; ", self.identifier, self.key_type, self.value_type)?;
self.comment.fmt(f)?;
Ok(())
}
}
171 changes: 171 additions & 0 deletions compiler/ast/src/cst/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// Copyright (C) 2019-2024 Aleo Systems Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// 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/>.

//! The abstract syntax tree (ast) for a Leo program.
//!
//! This module contains the [`Ast`] type, a wrapper around the [`Program`] type.
//! The [`Ast`] type is intended to be parsed and modified by different passes
//! of the Leo compiler. The Leo compiler can generate a set of R1CS constraints from any [`Ast`].

#![allow(ambiguous_glob_reexports)]

pub mod r#struct;
pub use self::r#struct::*;


pub mod mapping;
pub use self::mapping::*;

pub mod program;
pub use self::program::*;

pub mod statement;
pub use self::statement::*;

pub mod functions;
pub use self::functions::*;


use leo_errors::{AstError, Result};

/// The abstract syntax tree (AST) for a Leo program.
///
/// The [`Ast`] type represents a Leo program as a series of recursive data types.
/// These data types form a tree that begins from a [`Program`] type root.
#[derive(Clone, Debug, Default)]
pub struct Cst {
pub cst: Program,
}

impl Cst {
/// Creates a new AST from a given program tree.
pub fn new(program: Program) -> Self {
Self { cst: program }
}

/// Returns a reference to the inner program AST representation.
pub fn as_repr(&self) -> &Program {
&self.cst
}

pub fn into_repr(self) -> Program {
self.cst
}

/// Serializes the ast into a JSON string.
pub fn to_json_string(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(&self.cst).map_err(|e| AstError::failed_to_convert_ast_to_json_string(&e))?)
}

// Converts the ast into a JSON value.
// Note that there is no corresponding `from_json_value` function
// since we modify JSON values leaving them unable to be converted
// back into Programs.
pub fn to_json_value(&self) -> Result<serde_json::Value> {
Ok(serde_json::to_value(&self.cst).map_err(|e| AstError::failed_to_convert_ast_to_json_value(&e))?)
}

/// Serializes the ast into a JSON file.
pub fn to_json_file(&self, mut path: std::path::PathBuf, file_name: &str) -> Result<()> {
path.push(file_name);
let file = std::fs::File::create(&path).map_err(|e| AstError::failed_to_create_ast_json_file(&path, &e))?;
let writer = std::io::BufWriter::new(file);
Ok(serde_json::to_writer_pretty(writer, &self.cst)
.map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e))?)
}

/// Serializes the ast into a JSON value and removes keys from object mappings before writing to a file.
pub fn to_json_file_without_keys(
&self,
mut path: std::path::PathBuf,
file_name: &str,
excluded_keys: &[&str],
) -> Result<()> {
path.push(file_name);
let file = std::fs::File::create(&path).map_err(|e| AstError::failed_to_create_ast_json_file(&path, &e))?;
let writer = std::io::BufWriter::new(file);

let mut value = self.to_json_value().unwrap();
for key in excluded_keys {
value = remove_key_from_json(value, key);
}
value = normalize_json_value(value);

Ok(serde_json::to_writer_pretty(writer, &value)
.map_err(|e| AstError::failed_to_write_ast_to_json_file(&path, &e))?)
}

/// Deserializes the JSON string into a ast.
pub fn from_json_string(json: &str) -> Result<Self> {
let cst: Program = serde_json::from_str(json).map_err(|e| AstError::failed_to_read_json_string_to_ast(&e))?;
Ok(Self { cst })
}

/// Deserializes the JSON string into a ast from a file.
pub fn from_json_file(path: std::path::PathBuf) -> Result<Self> {
let data = std::fs::read_to_string(&path).map_err(|e| AstError::failed_to_read_json_file(&path, &e))?;
Self::from_json_string(&data)
}
}

impl AsRef<Program> for Cst {
fn as_ref(&self) -> &Program {
&self.cst
}
}


/// Helper function to recursively filter keys from AST JSON
pub fn remove_key_from_json(value: serde_json::Value, key: &str) -> serde_json::Value {
match value {
serde_json::Value::Object(map) => serde_json::Value::Object(
map.into_iter().filter(|(k, _)| k != key).map(|(k, v)| (k, remove_key_from_json(v, key))).collect(),
),
serde_json::Value::Array(values) => {
serde_json::Value::Array(values.into_iter().map(|v| remove_key_from_json(v, key)).collect())
}
_ => value,
}
}

/// Helper function to normalize AST JSON into a form compatible with tgc.
/// This function will traverse the original JSON value and produce a new
/// one under the following rules:
/// 1. Remove empty object mappings from JSON arrays
/// 2. If there are two elements in a JSON array and one is an empty object
/// mapping and the other is not, then lift up the one that isn't
pub fn normalize_json_value(value: serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Array(vec) => {
let orig_length = vec.len();
let mut new_vec: Vec<serde_json::Value> = vec
.into_iter()
.filter(|v| !matches!(v, serde_json::Value::Object(map) if map.is_empty()))
.map(normalize_json_value)
.collect();

if orig_length == 2 && new_vec.len() == 1 {
new_vec.pop().unwrap()
} else {
serde_json::Value::Array(new_vec)
}
}
serde_json::Value::Object(map) => {
serde_json::Value::Object(map.into_iter().map(|(k, v)| (k, normalize_json_value(v))).collect())
}
_ => value,
}
}
Loading
Loading