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

feat: Add context-centric based API for noir_wasm #3798

Merged
merged 51 commits into from
Dec 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
7e0a3d1
make `find_module` be an immutable reference
kevaundray Dec 10, 2023
b2ff05b
add method in nargo that pre-populates the FileManager
kevaundray Dec 10, 2023
5592348
change add_file to `name_to_id` -- we assume that the file manager ha…
kevaundray Dec 10, 2023
d5fd4e0
cargo
kevaundray Dec 10, 2023
2f137b7
Update tooling/nargo/src/lib.rs
kevaundray Dec 10, 2023
41ae81f
add a method in file manager that allows us to add a file with its so…
kevaundray Dec 10, 2023
c7f576c
add deprecation TODO to file_reader
kevaundray Dec 10, 2023
a2460e6
add stdlib file in noirc_driver that returns the stdlib paths alongsi…
kevaundray Dec 10, 2023
270a0f4
add the contents of the stdlib whenever we call prepare_crate
kevaundray Dec 10, 2023
52d33a5
cargo
kevaundray Dec 10, 2023
a38c27c
cargo fmt
kevaundray Dec 10, 2023
6a5bf33
move tempfile to dev dependencies
kevaundray Dec 10, 2023
f72ce99
add files into file manager in test since find_module does not add fi…
kevaundray Dec 10, 2023
b30ad54
insert all files for this packages dependencies into the file manager…
kevaundray Dec 10, 2023
15a94ee
cargo fmt
kevaundray Dec 10, 2023
4599361
remove un-needed fully qualified path
kevaundray Dec 10, 2023
f20109e
Add note on stdlib
kevaundray Dec 10, 2023
4413350
cargo fmt
kevaundray Dec 10, 2023
d6a24e8
add comment to process_dep_graph and fix setup_test_context
kevaundray Dec 11, 2023
552a4dd
replace expect with unwrap_or_else: expect doesn't allow you to add p…
kevaundray Dec 11, 2023
3f8551b
try: add a `PathToFileSourceMap` object
kevaundray Dec 11, 2023
dd94b46
remove extraneous forward slash
kevaundray Dec 11, 2023
3495de5
add file_manager_with_source_map method so we ensure that FileManager…
kevaundray Dec 11, 2023
851fab1
add expect
kevaundray Dec 11, 2023
3cd35fd
fix node tests
kevaundray Dec 11, 2023
d2590d5
fix browser tests and naming nit
kevaundray Dec 11, 2023
5b867d5
chore!: Remove `add_file` and `file_reader` from FileManager (#3762)
kevaundray Dec 11, 2023
5ebf83a
Update compiler/fm/src/lib.rs
kevaundray Dec 11, 2023
7a787d7
Merge branch 'master' into kw/make-fm-read-only
kevaundray Dec 11, 2023
419273e
file_reader is no longer being used
kevaundray Dec 11, 2023
d120852
Merge branch 'master' into kw/make-fm-read-only
kevaundray Dec 11, 2023
1e9ac97
chore: add simple doc comments for `add_file_with_source` methods
TomAFrench Dec 13, 2023
2350034
add `compile_new` file which uses a more context based API
kevaundray Dec 13, 2023
f472188
modify visibility so we can re-use methods in compile.rs
kevaundray Dec 13, 2023
dd29cf9
cargo fmt
kevaundray Dec 13, 2023
4f18e19
expose API
kevaundray Dec 13, 2023
403bcde
Rename structs so we don't have the Wrapper postfix
kevaundray Dec 13, 2023
5d8bd90
cargo fmt
kevaundray Dec 13, 2023
9e0e5a5
allow program width to be configurable
kevaundray Dec 14, 2023
994e1c2
Merge remote-tracking branch 'origin/master' into kw/add-context-base…
kevaundray Dec 14, 2023
97b9325
fix bad merge
kevaundray Dec 14, 2023
4b5a348
Merge remote-tracking branch 'origin/master' into kw/add-context-base…
kevaundray Dec 16, 2023
e282753
rename ContextWrapper to CompilerContext
kevaundray Dec 16, 2023
067bc71
rename export
kevaundray Dec 16, 2023
915f309
add js test
kevaundray Dec 16, 2023
0d42d09
cargo fmt
kevaundray Dec 16, 2023
9ab0dac
fix: typo
kevaundray Dec 16, 2023
6dd1764
make DependencyGraph pub(crate) visibility, so it can be used to make…
kevaundray Dec 16, 2023
4de1c7f
add compile_ method
kevaundray Dec 16, 2023
54ed150
expose compile_ method
kevaundray Dec 16, 2023
9e99c4d
add test for compile_
kevaundray Dec 16, 2023
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
18 changes: 9 additions & 9 deletions compiler/wasm/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,20 +120,19 @@ impl JsCompileResult {
}
}

#[derive(Deserialize)]
struct DependencyGraph {
root_dependencies: Vec<CrateName>,
library_dependencies: HashMap<CrateName, Vec<CrateName>>,
#[derive(Deserialize, Default)]
pub(crate) struct DependencyGraph {
pub(crate) root_dependencies: Vec<CrateName>,
pub(crate) library_dependencies: HashMap<CrateName, Vec<CrateName>>,
}

#[wasm_bindgen]
// This is a map containing the paths of all of the files in the entry-point crate and
// the transitive dependencies of the entry-point crate.
//
// This is for all intents and purposes the file system that the compiler will use to resolve/compile
// files in the crate being compiled and its dependencies.
#[derive(Deserialize, Default)]
pub struct PathToFileSourceMap(HashMap<std::path::PathBuf, String>);
pub struct PathToFileSourceMap(pub(crate) HashMap<std::path::PathBuf, String>);

#[wasm_bindgen]
impl PathToFileSourceMap {
Expand Down Expand Up @@ -228,7 +227,7 @@ pub fn compile(
//
// For all intents and purposes, the file manager being returned
// should be considered as immutable.
fn file_manager_with_source_map(source_map: PathToFileSourceMap) -> FileManager {
pub(crate) fn file_manager_with_source_map(source_map: PathToFileSourceMap) -> FileManager {
let root = Path::new("");
let mut fm = FileManager::new(root);

Expand Down Expand Up @@ -277,7 +276,7 @@ fn add_noir_lib(context: &mut Context, library_name: &CrateName) -> CrateId {
prepare_dependency(context, &path_to_lib)
}

fn preprocess_program(program: CompiledProgram) -> CompileResult {
pub(crate) fn preprocess_program(program: CompiledProgram) -> CompileResult {
let debug_artifact = DebugArtifact {
debug_symbols: vec![program.debug],
file_map: program.file_map,
Expand All @@ -295,7 +294,8 @@ fn preprocess_program(program: CompiledProgram) -> CompileResult {
CompileResult::Program { program: preprocessed_program, debug: debug_artifact }
}

fn preprocess_contract(contract: CompiledContract) -> CompileResult {
// TODO: This method should not be doing so much, most of this should be done in nargo or the driver
pub(crate) fn preprocess_contract(contract: CompiledContract) -> CompileResult {
let debug_artifact = DebugArtifact {
debug_symbols: contract.functions.iter().map(|function| function.debug.clone()).collect(),
file_map: contract.file_map,
Expand Down
336 changes: 336 additions & 0 deletions compiler/wasm/src/compile_new.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,336 @@
use crate::compile::{
file_manager_with_source_map, preprocess_contract, preprocess_program, JsCompileResult,
PathToFileSourceMap,
};
use crate::errors::{CompileError, JsCompileError};
use noirc_driver::{
add_dep, compile_contract, compile_main, prepare_crate, prepare_dependency, CompileOptions,
};
use noirc_frontend::{
graph::{CrateGraph, CrateId, CrateName},
hir::Context,
};
use std::path::Path;
use wasm_bindgen::prelude::wasm_bindgen;

/// This is a wrapper class that is wasm-bindgen compatible
/// We do not use js_name and rename it like CrateId because
/// then the impl block is not picked up in javascript.
#[wasm_bindgen]
pub struct CompilerContext {
context: Context,
kevaundray marked this conversation as resolved.
Show resolved Hide resolved
}

#[wasm_bindgen(js_name = "CrateId")]
#[derive(Debug, Copy, Clone)]
pub struct CrateIDWrapper(CrateId);
kevaundray marked this conversation as resolved.
Show resolved Hide resolved

#[wasm_bindgen]
impl CompilerContext {
#[wasm_bindgen(constructor)]
pub fn new(source_map: PathToFileSourceMap) -> CompilerContext {
console_error_panic_hook::set_once();

let fm = file_manager_with_source_map(source_map);
let graph = CrateGraph::default();
CompilerContext { context: Context::new(fm, graph) }
}

#[cfg(test)]
pub(crate) fn crate_graph(&self) -> &CrateGraph {
&self.context.crate_graph
}
#[cfg(test)]
pub(crate) fn root_crate_id(&self) -> CrateIDWrapper {
CrateIDWrapper(*self.context.root_crate_id())
}

// Processes the root crate by adding it to the package graph and automatically
// importing the stdlib as a dependency for it.
//
// Its ID in the package graph is returned
pub fn process_root_crate(&mut self, path_to_crate: String) -> CrateIDWrapper {
let path_to_crate = Path::new(&path_to_crate);

// Adds the root crate to the crate graph and returns its crate id
CrateIDWrapper(prepare_crate(&mut self.context, path_to_crate))
}

pub fn process_dependency_crate(&mut self, path_to_crate: String) -> CrateIDWrapper {
let path_to_crate = Path::new(&path_to_crate);

// Adds the root crate to the crate graph and returns its crate id
CrateIDWrapper(prepare_dependency(&mut self.context, path_to_crate))
}

// Adds a named edge from one crate to the other.
//
// For example, lets say we have two crates CrateId1 and CrateId2
// This function will add an edge from CrateId1 to CrateId2 and the edge will be named `crate_name`
//
// This essentially says that CrateId1 depends on CrateId2 and the dependency is named `crate_name`
//
// We pass references to &CrateIdWrapper even though it is a copy because Rust's move semantics are
// not respected once we use javascript. ie it will actually allocated a new object in javascript
// then deallocate that object if we do not pass as a reference.
pub fn add_dependency_edge(
&mut self,
crate_name: String,
from: &CrateIDWrapper,
to: &CrateIDWrapper,
) {
let parsed_crate_name: CrateName = crate_name
.parse()
.unwrap_or_else(|_| panic!("Failed to parse crate name {}", crate_name));
add_dep(&mut self.context, from.0, to.0, parsed_crate_name);
}

pub fn compile_program(
mut self,
program_width: usize,
) -> Result<JsCompileResult, JsCompileError> {
let compile_options = CompileOptions::default();
let np_language = acvm::Language::PLONKCSat { width: program_width };

let root_crate_id = *self.context.root_crate_id();

let compiled_program =
compile_main(&mut self.context, root_crate_id, &compile_options, None, true)
.map_err(|errs| {
CompileError::with_file_diagnostics(
"Failed to compile program",
errs,
&self.context.file_manager,
)
})?
.0;

let optimized_program = nargo::ops::optimize_program(compiled_program, np_language);

let compile_output = preprocess_program(optimized_program);
Ok(JsCompileResult::new(compile_output))
}

pub fn compile_contract(
mut self,
program_width: usize,
) -> Result<JsCompileResult, JsCompileError> {
let compile_options = CompileOptions::default();
let np_language = acvm::Language::PLONKCSat { width: program_width };
let root_crate_id = *self.context.root_crate_id();

let compiled_contract =
compile_contract(&mut self.context, root_crate_id, &compile_options)
.map_err(|errs| {
CompileError::with_file_diagnostics(
"Failed to compile contract",
errs,
&self.context.file_manager,
)
})?
.0;

let optimized_contract = nargo::ops::optimize_contract(compiled_contract, np_language);

let compile_output = preprocess_contract(optimized_contract);
Ok(JsCompileResult::new(compile_output))
kevaundray marked this conversation as resolved.
Show resolved Hide resolved
}
}

/// This is a method that exposes the same API as `compile`
/// But uses the Context based APi internally
#[wasm_bindgen]
pub fn compile_(
entry_point: String,
contracts: Option<bool>,
dependency_graph: Option<crate::compile::JsDependencyGraph>,
file_source_map: PathToFileSourceMap,
) -> Result<JsCompileResult, JsCompileError> {
use std::collections::HashMap;

console_error_panic_hook::set_once();

let dependency_graph: crate::compile::DependencyGraph =
if let Some(dependency_graph) = dependency_graph {
<wasm_bindgen::JsValue as gloo_utils::format::JsValueSerdeExt>::into_serde(
&wasm_bindgen::JsValue::from(dependency_graph),
)
.map_err(|err| err.to_string())?
} else {
crate::compile::DependencyGraph::default()
};

let mut compiler_context = CompilerContext::new(file_source_map);

// Set the root crate
let root_id = compiler_context.process_root_crate(entry_point.clone());

let add_noir_lib = |context: &mut CompilerContext, lib_name: &CrateName| -> CrateIDWrapper {
let lib_name_string = lib_name.to_string();
let path_to_lib = Path::new(&lib_name_string)
.join("lib.nr")
.to_str()
.expect("paths are expected to be valid utf-8")
.to_string();
context.process_dependency_crate(path_to_lib)
};

// Add the dependency graph
let mut crate_names: HashMap<CrateName, CrateIDWrapper> = HashMap::new();
//
// Process the direct dependencies of the root
for lib_name in dependency_graph.root_dependencies {
let lib_name_string = lib_name.to_string();

let crate_id = add_noir_lib(&mut compiler_context, &lib_name);

crate_names.insert(lib_name.clone(), crate_id);

// Add the dependency edges
compiler_context.add_dependency_edge(lib_name_string, &root_id, &crate_id);
}

// Process the transitive dependencies of the root
for (lib_name, dependencies) in &dependency_graph.library_dependencies {
// first create the library crate if needed
// this crate might not have been registered yet because of the order of the HashMap
// e.g. {root: [lib1], libs: { lib2 -> [lib3], lib1 -> [lib2] }}
let crate_id = *crate_names
.entry(lib_name.clone())
.or_insert_with(|| add_noir_lib(&mut compiler_context, lib_name));

for dependency_name in dependencies {
let dependency_name_string = dependency_name.to_string();

let dep_crate_id = crate_names
.entry(dependency_name.clone())
.or_insert_with(|| add_noir_lib(&mut compiler_context, dependency_name));

compiler_context.add_dependency_edge(dependency_name_string, &crate_id, dep_crate_id);
}
}

let is_contract = contracts.unwrap_or(false);
let program_width = 3;

if is_contract {
compiler_context.compile_contract(program_width)
} else {
compiler_context.compile_program(program_width)
}
}

#[cfg(test)]
mod test {
use noirc_driver::prepare_crate;
use noirc_frontend::{graph::CrateGraph, hir::Context};

use crate::compile::{file_manager_with_source_map, PathToFileSourceMap};

use std::path::Path;

use super::CompilerContext;

fn setup_test_context(source_map: PathToFileSourceMap) -> CompilerContext {
let mut fm = file_manager_with_source_map(source_map);
// Add this due to us calling prepare_crate on "/main.nr" below
fm.add_file_with_source(Path::new("/main.nr"), "fn foo() {}".to_string());

let graph = CrateGraph::default();
let mut context = Context::new(fm, graph);
prepare_crate(&mut context, Path::new("/main.nr"));

CompilerContext { context }
}

#[test]
fn test_works_with_empty_dependency_graph() {
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved
let source_map = PathToFileSourceMap::default();
let context = setup_test_context(source_map);

// one stdlib + one root crate
assert_eq!(context.crate_graph().number_of_crates(), 2);
}

#[test]
fn test_works_with_root_dependencies() {
let source_map = PathToFileSourceMap(
vec![(Path::new("lib1/lib.nr").to_path_buf(), "fn foo() {}".to_string())]
.into_iter()
.collect(),
);

let mut context = setup_test_context(source_map);
context.process_dependency_crate("lib1/lib.nr".to_string());

assert_eq!(context.crate_graph().number_of_crates(), 3);
}

#[test]
fn test_works_with_duplicate_root_dependencies() {
let source_map = PathToFileSourceMap(
vec![(Path::new("lib1/lib.nr").to_path_buf(), "fn foo() {}".to_string())]
.into_iter()
.collect(),
);
let mut context = setup_test_context(source_map);

let lib1_crate_id = context.process_dependency_crate("lib1/lib.nr".to_string());
let root_crate_id = context.root_crate_id();

context.add_dependency_edge("lib1".to_string(), &root_crate_id, &lib1_crate_id);
context.add_dependency_edge("lib1".to_string(), &root_crate_id, &lib1_crate_id);

assert_eq!(context.crate_graph().number_of_crates(), 3);
}

#[test]
fn test_works_with_transitive_dependencies() {
let source_map = PathToFileSourceMap(
vec![
(Path::new("lib1/lib.nr").to_path_buf(), "fn foo() {}".to_string()),
(Path::new("lib2/lib.nr").to_path_buf(), "fn foo() {}".to_string()),
(Path::new("lib3/lib.nr").to_path_buf(), "fn foo() {}".to_string()),
]
.into_iter()
.collect(),
);

let mut context = setup_test_context(source_map);

let lib1_crate_id = context.process_dependency_crate("lib1/lib.nr".to_string());
let lib2_crate_id = context.process_dependency_crate("lib2/lib.nr".to_string());
let lib3_crate_id = context.process_dependency_crate("lib3/lib.nr".to_string());
let root_crate_id = context.root_crate_id();

context.add_dependency_edge("lib1".to_string(), &root_crate_id, &lib1_crate_id);
context.add_dependency_edge("lib2".to_string(), &lib1_crate_id, &lib2_crate_id);
context.add_dependency_edge("lib3".to_string(), &lib2_crate_id, &lib3_crate_id);

assert_eq!(context.crate_graph().number_of_crates(), 5);
}

#[test]
fn test_works_with_missing_dependencies() {
let source_map = PathToFileSourceMap(
vec![
(Path::new("lib1/lib.nr").to_path_buf(), "fn foo() {}".to_string()),
(Path::new("lib2/lib.nr").to_path_buf(), "fn foo() {}".to_string()),
(Path::new("lib3/lib.nr").to_path_buf(), "fn foo() {}".to_string()),
]
.into_iter()
.collect(),
);
let mut context = setup_test_context(source_map);

let lib1_crate_id = context.process_dependency_crate("lib1/lib.nr".to_string());
let lib2_crate_id = context.process_dependency_crate("lib2/lib.nr".to_string());
let lib3_crate_id = context.process_dependency_crate("lib3/lib.nr".to_string());
let root_crate_id = context.root_crate_id();

context.add_dependency_edge("lib1".to_string(), &root_crate_id, &lib1_crate_id);
context.add_dependency_edge("lib3".to_string(), &lib2_crate_id, &lib3_crate_id);

assert_eq!(context.crate_graph().number_of_crates(), 5);
}
}
Loading
Loading