leo/types/src/program.rs

87 lines
2.6 KiB
Rust
Raw Normal View History

2020-06-08 06:57:22 +03:00
//! A typed Leo program consists of import, circuit, and function definitions.
//! Each defined type consists of typed statements and expressions.
use crate::{Circuit, Function, FunctionInput, Identifier, Import, TestFunction};
2020-06-08 09:30:39 +03:00
use leo_ast::files::File;
2020-04-17 22:51:02 +03:00
2020-05-14 01:19:25 +03:00
use std::collections::HashMap;
2020-06-08 06:57:22 +03:00
/// A simple program with statement expressions, program arguments and program returns.
#[derive(Debug, Clone)]
pub struct Program {
pub name: Identifier,
pub expected_inputs: Vec<FunctionInput>,
2020-06-08 06:57:22 +03:00
pub imports: Vec<Import>,
pub circuits: HashMap<Identifier, Circuit>,
pub functions: HashMap<Identifier, Function>,
pub tests: HashMap<Identifier, TestFunction>,
}
2020-04-20 23:06:47 +03:00
2020-06-08 06:57:22 +03:00
impl<'ast> Program {
//! Logic to convert from an abstract syntax tree (ast) representation to a Leo program.
2020-06-08 03:22:22 +03:00
pub fn from(file: File<'ast>, name: String) -> Self {
2020-04-16 21:36:23 +03:00
// Compiled ast -> aleo program representation
2020-04-17 22:51:02 +03:00
let imports = file
.imports
.into_iter()
.map(|import| Import::from(import))
.collect::<Vec<Import>>();
2020-04-16 21:36:23 +03:00
let mut circuits = HashMap::new();
let mut functions = HashMap::new();
2020-06-05 02:55:23 +03:00
let mut tests = HashMap::new();
let mut expected_inputs = vec![];
file.circuits.into_iter().for_each(|circuit| {
2020-06-08 09:30:39 +03:00
circuits.insert(Identifier::from(circuit.identifier.clone()), Circuit::from(circuit));
});
file.functions.into_iter().for_each(|function_def| {
2020-04-16 08:17:44 +03:00
functions.insert(
Identifier::from(function_def.function_name.clone()),
2020-06-08 06:35:50 +03:00
Function::from(function_def),
2020-04-16 08:17:44 +03:00
);
});
2020-06-05 02:55:23 +03:00
file.tests.into_iter().for_each(|test_def| {
tests.insert(
Identifier::from(test_def.function.function_name.clone()),
2020-06-08 06:35:50 +03:00
TestFunction::from(test_def),
2020-06-05 02:55:23 +03:00
);
});
if let Some(main_function) = functions.get(&Identifier::new("main".into())) {
expected_inputs = main_function.inputs.clone();
2020-05-06 03:24:34 +03:00
}
2020-06-08 06:57:22 +03:00
Self {
name: Identifier::new(name),
expected_inputs,
2020-04-17 22:51:02 +03:00
imports,
circuits,
2020-04-17 22:51:02 +03:00
functions,
2020-06-05 02:55:23 +03:00
tests,
2020-04-17 22:51:02 +03:00
}
}
}
2020-06-08 06:57:22 +03:00
impl Program {
pub fn new() -> Self {
Self {
name: Identifier::new("".into()),
expected_inputs: vec![],
2020-06-08 06:57:22 +03:00
imports: vec![],
circuits: HashMap::new(),
functions: HashMap::new(),
tests: HashMap::new(),
}
}
pub fn get_name(&self) -> String {
self.name.name.clone()
}
pub fn name(mut self, name: String) -> Self {
self.name = Identifier::new(name);
self
}
}