diff --git a/.github/workflows/test-js-packages.yml b/.github/workflows/test-js-packages.yml index abf6e6f3e16..80f9b58f62e 100644 --- a/.github/workflows/test-js-packages.yml +++ b/.github/workflows/test-js-packages.yml @@ -566,7 +566,14 @@ jobs: test-examples: name: Example scripts runs-on: ubuntu-24.04 - needs: [build-nargo, build-noir-execute, build-noir-ssa, build-acvm-js, build-noirc-abi] + needs: + [ + build-nargo, + build-noir-execute, + build-noir-ssa, + build-acvm-js, + build-noirc-abi, + ] timeout-minutes: 30 permissions: contents: read @@ -786,6 +793,31 @@ jobs: alert-comment-cc-users: "@TomAFrench" max-items-in-chart: 50 + test-nargo-doc: + needs: [build-nargo] + name: Nargo doc + runs-on: ubuntu-22.04 + timeout-minutes: 30 + permissions: + contents: read + + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Download nargo binary + uses: ./.github/actions/download-nargo + + - name: nargo doc on stdlib + working-directory: ./noir_stdlib + run: | + nargo doc + rm -rf ./docs + mv ./target/docs . + if ! git diff --exit-code; then + echo "nargo doc produced changes on noir_stdlib" + exit 1 + fi # This is a job which depends on all test jobs and reports the overall status. # This allows us to add/remove test jobs without having to update the required workflows. @@ -804,19 +836,20 @@ jobs: - test-noir-codegen - test-integration-node #- test-integration-browser + - test-nargo-doc - test-examples - compile-noir-contracts permissions: contents: read steps: - - name: Report overall success - run: | - if [[ $FAIL == true ]]; then - exit 1 - else - exit 0 - fi - env: - # We treat any skipped or failing jobs as a failure for the workflow as a whole. - FAIL: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }} + - name: Report overall success + run: | + if [[ $FAIL == true ]]; then + exit 1 + else + exit 0 + fi + env: + # We treat any skipped or failing jobs as a failure for the workflow as a whole. + FAIL: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }} diff --git a/Cargo.lock b/Cargo.lock index 4638edfb3c3..1dc5168da6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3154,6 +3154,15 @@ dependencies = [ "url", ] +[[package]] +name = "markdown" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cab8f2cadc416a82d2e783a1946388b31654d391d1c7d92cc1f03e295b1deb" +dependencies = [ + "unicode-id", +] + [[package]] name = "matchers" version = "0.2.0" @@ -3304,6 +3313,7 @@ dependencies = [ "lazy_static", "light-poseidon", "nargo", + "nargo_doc", "nargo_expand", "nargo_fmt", "nargo_toml", @@ -3348,6 +3358,18 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "nargo_doc" +version = "1.0.0-beta.14" +dependencies = [ + "iter-extended", + "markdown", + "noirc_driver", + "noirc_errors", + "noirc_frontend", + "serde", +] + [[package]] name = "nargo_expand" version = "1.0.0-beta.14" @@ -6592,6 +6614,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unicode-id" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ba288e709927c043cbe476718d37be306be53fb1fafecd0dbe36d072be2580" + [[package]] name = "unicode-ident" version = "1.0.18" diff --git a/Cargo.toml b/Cargo.toml index 8c1e742b220..6542cf47635 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ members = [ "tooling/ast_fuzzer/fuzz", "tooling/greybox_fuzzer", "tooling/nargo", + "tooling/nargo_doc", "tooling/nargo_expand", "tooling/nargo_fmt", "tooling/nargo_cli", @@ -111,6 +112,7 @@ noirc_span = { path = "compiler/noirc_span" } noir_greybox_fuzzer = { path = "tooling/greybox_fuzzer" } nargo = { path = "tooling/nargo" } nargo_cli = { path = "tooling/nargo_cli" } +nargo_doc = { path = "tooling/nargo_doc" } nargo_expand = { path = "tooling/nargo_expand" } nargo_fmt = { path = "tooling/nargo_fmt" } nargo_toml = { path = "tooling/nargo_toml" } @@ -169,10 +171,6 @@ pprof = { version = "^0.15.0", features = ["flamegraph", "criterion"] } prost = "0.13" prost-build = "0.13" protoc-bin-vendored = "3.1.0" - - -# MessagePack -rmp = "0.8.14" rmp-serde = "1.3.0" rmpv = "1.3.0" diff --git a/compiler/noirc_frontend/src/hir/printer/items.rs b/compiler/noirc_frontend/src/hir/printer/items.rs index 16106a246b5..bc5d89a2a10 100644 --- a/compiler/noirc_frontend/src/hir/printer/items.rs +++ b/compiler/noirc_frontend/src/hir/printer/items.rs @@ -7,16 +7,18 @@ mod hir_def; mod types; use crate::{ - Kind, NamedGeneric, Type, - ast::ItemVisibility, + Kind, NamedGeneric, QuotedType, Type, + ast::{IntegerBitSize, ItemVisibility}, hir::def_map::ModuleId, modules::module_def_id_to_reference_id, node_interner::{ FuncId, GlobalId, ImplMethod, Methods, TraitId, TraitImplId, TypeAliasId, TypeId, }, + shared::Signedness, }; use noirc_errors::Location; use std::collections::{BTreeMap, BTreeSet, HashSet}; +use strum::IntoEnumIterator; use crate::graph::CrateId; use crate::{ @@ -25,77 +27,85 @@ use crate::{ node_interner::NodeInterner, }; -pub(super) enum Item { +pub enum Item { Module(Module), DataType(DataType), Trait(Trait), TypeAlias(TypeAliasId), + PrimitiveType(PrimitiveType), Global(GlobalId), Function(FuncId), } impl Item { - pub(super) fn module_def_id(&self) -> ModuleDefId { + pub fn module_def_id(&self) -> ModuleDefId { match self { Item::Module(module) => ModuleDefId::ModuleId(module.id), Item::DataType(data_type) => ModuleDefId::TypeId(data_type.id), Item::Trait(trait_) => ModuleDefId::TraitId(trait_.id), Item::TypeAlias(type_alias_id) => ModuleDefId::TypeAliasId(*type_alias_id), + Item::PrimitiveType(_) => panic!("No ModuleDefId for PrimitiveType"), Item::Global(global_id) => ModuleDefId::GlobalId(*global_id), Item::Function(func_id) => ModuleDefId::FunctionId(*func_id), } } } -pub(super) struct Module { - pub(super) id: ModuleId, - pub(super) name: Option, - pub(super) is_contract: bool, - pub(super) imports: Vec, - pub(super) items: Vec<(ItemVisibility, Item)>, +pub struct Module { + pub id: ModuleId, + pub name: Option, + pub is_contract: bool, + pub imports: Vec, + pub items: Vec<(ItemVisibility, Item)>, } -pub(super) struct DataType { - pub(super) id: TypeId, - pub(super) impls: Vec, - pub(super) trait_impls: Vec, +pub struct DataType { + pub id: TypeId, + pub impls: Vec, + pub trait_impls: Vec, } -pub(super) struct Trait { - pub(super) id: TraitId, - pub(super) methods: Vec, - pub(super) trait_impls: Vec, +pub struct Trait { + pub id: TraitId, + pub methods: Vec, + pub trait_impls: Vec, } -pub(super) struct Impl { - pub(super) generics: BTreeSet<(String, Kind)>, - pub(super) typ: Type, - pub(super) methods: Vec<(ItemVisibility, FuncId)>, +pub struct PrimitiveType { + pub typ: Type, + pub impls: Vec, + pub trait_impls: Vec, } -pub(super) struct TraitImpl { - pub(super) generics: BTreeSet<(String, Kind)>, - pub(super) id: TraitImplId, - pub(super) methods: Vec, +pub struct Impl { + pub generics: BTreeSet<(String, Kind)>, + pub typ: Type, + pub methods: Vec<(ItemVisibility, FuncId)>, } -pub(super) struct Import { - pub(super) name: Ident, - pub(super) id: ModuleDefId, - pub(super) visibility: ItemVisibility, - pub(super) is_prelude: bool, +#[derive(Clone)] +pub struct TraitImpl { + pub generics: BTreeSet<(String, Kind)>, + pub id: TraitImplId, + pub methods: Vec, + /// True if the trait impl only mentions types from external crates. + /// (for example `impl Trait for Field` in a non-stdlib crate) + pub external_types: bool, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Import { + pub name: Ident, + pub id: ModuleDefId, + pub visibility: ItemVisibility, + pub is_prelude: bool, } pub(super) struct ItemBuilder<'context> { crate_id: CrateId, interner: &'context NodeInterner, def_maps: &'context DefMaps, - /// This set is initially created with all the trait impls in the crate. - /// As we traverse traits, will gather trait impls associated to those traits - /// that aren't associated to types in the current crate. - /// As we find structs and enums, we'll gather trait impls associated to those types. - /// Because a trait impl might be associated to multiple types, once we link a trait - /// impl to a type we'll remove it from this set. + /// All trait implementations in the current crate. trait_impls: HashSet, } @@ -109,7 +119,7 @@ impl<'context> ItemBuilder<'context> { Self { crate_id, interner, def_maps, trait_impls } } - pub(super) fn build_module(&mut self, module_id: ModuleId) -> Item { + pub(super) fn build_module(&mut self, module_id: ModuleId) -> Module { let attributes = self.interner.try_module_attributes(module_id); let name = attributes.map(|attributes| attributes.name.clone()); let module_data = &self.def_maps[&self.crate_id][module_id.local_id]; @@ -165,7 +175,7 @@ impl<'context> ItemBuilder<'context> { }) .collect(); - Item::Module(Module { id: module_id, name, is_contract, imports, items }) + Module { id: module_id, name, is_contract, imports, items } } fn module_def_id_location(&self, module_def_id: ModuleDefId) -> Location { @@ -176,7 +186,7 @@ impl<'context> ItemBuilder<'context> { fn build_module_def_id(&mut self, module_def_id: ModuleDefId) -> Option { Some(match module_def_id { - ModuleDefId::ModuleId(module_id) => self.build_module(module_id), + ModuleDefId::ModuleId(module_id) => Item::Module(self.build_module(module_id)), ModuleDefId::TypeId(type_id) => self.build_data_type(type_id), ModuleDefId::TypeAliasId(type_alias_id) => Item::TypeAlias(type_alias_id), ModuleDefId::TraitId(trait_id) => self.build_trait(trait_id), @@ -192,7 +202,7 @@ impl<'context> ItemBuilder<'context> { let impls = if let Some(methods) = self.interner.get_type_methods(&Type::DataType(data_type.clone(), vec![])) { - self.build_data_type_impls(methods.values()) + self.build_impls(methods.values()) } else { Vec::new() }; @@ -203,10 +213,7 @@ impl<'context> ItemBuilder<'context> { Item::DataType(DataType { id: type_id, impls, trait_impls }) } - fn build_data_type_impls<'a, 'b>( - &'a mut self, - methods: impl Iterator, - ) -> Vec { + fn build_impls<'a, 'b>(&'a mut self, methods: impl Iterator) -> Vec { // Gather all impl methods // First split methods by impl methods and trait impl methods let mut impl_methods = Vec::new(); @@ -279,25 +286,18 @@ impl<'context> ItemBuilder<'context> { trait_impls.into_iter().map(|(trait_impl, _)| self.build_trait_impl(trait_impl)).collect() } - /// Builds trait impls for traits, but only when those impls are - /// for types outside of the current crate as they are likely defined next - /// to the trait. fn build_trait_impls_for_trait(&mut self, trait_id: TraitId) -> Vec { - let mut trait_impls = self - .trait_impls - .iter() - .filter_map(|trait_impl_id| { - let trait_impl = self.interner.get_trait_implementation(*trait_impl_id); - let trait_impl = trait_impl.borrow(); - if trait_impl.trait_id == trait_id - && self.type_only_mention_types_outside_current_crate(&trait_impl.typ) - { - Some((*trait_impl_id, trait_impl.location)) - } else { - None - } - }) - .collect::>(); + let mut trait_impls = Vec::new(); + + for trait_impl_id in &self.trait_impls { + let trait_impl = self.interner.get_trait_implementation(*trait_impl_id); + let trait_impl = trait_impl.borrow(); + if trait_impl.trait_id != trait_id { + continue; + } + + trait_impls.push((*trait_impl_id, trait_impl.location)); + } self.sort_trait_impls(&mut trait_impls); @@ -314,11 +314,9 @@ impl<'context> ItemBuilder<'context> { } fn build_trait_impl(&mut self, trait_impl_id: TraitImplId) -> TraitImpl { - // Remove the trait impl from the set so we don't show it again - self.trait_impls.remove(&trait_impl_id); - let trait_impl = self.interner.get_trait_implementation(trait_impl_id); let trait_impl = trait_impl.borrow(); + let external_types = self.type_only_mention_types_outside_current_crate(&trait_impl.typ); let mut type_var_names = BTreeSet::new(); for generic in &trait_impl.trait_generics { @@ -330,6 +328,7 @@ impl<'context> ItemBuilder<'context> { generics: type_var_names, id: trait_impl_id, methods: trait_impl.methods.clone(), + external_types, } } @@ -415,6 +414,85 @@ impl<'context> ItemBuilder<'context> { | Type::Error => true, } } + + pub(super) fn add_primitive_types(&mut self, items: &mut Vec<(ItemVisibility, Item)>) { + self.add_primitive_type(Type::Bool, items); + self.add_primitive_type(Type::Integer(Signedness::Unsigned, IntegerBitSize::One), items); + self.add_primitive_type(Type::Integer(Signedness::Unsigned, IntegerBitSize::Eight), items); + self.add_primitive_type( + Type::Integer(Signedness::Unsigned, IntegerBitSize::Sixteen), + items, + ); + self.add_primitive_type( + Type::Integer(Signedness::Unsigned, IntegerBitSize::ThirtyTwo), + items, + ); + self.add_primitive_type( + Type::Integer(Signedness::Unsigned, IntegerBitSize::SixtyFour), + items, + ); + self.add_primitive_type( + Type::Integer(Signedness::Unsigned, IntegerBitSize::HundredTwentyEight), + items, + ); + self.add_primitive_type(Type::Integer(Signedness::Signed, IntegerBitSize::Eight), items); + self.add_primitive_type(Type::Integer(Signedness::Signed, IntegerBitSize::Sixteen), items); + self.add_primitive_type( + Type::Integer(Signedness::Signed, IntegerBitSize::ThirtyTwo), + items, + ); + self.add_primitive_type( + Type::Integer(Signedness::Signed, IntegerBitSize::SixtyFour), + items, + ); + self.add_primitive_type(Type::FieldElement, items); + self.add_primitive_type(Type::String(Box::new(Type::Error)), items); + self.add_primitive_type( + Type::FmtString(Box::new(Type::Error), Box::new(Type::Error)), + items, + ); + self.add_primitive_type(Type::Array(Box::new(Type::Error), Box::new(Type::Error)), items); + self.add_primitive_type(Type::Slice(Box::new(Type::Error)), items); + for quoted_type in QuotedType::iter() { + self.add_primitive_type(Type::Quoted(quoted_type), items); + } + } + + fn add_primitive_type(&mut self, typ: Type, items: &mut Vec<(ItemVisibility, Item)>) { + let mut impls = if let Some(methods) = self.interner.get_type_methods(&typ) { + self.build_impls(methods.values()) + } else { + Vec::new() + }; + if matches!(typ, Type::Bool | Type::Integer(..) | Type::FieldElement) { + // Numeric types seem to share all Field impls + impls.retain(|impl_| impl_.typ == typ); + } + + let trait_impls = self.build_primitive_type_trait_impls(&typ); + let primitive_type = PrimitiveType { typ: typ.clone(), impls, trait_impls }; + items.push((ItemVisibility::Public, Item::PrimitiveType(primitive_type))); + } + + fn build_primitive_type_trait_impls(&mut self, primitive_type: &Type) -> Vec { + let mut trait_impls = self + .trait_impls + .iter() + .filter_map(|trait_impl_id| { + let trait_impl = self.interner.get_trait_implementation(*trait_impl_id); + let trait_impl = trait_impl.borrow(); + if type_mentions_primitive_type(&trait_impl.typ, primitive_type) { + Some((*trait_impl_id, trait_impl.location)) + } else { + None + } + }) + .collect::>(); + + self.sort_trait_impls(&mut trait_impls); + + trait_impls.into_iter().map(|(trait_impl, _)| self.build_trait_impl(trait_impl)).collect() + } } fn gather_named_type_vars(typ: &Type, type_vars: &mut BTreeSet<(String, Kind)>) { @@ -533,3 +611,59 @@ fn type_mentions_data_type(typ: &Type, data_type: &crate::DataType) -> bool { | Type::Error => false, } } + +fn type_mentions_primitive_type(typ: &Type, target_type: &Type) -> bool { + if typ == target_type { + return true; + } + + match typ { + Type::Array(length, typ) => { + type_mentions_primitive_type(length, target_type) + || type_mentions_primitive_type(typ, target_type) + } + Type::Slice(typ) => type_mentions_primitive_type(typ, target_type), + Type::FmtString(length, typ) => { + type_mentions_primitive_type(length, target_type) + || type_mentions_primitive_type(typ, target_type) + } + Type::Tuple(types) => { + types.iter().any(|typ| type_mentions_primitive_type(typ, target_type)) + } + Type::DataType(_, generics) => { + generics.iter().any(|typ| type_mentions_primitive_type(typ, target_type)) + } + Type::Alias(_type_alias, generics) => { + generics.iter().any(|typ| type_mentions_primitive_type(typ, target_type)) + } + Type::TraitAsType(_, _, generics) => { + generics.ordered.iter().any(|typ| type_mentions_primitive_type(typ, target_type)) + || generics + .named + .iter() + .any(|named_type| type_mentions_primitive_type(&named_type.typ, target_type)) + } + Type::CheckedCast { from: _, to } => type_mentions_primitive_type(to, target_type), + Type::Function(args, ret, env, _) => { + args.iter().any(|typ| type_mentions_primitive_type(typ, target_type)) + || type_mentions_primitive_type(ret, target_type) + || type_mentions_primitive_type(env, target_type) + } + Type::Reference(typ, _) => type_mentions_primitive_type(typ, target_type), + Type::Forall(_, typ) => type_mentions_primitive_type(typ, target_type), + Type::InfixExpr(lhs, _, rhs, _) => { + type_mentions_primitive_type(lhs, target_type) + || type_mentions_primitive_type(rhs, target_type) + } + Type::Unit + | Type::Bool + | Type::Integer(..) + | Type::FieldElement + | Type::String(_) + | Type::Quoted(_) + | Type::Constant(..) + | Type::TypeVariable(..) + | Type::NamedGeneric(..) + | Type::Error => false, + } +} diff --git a/compiler/noirc_frontend/src/hir/printer/mod.rs b/compiler/noirc_frontend/src/hir/printer/mod.rs index f550d34bbd9..3df84438963 100644 --- a/compiler/noirc_frontend/src/hir/printer/mod.rs +++ b/compiler/noirc_frontend/src/hir/printer/mod.rs @@ -1,7 +1,8 @@ -use std::collections::{BTreeSet, HashMap}; +use std::collections::{BTreeSet, HashMap, HashSet}; use crate::graph::{CrateGraph, CrateId}; use crate::hir::printer::items::ItemBuilder; +use crate::node_interner::TraitImplId; use crate::{ DataType, Generics, Kind, NamedGeneric, Type, ast::{Ident, ItemVisibility}, @@ -22,7 +23,7 @@ use crate::{ token::{FunctionAttributeKind, LocatedToken, SecondaryAttribute, SecondaryAttributeKind}, }; -mod items; +pub mod items; use items::{Impl, Import, Item, Module, Trait, TraitImpl}; @@ -34,21 +35,29 @@ pub fn display_crate( def_maps: &DefMaps, interner: &NodeInterner, ) -> String { - let root_module_id = def_maps[&crate_id].root(); - let module_id = ModuleId { krate: crate_id, local_id: root_module_id }; - - let mut builder = ItemBuilder::new(crate_id, interner, def_maps); - let item = builder.build_module(module_id); + let module = crate_to_module(crate_id, def_maps, interner); let dependencies = &crate_graph[crate_id].dependencies; let mut string = String::new(); let mut printer = ItemPrinter::new(crate_id, interner, def_maps, dependencies, &mut string); - printer.show_item(item); + printer.show_module(module); string } +pub fn crate_to_module(crate_id: CrateId, def_maps: &DefMaps, interner: &NodeInterner) -> Module { + let root_module_id = def_maps[&crate_id].root(); + let module_id = ModuleId { krate: crate_id, local_id: root_module_id }; + + let mut builder = ItemBuilder::new(crate_id, interner, def_maps); + let mut module = builder.build_module(module_id); + if crate_id.is_stdlib() { + builder.add_primitive_types(&mut module.items); + } + module +} + struct ItemPrinter<'context, 'string> { crate_id: CrateId, interner: &'context NodeInterner, @@ -63,6 +72,9 @@ struct ItemPrinter<'context, 'string> { /// Trait constraints in scope. /// These are set when a trait, trait impl or function is visited. trait_constraints: Vec, + /// Keep track of trait impls that have been printed so we don't show a + /// same trait impl multiple times. + trait_impls_printed: HashSet, } impl<'context, 'string> ItemPrinter<'context, 'string> { @@ -87,6 +99,7 @@ impl<'context, 'string> ItemPrinter<'context, 'string> { imports, self_type: None, trait_constraints: Vec::new(), + trait_impls_printed: HashSet::new(), } } @@ -96,6 +109,9 @@ impl<'context, 'string> ItemPrinter<'context, 'string> { Item::DataType(data_type) => self.show_data_type(data_type), Item::Trait(trait_) => self.show_trait(trait_), Item::TypeAlias(type_alias_id) => self.show_type_alias(type_alias_id), + Item::PrimitiveType(_) => { + // TODO: we don't show primitive types yet + } Item::Global(global_id) => self.show_global(global_id), Item::Function(func_id) => self.show_function(func_id), } @@ -251,7 +267,9 @@ impl<'context, 'string> ItemPrinter<'context, 'string> { drop(data_type); self.show_data_type_impls(item_data_type.impls); - self.show_trait_impls(item_data_type.trait_impls); + + let trait_impls = item_data_type.trait_impls.iter().collect::>(); + self.show_trait_impls(&trait_impls); } fn show_struct(&mut self, data_type: &DataType) { @@ -339,7 +357,7 @@ impl<'context, 'string> ItemPrinter<'context, 'string> { self.self_type = None; } - fn show_trait_impls(&mut self, trait_impls: Vec) { + fn show_trait_impls(&mut self, trait_impls: &[&TraitImpl]) { for trait_impl in trait_impls { self.push_str("\n\n"); self.write_indent(); @@ -429,10 +447,21 @@ impl<'context, 'string> ItemPrinter<'context, 'string> { self.trait_constraints.clear(); - self.show_trait_impls(item_trait.trait_impls); + // Only show trait impls for types outside of the current crate: + // trait impls for types in this crate are already shown alongside the type definition. + let trait_impls = item_trait + .trait_impls + .iter() + .filter(|trait_impl| trait_impl.external_types) + .collect::>(); + self.show_trait_impls(&trait_impls); } - fn show_trait_impl(&mut self, item_trait_impl: TraitImpl) { + fn show_trait_impl(&mut self, item_trait_impl: &TraitImpl) { + if !self.trait_impls_printed.insert(item_trait_impl.id) { + return; + } + let trait_impl_id = item_trait_impl.id; let trait_impl = self.interner.get_trait_implementation(trait_impl_id); @@ -490,13 +519,13 @@ impl<'context, 'string> ItemPrinter<'context, 'string> { printed_item = true; } - for method in item_trait_impl.methods { + for method in &item_trait_impl.methods { if printed_item { self.push_str("\n\n"); } self.write_indent(); - let item = Item::Function(method); + let item = Item::Function(*method); let visibility = ItemVisibility::Private; self.show_item_with_visibility(item, visibility); diff --git a/compiler/noirc_frontend/src/hir_def/types.rs b/compiler/noirc_frontend/src/hir_def/types.rs index 9b145f2071a..8188426b97a 100644 --- a/compiler/noirc_frontend/src/hir_def/types.rs +++ b/compiler/noirc_frontend/src/hir_def/types.rs @@ -311,12 +311,10 @@ impl std::fmt::Display for Kind { } } -#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] -#[cfg_attr(test, derive(strum_macros::EnumIter))] +#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord, strum_macros::EnumIter)] pub enum QuotedType { Expr, Quoted, - TopLevelItem, Type, TypedExpr, TypeDefinition, @@ -1208,7 +1206,6 @@ impl std::fmt::Display for QuotedType { match self { QuotedType::Expr => write!(f, "Expr"), QuotedType::Quoted => write!(f, "Quoted"), - QuotedType::TopLevelItem => write!(f, "TopLevelItem"), QuotedType::Type => write!(f, "Type"), QuotedType::TypedExpr => write!(f, "TypedExpr"), QuotedType::TypeDefinition => write!(f, "TypeDefinition"), diff --git a/cspell.json b/cspell.json index 55c53d9e63e..56e081af3c5 100644 --- a/cspell.json +++ b/cspell.json @@ -289,6 +289,7 @@ "srem", "stdlib", "structs", + "stylesheet", "subexpression", "subshell", "subtrait", diff --git a/justfile b/justfile index 75aa953efaa..4400b909ae5 100644 --- a/justfile +++ b/justfile @@ -184,3 +184,8 @@ run-example EXAMPLE: # Runs spellcheck on Rust source and markdown files spellcheck: yarn spellcheck + +stdlib_docs: + cd noir_stdlib && nargo doc + rm -rf noir_stdlib/docs + mv noir_stdlib/target/docs noir_stdlib/docs \ No newline at end of file diff --git a/noir_stdlib/docs/all.html b/noir_stdlib/docs/all.html new file mode 100644 index 00000000000..b919448b139 --- /dev/null +++ b/noir_stdlib/docs/all.html @@ -0,0 +1,165 @@ + + + + + +All items in noir_stdlib documentation + + + +
+ +

All items in noir_stdlib

+

Structs

+ +

Traits

+ +

Type aliases

+ +

Primitive types

+ +

Functions

+ +
+ + diff --git a/noir_stdlib/docs/index.html b/noir_stdlib/docs/index.html new file mode 100644 index 00000000000..1c9efe6237c --- /dev/null +++ b/noir_stdlib/docs/index.html @@ -0,0 +1,21 @@ + + + + + + +noir_stdlib documentation documentation + + + +
+

noir_stdlib documentation

+

Crates

+
+ + diff --git a/noir_stdlib/docs/std/aes128/fn.aes128_encrypt.html b/noir_stdlib/docs/std/aes128/fn.aes128_encrypt.html new file mode 100644 index 00000000000..8d5f71a65bb --- /dev/null +++ b/noir_stdlib/docs/std/aes128/fn.aes128_encrypt.html @@ -0,0 +1,28 @@ + + + + + +Function aes128_encrypt documentation + + + +
+ +

Function aes128_encrypt

+
pub fn aes128_encrypt<let N: u32>(
+    input: [u8; N],
+    iv: [u8; 16],
+    key: [u8; 16],
+) -> [u8; N + 16 - N % 16]
+ +
+ + diff --git a/noir_stdlib/docs/std/aes128/index.html b/noir_stdlib/docs/std/aes128/index.html new file mode 100644 index 00000000000..a60ca4e5f51 --- /dev/null +++ b/noir_stdlib/docs/std/aes128/index.html @@ -0,0 +1,91 @@ + + + + + +Module aes128 documentation + + + +
+
noir_stdlib - std::aes128
+

Module aes128

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/append/index.html b/noir_stdlib/docs/std/append/index.html new file mode 100644 index 00000000000..9b864e4aa82 --- /dev/null +++ b/noir_stdlib/docs/std/append/index.html @@ -0,0 +1,91 @@ + + + + + +Module append documentation + + + +
+
noir_stdlib - std::append
+

Module append

+

Traits

+
+ + diff --git a/noir_stdlib/docs/std/append/trait.Append.html b/noir_stdlib/docs/std/append/trait.Append.html new file mode 100644 index 00000000000..dec3dc34d40 --- /dev/null +++ b/noir_stdlib/docs/std/append/trait.Append.html @@ -0,0 +1,52 @@ + + + + + +Trait Append documentation + + + +
+ +

Trait Append

+
pub trait Append {
+    // Required methods
+    pub fn empty() -> Self;
+    pub fn append(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn empty() -> Self + +pub fn append(self, other: Self) -> Self + +

Implementors

+

impl Append for CtString

+ +

impl Append for Quoted

+ +

impl<T> Append for [T]

+ +
+ + diff --git a/noir_stdlib/docs/std/array/index.html b/noir_stdlib/docs/std/array/index.html new file mode 100644 index 00000000000..7bc8b2ad3e9 --- /dev/null +++ b/noir_stdlib/docs/std/array/index.html @@ -0,0 +1,84 @@ + + + + + +Module array documentation + + + +
+
noir_stdlib - std::array
+

Module array

+
+ + diff --git a/noir_stdlib/docs/std/cmp/fn.max.html b/noir_stdlib/docs/std/cmp/fn.max.html new file mode 100644 index 00000000000..19f26ff524f --- /dev/null +++ b/noir_stdlib/docs/std/cmp/fn.max.html @@ -0,0 +1,34 @@ + + + + + +Function max documentation + + + +
+ +

Function max

+
pub fn max<T>(v1: T, v2: T) -> T
+
where + T: Ord
+ +
+ + diff --git a/noir_stdlib/docs/std/cmp/fn.min.html b/noir_stdlib/docs/std/cmp/fn.min.html new file mode 100644 index 00000000000..eea52684119 --- /dev/null +++ b/noir_stdlib/docs/std/cmp/fn.min.html @@ -0,0 +1,34 @@ + + + + + +Function min documentation + + + +
+ +

Function min

+
pub fn min<T>(v1: T, v2: T) -> T
+
where + T: Ord
+ +
+ + diff --git a/noir_stdlib/docs/std/cmp/index.html b/noir_stdlib/docs/std/cmp/index.html new file mode 100644 index 00000000000..0ac57bf6606 --- /dev/null +++ b/noir_stdlib/docs/std/cmp/index.html @@ -0,0 +1,101 @@ + + + + + +Module cmp documentation + + + +
+ +

Module cmp

+

Structs

+

Traits

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/cmp/struct.Ordering.html b/noir_stdlib/docs/std/cmp/struct.Ordering.html new file mode 100644 index 00000000000..1e559b8c8e4 --- /dev/null +++ b/noir_stdlib/docs/std/cmp/struct.Ordering.html @@ -0,0 +1,58 @@ + + + + + +Struct Ordering documentation + + + +
+ +

Struct Ordering

+
pub struct Ordering
+{ /* private fields */ }
+
+

Implementations

+

impl Ordering

+ +
pub fn less() -> Self + +pub fn equal() -> Self + +pub fn greater() -> Self + +

Trait implementations

+

impl Eq for Ordering

+ +
pub fn eq(self, other: Self) -> bool + +
+ + diff --git a/noir_stdlib/docs/std/cmp/trait.Eq.html b/noir_stdlib/docs/std/cmp/trait.Eq.html new file mode 100644 index 00000000000..7feee27572f --- /dev/null +++ b/noir_stdlib/docs/std/cmp/trait.Eq.html @@ -0,0 +1,197 @@ + + + + + +Trait Eq documentation + + + +
+ +

Trait Eq

+
pub trait Eq {
+    // Required methods
+    pub fn eq(self, other: Self) -> bool;
+}
+ +

Required methods

+
pub fn eq(self, other: Self) -> bool + +

Implementors

+

impl Eq for ()

+ +

impl<A, B> Eq for (A, B) +
where + A: Eq, + B: Eq

+ +

impl<A, B, C> Eq for (A, B, C) +
where + A: Eq, + B: Eq, + C: Eq

+ +

impl<A, B, C, D> Eq for (A, B, C, D) +
where + A: Eq, + B: Eq, + C: Eq, + D: Eq

+ +

impl<A, B, C, D, E> Eq for (A, B, C, D, E) +
where + A: Eq, + B: Eq, + C: Eq, + D: Eq, + E: Eq

+ +

impl Eq for BinaryOp

+ +

impl<let MaxLen: u32, T> Eq for BoundedVec<T, MaxLen> +
where + T: Eq

+ +

impl Eq for CompoundStruct

+ +

impl Eq for CtString

+ +

impl Eq for EmbeddedCurvePoint

+ +

impl Eq for EmbeddedCurveScalar

+ +

impl Eq for Field

+ +

impl Eq for FunctionDefinition

+ +

impl<B, K, let N: u32, V> Eq for HashMap<K, V, N, B> +
where + K: Eq, + K: Hash, + V: Eq, + B: BuildHasher

+ +

impl Eq for Module

+ +

impl<T> Eq for Option<T> +
where + T: Eq

+ +

impl Eq for Ordering

+ +

impl Eq for Quoted

+ +

impl Eq for TraitConstraint

+ +

impl Eq for TraitDefinition

+ +

impl Eq for Type

+ +

impl Eq for TypeDefinition

+ +

impl<B, K, V> Eq for UHashMap<K, V, B> +
where + K: Eq, + K: Hash, + V: Eq, + B: BuildHasher

+ +

impl Eq for UnaryOp

+ +

impl<let N: u32, T> Eq for [T; N] +
where + T: Eq

+ +

impl<T> Eq for [T] +
where + T: Eq

+ +

impl Eq for bool

+ +

impl Eq for i16

+ +

impl Eq for i32

+ +

impl Eq for i64

+ +

impl Eq for i8

+ +

impl<let N: u32> Eq for str<N>

+ +

impl Eq for u1

+ +

impl Eq for u128

+ +

impl Eq for u16

+ +

impl Eq for u32

+ +

impl Eq for u64

+ +

impl Eq for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/cmp/trait.Ord.html b/noir_stdlib/docs/std/cmp/trait.Ord.html new file mode 100644 index 00000000000..604293608c2 --- /dev/null +++ b/noir_stdlib/docs/std/cmp/trait.Ord.html @@ -0,0 +1,125 @@ + + + + + +Trait Ord documentation + + + +
+ +

Trait Ord

+
pub trait Ord {
+    // Required methods
+    pub fn cmp(self, other: Self) -> Ordering;
+}
+ +

Required methods

+
pub fn cmp(self, other: Self) -> Ordering + +

Implementors

+

impl Ord for ()

+ +

impl<A, B> Ord for (A, B) +
where + A: Ord, + B: Ord

+ +

impl<A, B, C> Ord for (A, B, C) +
where + A: Ord, + B: Ord, + C: Ord

+ +

impl<A, B, C, D> Ord for (A, B, C, D) +
where + A: Ord, + B: Ord, + C: Ord, + D: Ord

+ +

impl<A, B, C, D, E> Ord for (A, B, C, D, E) +
where + A: Ord, + B: Ord, + C: Ord, + D: Ord, + E: Ord

+ +

impl<T> Ord for Option<T> +
where + T: Ord

+ +

impl<let N: u32, T> Ord for [T; N] +
where + T: Ord

+ +

impl<T> Ord for [T] +
where + T: Ord

+ +

impl Ord for bool

+ +

impl Ord for i16

+ +

impl Ord for i32

+ +

impl Ord for i64

+ +

impl Ord for i8

+ +

impl Ord for u128

+ +

impl Ord for u16

+ +

impl Ord for u32

+ +

impl Ord for u64

+ +

impl Ord for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/collections/bounded_vec/index.html b/noir_stdlib/docs/std/collections/bounded_vec/index.html new file mode 100644 index 00000000000..e55215289d0 --- /dev/null +++ b/noir_stdlib/docs/std/collections/bounded_vec/index.html @@ -0,0 +1,36 @@ + + + + + +Module bounded_vec documentation + + + +
+
noir_stdlib - std::collections::bounded_vec
+

Module bounded_vec

+

Structs

    +
  • A BoundedVec<T, MaxLen> is a growable storage similar to a Vec<T> except that it +is bounded with a maximum possible length. Unlike Vec, BoundedVec is not implemented +via slices and thus is not subject to the same restrictions slices are (notably, nested +slices - and thus nested vectors as well - are disallowed).
  • +
+
+ + diff --git a/noir_stdlib/docs/std/collections/bounded_vec/struct.BoundedVec.html b/noir_stdlib/docs/std/collections/bounded_vec/struct.BoundedVec.html new file mode 100644 index 00000000000..d1d67e0d6eb --- /dev/null +++ b/noir_stdlib/docs/std/collections/bounded_vec/struct.BoundedVec.html @@ -0,0 +1,443 @@ + + + + + +Struct BoundedVec documentation + + + +
+ +

Struct BoundedVec

+
pub struct BoundedVec<T, let MaxLen: u32>
+{ /* private fields */ }
+
+
+

A BoundedVec<T, MaxLen> is a growable storage similar to a Vec<T> except that it +is bounded with a maximum possible length. Unlike Vec, BoundedVec is not implemented +via slices and thus is not subject to the same restrictions slices are (notably, nested +slices - and thus nested vectors as well - are disallowed).

+

Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by +pushing an additional element is also more efficient - the length only needs to be increased +by one.

+

For these reasons BoundedVec<T, N> should generally be preferred over Vec<T> when there +is a reasonable maximum bound that can be placed on the vector.

+

Example:

+
let mut vector: BoundedVec<Field, 10> = BoundedVec::new();
+for i in 0..5 {
+    vector.push(i);
+}
+assert(vector.len() == 5);
+assert(vector.max_len() == 10);
+
+
+

Implementations

+

impl<let MaxLen: u32, T> BoundedVec<T, MaxLen>

+ +
pub fn new() -> Self + +
+

Creates a new, empty vector of length zero.

+

Since this container is backed by an array internally, it still needs an initial value +to give each element. To resolve this, each element is zeroed internally. This value +is guaranteed to be inaccessible unless get_unchecked is used.

+

Example:

+
let empty_vector: BoundedVec<Field, 10> = BoundedVec::new();
+assert(empty_vector.len() == 0);
+
+

Note that whenever calling new the maximum length of the vector should always be specified +via a type signature:

+
fn good() -> BoundedVec<Field, 10> {
+    // Ok! MaxLen is specified with a type annotation
+    let v1: BoundedVec<Field, 3> = BoundedVec::new();
+    let v2 = BoundedVec::new();
+
+    // Ok! MaxLen is known from the type of `good`'s return value
+    v2
+}
+
+fn bad() {
+    // Error: Type annotation needed
+    // The compiler can't infer `MaxLen` from the following code:
+    let mut v3 = BoundedVec::new();
+    v3.push(5);
+}
+
+

This defaulting of MaxLen (and numeric generics in general) to zero may change in future noir versions +but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a +constraint failure at runtime when the vec is pushed to.

+
+
pub fn get(self, index: u32) -> T + +
+

Retrieves an element from the vector at the given index, starting from zero.

+

If the given index is equal to or greater than the length of the vector, this +will issue a constraint failure.

+

Example:

+
fn foo<let N: u32>(v: BoundedVec<u32, N>) {
+    let first = v.get(0);
+    let last = v.get(v.len() - 1);
+    assert(first != last);
+}
+
+
+
pub fn get_unchecked(self, index: u32) -> T + +
+

Retrieves an element from the vector at the given index, starting from zero, without +performing a bounds check.

+

Since this function does not perform a bounds check on length before accessing the element, +it is unsafe! Use at your own risk!

+

Example:

+
fn sum_of_first_three<let N: u32>(v: BoundedVec<u32, N>) -> u32 {
+    // Always ensure the length is larger than the largest
+    // index passed to get_unchecked
+    assert(v.len() > 2);
+    let first = v.get_unchecked(0);
+    let second = v.get_unchecked(1);
+    let third = v.get_unchecked(2);
+    first + second + third
+}
+
+
+
pub fn set(&mut self, index: u32, value: T) + +
+

Writes an element to the vector at the given index, starting from zero.

+

If the given index is equal to or greater than the length of the vector, this will issue a constraint failure.

+

Example:

+
fn foo<let N: u32>(v: BoundedVec<u32, N>) {
+    let first = v.get(0);
+    assert(first != 42);
+    v.set(0, 42);
+    let new_first = v.get(0);
+    assert(new_first == 42);
+}
+
+
+
pub fn set_unchecked(&mut self, index: u32, value: T) + +
+

Writes an element to the vector at the given index, starting from zero, without performing a bounds check.

+

Since this function does not perform a bounds check on length before accessing the element, it is unsafe! Use at your own risk!

+

Example:

+
fn set_unchecked_example() {
+    let mut vec: BoundedVec<u32, 5> = BoundedVec::new();
+    vec.extend_from_array([1, 2]);
+
+    // Here we're safely writing within the valid range of `vec`
+    // `vec` now has the value [42, 2]
+    vec.set_unchecked(0, 42);
+
+    // We can then safely read this value back out of `vec`.
+    // Notice that we use the checked version of `get` which would prevent reading unsafe values.
+    assert_eq(vec.get(0), 42);
+
+    // We've now written past the end of `vec`.
+    // As this index is still within the maximum potential length of `v`,
+    // it won't cause a constraint failure.
+    vec.set_unchecked(2, 42);
+    println(vec);
+
+    // This will write past the end of the maximum potential length of `vec`,
+    // it will then trigger a constraint failure.
+    vec.set_unchecked(5, 42);
+    println(vec);
+}
+
+
+
pub fn push(&mut self, elem: T) + +
+

Pushes an element to the end of the vector. This increases the length +of the vector by one.

+

Panics if the new length of the vector will be greater than the max length.

+

Example:

+
let mut v: BoundedVec<Field, 2> = BoundedVec::new();
+
+v.push(1);
+v.push(2);
+
+// Panics with failed assertion "push out of bounds"
+v.push(3);
+
+
+
pub fn len(self) -> u32 + +
+

Returns the current length of this vector

+

Example:

+
let mut v: BoundedVec<Field, 4> = BoundedVec::new();
+assert(v.len() == 0);
+
+v.push(100);
+assert(v.len() == 1);
+
+v.push(200);
+v.push(300);
+v.push(400);
+assert(v.len() == 4);
+
+let _ = v.pop();
+let _ = v.pop();
+assert(v.len() == 2);
+
+
+
pub fn max_len(_self: Self) -> u32 + +
+

Returns the maximum length of this vector. This is always +equal to the MaxLen parameter this vector was initialized with.

+

Example:

+
let mut v: BoundedVec<Field, 5> = BoundedVec::new();
+
+assert(v.max_len() == 5);
+v.push(10);
+assert(v.max_len() == 5);
+
+
+
pub fn storage(self) -> [T; MaxLen] + +
+

Returns the internal array within this vector.

+

Since arrays in Noir are immutable, mutating the returned storage array will not mutate +the storage held internally by this vector.

+

Note that uninitialized elements may be zeroed out!

+

Example:

+
let mut v: BoundedVec<Field, 5> = BoundedVec::new();
+
+assert(v.storage() == [0, 0, 0, 0, 0]);
+
+v.push(57);
+assert(v.storage() == [57, 0, 0, 0, 0]);
+
+
+
pub fn extend_from_array<let Len: u32>(&mut self, array: [T; Len]) + +
+

Pushes each element from the given array to this vector.

+

Panics if pushing each element would cause the length of this vector +to exceed the maximum length.

+

Example:

+
let mut vec: BoundedVec<Field, 3> = BoundedVec::new();
+vec.extend_from_array([2, 4]);
+
+assert(vec.len == 2);
+assert(vec.get(0) == 2);
+assert(vec.get(1) == 4);
+
+
+
pub fn extend_from_slice(&mut self, slice: [T]) + +
+

Pushes each element from the given slice to this vector.

+

Panics if pushing each element would cause the length of this vector +to exceed the maximum length.

+

Example:

+
let mut vec: BoundedVec<Field, 3> = BoundedVec::new();
+vec.extend_from_slice(&[2, 4]);
+
+assert(vec.len == 2);
+assert(vec.get(0) == 2);
+assert(vec.get(1) == 4);
+
+
+
pub fn extend_from_bounded_vec<let Len: u32>(&mut self, vec: BoundedVec<T, Len>) + +
+

Pushes each element from the other vector to this vector. The length of +the other vector is left unchanged.

+

Panics if pushing each element would cause the length of this vector +to exceed the maximum length.

+
let mut v1: BoundedVec<Field, 5> = BoundedVec::new();
+let mut v2: BoundedVec<Field, 7> = BoundedVec::new();
+
+v2.extend_from_array([1, 2, 3]);
+v1.extend_from_bounded_vec(v2);
+
+assert(v1.storage() == [1, 2, 3, 0, 0]);
+assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]);
+
+
+
pub fn from_array<let Len: u32>(array: [T; Len]) -> Self + +
+

Creates a new vector, populating it with values derived from an array input. +The maximum length of the vector is determined based on the type signature.

+

Example:

+
let bounded_vec: BoundedVec<Field, 10> = BoundedVec::from_array([1, 2, 3])
+
+
+
pub fn pop(&mut self) -> T + +
+

Pops the element at the end of the vector. This will decrease the length +of the vector by one.

+

Panics if the vector is empty.

+

Example:

+
let mut v: BoundedVec<Field, 2> = BoundedVec::new();
+v.push(1);
+v.push(2);
+
+let two = v.pop();
+let one = v.pop();
+
+assert(two == 2);
+assert(one == 1);
+
+// error: cannot pop from an empty vector
+let _ = v.pop();
+
+
+
pub fn any<Env>(self, predicate: fn[Env](T) -> bool) -> bool + +
+

Returns true if the given predicate returns true for any element +in this vector.

+

Example:

+
let mut v: BoundedVec<u32, 3> = BoundedVec::new();
+v.extend_from_array([2, 4, 6]);
+
+let all_even = !v.any(|elem: u32| elem % 2 != 0);
+assert(all_even);
+
+
+
pub fn map<U, Env>(self, f: fn[Env](T) -> U) -> BoundedVec<U, MaxLen> + +
+

Creates a new vector of equal size by calling a closure on each element in this vector.

+

Example:

+
let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);
+let result = vec.map(|value| value * 2);
+
+let expected = BoundedVec::from_array([2, 4, 6, 8]);
+assert_eq(result, expected);
+
+
+
pub fn mapi<U, Env>(self, f: fn[Env](u32, T) -> U) -> BoundedVec<U, MaxLen> + +
+

Creates a new vector of equal size by calling a closure on each element +in this vector, along with its index.

+

Example:

+
let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);
+let result = vec.mapi(|i, value| i + value * 2);
+
+let expected = BoundedVec::from_array([2, 5, 8, 11]);
+assert_eq(result, expected);
+
+
+
pub fn for_each<Env>(self, f: fn[Env](T)) + +
+

Calls a closure on each element in this vector.

+

Example:

+
let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);
+let mut result = BoundedVec::<u32, 4>::new();
+vec.for_each(|value| result.push(value * 2));
+
+let expected = BoundedVec::from_array([2, 4, 6, 8]);
+assert_eq(result, expected);
+
+
+
pub fn for_eachi<Env>(self, f: fn[Env](u32, T)) + +
+

Calls a closure on each element in this vector, along with its index.

+

Example:

+
let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);
+let mut result = BoundedVec::<u32, 4>::new();
+vec.for_eachi(|i, value| result.push(i + value * 2));
+
+let expected = BoundedVec::from_array([2, 5, 8, 11]);
+assert_eq(result, expected);
+
+
+
pub fn from_parts(array: [T; MaxLen], len: u32) -> Self + +
+

Creates a new BoundedVec from the given array and length. +The given length must be less than or equal to the length of the array.

+

This function will zero out any elements at or past index len of array. +This incurs an extra runtime cost of O(MaxLen). If you are sure your array is +zeroed after that index, you can use from_parts_unchecked to remove the extra loop.

+

Example:

+
let vec: BoundedVec<u32, 4> = BoundedVec::from_parts([1, 2, 3, 0], 3);
+assert_eq(vec.len(), 3);
+
+
+
pub fn from_parts_unchecked(array: [T; MaxLen], len: u32) -> Self + +
+

Creates a new BoundedVec from the given array and length. +The given length must be less than or equal to the length of the array.

+

This function is unsafe because it expects all elements past the len index +of array to be zeroed, but does not check for this internally. Use from_parts +for a safe version of this function which does zero out any indices past the +given length. Invalidating this assumption can notably cause BoundedVec::eq +to give incorrect results since it will check even elements past len.

+

Example:

+
let vec: BoundedVec<u32, 4> = BoundedVec::from_parts_unchecked([1, 2, 3, 0], 3);
+assert_eq(vec.len(), 3);
+
+// invalid use!
+let vec1: BoundedVec<u32, 4> = BoundedVec::from_parts_unchecked([1, 2, 3, 1], 3);
+let vec2: BoundedVec<u32, 4> = BoundedVec::from_parts_unchecked([1, 2, 3, 2], 3);
+
+// both vecs have length 3 so we'd expect them to be equal, but this
+// fails because elements past the length are still checked in eq
+assert_eq(vec1, vec2); // fails
+
+
+

Trait implementations

+

impl<let MaxLen: u32, T> Eq for BoundedVec<T, MaxLen> +
where + T: Eq

+ +
pub fn eq(self, other: Self) -> bool + +

impl<let Len: u32, let MaxLen: u32, T> From<[T; Len]> for BoundedVec<T, MaxLen>

+ +
pub fn from(array: [T; Len]) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/collections/index.html b/noir_stdlib/docs/std/collections/index.html new file mode 100644 index 00000000000..94251b05aff --- /dev/null +++ b/noir_stdlib/docs/std/collections/index.html @@ -0,0 +1,94 @@ + + + + + +Module collections documentation + + + +
+
noir_stdlib - std::collections
+

Module collections

+

Modules

+
+ + diff --git a/noir_stdlib/docs/std/collections/map/index.html b/noir_stdlib/docs/std/collections/map/index.html new file mode 100644 index 00000000000..9c9e37fd668 --- /dev/null +++ b/noir_stdlib/docs/std/collections/map/index.html @@ -0,0 +1,33 @@ + + + + + +Module map documentation + + + +
+ +

Module map

+

Structs

    +
  • HashMap<Key, Value, MaxLen, Hasher> is used to efficiently store and look up key-value pairs.
  • +
+
+ + diff --git a/noir_stdlib/docs/std/collections/map/struct.HashMap.html b/noir_stdlib/docs/std/collections/map/struct.HashMap.html new file mode 100644 index 00000000000..c0a537822e8 --- /dev/null +++ b/noir_stdlib/docs/std/collections/map/struct.HashMap.html @@ -0,0 +1,366 @@ + + + + + +Struct HashMap documentation + + + +
+ +

Struct HashMap

+
pub struct HashMap<K, V, let N: u32, B>
+{ /* private fields */ }
+
+
+

HashMap<Key, Value, MaxLen, Hasher> is used to efficiently store and look up key-value pairs.

+

HashMap is a bounded type which can store anywhere from zero to MaxLen total elements. +Note that due to hash collisions, the actual maximum number of elements stored by any particular +hashmap is likely lower than MaxLen. This is true even with cryptographic hash functions since +every hash value will be performed modulo MaxLen.

+

Example:

+
// Create a mapping from Fields to u32s with a maximum length of 12
+// using a poseidon2 hasher
+use std::hash::poseidon2::Poseidon2Hasher;
+let mut map: HashMap<Field, u32, 12, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+
+map.insert(1, 2);
+map.insert(3, 4);
+
+let two = map.get(1).unwrap();
+
+
+

Implementations

+

impl<B, K, let N: u32, V> HashMap<K, V, N, B>

+ +
pub fn with_hasher(_build_hasher: B) -> Self +
where + B: BuildHasher
+ +
+

Creates a hashmap with an existing BuildHasher. This can be used to ensure multiple +hashmaps are created with the same hasher instance.

+

Example:

+
let my_hasher: BuildHasherDefault<Poseidon2Hasher> = Default::default();
+let hashmap: HashMap<u8, u32, 10, BuildHasherDefault<Poseidon2Hasher>> = HashMap::with_hasher(my_hasher);
+assert(hashmap.is_empty());
+
+
+
pub fn clear(&mut self) + +
+

Clears the hashmap, removing all key-value pairs from it.

+

Example:

+
assert(!map.is_empty());
+map.clear();
+assert(map.is_empty());
+
+
+
pub fn contains_key(self, key: K) -> bool +
where + K: Hash, + K: Eq, + B: BuildHasher
+ +
+

Returns true if the hashmap contains the given key. Unlike get, this will not also return +the value associated with the key.

+

Example:

+
if map.contains_key(7) {
+    let value = map.get(7);
+    assert(value.is_some());
+} else {
+    println("No value for key 7!");
+}
+
+
+
pub fn is_empty(self) -> bool + +
+

Returns true if the length of the hash map is empty.

+

Example:

+
assert(map.is_empty());
+
+map.insert(1, 2);
+assert(!map.is_empty());
+
+map.remove(1);
+assert(map.is_empty());
+
+
+
pub fn entries(self) -> BoundedVec<(K, V), N> + +
+

Returns a vector of each key-value pair present in the hashmap.

+

The length of the returned vector is always equal to the length of the hashmap.

+

Example:

+
let entries = map.entries();
+
+// The length of a hashmap may not be compile-time known, so we
+// need to loop over its capacity instead
+for i in 0..map.capacity() {
+    if i < entries.len() {
+        let (key, value) = entries.get(i);
+        println(f"{key} -> {value}");
+    }
+}
+
+
+
pub fn keys(self) -> BoundedVec<K, N> + +
+

Returns a vector of each key present in the hashmap.

+

The length of the returned vector is always equal to the length of the hashmap.

+

Example:

+
let keys = map.keys();
+
+for i in 0..keys.max_len() {
+    if i < keys.len() {
+        let key = keys.get_unchecked(i);
+        let value = map.get(key).unwrap_unchecked();
+        println(f"{key} -> {value}");
+    }
+}
+
+
+
pub fn values(self) -> BoundedVec<V, N> + +
+

Returns a vector of each value present in the hashmap.

+

The length of the returned vector is always equal to the length of the hashmap.

+

Example:

+
let values = map.values();
+
+for i in 0..values.max_len() {
+    if i < values.len() {
+        let value = values.get_unchecked(i);
+        println(f"Found value {value}");
+    }
+}
+
+
+
pub fn iter_mut(&mut self, f: fn(K, V) -> (K, V)) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +
+

Iterates through each key-value pair of the HashMap, setting each key-value pair to the +result returned from the given function.

+

Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated +through. If this is not desired, use iter_values_mut if only values need to be mutated, +or entries if neither keys nor values need to be mutated.

+

The iteration order is left unspecified. As a result, if two keys are mutated to become +equal, which of the two values that will be present for the key in the resulting map is also unspecified.

+

Example:

+
// Add 1 to each key in the map, and double the value associated with that key.
+map.iter_mut(|k, v| (k + 1, v * 2));
+
+
+
pub fn iter_keys_mut(&mut self, f: fn(K) -> K) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +
+

Iterates through the HashMap, mutating each key to the result returned from +the given function.

+

Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated +through. If only iteration is desired and the keys are not intended to be mutated, +prefer using entries instead.

+

The iteration order is left unspecified. As a result, if two keys are mutated to become +equal, which of the two values that will be present for the key in the resulting map is also unspecified.

+

Example:

+
// Double each key, leaving the value associated with that key untouched
+map.iter_keys_mut(|k| k * 2);
+
+
+
pub fn iter_values_mut(&mut self, f: fn(V) -> V) + +
+

Iterates through the HashMap, applying the given function to each value and mutating the +value to equal the result. This function is more efficient than iter_mut and iter_keys_mut +because the keys are untouched and the underlying hashmap thus does not need to be reordered.

+

Example:

+
// Halve each value
+map.iter_values_mut(|v| v / 2);
+
+
+
pub fn retain(&mut self, f: fn(K, V) -> bool) + +
+

Retains only the key-value pairs for which the given function returns true. +Any key-value pairs for which the function returns false will be removed from the map.

+

Example:

+
map.retain(|k, v| (k != 0) & (v != 0));
+
+
+
pub fn len(self) -> u32 + +
+

Returns the current length of this hash map.

+

Example:

+
// This is equivalent to checking map.is_empty()
+assert(map.len() == 0);
+
+map.insert(1, 2);
+map.insert(3, 4);
+map.insert(5, 6);
+assert(map.len() == 3);
+
+// 3 was already present as a key in the hash map, so the length is unchanged
+map.insert(3, 7);
+assert(map.len() == 3);
+
+map.remove(1);
+assert(map.len() == 2);
+
+
+
pub fn capacity(_self: Self) -> u32 + +
+

Returns the maximum capacity of this hashmap. This is always equal to the capacity +specified in the hashmap's type.

+

Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a +static capacity that does not increase as the map grows larger. Thus, this capacity +is also the maximum possible element count that can be inserted into the hashmap. +Due to hash collisions (modulo the hashmap length), it is likely the actual maximum +element count will be lower than the full capacity.

+

Example:

+
let empty_map: HashMap<Field, Field, 42, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+assert(empty_map.len() == 0);
+assert(empty_map.capacity() == 42);
+
+
+
pub fn get(self, key: K) -> Option<V> +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +
+

Retrieves a value from the hashmap, returning Option::none() if it was not found.

+

Example:

+
fn get_example(map: HashMap<Field, Field, 5, BuildHasherDefault<Poseidon2Hasher>>) {
+    let x = map.get(12);
+
+    if x.is_some() {
+        assert(x.unwrap() == 42);
+    }
+}
+
+
+
pub fn insert(&mut self, key: K, value: V) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +
+

Inserts a new key-value pair into the map. If the key was already in the map, its +previous value will be overridden with the newly provided one.

+

Example:

+
let mut map: HashMap<Field, Field, 5, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+map.insert(12, 42);
+assert(map.len() == 1);
+
+
+
pub fn remove(&mut self, key: K) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +
+

Removes the given key-value pair from the map. If the key was not already present +in the map, this does nothing.

+

Example:

+
let mut map: HashMap<Field, Field, 5, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+map.insert(12, 42);
+assert(!map.is_empty());
+
+map.remove(12);
+assert(map.is_empty());
+
+// If a key was not present in the map, remove does nothing
+map.remove(12);
+assert(map.is_empty());
+
+
+

Trait implementations

+

impl<B, K, let N: u32, V> Default for HashMap<K, V, N, B> +
where + B: BuildHasher, + B: Default

+ +
pub fn default() -> Self + +
+

Constructs an empty HashMap.

+

Example:

+
let hashmap: HashMap<u8, u32, 10, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+assert(hashmap.is_empty());
+
+
+

impl<B, K, let N: u32, V> Eq for HashMap<K, V, N, B> +
where + K: Eq, + K: Hash, + V: Eq, + B: BuildHasher

+ +
pub fn eq(self, other: Self) -> bool + +
+

Checks if two HashMaps are equal.

+

Example:

+
let mut map1: HashMap<Field, u64, 4, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+let mut map2: HashMap<Field, u64, 4, BuildHasherDefault<Poseidon2Hasher>> = HashMap::default();
+
+map1.insert(1, 2);
+map1.insert(3, 4);
+
+map2.insert(3, 4);
+map2.insert(1, 2);
+
+assert(map1 == map2);
+
+
+
+ + diff --git a/noir_stdlib/docs/std/collections/umap/index.html b/noir_stdlib/docs/std/collections/umap/index.html new file mode 100644 index 00000000000..980c1317158 --- /dev/null +++ b/noir_stdlib/docs/std/collections/umap/index.html @@ -0,0 +1,33 @@ + + + + + +Module umap documentation + + + +
+ +

Module umap

+

Structs

+
+ + diff --git a/noir_stdlib/docs/std/collections/umap/struct.UHashMap.html b/noir_stdlib/docs/std/collections/umap/struct.UHashMap.html new file mode 100644 index 00000000000..9d5695c8951 --- /dev/null +++ b/noir_stdlib/docs/std/collections/umap/struct.UHashMap.html @@ -0,0 +1,133 @@ + + + + + +Struct UHashMap documentation + + + +
+ +

Struct UHashMap

+
pub struct UHashMap<K, V, B>
+{ /* private fields */ }
+
+

Implementations

+

impl<B, K, V> UHashMap<K, V, B>

+ +
pub fn with_hasher(_build_hasher: B) -> Self +
where + B: BuildHasher
+ +pub fn with_hasher_and_capacity(_build_hasher: B, capacity: u32) -> Self +
where + B: BuildHasher
+ +pub fn clear(&mut self) + +pub fn contains_key(self, key: K) -> bool +
where + K: Hash, + K: Eq, + B: BuildHasher
+ +pub fn is_empty(self) -> bool + +pub fn entries(self) -> [(K, V)] + +pub fn keys(self) -> [K] + +pub fn values(self) -> [V] + +pub unconstrained fn iter_mut(&mut self, f: fn(K, V) -> (K, V)) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +pub unconstrained fn iter_keys_mut(&mut self, f: fn(K) -> K) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +pub fn iter_values_mut(&mut self, f: fn(V) -> V) + +pub fn retain(&mut self, f: fn(K, V) -> bool) + +pub fn len(self) -> u32 + +pub fn capacity(self) -> u32 + +pub unconstrained fn get(self, key: K) -> Option<V> +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +pub unconstrained fn insert(&mut self, key: K, value: V) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +pub unconstrained fn remove(&mut self, key: K) +
where + K: Eq, + K: Hash, + B: BuildHasher
+ +

Trait implementations

+

impl<B, K, V> Default for UHashMap<K, V, B> +
where + B: BuildHasher, + B: Default

+ +
pub fn default() -> Self + +

impl<B, K, V> Eq for UHashMap<K, V, B> +
where + K: Eq, + K: Hash, + V: Eq, + B: BuildHasher

+ +
pub fn eq(self, other: Self) -> bool + +
+ + diff --git a/noir_stdlib/docs/std/collections/vec/index.html b/noir_stdlib/docs/std/collections/vec/index.html new file mode 100644 index 00000000000..304cb86f1ce --- /dev/null +++ b/noir_stdlib/docs/std/collections/vec/index.html @@ -0,0 +1,33 @@ + + + + + +Module vec documentation + + + +
+ +

Module vec

+

Structs

+
+ + diff --git a/noir_stdlib/docs/std/collections/vec/struct.Vec.html b/noir_stdlib/docs/std/collections/vec/struct.Vec.html new file mode 100644 index 00000000000..ab660ee36c1 --- /dev/null +++ b/noir_stdlib/docs/std/collections/vec/struct.Vec.html @@ -0,0 +1,90 @@ + + + + + +Struct Vec documentation + + + +
+ +

Struct Vec

+
pub struct Vec<T>
+{ /* private fields */ }
+
+

Implementations

+

impl<T> Vec<T>

+ +
pub fn new() -> Self + +pub fn from_slice(slice: [T]) -> Self + +pub fn get(self, index: u32) -> T + +
+

Get an element from the vector at the given index. +Panics if the given index +points beyond the end of the vector.

+
+
pub fn set(&mut self, index: u32, value: T) + +
+

Write an element to the vector at the given index. +Panics if the given index points beyond the end of the vector (self.len()).

+
+
pub fn push(&mut self, elem: T) + +
+

Push a new element to the end of the vector, returning a +new vector with a length one greater than the +original unmodified vector.

+
+
pub fn pop(&mut self) -> T + +
+

Pop an element from the end of the given vector, returning +a new vector with a length of one less than the given vector, +as well as the popped element. +Panics if the given vector's length is zero.

+
+
pub fn insert(&mut self, index: u32, elem: T) + +
+

Insert an element at a specified index, shifting all elements +after it to the right

+
+
pub fn remove(&mut self, index: u32) -> T + +
+

Remove an element at a specified index, shifting all elements +after it to the left, returning the removed element

+
+
pub fn len(self) -> u32 + +
+

Returns the number of elements in the vector

+
+
+ + diff --git a/noir_stdlib/docs/std/compat/fn.is_bn254.html b/noir_stdlib/docs/std/compat/fn.is_bn254.html new file mode 100644 index 00000000000..758b77fa7ee --- /dev/null +++ b/noir_stdlib/docs/std/compat/fn.is_bn254.html @@ -0,0 +1,24 @@ + + + + + +Function is_bn254 documentation + + + +
+ +

Function is_bn254

+
pub fn is_bn254() -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/compat/index.html b/noir_stdlib/docs/std/compat/index.html new file mode 100644 index 00000000000..90cb1f42392 --- /dev/null +++ b/noir_stdlib/docs/std/compat/index.html @@ -0,0 +1,91 @@ + + + + + +Module compat documentation + + + +
+
noir_stdlib - std::compat
+

Module compat

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/convert/index.html b/noir_stdlib/docs/std/convert/index.html new file mode 100644 index 00000000000..83d970cda37 --- /dev/null +++ b/noir_stdlib/docs/std/convert/index.html @@ -0,0 +1,94 @@ + + + + + +Module convert documentation + + + +
+
noir_stdlib - std::convert
+

Module convert

+

Traits

    +
  • A generic interface for casting between primitive types, +equivalent of using the as keyword between values.
  • +
  • +
  • +
+
+ + diff --git a/noir_stdlib/docs/std/convert/trait.AsPrimitive.html b/noir_stdlib/docs/std/convert/trait.AsPrimitive.html new file mode 100644 index 00000000000..d503cdd45bb --- /dev/null +++ b/noir_stdlib/docs/std/convert/trait.AsPrimitive.html @@ -0,0 +1,390 @@ + + + + + +Trait AsPrimitive documentation + + + +
+ +

Trait AsPrimitive

+
pub trait AsPrimitive<T> {
+    // Required methods
+    pub fn as_(self) -> T;
+}
+ +
+

A generic interface for casting between primitive types, +equivalent of using the as keyword between values.

+

Example

+
let x: Field = 1234567890;
+let y: u8 = x as u8;
+let z: u8 = x.as_();
+assert_eq(y, z);
+
+
+

Required methods

+
pub fn as_(self) -> T + +
+

The equivalent of doing self as T.

+
+

Implementors

+

impl AsPrimitive<bool> for Field

+ +

impl AsPrimitive<u128> for Field

+ +

impl AsPrimitive<u16> for Field

+ +

impl AsPrimitive<u32> for Field

+ +

impl AsPrimitive<u64> for Field

+ +

impl AsPrimitive<u8> for Field

+ +

impl AsPrimitive<Field> for bool

+ +

impl AsPrimitive<bool> for bool

+ +

impl AsPrimitive<i16> for bool

+ +

impl AsPrimitive<i32> for bool

+ +

impl AsPrimitive<i64> for bool

+ +

impl AsPrimitive<i8> for bool

+ +

impl AsPrimitive<u128> for bool

+ +

impl AsPrimitive<u16> for bool

+ +

impl AsPrimitive<u32> for bool

+ +

impl AsPrimitive<u64> for bool

+ +

impl AsPrimitive<u8> for bool

+ +

impl AsPrimitive<bool> for i16

+ +

impl AsPrimitive<i16> for i16

+ +

impl AsPrimitive<i32> for i16

+ +

impl AsPrimitive<i64> for i16

+ +

impl AsPrimitive<i8> for i16

+ +

impl AsPrimitive<u128> for i16

+ +

impl AsPrimitive<u16> for i16

+ +

impl AsPrimitive<u32> for i16

+ +

impl AsPrimitive<u64> for i16

+ +

impl AsPrimitive<u8> for i16

+ +

impl AsPrimitive<bool> for i32

+ +

impl AsPrimitive<i16> for i32

+ +

impl AsPrimitive<i32> for i32

+ +

impl AsPrimitive<i64> for i32

+ +

impl AsPrimitive<i8> for i32

+ +

impl AsPrimitive<u128> for i32

+ +

impl AsPrimitive<u16> for i32

+ +

impl AsPrimitive<u32> for i32

+ +

impl AsPrimitive<u64> for i32

+ +

impl AsPrimitive<u8> for i32

+ +

impl AsPrimitive<bool> for i64

+ +

impl AsPrimitive<i16> for i64

+ +

impl AsPrimitive<i32> for i64

+ +

impl AsPrimitive<i64> for i64

+ +

impl AsPrimitive<i8> for i64

+ +

impl AsPrimitive<u128> for i64

+ +

impl AsPrimitive<u16> for i64

+ +

impl AsPrimitive<u32> for i64

+ +

impl AsPrimitive<u64> for i64

+ +

impl AsPrimitive<u8> for i64

+ +

impl AsPrimitive<bool> for i8

+ +

impl AsPrimitive<i16> for i8

+ +

impl AsPrimitive<i32> for i8

+ +

impl AsPrimitive<i64> for i8

+ +

impl AsPrimitive<i8> for i8

+ +

impl AsPrimitive<u128> for i8

+ +

impl AsPrimitive<u16> for i8

+ +

impl AsPrimitive<u32> for i8

+ +

impl AsPrimitive<u64> for i8

+ +

impl AsPrimitive<u8> for i8

+ +

impl AsPrimitive<Field> for u128

+ +

impl AsPrimitive<bool> for u128

+ +

impl AsPrimitive<i16> for u128

+ +

impl AsPrimitive<i32> for u128

+ +

impl AsPrimitive<i64> for u128

+ +

impl AsPrimitive<i8> for u128

+ +

impl AsPrimitive<u128> for u128

+ +

impl AsPrimitive<u16> for u128

+ +

impl AsPrimitive<u32> for u128

+ +

impl AsPrimitive<u64> for u128

+ +

impl AsPrimitive<u8> for u128

+ +

impl AsPrimitive<Field> for u16

+ +

impl AsPrimitive<bool> for u16

+ +

impl AsPrimitive<i16> for u16

+ +

impl AsPrimitive<i32> for u16

+ +

impl AsPrimitive<i64> for u16

+ +

impl AsPrimitive<i8> for u16

+ +

impl AsPrimitive<u128> for u16

+ +

impl AsPrimitive<u16> for u16

+ +

impl AsPrimitive<u32> for u16

+ +

impl AsPrimitive<u64> for u16

+ +

impl AsPrimitive<u8> for u16

+ +

impl AsPrimitive<Field> for u32

+ +

impl AsPrimitive<bool> for u32

+ +

impl AsPrimitive<i16> for u32

+ +

impl AsPrimitive<i32> for u32

+ +

impl AsPrimitive<i64> for u32

+ +

impl AsPrimitive<i8> for u32

+ +

impl AsPrimitive<u128> for u32

+ +

impl AsPrimitive<u16> for u32

+ +

impl AsPrimitive<u32> for u32

+ +

impl AsPrimitive<u64> for u32

+ +

impl AsPrimitive<u8> for u32

+ +

impl AsPrimitive<Field> for u64

+ +

impl AsPrimitive<bool> for u64

+ +

impl AsPrimitive<i16> for u64

+ +

impl AsPrimitive<i32> for u64

+ +

impl AsPrimitive<i64> for u64

+ +

impl AsPrimitive<i8> for u64

+ +

impl AsPrimitive<u128> for u64

+ +

impl AsPrimitive<u16> for u64

+ +

impl AsPrimitive<u32> for u64

+ +

impl AsPrimitive<u64> for u64

+ +

impl AsPrimitive<u8> for u64

+ +

impl AsPrimitive<Field> for u8

+ +

impl AsPrimitive<bool> for u8

+ +

impl AsPrimitive<i16> for u8

+ +

impl AsPrimitive<i32> for u8

+ +

impl AsPrimitive<i64> for u8

+ +

impl AsPrimitive<i8> for u8

+ +

impl AsPrimitive<u128> for u8

+ +

impl AsPrimitive<u16> for u8

+ +

impl AsPrimitive<u32> for u8

+ +

impl AsPrimitive<u64> for u8

+ +

impl AsPrimitive<u8> for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/convert/trait.From.html b/noir_stdlib/docs/std/convert/trait.From.html new file mode 100644 index 00000000000..7fd3d092fb4 --- /dev/null +++ b/noir_stdlib/docs/std/convert/trait.From.html @@ -0,0 +1,146 @@ + + + + + +Trait From documentation + + + +
+ +

Trait From

+
pub trait From<T> {
+    // Required methods
+    pub fn from(input: T) -> Self;
+}
+ +

Required methods

+
pub fn from(input: T) -> Self + +

Implementors

+

impl<let Len: u32, let MaxLen: u32, T> From<[T; Len]> for BoundedVec<T, MaxLen>

+ +

impl From<bool> for Field

+ +

impl From<u128> for Field

+ +

impl From<u16> for Field

+ +

impl From<u32> for Field

+ +

impl From<u64> for Field

+ +

impl From<u8> for Field

+ +

impl<T> From<T> for T

+ +

impl<let N: u32> From<str<N>> for [u8; N]

+ +

impl From<bool> for i16

+ +

impl From<i8> for i16

+ +

impl From<bool> for i32

+ +

impl From<i16> for i32

+ +

impl From<i8> for i32

+ +

impl From<bool> for i64

+ +

impl From<i16> for i64

+ +

impl From<i32> for i64

+ +

impl From<i8> for i64

+ +

impl From<bool> for i8

+ +

impl<let N: u32> From<[u8; N]> for str<N>

+ +

impl From<bool> for u128

+ +

impl From<u16> for u128

+ +

impl From<u32> for u128

+ +

impl From<u64> for u128

+ +

impl From<u8> for u128

+ +

impl From<bool> for u16

+ +

impl From<u8> for u16

+ +

impl From<bool> for u32

+ +

impl From<u16> for u32

+ +

impl From<u8> for u32

+ +

impl From<bool> for u64

+ +

impl From<u16> for u64

+ +

impl From<u32> for u64

+ +

impl From<u8> for u64

+ +

impl From<bool> for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/convert/trait.Into.html b/noir_stdlib/docs/std/convert/trait.Into.html new file mode 100644 index 00000000000..ed1e0b69506 --- /dev/null +++ b/noir_stdlib/docs/std/convert/trait.Into.html @@ -0,0 +1,46 @@ + + + + + +Trait Into documentation + + + +
+ +

Trait Into

+
pub trait Into<T> {
+    // Required methods
+    pub fn into(self) -> T;
+}
+ +

Required methods

+
pub fn into(self) -> T + +

Implementors

+

impl<T, U> Into<T> for U +
where + T: From<U>

+ +
+ + diff --git a/noir_stdlib/docs/std/default/index.html b/noir_stdlib/docs/std/default/index.html new file mode 100644 index 00000000000..8dfbd045982 --- /dev/null +++ b/noir_stdlib/docs/std/default/index.html @@ -0,0 +1,91 @@ + + + + + +Module default documentation + + + +
+
noir_stdlib - std::default
+

Module default

+

Traits

+
+ + diff --git a/noir_stdlib/docs/std/default/trait.Default.html b/noir_stdlib/docs/std/default/trait.Default.html new file mode 100644 index 00000000000..7cd52e125b1 --- /dev/null +++ b/noir_stdlib/docs/std/default/trait.Default.html @@ -0,0 +1,146 @@ + + + + + +Trait Default documentation + + + +
+ +

Trait Default

+
pub trait Default {
+    // Required methods
+    pub fn default() -> Self;
+}
+ +

Required methods

+
pub fn default() -> Self + +

Implementors

+

impl Default for ()

+ +

impl<A, B> Default for (A, B) +
where + A: Default, + B: Default

+ +

impl<A, B, C> Default for (A, B, C) +
where + A: Default, + B: Default, + C: Default

+ +

impl<A, B, C, D> Default for (A, B, C, D) +
where + A: Default, + B: Default, + C: Default, + D: Default

+ +

impl<A, B, C, D, E> Default for (A, B, C, D, E) +
where + A: Default, + B: Default, + C: Default, + D: Default, + E: Default

+ +

impl<H> Default for BuildHasherDefault<H> +
where + H: Hasher, + H: Default

+ +

impl Default for Field

+ +

impl<B, K, let N: u32, V> Default for HashMap<K, V, N, B> +
where + B: BuildHasher, + B: Default

+ +

impl<T> Default for Option<T>

+ +

impl Default for Poseidon2Hasher

+ +

impl<K, V> Default for Slot<K, V>

+ +

impl<K, V> Default for Slot<K, V>

+ +

impl<B, K, V> Default for UHashMap<K, V, B> +
where + B: BuildHasher, + B: Default

+ +

impl<let N: u32, T> Default for [T; N] +
where + T: Default

+ +

impl<T> Default for [T]

+ +

impl Default for bool

+ +

impl Default for i16

+ +

impl Default for i32

+ +

impl Default for i64

+ +

impl Default for i8

+ +

impl Default for u1

+ +

impl Default for u128

+ +

impl Default for u16

+ +

impl Default for u32

+ +

impl Default for u64

+ +

impl Default for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ecdsa_secp256k1/fn._verify_signature.html b/noir_stdlib/docs/std/ecdsa_secp256k1/fn._verify_signature.html new file mode 100644 index 00000000000..3e68211fb8f --- /dev/null +++ b/noir_stdlib/docs/std/ecdsa_secp256k1/fn._verify_signature.html @@ -0,0 +1,31 @@ + + + + + +Function _verify_signature documentation + + + +
+ +

Function _verify_signature

+
pub fn _verify_signature(
+    public_key_x: [u8; 32],
+    public_key_y: [u8; 32],
+    signature: [u8; 64],
+    message_hash: [u8; 32],
+    predicate: bool,
+) -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/ecdsa_secp256k1/fn.verify_signature.html b/noir_stdlib/docs/std/ecdsa_secp256k1/fn.verify_signature.html new file mode 100644 index 00000000000..10261821891 --- /dev/null +++ b/noir_stdlib/docs/std/ecdsa_secp256k1/fn.verify_signature.html @@ -0,0 +1,52 @@ + + + + + +Function verify_signature documentation + + + +
+ +

Function verify_signature

+
pub fn verify_signature(
+    public_key_x: [u8; 32],
+    public_key_y: [u8; 32],
+    signature: [u8; 64],
+    message_hash: [u8; 32],
+) -> bool
+ +
+

Verifies a ECDSA signature over the secp256k1 curve.

+
    +
  • inputs: +
      +
    • x coordinate of public key as 32 bytes
    • +
    • y coordinate of public key as 32 bytes
    • +
    • the signature, as a 64 bytes array +The signature internally will be represented as (r, s), +where r and s are fixed-sized big endian scalar values. +As the secp256k1 has a 256-bit modulus, we have a 64 byte signature +while r and s will both be 32 bytes. +We expect s to be normalized. This means given the curve's order, +s should be less than or equal to order / 2. +This is done to prevent malleability. +For more context regarding malleability you can reference BIP 0062.
    • +
    • the hash of the message, as a vector of bytes
    • +
    +
  • +
  • output: false for failure and true for success
  • +
+
+
+ + diff --git a/noir_stdlib/docs/std/ecdsa_secp256k1/index.html b/noir_stdlib/docs/std/ecdsa_secp256k1/index.html new file mode 100644 index 00000000000..6446cd79589 --- /dev/null +++ b/noir_stdlib/docs/std/ecdsa_secp256k1/index.html @@ -0,0 +1,111 @@ + + + + + +Module ecdsa_secp256k1 documentation + + + +
+
noir_stdlib - std::ecdsa_secp256k1
+

Module ecdsa_secp256k1

+

Functions

    +
  • +
  • Verifies a ECDSA signature over the secp256k1 curve.

    +
      +
    • inputs: +
        +
      • x coordinate of public key as 32 bytes
      • +
      • y coordinate of public key as 32 bytes
      • +
      • the signature, as a 64 bytes array +The signature internally will be represented as (r, s), +where r and s are fixed-sized big endian scalar values. +As the secp256k1 has a 256-bit modulus, we have a 64 byte signature +while r and s will both be 32 bytes. +We expect s to be normalized. This means given the curve's order, +s should be less than or equal to order / 2. +This is done to prevent malleability. +For more context regarding malleability you can reference BIP 0062.
      • +
      • the hash of the message, as a vector of bytes
      • +
      +
    • +
    • output: false for failure and true for success
    • +
  • +
+
+ + diff --git a/noir_stdlib/docs/std/ecdsa_secp256r1/fn._verify_signature.html b/noir_stdlib/docs/std/ecdsa_secp256r1/fn._verify_signature.html new file mode 100644 index 00000000000..3a2a642e947 --- /dev/null +++ b/noir_stdlib/docs/std/ecdsa_secp256r1/fn._verify_signature.html @@ -0,0 +1,31 @@ + + + + + +Function _verify_signature documentation + + + +
+ +

Function _verify_signature

+
pub fn _verify_signature(
+    public_key_x: [u8; 32],
+    public_key_y: [u8; 32],
+    signature: [u8; 64],
+    message_hash: [u8; 32],
+    predicate: bool,
+) -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/ecdsa_secp256r1/fn.verify_signature.html b/noir_stdlib/docs/std/ecdsa_secp256r1/fn.verify_signature.html new file mode 100644 index 00000000000..8988090259e --- /dev/null +++ b/noir_stdlib/docs/std/ecdsa_secp256r1/fn.verify_signature.html @@ -0,0 +1,30 @@ + + + + + +Function verify_signature documentation + + + +
+ +

Function verify_signature

+
pub fn verify_signature(
+    public_key_x: [u8; 32],
+    public_key_y: [u8; 32],
+    signature: [u8; 64],
+    message_hash: [u8; 32],
+) -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/ecdsa_secp256r1/index.html b/noir_stdlib/docs/std/ecdsa_secp256r1/index.html new file mode 100644 index 00000000000..d15e50db5f0 --- /dev/null +++ b/noir_stdlib/docs/std/ecdsa_secp256r1/index.html @@ -0,0 +1,92 @@ + + + + + +Module ecdsa_secp256r1 documentation + + + +
+
noir_stdlib - std::ecdsa_secp256r1
+

Module ecdsa_secp256r1

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add.html b/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add.html new file mode 100644 index 00000000000..05aa70029df --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add.html @@ -0,0 +1,39 @@ + + + + + +Function embedded_curve_add documentation + + + +
+ +

Function embedded_curve_add

+
pub fn embedded_curve_add(
+    point1: EmbeddedCurvePoint,
+    point2: EmbeddedCurvePoint,
+) -> EmbeddedCurvePoint
+ +
+

This function only assumes that the points are on the curve +It handles corner cases around the infinity point causing some overhead compared to embedded_curve_add_not_nul and embedded_curve_add_unsafe

+
+
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add_not_nul.html b/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add_not_nul.html new file mode 100644 index 00000000000..f88f1b37030 --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add_not_nul.html @@ -0,0 +1,43 @@ + + + + + +Function embedded_curve_add_not_nul documentation + + + +
+ +

Function embedded_curve_add_not_nul

+
pub fn embedded_curve_add_not_nul(
+    point1: EmbeddedCurvePoint,
+    point2: EmbeddedCurvePoint,
+) -> EmbeddedCurvePoint
+ +
+

This function assumes that: +The points are on the curve, and +The points don't share an x-coordinate, and +Neither point is the infinity point. +If it is used with correct input, the function ensures the correct non-zero result is returned. +Except for points on the curve, the other assumptions are checked by the function. It will cause assertion failure if they are not respected.

+
+
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add_unsafe.html b/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add_unsafe.html new file mode 100644 index 00000000000..aecd983044e --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/fn.embedded_curve_add_unsafe.html @@ -0,0 +1,42 @@ + + + + + +Function embedded_curve_add_unsafe documentation + + + +
+ +

Function embedded_curve_add_unsafe

+
pub fn embedded_curve_add_unsafe(
+    point1: EmbeddedCurvePoint,
+    point2: EmbeddedCurvePoint,
+) -> EmbeddedCurvePoint
+ +
+

Unsafe ec addition +If the inputs are the same, it will perform a doubling, but only if point1 and point2 are the same variable. +If they have the same value but are different variables, the result will be incorrect because in this case +it assumes (but does not check) that the points' x-coordinates are not equal. +It also assumes neither point is the infinity point.

+
+
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/fn.fixed_base_scalar_mul.html b/noir_stdlib/docs/std/embedded_curve_ops/fn.fixed_base_scalar_mul.html new file mode 100644 index 00000000000..3a61541ac37 --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/fn.fixed_base_scalar_mul.html @@ -0,0 +1,32 @@ + + + + + +Function fixed_base_scalar_mul documentation + + + +
+ +

Function fixed_base_scalar_mul

+
pub fn fixed_base_scalar_mul(scalar: EmbeddedCurveScalar) -> EmbeddedCurvePoint
+ +
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/fn.multi_scalar_mul.html b/noir_stdlib/docs/std/embedded_curve_ops/fn.multi_scalar_mul.html new file mode 100644 index 00000000000..accdf720e05 --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/fn.multi_scalar_mul.html @@ -0,0 +1,35 @@ + + + + + +Function multi_scalar_mul documentation + + + +
+ +

Function multi_scalar_mul

+
pub fn multi_scalar_mul<let N: u32>(
+    points: [EmbeddedCurvePoint; N],
+    scalars: [EmbeddedCurveScalar; N],
+) -> EmbeddedCurvePoint
+ +
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/index.html b/noir_stdlib/docs/std/embedded_curve_ops/index.html new file mode 100644 index 00000000000..9810e83aa00 --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/index.html @@ -0,0 +1,114 @@ + + + + + +Module embedded_curve_ops documentation + + + +
+
noir_stdlib - std::embedded_curve_ops
+

Module embedded_curve_ops

+

Structs

    +
  • A point on the embedded elliptic curve +By definition, the base field of the embedded curve is the scalar field of the proof system curve, i.e the Noir Field. +x and y denotes the Weierstrass coordinates of the point, if is_infinite is false.
  • +
  • Scalar for the embedded curve represented as low and high limbs +By definition, the scalar field of the embedded curve is base field of the proving system curve. +It may not fit into a Field element, so it is represented with two Field elements; its low and high limbs.
  • +
+

Functions

    +
  • This function only assumes that the points are on the curve +It handles corner cases around the infinity point causing some overhead compared to embedded_curve_add_not_nul and embedded_curve_add_unsafe
  • +
  • This function assumes that: +The points are on the curve, and +The points don't share an x-coordinate, and +Neither point is the infinity point. +If it is used with correct input, the function ensures the correct non-zero result is returned. +Except for points on the curve, the other assumptions are checked by the function. It will cause assertion failure if they are not respected.
  • +
  • Unsafe ec addition +If the inputs are the same, it will perform a doubling, but only if point1 and point2 are the same variable. +If they have the same value but are different variables, the result will be incorrect because in this case +it assumes (but does not check) that the points' x-coordinates are not equal. +It also assumes neither point is the infinity point.
  • +
  • +
  • +
+
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/struct.EmbeddedCurvePoint.html b/noir_stdlib/docs/std/embedded_curve_ops/struct.EmbeddedCurvePoint.html new file mode 100644 index 00000000000..c1602a2c35a --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/struct.EmbeddedCurvePoint.html @@ -0,0 +1,121 @@ + + + + + +Struct EmbeddedCurvePoint documentation + + + +
+ +

Struct EmbeddedCurvePoint

+
pub struct EmbeddedCurvePoint {
+    pub x: Field,
+    pub y: Field,
+    pub is_infinite: bool,
+}
+
+
+

A point on the embedded elliptic curve +By definition, the base field of the embedded curve is the scalar field of the proof system curve, i.e the Noir Field. +x and y denotes the Weierstrass coordinates of the point, if is_infinite is false.

+
+

Fields

+ +
+
is_infinite: bool
+

Implementations

+

impl EmbeddedCurvePoint

+ +
pub fn double(self) -> Self + +
+

Elliptic curve point doubling operation +returns the doubled point of a point P, i.e P+P

+
+
pub fn point_at_infinity() -> Self + +
+

Returns the null element of the curve; 'the point at infinity'

+
+
pub fn generator() -> Self + +
+

Returns the curve's generator point.

+
+

Trait implementations

+

impl Add for EmbeddedCurvePoint

+ +
pub fn add(self, other: Self) -> Self + +
+

Adds two points P+Q, using the curve addition formula, and also handles point at infinity

+
+

impl Eq for EmbeddedCurvePoint

+ +
pub fn eq(self, b: Self) -> bool + +
+

Checks whether two points are equal

+
+

impl Hash for EmbeddedCurvePoint

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Neg for EmbeddedCurvePoint

+ +
pub fn neg(self) -> Self + +
+

Negates a point P, i.e returns -P, by negating the y coordinate. +If the point is at infinity, then the result is also at infinity.

+
+

impl Sub for EmbeddedCurvePoint

+ +
pub fn sub(self, other: Self) -> Self + +
+

Points subtraction operation, using addition and negation

+
+
+ + diff --git a/noir_stdlib/docs/std/embedded_curve_ops/struct.EmbeddedCurveScalar.html b/noir_stdlib/docs/std/embedded_curve_ops/struct.EmbeddedCurveScalar.html new file mode 100644 index 00000000000..2197d49a428 --- /dev/null +++ b/noir_stdlib/docs/std/embedded_curve_ops/struct.EmbeddedCurveScalar.html @@ -0,0 +1,77 @@ + + + + + +Struct EmbeddedCurveScalar documentation + + + +
+ +

Struct EmbeddedCurveScalar

+
pub struct EmbeddedCurveScalar {
+    pub lo: Field,
+    pub hi: Field,
+}
+
+
+

Scalar for the embedded curve represented as low and high limbs +By definition, the scalar field of the embedded curve is base field of the proving system curve. +It may not fit into a Field element, so it is represented with two Field elements; its low and high limbs.

+
+

Fields

+
lo: Field
+
hi: Field
+

Implementations

+

impl EmbeddedCurveScalar

+ +
pub fn new(lo: Field, hi: Field) -> Self + +pub fn from_field(scalar: Field) -> Self + +

Trait implementations

+

impl Eq for EmbeddedCurveScalar

+ +
pub fn eq(self, other: Self) -> bool + +

impl Hash for EmbeddedCurveScalar

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/field/bn254/fn.assert_gt.html b/noir_stdlib/docs/std/field/bn254/fn.assert_gt.html new file mode 100644 index 00000000000..e1c8511964c --- /dev/null +++ b/noir_stdlib/docs/std/field/bn254/fn.assert_gt.html @@ -0,0 +1,28 @@ + + + + + +Function assert_gt documentation + + + +
+ +

Function assert_gt

+
pub fn assert_gt(a: Field, b: Field)
+ +
+ + diff --git a/noir_stdlib/docs/std/field/bn254/fn.assert_lt.html b/noir_stdlib/docs/std/field/bn254/fn.assert_lt.html new file mode 100644 index 00000000000..d97ad19bb7b --- /dev/null +++ b/noir_stdlib/docs/std/field/bn254/fn.assert_lt.html @@ -0,0 +1,28 @@ + + + + + +Function assert_lt documentation + + + +
+ +

Function assert_lt

+
pub fn assert_lt(a: Field, b: Field)
+ +
+ + diff --git a/noir_stdlib/docs/std/field/bn254/fn.decompose.html b/noir_stdlib/docs/std/field/bn254/fn.decompose.html new file mode 100644 index 00000000000..bac87be3fdd --- /dev/null +++ b/noir_stdlib/docs/std/field/bn254/fn.decompose.html @@ -0,0 +1,31 @@ + + + + + +Function decompose documentation + + + +
+ +

Function decompose

+
pub fn decompose(x: Field) -> (Field, Field)
+ +
+

Decompose a single field into two 16 byte fields.

+
+
+ + diff --git a/noir_stdlib/docs/std/field/bn254/fn.gt.html b/noir_stdlib/docs/std/field/bn254/fn.gt.html new file mode 100644 index 00000000000..1d65c35ba2a --- /dev/null +++ b/noir_stdlib/docs/std/field/bn254/fn.gt.html @@ -0,0 +1,28 @@ + + + + + +Function gt documentation + + + +
+ +

Function gt

+
pub fn gt(a: Field, b: Field) -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/field/bn254/fn.lt.html b/noir_stdlib/docs/std/field/bn254/fn.lt.html new file mode 100644 index 00000000000..75896702e0a --- /dev/null +++ b/noir_stdlib/docs/std/field/bn254/fn.lt.html @@ -0,0 +1,28 @@ + + + + + +Function lt documentation + + + +
+ +

Function lt

+
pub fn lt(a: Field, b: Field) -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/field/bn254/index.html b/noir_stdlib/docs/std/field/bn254/index.html new file mode 100644 index 00000000000..94b2296d45e --- /dev/null +++ b/noir_stdlib/docs/std/field/bn254/index.html @@ -0,0 +1,42 @@ + + + + + +Module bn254 documentation + + + +
+ +

Module bn254

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/field/fn.bytes32_to_field.html b/noir_stdlib/docs/std/field/fn.bytes32_to_field.html new file mode 100644 index 00000000000..5f07f2e47df --- /dev/null +++ b/noir_stdlib/docs/std/field/fn.bytes32_to_field.html @@ -0,0 +1,32 @@ + + + + + +Function bytes32_to_field documentation + + + +
+ +

Function bytes32_to_field

+
pub fn bytes32_to_field(bytes32: [u8; 32]) -> Field
+ +
+ + diff --git a/noir_stdlib/docs/std/field/fn.modulus_be_bits.html b/noir_stdlib/docs/std/field/fn.modulus_be_bits.html new file mode 100644 index 00000000000..a0bf86b19f0 --- /dev/null +++ b/noir_stdlib/docs/std/field/fn.modulus_be_bits.html @@ -0,0 +1,32 @@ + + + + + +Function modulus_be_bits documentation + + + +
+ +

Function modulus_be_bits

+
pub comptime fn modulus_be_bits() -> [u1]
+ +
+ + diff --git a/noir_stdlib/docs/std/field/fn.modulus_be_bytes.html b/noir_stdlib/docs/std/field/fn.modulus_be_bytes.html new file mode 100644 index 00000000000..60f3df8a444 --- /dev/null +++ b/noir_stdlib/docs/std/field/fn.modulus_be_bytes.html @@ -0,0 +1,32 @@ + + + + + +Function modulus_be_bytes documentation + + + +
+ +

Function modulus_be_bytes

+
pub comptime fn modulus_be_bytes() -> [u8]
+ +
+ + diff --git a/noir_stdlib/docs/std/field/fn.modulus_le_bits.html b/noir_stdlib/docs/std/field/fn.modulus_le_bits.html new file mode 100644 index 00000000000..a9c0444589b --- /dev/null +++ b/noir_stdlib/docs/std/field/fn.modulus_le_bits.html @@ -0,0 +1,32 @@ + + + + + +Function modulus_le_bits documentation + + + +
+ +

Function modulus_le_bits

+
pub comptime fn modulus_le_bits() -> [u1]
+ +
+ + diff --git a/noir_stdlib/docs/std/field/fn.modulus_le_bytes.html b/noir_stdlib/docs/std/field/fn.modulus_le_bytes.html new file mode 100644 index 00000000000..4c9d4f8c68b --- /dev/null +++ b/noir_stdlib/docs/std/field/fn.modulus_le_bytes.html @@ -0,0 +1,32 @@ + + + + + +Function modulus_le_bytes documentation + + + +
+ +

Function modulus_le_bytes

+
pub comptime fn modulus_le_bytes() -> [u8]
+ +
+ + diff --git a/noir_stdlib/docs/std/field/fn.modulus_num_bits.html b/noir_stdlib/docs/std/field/fn.modulus_num_bits.html new file mode 100644 index 00000000000..3ea65958a06 --- /dev/null +++ b/noir_stdlib/docs/std/field/fn.modulus_num_bits.html @@ -0,0 +1,32 @@ + + + + + +Function modulus_num_bits documentation + + + +
+ +

Function modulus_num_bits

+
pub comptime fn modulus_num_bits() -> u64
+ +
+ + diff --git a/noir_stdlib/docs/std/field/index.html b/noir_stdlib/docs/std/field/index.html new file mode 100644 index 00000000000..37d473fadcd --- /dev/null +++ b/noir_stdlib/docs/std/field/index.html @@ -0,0 +1,100 @@ + + + + + +Module field documentation + + + +
+
noir_stdlib - std::field
+

Module field

+

Modules

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/fn.as_witness.html b/noir_stdlib/docs/std/fn.as_witness.html new file mode 100644 index 00000000000..a39ee6bcb11 --- /dev/null +++ b/noir_stdlib/docs/std/fn.as_witness.html @@ -0,0 +1,85 @@ + + + + + +Function as_witness documentation + + + +
+ +

Function as_witness

+
pub fn as_witness(x: Field)
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.assert_constant.html b/noir_stdlib/docs/std/fn.assert_constant.html new file mode 100644 index 00000000000..2b7c2cb35dc --- /dev/null +++ b/noir_stdlib/docs/std/fn.assert_constant.html @@ -0,0 +1,85 @@ + + + + + +Function assert_constant documentation + + + +
+ +

Function assert_constant

+
pub fn assert_constant<T>(x: T)
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.print.html b/noir_stdlib/docs/std/fn.print.html new file mode 100644 index 00000000000..0abd30cd727 --- /dev/null +++ b/noir_stdlib/docs/std/fn.print.html @@ -0,0 +1,85 @@ + + + + + +Function print documentation + + + +
+ +

Function print

+
pub fn print<T>(input: T)
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.println.html b/noir_stdlib/docs/std/fn.println.html new file mode 100644 index 00000000000..14619ff9102 --- /dev/null +++ b/noir_stdlib/docs/std/fn.println.html @@ -0,0 +1,85 @@ + + + + + +Function println documentation + + + +
+ +

Function println

+
pub fn println<T>(input: T)
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.static_assert.html b/noir_stdlib/docs/std/fn.static_assert.html new file mode 100644 index 00000000000..4f3159c767d --- /dev/null +++ b/noir_stdlib/docs/std/fn.static_assert.html @@ -0,0 +1,85 @@ + + + + + +Function static_assert documentation + + + +
+ +

Function static_assert

+
pub fn static_assert<T>(predicate: bool, message: T)
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.verify_proof_with_type.html b/noir_stdlib/docs/std/fn.verify_proof_with_type.html new file mode 100644 index 00000000000..93120240cab --- /dev/null +++ b/noir_stdlib/docs/std/fn.verify_proof_with_type.html @@ -0,0 +1,116 @@ + + + + + +Function verify_proof_with_type documentation + + + +
+ +

Function verify_proof_with_type

+
pub fn verify_proof_with_type<let N: u32, let M: u32, let K: u32>(
+    verification_key: [Field; N],
+    proof: [Field; M],
+    public_inputs: [Field; K],
+    key_hash: Field,
+    proof_type: u32,
+)
+ +
+

Asserts the validity of the provided proof and public inputs against the provided verification key and hash.

+

The ACVM cannot determine whether the provided proof is valid during execution as this requires knowledge of +the backend against which the program is being proven. However if an invalid proof if submitted, the program may +fail to prove or the backend may generate a proof which will subsequently fail to verify.

+

Important Note

+

If you are not developing your own backend such as Barretenberg +you probably shouldn't need to interact with this function directly. It's easier and safer to use a verification +library which is published by the developers of the backend which will document or enforce any safety requirements.

+

If you use this directly, you're liable to introduce underconstrainedness bugs and your circuit will be insecure.

+

Arguments

+
    +
  • verification_key: The verification key of the circuit to be verified.
  • +
  • proof: The proof to be verified.
  • +
  • public_inputs: The public inputs associated with proof
  • +
  • key_hash: The hash of verification_key of the form expected by the backend.
  • +
  • proof_type: An identifier for the proving scheme used to generate the proof to be verified. This allows +for a single backend to support verifying multiple proving schemes.
  • +
+

Constraining key_hash

+

The Noir compiler does not by itself constrain that key_hash is a valid hash of verification_key. +This is because different backends may differ in how they hash their verification keys. +It is then the responsibility of either the noir developer (by explicitly hashing the verification key +in the correct manner) or by the proving system itself internally asserting the correctness of key_hash.

+
+
+ + diff --git a/noir_stdlib/docs/std/fn.wrapping_add.html b/noir_stdlib/docs/std/fn.wrapping_add.html new file mode 100644 index 00000000000..5874ec197db --- /dev/null +++ b/noir_stdlib/docs/std/fn.wrapping_add.html @@ -0,0 +1,88 @@ + + + + + +Function wrapping_add documentation + + + +
+ +

Function wrapping_add

+
pub fn wrapping_add<T>(x: T, y: T) -> T
+
where + T: AsPrimitive<Field>, + Field: AsPrimitive<T>
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.wrapping_mul.html b/noir_stdlib/docs/std/fn.wrapping_mul.html new file mode 100644 index 00000000000..e1f2e1d9929 --- /dev/null +++ b/noir_stdlib/docs/std/fn.wrapping_mul.html @@ -0,0 +1,88 @@ + + + + + +Function wrapping_mul documentation + + + +
+ +

Function wrapping_mul

+
pub fn wrapping_mul<T>(x: T, y: T) -> T
+
where + T: AsPrimitive<Field>, + Field: AsPrimitive<T>
+ +
+ + diff --git a/noir_stdlib/docs/std/fn.wrapping_sub.html b/noir_stdlib/docs/std/fn.wrapping_sub.html new file mode 100644 index 00000000000..91f8399d6ff --- /dev/null +++ b/noir_stdlib/docs/std/fn.wrapping_sub.html @@ -0,0 +1,88 @@ + + + + + +Function wrapping_sub documentation + + + +
+ +

Function wrapping_sub

+
pub fn wrapping_sub<T>(x: T, y: T) -> T
+
where + T: AsPrimitive<Field>, + Field: AsPrimitive<T>
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.blake2s.html b/noir_stdlib/docs/std/hash/fn.blake2s.html new file mode 100644 index 00000000000..4f6cd7a187d --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.blake2s.html @@ -0,0 +1,44 @@ + + + + + +Function blake2s documentation + + + +
+ +

Function blake2s

+
pub fn blake2s<let N: u32>(input: [u8; N]) -> [u8; 32]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.blake3.html b/noir_stdlib/docs/std/hash/fn.blake3.html new file mode 100644 index 00000000000..0cc199a7a76 --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.blake3.html @@ -0,0 +1,44 @@ + + + + + +Function blake3 documentation + + + +
+ +

Function blake3

+
pub fn blake3<let N: u32>(input: [u8; N]) -> [u8; 32]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.derive_generators.html b/noir_stdlib/docs/std/hash/fn.derive_generators.html new file mode 100644 index 00000000000..1544e16dc9b --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.derive_generators.html @@ -0,0 +1,47 @@ + + + + + +Function derive_generators documentation + + + +
+ +

Function derive_generators

+
pub fn derive_generators<let N: u32, let M: u32>(
+    domain_separator_bytes: [u8; M],
+    starting_index: u32,
+) -> [EmbeddedCurvePoint; N]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.keccakf1600.html b/noir_stdlib/docs/std/hash/fn.keccakf1600.html new file mode 100644 index 00000000000..dfd385b4eee --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.keccakf1600.html @@ -0,0 +1,44 @@ + + + + + +Function keccakf1600 documentation + + + +
+ +

Function keccakf1600

+
pub fn keccakf1600(input: [u64; 25]) -> [u64; 25]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.pedersen_commitment.html b/noir_stdlib/docs/std/hash/fn.pedersen_commitment.html new file mode 100644 index 00000000000..7025f92d841 --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.pedersen_commitment.html @@ -0,0 +1,44 @@ + + + + + +Function pedersen_commitment documentation + + + +
+ +

Function pedersen_commitment

+
pub fn pedersen_commitment<let N: u32>(input: [Field; N]) -> EmbeddedCurvePoint
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.pedersen_commitment_with_separator.html b/noir_stdlib/docs/std/hash/fn.pedersen_commitment_with_separator.html new file mode 100644 index 00000000000..a990997371d --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.pedersen_commitment_with_separator.html @@ -0,0 +1,47 @@ + + + + + +Function pedersen_commitment_with_separator documentation + + + +
+ +

Function pedersen_commitment_with_separator

+
pub fn pedersen_commitment_with_separator<let N: u32>(
+    input: [Field; N],
+    separator: u32,
+) -> EmbeddedCurvePoint
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.pedersen_hash.html b/noir_stdlib/docs/std/hash/fn.pedersen_hash.html new file mode 100644 index 00000000000..43c909ddd58 --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.pedersen_hash.html @@ -0,0 +1,44 @@ + + + + + +Function pedersen_hash documentation + + + +
+ +

Function pedersen_hash

+
pub fn pedersen_hash<let N: u32>(input: [Field; N]) -> Field
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.pedersen_hash_with_separator.html b/noir_stdlib/docs/std/hash/fn.pedersen_hash_with_separator.html new file mode 100644 index 00000000000..fe170fe4525 --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.pedersen_hash_with_separator.html @@ -0,0 +1,47 @@ + + + + + +Function pedersen_hash_with_separator documentation + + + +
+ +

Function pedersen_hash_with_separator

+
pub fn pedersen_hash_with_separator<let N: u32>(
+    input: [Field; N],
+    separator: u32,
+) -> Field
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.poseidon2_permutation.html b/noir_stdlib/docs/std/hash/fn.poseidon2_permutation.html new file mode 100644 index 00000000000..453e4b08639 --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.poseidon2_permutation.html @@ -0,0 +1,44 @@ + + + + + +Function poseidon2_permutation documentation + + + +
+ +

Function poseidon2_permutation

+
pub fn poseidon2_permutation<let N: u32>(input: [Field; N], state_len: u32) -> [Field; N]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/fn.sha256_compression.html b/noir_stdlib/docs/std/hash/fn.sha256_compression.html new file mode 100644 index 00000000000..288f443a1fe --- /dev/null +++ b/noir_stdlib/docs/std/hash/fn.sha256_compression.html @@ -0,0 +1,44 @@ + + + + + +Function sha256_compression documentation + + + +
+ +

Function sha256_compression

+
pub fn sha256_compression(input: [u32; 16], state: [u32; 8]) -> [u32; 8]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/index.html b/noir_stdlib/docs/std/hash/index.html new file mode 100644 index 00000000000..1c02a9efe35 --- /dev/null +++ b/noir_stdlib/docs/std/hash/index.html @@ -0,0 +1,114 @@ + + + + + +Module hash documentation + + + +
+ +

Module hash

+

Modules

+

Structs

+

Traits

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/hash/keccak/fn.keccakf1600.html b/noir_stdlib/docs/std/hash/keccak/fn.keccakf1600.html new file mode 100644 index 00000000000..a1a18b5e869 --- /dev/null +++ b/noir_stdlib/docs/std/hash/keccak/fn.keccakf1600.html @@ -0,0 +1,24 @@ + + + + + +Function keccakf1600 documentation + + + +
+ +

Function keccakf1600

+
pub fn keccakf1600(input: [u64; 25]) -> [u64; 25]
+ +
+ + diff --git a/noir_stdlib/docs/std/hash/keccak/index.html b/noir_stdlib/docs/std/hash/keccak/index.html new file mode 100644 index 00000000000..9f232064829 --- /dev/null +++ b/noir_stdlib/docs/std/hash/keccak/index.html @@ -0,0 +1,50 @@ + + + + + +Module keccak documentation + + + +
+
noir_stdlib - std::hash::keccak
+

Module keccak

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/hash/struct.BuildHasherDefault.html b/noir_stdlib/docs/std/hash/struct.BuildHasherDefault.html new file mode 100644 index 00000000000..b583556c03a --- /dev/null +++ b/noir_stdlib/docs/std/hash/struct.BuildHasherDefault.html @@ -0,0 +1,65 @@ + + + + + +Struct BuildHasherDefault documentation + + + +
+ +

Struct BuildHasherDefault

+
pub struct BuildHasherDefault<H> {}
+
+

Trait implementations

+

impl<H> BuildHasher for BuildHasherDefault<H> +
where + H: Hasher, + H: Default

+ +
pub fn build_hasher(_self: Self) -> H + +

impl<H> Default for BuildHasherDefault<H> +
where + H: Hasher, + H: Default

+ +
pub fn default() -> Self + +
+ + diff --git a/noir_stdlib/docs/std/hash/trait.BuildHasher.html b/noir_stdlib/docs/std/hash/trait.BuildHasher.html new file mode 100644 index 00000000000..e0b9ec288c2 --- /dev/null +++ b/noir_stdlib/docs/std/hash/trait.BuildHasher.html @@ -0,0 +1,67 @@ + + + + + +Trait BuildHasher documentation + + + +
+ +

Trait BuildHasher

+
pub trait BuildHasher {
+    type H: Hasher;
+
+    // Required methods
+    pub fn build_hasher(self) -> H;
+}
+ +

Required methods

+
pub fn build_hasher(self) -> H + +

Implementors

+

impl<H> BuildHasher for BuildHasherDefault<H> +
where + H: Hasher, + H: Default

+ +
+ + diff --git a/noir_stdlib/docs/std/hash/trait.Hash.html b/noir_stdlib/docs/std/hash/trait.Hash.html new file mode 100644 index 00000000000..721bd1bb4ec --- /dev/null +++ b/noir_stdlib/docs/std/hash/trait.Hash.html @@ -0,0 +1,183 @@ + + + + + +Trait Hash documentation + + + +
+ +

Trait Hash

+
pub trait Hash {
+    // Required methods
+    pub fn hash<H>(self, state: &mut H)
+
where + H: Hasher
; +}
+ +

Required methods

+
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

Implementors

+

impl Hash for ()

+ +

impl<A, B> Hash for (A, B) +
where + A: Hash, + B: Hash

+ +

impl<A, B, C> Hash for (A, B, C) +
where + A: Hash, + B: Hash, + C: Hash

+ +

impl<A, B, C, D> Hash for (A, B, C, D) +
where + A: Hash, + B: Hash, + C: Hash, + D: Hash

+ +

impl<A, B, C, D, E> Hash for (A, B, C, D, E) +
where + A: Hash, + B: Hash, + C: Hash, + D: Hash, + E: Hash

+ +

impl Hash for BinaryOp

+ +

impl Hash for CtString

+ +

impl Hash for EmbeddedCurvePoint

+ +

impl Hash for EmbeddedCurveScalar

+ +

impl Hash for Field

+ +

impl Hash for FunctionDefinition

+ +

impl Hash for Module

+ +

impl<T> Hash for Option<T> +
where + T: Hash

+ +

impl Hash for Quoted

+ +

impl Hash for TraitConstraint

+ +

impl Hash for TraitDefinition

+ +

impl Hash for Type

+ +

impl Hash for TypeDefinition

+ +

impl Hash for UnaryOp

+ +

impl<let N: u32, T> Hash for [T; N] +
where + T: Hash

+ +

impl<T> Hash for [T] +
where + T: Hash

+ +

impl Hash for bool

+ +

impl Hash for i16

+ +

impl Hash for i32

+ +

impl Hash for i64

+ +

impl Hash for i8

+ +

impl Hash for u1

+ +

impl Hash for u128

+ +

impl Hash for u16

+ +

impl Hash for u32

+ +

impl Hash for u64

+ +

impl Hash for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/hash/trait.Hasher.html b/noir_stdlib/docs/std/hash/trait.Hasher.html new file mode 100644 index 00000000000..8b61dfd6547 --- /dev/null +++ b/noir_stdlib/docs/std/hash/trait.Hasher.html @@ -0,0 +1,66 @@ + + + + + +Trait Hasher documentation + + + +
+ +

Trait Hasher

+
pub trait Hasher {
+    // Required methods
+    pub fn finish(self) -> Field;
+    pub fn write(&mut self: &mut Self, input: Field);
+}
+ +

Required methods

+
pub fn finish(self) -> Field + +pub fn write(&mut self: &mut Self, input: Field) + +

Implementors

+

impl Hasher for Poseidon2Hasher

+ +
+ + diff --git a/noir_stdlib/docs/std/hint/fn.black_box.html b/noir_stdlib/docs/std/hint/fn.black_box.html new file mode 100644 index 00000000000..08f82ecd536 --- /dev/null +++ b/noir_stdlib/docs/std/hint/fn.black_box.html @@ -0,0 +1,29 @@ + + + + + +Function black_box documentation + + + +
+ +

Function black_box

+
pub fn black_box<T>(value: T) -> T
+ +
+

An identity function that hints to the compiler to be maximally pessimistic about what black_box could do.

+

This can be used to block the SSA optimization passes being applied to a value, which should help to prevent +test programs from being optimized down to nothing and have them resemble runtime code more closely.

+
+
+ + diff --git a/noir_stdlib/docs/std/hint/index.html b/noir_stdlib/docs/std/hint/index.html new file mode 100644 index 00000000000..14ecc4356f0 --- /dev/null +++ b/noir_stdlib/docs/std/hint/index.html @@ -0,0 +1,91 @@ + + + + + +Module hint documentation + + + +
+ +

Module hint

+

Functions

    +
  • An identity function that hints to the compiler to be maximally pessimistic about what black_box could do.
  • +
+
+ + diff --git a/noir_stdlib/docs/std/index.html b/noir_stdlib/docs/std/index.html new file mode 100644 index 00000000000..fdbc7113206 --- /dev/null +++ b/noir_stdlib/docs/std/index.html @@ -0,0 +1,91 @@ + + + + + +Crate std documentation + + + +
+ +

Crate std

+

Modules

+

Primitive types

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/mem/fn.array_refcount.html b/noir_stdlib/docs/std/mem/fn.array_refcount.html new file mode 100644 index 00000000000..5314b38b871 --- /dev/null +++ b/noir_stdlib/docs/std/mem/fn.array_refcount.html @@ -0,0 +1,32 @@ + + + + + +Function array_refcount documentation + + + +
+ +

Function array_refcount

+
pub fn array_refcount<T, let N: u32>(array: [T; N]) -> u32
+ +
+

Returns the internal reference count of an array value in unconstrained code.

+

Arrays only have reference count in unconstrained code - using this anywhere +else will return zero.

+
+
+ + diff --git a/noir_stdlib/docs/std/mem/fn.checked_transmute.html b/noir_stdlib/docs/std/mem/fn.checked_transmute.html new file mode 100644 index 00000000000..75994af5b3f --- /dev/null +++ b/noir_stdlib/docs/std/mem/fn.checked_transmute.html @@ -0,0 +1,36 @@ + + + + + +Function checked_transmute documentation + + + +
+ +

Function checked_transmute

+
pub fn checked_transmute<T, U>(value: T) -> U
+ +
+

Transmutes a value of type T to a value of type U.

+

Both types are asserted to be equal during compilation but after type checking. +If not, a compilation error is issued.

+

This function is useful for types using arithmetic generics in cases +which the compiler otherwise cannot prove equal during type checking. +You can use this to obtain a value of the correct type while still asserting +that it is equal to the previous.

+
+
+ + diff --git a/noir_stdlib/docs/std/mem/fn.slice_refcount.html b/noir_stdlib/docs/std/mem/fn.slice_refcount.html new file mode 100644 index 00000000000..9f22e7a0edc --- /dev/null +++ b/noir_stdlib/docs/std/mem/fn.slice_refcount.html @@ -0,0 +1,32 @@ + + + + + +Function slice_refcount documentation + + + +
+ +

Function slice_refcount

+
pub fn slice_refcount<T>(slice: [T]) -> u32
+ +
+

Returns the internal reference count of a slice value in unconstrained code.

+

Slices only have reference count in unconstrained code - using this anywhere +else will return zero.

+
+
+ + diff --git a/noir_stdlib/docs/std/mem/fn.zeroed.html b/noir_stdlib/docs/std/mem/fn.zeroed.html new file mode 100644 index 00000000000..0f5fa7957ae --- /dev/null +++ b/noir_stdlib/docs/std/mem/fn.zeroed.html @@ -0,0 +1,32 @@ + + + + + +Function zeroed documentation + + + +
+ +

Function zeroed

+
pub fn zeroed<T>() -> T
+ +
+

For any type, return an instance of that type by initializing +all of its fields to 0. This is considered to be unsafe since there +is no guarantee that all zeroes is a valid bit pattern for every type.

+
+
+ + diff --git a/noir_stdlib/docs/std/mem/index.html b/noir_stdlib/docs/std/mem/index.html new file mode 100644 index 00000000000..905d90ac7d5 --- /dev/null +++ b/noir_stdlib/docs/std/mem/index.html @@ -0,0 +1,96 @@ + + + + + +Module mem documentation + + + +
+ +

Module mem

+

Functions

    +
  • Returns the internal reference count of an array value in unconstrained code.
  • +
  • Transmutes a value of type T to a value of type U.
  • +
  • Returns the internal reference count of a slice value in unconstrained code.
  • +
  • For any type, return an instance of that type by initializing +all of its fields to 0. This is considered to be unsafe since there +is no guarantee that all zeroes is a valid bit pattern for every type.
  • +
+
+ + diff --git a/noir_stdlib/docs/std/meta/ctstring/index.html b/noir_stdlib/docs/std/meta/ctstring/index.html new file mode 100644 index 00000000000..4d1e25fbae4 --- /dev/null +++ b/noir_stdlib/docs/std/meta/ctstring/index.html @@ -0,0 +1,42 @@ + + + + + +Module ctstring documentation + + + +
+
noir_stdlib - std::meta::ctstring
+

Module ctstring

+

Traits

+
+ + diff --git a/noir_stdlib/docs/std/meta/ctstring/trait.AsCtString.html b/noir_stdlib/docs/std/meta/ctstring/trait.AsCtString.html new file mode 100644 index 00000000000..00d6bb0b879 --- /dev/null +++ b/noir_stdlib/docs/std/meta/ctstring/trait.AsCtString.html @@ -0,0 +1,45 @@ + + + + + +Trait AsCtString documentation + + + +
+ +

Trait AsCtString

+
pub trait AsCtString {
+    // Required methods
+    pub comptime fn as_ctstring(self) -> CtString;
+}
+ +

Required methods

+
pub comptime fn as_ctstring(self) -> CtString + +

Implementors

+

impl<let N: u32, T> AsCtString for fmtstr<N, T>

+ +

impl<let N: u32> AsCtString for str<N>

+ +
+ + diff --git a/noir_stdlib/docs/std/meta/expr/index.html b/noir_stdlib/docs/std/meta/expr/index.html new file mode 100644 index 00000000000..881e3416b28 --- /dev/null +++ b/noir_stdlib/docs/std/meta/expr/index.html @@ -0,0 +1,38 @@ + + + + + +Module expr documentation + + + +
+ +

Module expr

+
+

Contains methods on the built-in Expr type for quoted, syntactically valid expressions.

+
+
+ + diff --git a/noir_stdlib/docs/std/meta/fn.derive.html b/noir_stdlib/docs/std/meta/fn.derive.html new file mode 100644 index 00000000000..25e1959eada --- /dev/null +++ b/noir_stdlib/docs/std/meta/fn.derive.html @@ -0,0 +1,36 @@ + + + + + +Function derive documentation + + + +
+ +

Function derive

+
pub comptime fn derive(s: TypeDefinition, traits: [TraitDefinition]) -> Quoted
+ +
+ + diff --git a/noir_stdlib/docs/std/meta/fn.derive_via.html b/noir_stdlib/docs/std/meta/fn.derive_via.html new file mode 100644 index 00000000000..7943045f010 --- /dev/null +++ b/noir_stdlib/docs/std/meta/fn.derive_via.html @@ -0,0 +1,36 @@ + + + + + +Function derive_via documentation + + + +
+ +

Function derive_via

+
pub comptime fn derive_via(t: TraitDefinition, f: DeriveFunction)
+ +
+ + diff --git a/noir_stdlib/docs/std/meta/fn.make_trait_impl.html b/noir_stdlib/docs/std/meta/fn.make_trait_impl.html new file mode 100644 index 00000000000..cf6ca2ace5b --- /dev/null +++ b/noir_stdlib/docs/std/meta/fn.make_trait_impl.html @@ -0,0 +1,57 @@ + + + + + +Function make_trait_impl documentation + + + +
+ +

Function make_trait_impl

+
pub comptime fn make_trait_impl<Env1, Env2>(
+    s: TypeDefinition,
+    trait_name: Quoted,
+    function_signature: Quoted,
+    for_each_field: fn[Env1](Quoted) -> Quoted,
+    join_fields_with: Quoted,
+    body: fn[Env2](Quoted) -> Quoted,
+) -> Quoted
+ +
+

make_impl is a helper function to make a simple impl, usually while deriving a trait. +This impl has a couple assumptions:

+
    +
  1. The impl only has one function, with the signature function_signature
  2. +
  3. The trait itself does not have any generics.
  4. +
+

While these assumptions are met, make_impl will create an impl from a TypeDefinition, +automatically filling in the required generics from the type, along with the where clause. +The function body is created by mapping each field with for_each_field and joining the +results with join_fields_with. The result of this is passed to the body function for +any final processing - e.g. wrapping each field in a StructConstructor { .. } expression.

+

See derive_eq and derive_default for example usage.

+
+
+ + diff --git a/noir_stdlib/docs/std/meta/fn.type_of.html b/noir_stdlib/docs/std/meta/fn.type_of.html new file mode 100644 index 00000000000..88330762c96 --- /dev/null +++ b/noir_stdlib/docs/std/meta/fn.type_of.html @@ -0,0 +1,39 @@ + + + + + +Function type_of documentation + + + +
+ +

Function type_of

+
pub comptime fn type_of<T>(x: T) -> Type
+ +
+

Returns the type of any value

+
+
+ + diff --git a/noir_stdlib/docs/std/meta/fn.unquote.html b/noir_stdlib/docs/std/meta/fn.unquote.html new file mode 100644 index 00000000000..809652ad93f --- /dev/null +++ b/noir_stdlib/docs/std/meta/fn.unquote.html @@ -0,0 +1,41 @@ + + + + + +Function unquote documentation + + + +
+ +

Function unquote

+
pub comptime fn unquote(code: Quoted) -> Quoted
+ +
+

Calling unquote as a macro (via unquote!(arg)) will unquote +its argument. Since this is the effect ! already does, unquote +itself does not need to do anything besides return its argument.

+
+
+ + diff --git a/noir_stdlib/docs/std/meta/format_string/index.html b/noir_stdlib/docs/std/meta/format_string/index.html new file mode 100644 index 00000000000..61243d19164 --- /dev/null +++ b/noir_stdlib/docs/std/meta/format_string/index.html @@ -0,0 +1,35 @@ + + + + + +Module format_string documentation + + + +
+
noir_stdlib - std::meta::format_string
+

Module format_string

+
+ + diff --git a/noir_stdlib/docs/std/meta/function_def/index.html b/noir_stdlib/docs/std/meta/function_def/index.html new file mode 100644 index 00000000000..9660f70c1cc --- /dev/null +++ b/noir_stdlib/docs/std/meta/function_def/index.html @@ -0,0 +1,35 @@ + + + + + +Module function_def documentation + + + +
+
noir_stdlib - std::meta::function_def
+

Module function_def

+
+ + diff --git a/noir_stdlib/docs/std/meta/index.html b/noir_stdlib/docs/std/meta/index.html new file mode 100644 index 00000000000..2bcee8240ff --- /dev/null +++ b/noir_stdlib/docs/std/meta/index.html @@ -0,0 +1,112 @@ + + + + + +Module meta documentation + + + +
+ +

Module meta

+

Modules

    +
  • +
  • +
  • Contains methods on the built-in Type type used for representing a type in the source program.
  • +
+

Type aliases

+

Functions

    +
  • +
  • +
  • make_impl is a helper function to make a simple impl, usually while deriving a trait. +This impl has a couple assumptions:

    +
      +
    1. The impl only has one function, with the signature function_signature
    2. +
    3. The trait itself does not have any generics.
    4. +
  • +
  • Returns the type of any value
  • +
  • Calling unquote as a macro (via unquote!(arg)) will unquote +its argument. Since this is the effect ! already does, unquote +itself does not need to do anything besides return its argument.
  • +
+
+ + diff --git a/noir_stdlib/docs/std/meta/module/index.html b/noir_stdlib/docs/std/meta/module/index.html new file mode 100644 index 00000000000..f1395478346 --- /dev/null +++ b/noir_stdlib/docs/std/meta/module/index.html @@ -0,0 +1,35 @@ + + + + + +Module module documentation + + + +
+
noir_stdlib - std::meta::module
+

Module module

+
+ + diff --git a/noir_stdlib/docs/std/meta/op/index.html b/noir_stdlib/docs/std/meta/op/index.html new file mode 100644 index 00000000000..6927e470932 --- /dev/null +++ b/noir_stdlib/docs/std/meta/op/index.html @@ -0,0 +1,43 @@ + + + + + +Module op documentation + + + +
+ +

Module op

+

Structs

+
+ + diff --git a/noir_stdlib/docs/std/meta/op/struct.BinaryOp.html b/noir_stdlib/docs/std/meta/op/struct.BinaryOp.html new file mode 100644 index 00000000000..6c51febcdd9 --- /dev/null +++ b/noir_stdlib/docs/std/meta/op/struct.BinaryOp.html @@ -0,0 +1,100 @@ + + + + + +Struct BinaryOp documentation + + + +
+ +

Struct BinaryOp

+
pub struct BinaryOp
+{ /* private fields */ }
+
+

Implementations

+

impl BinaryOp

+ +
pub fn is_add(self) -> bool + +pub fn is_subtract(self) -> bool + +pub fn is_multiply(self) -> bool + +pub fn is_divide(self) -> bool + +pub fn is_equal(self) -> bool + +pub fn is_not_equal(self) -> bool + +pub fn is_less_than(self) -> bool + +pub fn is_less_than_or_equal(self) -> bool + +pub fn is_greater_than(self) -> bool + +pub fn is_greater_than_or_equal(self) -> bool + +pub fn is_and(self) -> bool + +pub fn is_or(self) -> bool + +pub fn is_xor(self) -> bool + +pub fn is_shift_right(self) -> bool + +pub fn is_shift_left(self) -> bool + +pub fn is_modulo(self) -> bool + +pub comptime fn quoted(self) -> Quoted + +

Trait implementations

+

impl Eq for BinaryOp

+ +
pub fn eq(self, other: Self) -> bool + +

impl Hash for BinaryOp

+ +
pub fn hash<H>(self, h: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/meta/op/struct.UnaryOp.html b/noir_stdlib/docs/std/meta/op/struct.UnaryOp.html new file mode 100644 index 00000000000..a91c8570949 --- /dev/null +++ b/noir_stdlib/docs/std/meta/op/struct.UnaryOp.html @@ -0,0 +1,64 @@ + + + + + +Struct UnaryOp documentation + + + +
+ +

Struct UnaryOp

+
pub struct UnaryOp
+{ /* private fields */ }
+
+

Implementations

+

impl UnaryOp

+ +
pub fn is_minus(self) -> bool + +pub fn is_not(self) -> bool + +pub fn is_mutable_reference(self) -> bool + +pub fn is_dereference(self) -> bool + +pub comptime fn quoted(self) -> Quoted + +

Trait implementations

+

impl Eq for UnaryOp

+ +
pub fn eq(self, other: Self) -> bool + +

impl Hash for UnaryOp

+ +
pub fn hash<H>(self, h: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/meta/quoted/index.html b/noir_stdlib/docs/std/meta/quoted/index.html new file mode 100644 index 00000000000..a640588f12a --- /dev/null +++ b/noir_stdlib/docs/std/meta/quoted/index.html @@ -0,0 +1,35 @@ + + + + + +Module quoted documentation + + + +
+
noir_stdlib - std::meta::quoted
+

Module quoted

+
+ + diff --git a/noir_stdlib/docs/std/meta/trait_constraint/index.html b/noir_stdlib/docs/std/meta/trait_constraint/index.html new file mode 100644 index 00000000000..0568ac63b31 --- /dev/null +++ b/noir_stdlib/docs/std/meta/trait_constraint/index.html @@ -0,0 +1,35 @@ + + + + + +Module trait_constraint documentation + + + +
+
noir_stdlib - std::meta::trait_constraint
+

Module trait_constraint

+
+ + diff --git a/noir_stdlib/docs/std/meta/trait_def/index.html b/noir_stdlib/docs/std/meta/trait_def/index.html new file mode 100644 index 00000000000..453b234cd97 --- /dev/null +++ b/noir_stdlib/docs/std/meta/trait_def/index.html @@ -0,0 +1,35 @@ + + + + + +Module trait_def documentation + + + +
+
noir_stdlib - std::meta::trait_def
+

Module trait_def

+
+ + diff --git a/noir_stdlib/docs/std/meta/trait_impl/index.html b/noir_stdlib/docs/std/meta/trait_impl/index.html new file mode 100644 index 00000000000..fc797cdf8b3 --- /dev/null +++ b/noir_stdlib/docs/std/meta/trait_impl/index.html @@ -0,0 +1,35 @@ + + + + + +Module trait_impl documentation + + + +
+
noir_stdlib - std::meta::trait_impl
+

Module trait_impl

+
+ + diff --git a/noir_stdlib/docs/std/meta/typ/fn.fresh_type_variable.html b/noir_stdlib/docs/std/meta/typ/fn.fresh_type_variable.html new file mode 100644 index 00000000000..cf75ac3af2d --- /dev/null +++ b/noir_stdlib/docs/std/meta/typ/fn.fresh_type_variable.html @@ -0,0 +1,70 @@ + + + + + +Function fresh_type_variable documentation + + + +
+ +

Function fresh_type_variable

+
pub comptime fn fresh_type_variable() -> Type
+ +
+

Creates and returns an unbound type variable. This is a special kind of type internal +to type checking which will type check with any other type. When it is type checked +against another type it will also be set to that type. For example, if a is a type +variable and we have the type equality (a, i32) = (u8, i32), the compiler will set +a equal to u8.

+

Unbound type variables will often be rendered as _ while printing them. Bound type +variables will appear as the type they are bound to.

+

This can be used in conjunction with functions which internally perform type checks +such as Type::implements or Type::get_trait_impl to potentially grab some of the types used.

+

Note that calling Type::implements or Type::get_trait_impl on a type variable will always +fail.

+

Example:

+
trait Serialize<let N: u32> {}
+
+impl Serialize<1> for Field {}
+
+impl<T, let N: u32, let M: u32> Serialize<N * M> for [T; N]
+    where T: Serialize<M> {}
+
+impl<T, U, let N: u32, let M: u32> Serialize<N + M> for (T, U)
+    where T: Serialize<N>, U: Serialize<M> {}
+
+fn fresh_variable_example() {
+    let typevar1 = std::meta::typ::fresh_type_variable();
+    let constraint = quote { Serialize<$typevar1> }.as_trait_constraint();
+    let field_type = quote { Field }.as_type();
+
+    // Search for a trait impl (binding typevar1 to 1 when the impl is found):
+    assert(field_type.implements(constraint));
+
+    // typevar1 should be bound to the "1" generic now:
+    assert_eq(typevar1.as_constant().unwrap(), 1);
+
+    // If we want to do the same with a different type, we need to
+    // create a new type variable now that `typevar1` is bound
+    let typevar2 = std::meta::typ::fresh_type_variable();
+    let constraint = quote { Serialize<$typevar2> }.as_trait_constraint();
+    let array_type = quote { [(Field, Field); 5] }.as_type();
+    assert(array_type.implements(constraint));
+
+    // Now typevar2 should be bound to the serialized pair size 2 times the array length 5
+    assert_eq(typevar2.as_constant().unwrap(), 10);
+}
+
+
+
+ + diff --git a/noir_stdlib/docs/std/meta/typ/index.html b/noir_stdlib/docs/std/meta/typ/index.html new file mode 100644 index 00000000000..a88dd784f4f --- /dev/null +++ b/noir_stdlib/docs/std/meta/typ/index.html @@ -0,0 +1,49 @@ + + + + + +Module typ documentation + + + +
+ +

Module typ

+
+

Contains methods on the built-in Type type used for representing a type in the source program.

+
+

Functions

    +
  • Creates and returns an unbound type variable. This is a special kind of type internal +to type checking which will type check with any other type. When it is type checked +against another type it will also be set to that type. For example, if a is a type +variable and we have the type equality (a, i32) = (u8, i32), the compiler will set +a equal to u8.
  • +
+
+ + diff --git a/noir_stdlib/docs/std/meta/type.DeriveFunction.html b/noir_stdlib/docs/std/meta/type.DeriveFunction.html new file mode 100644 index 00000000000..97b82746fc8 --- /dev/null +++ b/noir_stdlib/docs/std/meta/type.DeriveFunction.html @@ -0,0 +1,36 @@ + + + + + +Type alias DeriveFunction documentation + + + +
+ +

Type alias DeriveFunction

+
pub type DeriveFunction = fn(TypeDefinition) -> Quoted;
+ +
+ + diff --git a/noir_stdlib/docs/std/meta/type_def/index.html b/noir_stdlib/docs/std/meta/type_def/index.html new file mode 100644 index 00000000000..6e7facda5d2 --- /dev/null +++ b/noir_stdlib/docs/std/meta/type_def/index.html @@ -0,0 +1,35 @@ + + + + + +Module type_def documentation + + + +
+
noir_stdlib - std::meta::type_def
+

Module type_def

+
+ + diff --git a/noir_stdlib/docs/std/meta/typed_expr/index.html b/noir_stdlib/docs/std/meta/typed_expr/index.html new file mode 100644 index 00000000000..ad0d9835850 --- /dev/null +++ b/noir_stdlib/docs/std/meta/typed_expr/index.html @@ -0,0 +1,38 @@ + + + + + +Module typed_expr documentation + + + +
+
noir_stdlib - std::meta::typed_expr
+

Module typed_expr

+
+

Contains methods on the built-in TypedExpr type for resolved and type-checked expressions.

+
+
+ + diff --git a/noir_stdlib/docs/std/meta/unresolved_type/index.html b/noir_stdlib/docs/std/meta/unresolved_type/index.html new file mode 100644 index 00000000000..afb4233768c --- /dev/null +++ b/noir_stdlib/docs/std/meta/unresolved_type/index.html @@ -0,0 +1,38 @@ + + + + + +Module unresolved_type documentation + + + +
+
noir_stdlib - std::meta::unresolved_type
+

Module unresolved_type

+
+

Contains methods on the built-in UnresolvedType type for the syntax of types.

+
+
+ + diff --git a/noir_stdlib/docs/std/ops/index.html b/noir_stdlib/docs/std/ops/index.html new file mode 100644 index 00000000000..9cb0ec74d60 --- /dev/null +++ b/noir_stdlib/docs/std/ops/index.html @@ -0,0 +1,105 @@ + + + + + +Module ops documentation + + + +
+ +

Module ops

+

Traits

+
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Add.html b/noir_stdlib/docs/std/ops/trait.Add.html new file mode 100644 index 00000000000..fd9a11a35e6 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Add.html @@ -0,0 +1,89 @@ + + + + + +Trait Add documentation + + + +
+ +

Trait Add

+
pub trait Add {
+    // Required methods
+    pub fn add(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn add(self, other: Self) -> Self + +

Implementors

+

impl Add for EmbeddedCurvePoint

+ +

impl Add for Field

+ +

impl Add for i16

+ +

impl Add for i32

+ +

impl Add for i64

+ +

impl Add for i8

+ +

impl Add for u1

+ +

impl Add for u128

+ +

impl Add for u16

+ +

impl Add for u32

+ +

impl Add for u64

+ +

impl Add for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.BitAnd.html b/noir_stdlib/docs/std/ops/trait.BitAnd.html new file mode 100644 index 00000000000..c42fc0fd3a4 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.BitAnd.html @@ -0,0 +1,86 @@ + + + + + +Trait BitAnd documentation + + + +
+ +

Trait BitAnd

+
pub trait BitAnd {
+    // Required methods
+    pub fn bitand(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn bitand(self, other: Self) -> Self + +

Implementors

+

impl BitAnd for bool

+ +

impl BitAnd for i16

+ +

impl BitAnd for i32

+ +

impl BitAnd for i64

+ +

impl BitAnd for i8

+ +

impl BitAnd for u1

+ +

impl BitAnd for u128

+ +

impl BitAnd for u16

+ +

impl BitAnd for u32

+ +

impl BitAnd for u64

+ +

impl BitAnd for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.BitOr.html b/noir_stdlib/docs/std/ops/trait.BitOr.html new file mode 100644 index 00000000000..263d5197a98 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.BitOr.html @@ -0,0 +1,86 @@ + + + + + +Trait BitOr documentation + + + +
+ +

Trait BitOr

+
pub trait BitOr {
+    // Required methods
+    pub fn bitor(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn bitor(self, other: Self) -> Self + +

Implementors

+

impl BitOr for bool

+ +

impl BitOr for i16

+ +

impl BitOr for i32

+ +

impl BitOr for i64

+ +

impl BitOr for i8

+ +

impl BitOr for u1

+ +

impl BitOr for u128

+ +

impl BitOr for u16

+ +

impl BitOr for u32

+ +

impl BitOr for u64

+ +

impl BitOr for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.BitXor.html b/noir_stdlib/docs/std/ops/trait.BitXor.html new file mode 100644 index 00000000000..ce5dee1cbf9 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.BitXor.html @@ -0,0 +1,86 @@ + + + + + +Trait BitXor documentation + + + +
+ +

Trait BitXor

+
pub trait BitXor {
+    // Required methods
+    pub fn bitxor(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn bitxor(self, other: Self) -> Self + +

Implementors

+

impl BitXor for bool

+ +

impl BitXor for i16

+ +

impl BitXor for i32

+ +

impl BitXor for i64

+ +

impl BitXor for i8

+ +

impl BitXor for u1

+ +

impl BitXor for u128

+ +

impl BitXor for u16

+ +

impl BitXor for u32

+ +

impl BitXor for u64

+ +

impl BitXor for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Div.html b/noir_stdlib/docs/std/ops/trait.Div.html new file mode 100644 index 00000000000..9664ae0dfe4 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Div.html @@ -0,0 +1,86 @@ + + + + + +Trait Div documentation + + + +
+ +

Trait Div

+
pub trait Div {
+    // Required methods
+    pub fn div(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn div(self, other: Self) -> Self + +

Implementors

+

impl Div for Field

+ +

impl Div for i16

+ +

impl Div for i32

+ +

impl Div for i64

+ +

impl Div for i8

+ +

impl Div for u1

+ +

impl Div for u128

+ +

impl Div for u16

+ +

impl Div for u32

+ +

impl Div for u64

+ +

impl Div for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Mul.html b/noir_stdlib/docs/std/ops/trait.Mul.html new file mode 100644 index 00000000000..0942d8ff271 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Mul.html @@ -0,0 +1,86 @@ + + + + + +Trait Mul documentation + + + +
+ +

Trait Mul

+
pub trait Mul {
+    // Required methods
+    pub fn mul(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn mul(self, other: Self) -> Self + +

Implementors

+

impl Mul for Field

+ +

impl Mul for i16

+ +

impl Mul for i32

+ +

impl Mul for i64

+ +

impl Mul for i8

+ +

impl Mul for u1

+ +

impl Mul for u128

+ +

impl Mul for u16

+ +

impl Mul for u32

+ +

impl Mul for u64

+ +

impl Mul for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Neg.html b/noir_stdlib/docs/std/ops/trait.Neg.html new file mode 100644 index 00000000000..604a5675d87 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Neg.html @@ -0,0 +1,71 @@ + + + + + +Trait Neg documentation + + + +
+ +

Trait Neg

+
pub trait Neg {
+    // Required methods
+    pub fn neg(self) -> Self;
+}
+ +

Required methods

+
pub fn neg(self) -> Self + +

Implementors

+

impl Neg for EmbeddedCurvePoint

+ +

impl Neg for Field

+ +

impl Neg for i16

+ +

impl Neg for i32

+ +

impl Neg for i64

+ +

impl Neg for i8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Not.html b/noir_stdlib/docs/std/ops/trait.Not.html new file mode 100644 index 00000000000..95da53b6722 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Not.html @@ -0,0 +1,86 @@ + + + + + +Trait Not documentation + + + +
+ +

Trait Not

+
pub trait Not {
+    // Required methods
+    pub fn not(self) -> Self;
+}
+ +

Required methods

+
pub fn not(self) -> Self + +

Implementors

+

impl Not for bool

+ +

impl Not for i16

+ +

impl Not for i32

+ +

impl Not for i64

+ +

impl Not for i8

+ +

impl Not for u1

+ +

impl Not for u128

+ +

impl Not for u16

+ +

impl Not for u32

+ +

impl Not for u64

+ +

impl Not for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Rem.html b/noir_stdlib/docs/std/ops/trait.Rem.html new file mode 100644 index 00000000000..55d880ce909 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Rem.html @@ -0,0 +1,83 @@ + + + + + +Trait Rem documentation + + + +
+ +

Trait Rem

+
pub trait Rem {
+    // Required methods
+    pub fn rem(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn rem(self, other: Self) -> Self + +

Implementors

+

impl Rem for i16

+ +

impl Rem for i32

+ +

impl Rem for i64

+ +

impl Rem for i8

+ +

impl Rem for u1

+ +

impl Rem for u128

+ +

impl Rem for u16

+ +

impl Rem for u32

+ +

impl Rem for u64

+ +

impl Rem for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Shl.html b/noir_stdlib/docs/std/ops/trait.Shl.html new file mode 100644 index 00000000000..92b52a78781 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Shl.html @@ -0,0 +1,83 @@ + + + + + +Trait Shl documentation + + + +
+ +

Trait Shl

+
pub trait Shl {
+    // Required methods
+    pub fn shl(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn shl(self, other: Self) -> Self + +

Implementors

+

impl Shl for i16

+ +

impl Shl for i32

+ +

impl Shl for i64

+ +

impl Shl for i8

+ +

impl Shl for u1

+ +

impl Shl for u128

+ +

impl Shl for u16

+ +

impl Shl for u32

+ +

impl Shl for u64

+ +

impl Shl for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Shr.html b/noir_stdlib/docs/std/ops/trait.Shr.html new file mode 100644 index 00000000000..8007170318a --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Shr.html @@ -0,0 +1,83 @@ + + + + + +Trait Shr documentation + + + +
+ +

Trait Shr

+
pub trait Shr {
+    // Required methods
+    pub fn shr(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn shr(self, other: Self) -> Self + +

Implementors

+

impl Shr for i16

+ +

impl Shr for i32

+ +

impl Shr for i64

+ +

impl Shr for i8

+ +

impl Shr for u1

+ +

impl Shr for u128

+ +

impl Shr for u16

+ +

impl Shr for u32

+ +

impl Shr for u64

+ +

impl Shr for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.Sub.html b/noir_stdlib/docs/std/ops/trait.Sub.html new file mode 100644 index 00000000000..b2f0f121c9e --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.Sub.html @@ -0,0 +1,89 @@ + + + + + +Trait Sub documentation + + + +
+ +

Trait Sub

+
pub trait Sub {
+    // Required methods
+    pub fn sub(self, other: Self) -> Self;
+}
+ +

Required methods

+
pub fn sub(self, other: Self) -> Self + +

Implementors

+

impl Sub for EmbeddedCurvePoint

+ +

impl Sub for Field

+ +

impl Sub for i16

+ +

impl Sub for i32

+ +

impl Sub for i64

+ +

impl Sub for i8

+ +

impl Sub for u1

+ +

impl Sub for u128

+ +

impl Sub for u16

+ +

impl Sub for u32

+ +

impl Sub for u64

+ +

impl Sub for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.WrappingAdd.html b/noir_stdlib/docs/std/ops/trait.WrappingAdd.html new file mode 100644 index 00000000000..7daf6d25825 --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.WrappingAdd.html @@ -0,0 +1,86 @@ + + + + + +Trait WrappingAdd documentation + + + +
+ +

Trait WrappingAdd

+
pub trait WrappingAdd {
+    // Required methods
+    pub fn wrapping_add(self, y: Self) -> Self;
+}
+ +

Required methods

+
pub fn wrapping_add(self, y: Self) -> Self + +

Implementors

+

impl WrappingAdd for Field

+ +

impl WrappingAdd for i16

+ +

impl WrappingAdd for i32

+ +

impl WrappingAdd for i64

+ +

impl WrappingAdd for i8

+ +

impl WrappingAdd for u1

+ +

impl WrappingAdd for u128

+ +

impl WrappingAdd for u16

+ +

impl WrappingAdd for u32

+ +

impl WrappingAdd for u64

+ +

impl WrappingAdd for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.WrappingMul.html b/noir_stdlib/docs/std/ops/trait.WrappingMul.html new file mode 100644 index 00000000000..6f0d333c80c --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.WrappingMul.html @@ -0,0 +1,86 @@ + + + + + +Trait WrappingMul documentation + + + +
+ +

Trait WrappingMul

+
pub trait WrappingMul {
+    // Required methods
+    pub fn wrapping_mul(self, y: Self) -> Self;
+}
+ +

Required methods

+
pub fn wrapping_mul(self, y: Self) -> Self + +

Implementors

+

impl WrappingMul for Field

+ +

impl WrappingMul for i16

+ +

impl WrappingMul for i32

+ +

impl WrappingMul for i64

+ +

impl WrappingMul for i8

+ +

impl WrappingMul for u1

+ +

impl WrappingMul for u128

+ +

impl WrappingMul for u16

+ +

impl WrappingMul for u32

+ +

impl WrappingMul for u64

+ +

impl WrappingMul for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/ops/trait.WrappingSub.html b/noir_stdlib/docs/std/ops/trait.WrappingSub.html new file mode 100644 index 00000000000..6b9dc8fe47e --- /dev/null +++ b/noir_stdlib/docs/std/ops/trait.WrappingSub.html @@ -0,0 +1,86 @@ + + + + + +Trait WrappingSub documentation + + + +
+ +

Trait WrappingSub

+
pub trait WrappingSub {
+    // Required methods
+    pub fn wrapping_sub(self, y: Self) -> Self;
+}
+ +

Required methods

+
pub fn wrapping_sub(self, y: Self) -> Self + +

Implementors

+

impl WrappingSub for Field

+ +

impl WrappingSub for i16

+ +

impl WrappingSub for i32

+ +

impl WrappingSub for i64

+ +

impl WrappingSub for i8

+ +

impl WrappingSub for u1

+ +

impl WrappingSub for u128

+ +

impl WrappingSub for u16

+ +

impl WrappingSub for u32

+ +

impl WrappingSub for u64

+ +

impl WrappingSub for u8

+ +
+ + diff --git a/noir_stdlib/docs/std/option/index.html b/noir_stdlib/docs/std/option/index.html new file mode 100644 index 00000000000..5d9bf588b2f --- /dev/null +++ b/noir_stdlib/docs/std/option/index.html @@ -0,0 +1,91 @@ + + + + + +Module option documentation + + + +
+
noir_stdlib - std::option
+

Module option

+

Structs

+
+ + diff --git a/noir_stdlib/docs/std/option/struct.Option.html b/noir_stdlib/docs/std/option/struct.Option.html new file mode 100644 index 00000000000..54cf9419ea3 --- /dev/null +++ b/noir_stdlib/docs/std/option/struct.Option.html @@ -0,0 +1,189 @@ + + + + + +Struct Option documentation + + + +
+ +

Struct Option

+
pub struct Option<T>
+{ /* private fields */ }
+
+

Implementations

+

impl<T> Option<T>

+ +
pub fn none() -> Self + +
+

Constructs a None value

+
+
pub fn some(_value: T) -> Self + +
+

Constructs a Some wrapper around the given value

+
+
pub fn is_none(self) -> bool + +
+

True if this Option is None

+
+
pub fn is_some(self) -> bool + +
+

True if this Option is Some

+
+
pub fn unwrap(self) -> T + +
+

Asserts self.is_some() and returns the wrapped value.

+
+
pub fn unwrap_unchecked(self) -> T + +
+

Returns the inner value without asserting self.is_some() +Note that if self is None, there is no guarantee what value will be returned, +only that it will be of type T.

+
+
pub fn unwrap_or(self, default: T) -> T + +
+

Returns the wrapped value if self.is_some(). Otherwise, returns the given default value.

+
+
pub fn unwrap_or_else<Env>(self, default: fn[Env]() -> T) -> T + +
+

Returns the wrapped value if self.is_some(). Otherwise, calls the given function to return +a default value.

+
+
pub fn expect<let N: u32, MessageTypes>( + self, + message: fmtstr<N, MessageTypes>, +) -> T + +
+

Asserts self.is_some() with a provided custom message and returns the contained Some value

+
+
pub fn map<U, Env>(self, f: fn[Env](T) -> U) -> Option<U> + +
+

If self is Some(x), this returns Some(f(x)). Otherwise, this returns None.

+
+
pub fn map_or<U, Env>(self, default: U, f: fn[Env](T) -> U) -> U + +
+

If self is Some(x), this returns f(x). Otherwise, this returns the given default value.

+
+
pub fn map_or_else<U, Env1, Env2>( + self, + default: fn[Env1]() -> U, + f: fn[Env2](T) -> U, +) -> U + +
+

If self is Some(x), this returns f(x). Otherwise, this returns default().

+
+
pub fn and(self, other: Self) -> Self + +
+

Returns None if self is None. Otherwise, this returns other.

+
+
pub fn and_then<U, Env>(self, f: fn[Env](T) -> Option<U>) -> Option<U> + +
+

If self is None, this returns None. Otherwise, this calls the given function +with the Some value contained within self, and returns the result of that call.

+

In some languages this function is called flat_map or bind.

+
+
pub fn or(self, other: Self) -> Self + +
+

If self is Some, return self. Otherwise, return other.

+
+
pub fn or_else<Env>(self, default: fn[Env]() -> Self) -> Self + +
+

If self is Some, return self. Otherwise, return default().

+
+
pub fn xor(self, other: Self) -> Self + +pub fn filter<Env>(self, predicate: fn[Env](T) -> bool) -> Self + +
+

Returns Some(x) if self is Some(x) and predicate(x) is true. +Otherwise, this returns None

+
+
pub fn flatten(option: Option<Self>) -> Self + +
+

Flattens an Option<Option<T>> into a Option<T>. +This returns None if the outer Option is None. Otherwise, this returns the inner Option.

+
+

Trait implementations

+

impl<T> Default for Option<T>

+ +
pub fn default() -> Self + +

impl<T> Eq for Option<T> +
where + T: Eq

+ +
pub fn eq(self, other: Self) -> bool + +

impl<T> Hash for Option<T> +
where + T: Hash

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl<T> Ord for Option<T> +
where + T: Ord

+ +
pub fn cmp(self, other: Self) -> Ordering + +
+ + diff --git a/noir_stdlib/docs/std/panic/fn.panic.html b/noir_stdlib/docs/std/panic/fn.panic.html new file mode 100644 index 00000000000..3687d5884f3 --- /dev/null +++ b/noir_stdlib/docs/std/panic/fn.panic.html @@ -0,0 +1,24 @@ + + + + + +Function panic documentation + + + +
+ +

Function panic

+
pub fn panic<T, U, let N: u32>(message: fmtstr<N, T>) -> U
+ +
+ + diff --git a/noir_stdlib/docs/std/panic/index.html b/noir_stdlib/docs/std/panic/index.html new file mode 100644 index 00000000000..254fcca1332 --- /dev/null +++ b/noir_stdlib/docs/std/panic/index.html @@ -0,0 +1,91 @@ + + + + + +Module panic documentation + + + +
+
noir_stdlib - std::panic
+

Module panic

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/prelude/index.html b/noir_stdlib/docs/std/prelude/index.html new file mode 100644 index 00000000000..5e4388b2c05 --- /dev/null +++ b/noir_stdlib/docs/std/prelude/index.html @@ -0,0 +1,104 @@ + + + + + +Module prelude documentation + + + +
+
noir_stdlib - std::prelude
+

Module prelude

+

Re-exports

+
+ + diff --git a/noir_stdlib/docs/std/primitive.CtString.html b/noir_stdlib/docs/std/primitive.CtString.html new file mode 100644 index 00000000000..0069b72e8a8 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.CtString.html @@ -0,0 +1,130 @@ + + + + + +Primitive type CtString documentation + + + +
+ +

Primitive type CtString

+

Implementations

+

impl CtString

+ +
pub comptime fn new() -> Self + +pub comptime fn append_str<let N: u32>(self, s: str<N>) -> Self + +pub comptime fn append_fmtstr<let N: u32, T>(self, s: fmtstr<N, T>) -> Self + +pub comptime fn as_quoted_str(self) -> Quoted + +
+

CtString cannot directly return a str since the size would not be known. +To get around this, we return a quoted str and the underlying str can +be accessed using macro insertion foo.as_quoted_str!().

+
+

Trait implementations

+

impl Append for CtString

+ +
pub fn empty() -> Self + +pub fn append(self, other: Self) -> Self + +

impl Eq for CtString

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for CtString

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.Expr.html b/noir_stdlib/docs/std/primitive.Expr.html new file mode 100644 index 00000000000..8ebdcef3f81 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.Expr.html @@ -0,0 +1,331 @@ + + + + + +Primitive type Expr documentation + + + +
+ +

Primitive type Expr

+

Implementations

+

impl Expr

+ +
pub comptime fn as_array(self) -> Option<[Self]> + +
+

If this expression is an array literal [elem1, ..., elemN], this returns a slice of each element in the array.

+
+
pub comptime fn as_assert(self) -> Option<(Self, Option<Self>)> + +
+

If this expression is an assert, this returns the assert expression and the optional message.

+
+
pub comptime fn as_assert_eq(self) -> Option<(Self, Self, Option<Self>)> + +
+

If this expression is an assert_eq, this returns the left-hand-side and right-hand-side +expressions, together with the optional message.

+
+
pub comptime fn as_assign(self) -> Option<(Self, Self)> + +
+

If this expression is an assignment, this returns a tuple with the left hand side +and right hand side in order.

+
+
pub comptime fn as_binary_op(self) -> Option<(Self, BinaryOp, Self)> + +
+

If this expression is a binary operator operation <lhs> <op> <rhs>, +return the left-hand side, operator, and the right-hand side of the operation.

+
+
pub comptime fn as_block(self) -> Option<[Self]> + +
+

If this expression is a block { stmt1; stmt2; ...; stmtN }, return +a slice containing each statement.

+
+
pub comptime fn as_bool(self) -> Option<bool> + +
+

If this expression is a boolean literal, return that literal.

+
+
pub comptime fn as_cast(self) -> Option<(Self, UnresolvedType)> + +
+

If this expression is a cast expression expr as type, returns the casted +expression and the type to cast to.

+
+
pub comptime fn as_comptime(self) -> Option<[Self]> + +
+

If this expression is a comptime { stmt1; stmt2; ...; stmtN } block, +return each statement in the block.

+
+
pub comptime fn as_constructor(self) -> Option<(UnresolvedType, [(Quoted, Self)])> + +
+

If this expression is a constructor Type { field1: expr1, ..., fieldN: exprN }, +return the type and the fields.

+
+
pub comptime fn as_for(self) -> Option<(Quoted, Self, Self)> + +
+

If this expression is a for statement over a single expression, return the identifier, +the expression and the for loop body.

+
+
pub comptime fn as_for_range(self) -> Option<(Quoted, Self, Self, Self)> + +
+

If this expression is a for statement over a range, return the identifier, +the range start, the range end and the for loop body.

+
+
pub comptime fn as_function_call(self) -> Option<(Self, [Self])> + +
+

If this expression is a function call foo(arg1, ..., argN), return +the function and a slice of each argument.

+
+
pub comptime fn as_if(self) -> Option<(Self, Self, Option<Self>)> + +
+

If this expression is an if condition { then_branch } else { else_branch }, +return the condition, then branch, and else branch. If there is no else branch, +None is returned for that branch instead.

+
+
pub comptime fn as_index(self) -> Option<(Self, Self)> + +
+

If this expression is an index into an array array[index], return the +array and the index.

+
+
pub comptime fn as_integer(self) -> Option<(Field, bool)> + +
+

If this expression is an integer literal, return the integer as a field +as well as whether the integer is negative (true) or not (false).

+
+
pub comptime fn as_lambda( + self, +) -> Option<([(Self, Option<UnresolvedType>)], Option<UnresolvedType>, Self)> + +
+

If this expression is a lambda, returns the parameters, return type and body.

+
+
pub comptime fn as_let(self) -> Option<(Self, Option<UnresolvedType>, Self)> + +
+

If this expression is a let statement, returns the let pattern as an Expr, +the optional type annotation, and the assigned expression.

+
+
pub comptime fn as_member_access(self) -> Option<(Self, Quoted)> + +
+

If this expression is a member access foo.bar, return the struct/tuple +expression and the field. The field will be represented as a quoted value.

+
+
pub comptime fn as_method_call(self) -> Option<(Self, Quoted, [UnresolvedType], [Self])> + +
+

If this expression is a method call foo.bar::<generic1, ..., genericM>(arg1, ..., argN), return +the receiver, method name, a slice of each generic argument, and a slice of each argument.

+
+
pub comptime fn as_repeated_element_array(self) -> Option<(Self, Self)> + +
+

If this expression is a repeated element array [elem; length], return +the repeated element and the length expressions.

+
+
pub comptime fn as_repeated_element_slice(self) -> Option<(Self, Self)> + +
+

If this expression is a repeated element slice [elem; length], return +the repeated element and the length expressions.

+
+
pub comptime fn as_slice(self) -> Option<[Self]> + +
+

If this expression is a slice literal &[elem1, ..., elemN], +return each element of the slice.

+
+
pub comptime fn as_tuple(self) -> Option<[Self]> + +
+

If this expression is a tuple (field1, ..., fieldN), +return each element of the tuple.

+
+
pub comptime fn as_unary_op(self) -> Option<(UnaryOp, Self)> + +
+

If this expression is a unary operation <op> <rhs>, +return the unary operator as well as the right-hand side expression.

+
+
pub comptime fn as_unsafe(self) -> Option<[Self]> + +
+

If this expression is an unsafe { stmt1; ...; stmtN } block, +return each statement inside in a slice.

+
+
pub comptime fn has_semicolon(self) -> bool + +
+

Returns true if this expression is trailed by a semicolon.

+

Example:

+
comptime {
+    let expr1 = quote { 1 + 2 }.as_expr().unwrap();
+    let expr2 = quote { 1 + 2; }.as_expr().unwrap();
+
+    assert(expr1.as_binary_op().is_some());
+    assert(expr2.as_binary_op().is_some());
+
+    assert(!expr1.has_semicolon());
+    assert(expr2.has_semicolon());
+}
+
+
+
pub comptime fn is_break(self) -> bool + +
+

Returns true if this expression is break.

+
+
pub comptime fn is_continue(self) -> bool + +
+

Returns true if this expression is continue.

+
+
pub comptime fn modify<Env>(self, f: fn[Env](Self) -> Option<Self>) -> Self + +
+

Applies a mapping function to this expression and to all of its sub-expressions. +f will be applied to each sub-expression first, then applied to the expression itself.

+

This happens recursively for every expression within self.

+

For example, calling modify on (&[1], &[2, 3]) with an f that returns Option::some +for expressions that are integers, doubling them, would return (&[2], &[4, 6]).

+
+
pub comptime fn quoted(self) -> Quoted + +
+

Returns this expression as a Quoted value. It's the same as quote { $self }.

+
+
pub comptime fn resolve(self, in_function: Option<FunctionDefinition>) -> TypedExpr + +
+

Resolves and type-checks this expression and returns the result as a TypedExpr.

+

The in_function argument specifies where the expression is resolved:

+
    +
  • If it's none, the expression is resolved in the function where resolve was called
  • +
  • If it's some, the expression is resolved in the given function
  • +
+

If any names used by this expression are not in scope or if there are any type errors, +this will give compiler errors as if the expression was written directly into +the current comptime function.

+
+
+ + diff --git a/noir_stdlib/docs/std/primitive.Field.html b/noir_stdlib/docs/std/primitive.Field.html new file mode 100644 index 00000000000..6480652c49a --- /dev/null +++ b/noir_stdlib/docs/std/primitive.Field.html @@ -0,0 +1,290 @@ + + + + + +Primitive type Field documentation + + + +
+ +

Primitive type Field

+

Implementations

+

impl Field

+ +
pub fn assert_max_bit_size<let BIT_SIZE: u32>(self) + +
+

Asserts that self can be represented in bit_size bits.

+

Failures

+

Causes a constraint failure for Field values exceeding 2^{bit_size}.

+
+
pub fn to_le_bits<let N: u32>(self) -> [u1; N] + +
+

Decomposes self into its little endian bit decomposition as a [u1; N] array. +This slice will be zero padded should not all bits be necessary to represent self.

+

Failures

+

Causes a constraint failure for Field values exceeding 2^N as the resulting slice will not +be able to represent the original Field.

+

Safety

+

The bit decomposition returned is canonical and is guaranteed to not overflow the modulus.

+
+
pub fn to_be_bits<let N: u32>(self) -> [u1; N] + +
+

Decomposes self into its big endian bit decomposition as a [u1; N] array. +This array will be zero padded should not all bits be necessary to represent self.

+

Failures

+

Causes a constraint failure for Field values exceeding 2^N as the resulting slice will not +be able to represent the original Field.

+

Safety

+

The bit decomposition returned is canonical and is guaranteed to not overflow the modulus.

+
+
pub fn to_le_bytes<let N: u32>(self) -> [u8; N] + +
+

Decomposes self into its little endian byte decomposition as a [u8;N] array +This array will be zero padded should not all bytes be necessary to represent self.

+

Failures

+

The length N of the array must be big enough to contain all the bytes of the 'self', +and no more than the number of bytes required to represent the field modulus

+

Safety

+

The result is ensured to be the canonical decomposition of the field element

+
+
pub fn to_be_bytes<let N: u32>(self) -> [u8; N] + +
+

Decomposes self into its big endian byte decomposition as a [u8;N] array of length required to represent the field modulus +This array will be zero padded should not all bytes be necessary to represent self.

+

Failures

+

The length N of the array must be big enough to contain all the bytes of the 'self', +and no more than the number of bytes required to represent the field modulus

+

Safety

+

The result is ensured to be the canonical decomposition of the field element

+
+
pub fn pow_32(self, exponent: Self) -> Self + +pub fn sgn0(self) -> u1 + +pub fn lt(self, another: Self) -> bool + +pub fn from_le_bytes<let N: u32>(bytes: [u8; N]) -> Self + +
+

Convert a little endian byte array to a field element. +If the provided byte array overflows the field modulus then the Field will silently wrap around.

+
+
pub fn from_be_bytes<let N: u32>(bytes: [u8; N]) -> Self + +
+

Convert a big endian byte array to a field element. +If the provided byte array overflows the field modulus then the Field will silently wrap around.

+
+

Trait implementations

+

impl Add for Field

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<bool> for Field

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<u128> for Field

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for Field

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for Field

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for Field

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for Field

+ +
pub fn as_(self) -> u8 + +

impl Default for Field

+ +
pub fn default() -> Self + +

impl Div for Field

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for Field

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for Field

+ +
pub fn from(value: bool) -> Self + +

impl From<u128> for Field

+ +
pub fn from(value: u128) -> Self + +

impl From<u16> for Field

+ +
pub fn from(value: u16) -> Self + +

impl From<u32> for Field

+ +
pub fn from(value: u32) -> Self + +

impl From<u64> for Field

+ +
pub fn from(value: u64) -> Self + +

impl From<u8> for Field

+ +
pub fn from(value: u8) -> Self + +

impl Hash for Field

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for Field

+ +
pub fn mul(self, other: Self) -> Self + +

impl Neg for Field

+ +
pub fn neg(self) -> Self + +

impl Sub for Field

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for Field

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for Field

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for Field

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.FunctionDefinition.html b/noir_stdlib/docs/std/primitive.FunctionDefinition.html new file mode 100644 index 00000000000..d6acf837f62 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.FunctionDefinition.html @@ -0,0 +1,151 @@ + + + + + +Primitive type FunctionDefinition documentation + + + +
+ +

Primitive type FunctionDefinition

+

Implementations

+

impl FunctionDefinition

+ +
pub comptime fn add_attribute<let N: u32>(self, attribute: str<N>) + +pub comptime fn as_typed_expr(self) -> TypedExpr + +pub comptime fn body(self) -> Expr + +pub comptime fn has_named_attribute<let N: u32>(self, name: str<N>) -> bool + +pub comptime fn is_unconstrained(self) -> bool + +pub comptime fn module(self) -> Module + +pub comptime fn name(self) -> Quoted + +pub comptime fn parameters(self) -> [(Quoted, Type)] + +pub comptime fn return_type(self) -> Type + +pub comptime fn set_body(self, body: Expr) + +pub comptime fn set_parameters(self, parameters: [(Quoted, Type)]) + +pub comptime fn set_return_type(self, return_type: Type) + +pub comptime fn set_return_public(self, public: bool) + +pub comptime fn set_unconstrained(self, value: bool) + +pub comptime fn visibility(self) -> Quoted + +

Trait implementations

+

impl Eq for FunctionDefinition

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for FunctionDefinition

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.Module.html b/noir_stdlib/docs/std/primitive.Module.html new file mode 100644 index 00000000000..1c3cfc33867 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.Module.html @@ -0,0 +1,130 @@ + + + + + +Primitive type Module documentation + + + +
+ +

Primitive type Module

+

Implementations

+

impl Module

+ +
pub comptime fn add_item(self, item: Quoted) + +pub comptime fn has_named_attribute<let N: u32>(self, name: str<N>) -> bool + +pub comptime fn is_contract(self) -> bool + +pub comptime fn functions(self) -> [FunctionDefinition] + +pub comptime fn structs(self) -> [TypeDefinition] + +pub comptime fn child_modules(self) -> [Self] + +pub comptime fn name(self) -> Quoted + +pub comptime fn parent(self) -> Option<Self> + +

Trait implementations

+

impl Eq for Module

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for Module

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.Quoted.html b/noir_stdlib/docs/std/primitive.Quoted.html new file mode 100644 index 00000000000..28aea51f19a --- /dev/null +++ b/noir_stdlib/docs/std/primitive.Quoted.html @@ -0,0 +1,128 @@ + + + + + +Primitive type Quoted documentation + + + +
+ +

Primitive type Quoted

+

Implementations

+

impl Quoted

+ +
pub comptime fn as_expr(self) -> Option<Expr> + +pub comptime fn as_module(self) -> Option<Module> + +pub comptime fn as_trait_constraint(self) -> TraitConstraint + +pub comptime fn as_type(self) -> Type + +pub comptime fn tokens(self) -> [Self] + +

Trait implementations

+

impl Append for Quoted

+ +
pub comptime fn empty() -> Self + +pub comptime fn append(self, other: Self) -> Self + +

impl Eq for Quoted

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for Quoted

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.TraitConstraint.html b/noir_stdlib/docs/std/primitive.TraitConstraint.html new file mode 100644 index 00000000000..359b5d810ef --- /dev/null +++ b/noir_stdlib/docs/std/primitive.TraitConstraint.html @@ -0,0 +1,100 @@ + + + + + +Primitive type TraitConstraint documentation + + + +
+ +

Primitive type TraitConstraint

+

Trait implementations

+

impl Eq for TraitConstraint

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for TraitConstraint

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.TraitDefinition.html b/noir_stdlib/docs/std/primitive.TraitDefinition.html new file mode 100644 index 00000000000..c36d2a0ef6e --- /dev/null +++ b/noir_stdlib/docs/std/primitive.TraitDefinition.html @@ -0,0 +1,109 @@ + + + + + +Primitive type TraitDefinition documentation + + + +
+ +

Primitive type TraitDefinition

+

Implementations

+

impl TraitDefinition

+ +
pub comptime fn as_trait_constraint(_self: Self) -> TraitConstraint + +

Trait implementations

+

impl Eq for TraitDefinition

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for TraitDefinition

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.TraitImpl.html b/noir_stdlib/docs/std/primitive.TraitImpl.html new file mode 100644 index 00000000000..6110e6b185e --- /dev/null +++ b/noir_stdlib/docs/std/primitive.TraitImpl.html @@ -0,0 +1,96 @@ + + + + + +Primitive type TraitImpl documentation + + + +
+ +

Primitive type TraitImpl

+

Implementations

+

impl TraitImpl

+ +
pub comptime fn trait_generic_args(self) -> [Type] + +pub comptime fn methods(self) -> [FunctionDefinition] + +
+ + diff --git a/noir_stdlib/docs/std/primitive.Type.html b/noir_stdlib/docs/std/primitive.Type.html new file mode 100644 index 00000000000..c866884fa38 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.Type.html @@ -0,0 +1,231 @@ + + + + + +Primitive type Type documentation + + + +
+ +

Primitive type Type

+

Implementations

+

impl Type

+ +
pub comptime fn as_array(self) -> Option<(Self, Self)> + +
+

If this type is an array, return a pair of (element type, size type).

+

Example:

+
comptime {
+    let array_type = quote { [Field; 3] }.as_type();
+    let (field_type, three_type) = array_type.as_array().unwrap();
+
+    assert(field_type.is_field());
+    assert_eq(three_type.as_constant().unwrap(), 3);
+}
+
+
+
pub comptime fn as_constant(self) -> Option<u32> + +
+

If this type is a constant integer (such as the 3 in the array type [Field; 3]), +return the numeric constant.

+
+
pub comptime fn as_integer(self) -> Option<(bool, u8)> + +
+

If this is an integer type, return a boolean which is true +if the type is signed, as well as the number of bits of this integer type.

+
+
pub comptime fn as_mutable_reference(self) -> Option<Self> + +
+

If this is a mutable reference type &mut T, returns the mutable type T.

+
+
pub comptime fn as_slice(self) -> Option<Self> + +
+

If this is a slice type, return the element type of the slice.

+
+
pub comptime fn as_str(self) -> Option<Self> + +
+

If this is a str<N> type, returns the length N as a type.

+
+
pub comptime fn as_struct(self) -> Option<(TypeDefinition, [Self])> + +pub comptime fn as_data_type(self) -> Option<(TypeDefinition, [Self])> + +
+

If this is a struct or enum type, returns the type in addition to any generic arguments on this type.

+
+
pub comptime fn as_tuple(self) -> Option<[Self]> + +
+

If this is a tuple type, returns each element type of the tuple.

+
+
pub comptime fn get_trait_impl(self, constraint: TraitConstraint) -> Option<TraitImpl> + +
+

Retrieves the trait implementation that implements the given +trait constraint for this type. If the trait constraint is not +found, None is returned. Note that since the concrete trait implementation +for a trait constraint specified from a where clause is unknown, +this function will return None in these cases. If you only want to know +whether a type implements a trait, use implements instead.

+

Example:

+
comptime {
+    let field_type = quote { Field }.as_type();
+    let default = quote { Default }.as_trait_constraint();
+
+    let the_impl: TraitImpl = field_type.get_trait_impl(default).unwrap();
+    assert(the_impl.methods().len(), 1);
+}
+
+
+
pub comptime fn implements(self, constraint: TraitConstraint) -> bool + +
+

Returns true if this type implements the given trait. Note that unlike +get_trait_impl this will also return true for any where constraints +in scope.

+

Example:

+
fn foo<T>() where T: Default {
+    comptime {
+        let field_type = quote { Field }.as_type();
+        let default = quote { Default }.as_trait_constraint();
+        assert(field_type.implements(default));
+
+        let t = quote { T }.as_type();
+        assert(t.implements(default));
+    }
+}
+
+
+
pub comptime fn is_bool(self) -> bool + +
+

Returns true if this type is bool.

+
+
pub comptime fn is_field(self) -> bool + +
+

Returns true if this type is Field.

+
+
pub comptime fn is_unit(self) -> bool + +
+

Returns true if this type is the unit () type.

+
+

Trait implementations

+

impl Eq for Type

+ +
pub comptime fn eq(self, other: Self) -> bool + +
+

Note that this is syntactic equality, this is not the same as whether two types will type check +to be the same type. Unless type inference or generics are being used however, users should not +typically have to worry about this distinction.

+
+

impl Hash for Type

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.TypeDefinition.html b/noir_stdlib/docs/std/primitive.TypeDefinition.html new file mode 100644 index 00000000000..5fc81dacdd2 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.TypeDefinition.html @@ -0,0 +1,171 @@ + + + + + +Primitive type TypeDefinition documentation + + + +
+ +

Primitive type TypeDefinition

+

Implementations

+

impl TypeDefinition

+ +
pub comptime fn add_attribute<let N: u32>(self, attribute: str<N>) + +pub comptime fn add_generic<let N: u32>(self, generic_name: str<N>) -> Type + +pub comptime fn as_type(self) -> Type + +
+

Return a syntactic version of this type definition as a type. +For example, type Foo<A, B> { ... }) would return Foo<A, B> when called with this method.

+
+
pub comptime fn as_type_with_generics(self, generics: [Type]) -> Option<Type> + +
+

Return this type applied to the given generic arguments. +For example, given type Foo<A, B> { ... }) could be applied to &[quote[i32].as_type(), quote[Field].as_type()] +to return Foo<i32, Field>.

+

If an incorrect number of generic arguments are given, this function will return None. +Otherwise, this function returns Some with the resulting type inside.

+
+
pub comptime fn has_named_attribute<let N: u32>(self, name: str<N>) -> bool + +pub comptime fn generics(self) -> [(Type, Option<Type>)] + +
+

Return (type, option<type>) pairs of each generic in this type definition. +If a generic is numeric, the second element of the pair will contain the numeric type.

+
+
pub comptime fn fields(self, generic_args: [Type]) -> [(Quoted, Type, Quoted)] + +
+

Returns (name, type, visibility) tuples of each field in this type. +Any generic types used in each field type is automatically substituted with the +provided generic arguments.

+
+
pub comptime fn fields_as_written(self) -> [(Quoted, Type, Quoted)] + +
+

Returns (name, type, visibility) tuples of each field in this type. Each type is as-is +with any generic arguments unchanged. Unless the field types are not needed, +users should generally prefer to use TypeDefinition::fields over this +function if possible.

+
+
pub comptime fn module(self) -> Module + +pub comptime fn name(self) -> Quoted + +pub comptime fn set_fields(self, new_fields: [(Quoted, Type, Quoted)]) + +
+

Sets the fields of this type to the given fields list. +All existing fields of the type will be overridden with the given fields. +Each element of the fields list corresponds to the name and type of a field. +Each name is expected to be a single identifier.

+
+

Trait implementations

+

impl Eq for TypeDefinition

+ +
pub comptime fn eq(self, other: Self) -> bool + +

impl Hash for TypeDefinition

+ +
pub comptime fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +
+ + diff --git a/noir_stdlib/docs/std/primitive.TypedExpr.html b/noir_stdlib/docs/std/primitive.TypedExpr.html new file mode 100644 index 00000000000..19eaae6b9c3 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.TypedExpr.html @@ -0,0 +1,102 @@ + + + + + +Primitive type TypedExpr documentation + + + +
+ +

Primitive type TypedExpr

+

Implementations

+

impl TypedExpr

+ +
pub comptime fn as_function_definition(self) -> Option<FunctionDefinition> + +
+

If this expression refers to a function definitions, returns it. Otherwise returns Option::none().

+
+
pub comptime fn get_type(self) -> Option<Type> + +
+

Returns the type of the expression, if the expression could be resolved without errors.

+
+
+ + diff --git a/noir_stdlib/docs/std/primitive.UnresolvedType.html b/noir_stdlib/docs/std/primitive.UnresolvedType.html new file mode 100644 index 00000000000..373f1a72eba --- /dev/null +++ b/noir_stdlib/docs/std/primitive.UnresolvedType.html @@ -0,0 +1,120 @@ + + + + + +Primitive type UnresolvedType documentation + + + +
+ +

Primitive type UnresolvedType

+

Implementations

+

impl UnresolvedType

+ +
pub comptime fn as_mutable_reference(self) -> Option<Self> + +
+

If this is a mutable reference type &mut T, returns the mutable type T.

+
+
pub comptime fn as_slice(self) -> Option<Self> + +
+

If this is a slice &[T], returns the element type T.

+
+
pub comptime fn is_bool(self) -> bool + +
+

Returns true if this type is bool.

+
+
pub comptime fn is_field(self) -> bool + +
+

Returns true if this type refers to the Field type.

+
+
pub comptime fn is_unit(self) -> bool + +
+

Returns true if this type is the unit () type.

+
+
+ + diff --git a/noir_stdlib/docs/std/primitive.array.html b/noir_stdlib/docs/std/primitive.array.html new file mode 100644 index 00000000000..db5e218c5a6 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.array.html @@ -0,0 +1,300 @@ + + + + + +Primitive type array documentation + + + +
+ +

Primitive type array

+

Implementations

+

impl<let N: u32, T> [T; N]

+ +
pub fn sort_via<Env>(self, ordering: fn[Env](T, T) -> bool) -> Self +
where + T: Eq
+ +
+

Returns a new sorted array by sorting it with a custom comparison function. +The original array remains untouched. +The ordering function must return true if the first argument should be sorted to be before the second argument or is equal to the second argument.

+

Using this method with an operator like < that does not return true for equal values will result in an assertion failure for arrays with equal elements.

+

Example:

+
fn main() {
+    let arr = [42, 32]
+    let sorted_ascending = arr.sort_via(|a, b| a <= b);
+    assert(sorted_ascending == [32, 42]); // verifies
+
+    let sorted_descending = arr.sort_via(|a, b| a >= b);
+    assert(sorted_descending == [32, 42]); // does not verify
+}
+
+
+

impl<let N: u32, T> [T; N]

+ +
pub fn len(self) -> u32 + +
+

Returns the length of this array.

+
fn len(self) -> Field
+
+

example

+
fn main() {
+    let array = [42, 42];
+    assert(array.len() == 2);
+}
+
+
+
pub fn as_slice(self) -> [T] + +
+

Returns this array as a slice.

+
let array = [1, 2];
+let slice = array.as_slice();
+assert_eq(slice, &[1, 2]);
+
+
+
pub fn map<U, Env>(self, f: fn[Env](T) -> U) -> [U; N] + +
+

Applies a function to each element of this array, returning a new array containing the mapped elements.

+

Example:

+
let a = [1, 2, 3];
+let b = a.map(|a| a * 2);
+assert_eq(b, [2, 4, 6]);
+
+
+
pub fn mapi<U, Env>(self, f: fn[Env](u32, T) -> U) -> [U; N] + +
+

Applies a function to each element of this array along with its index, +returning a new array containing the mapped elements.

+

Example:

+
let a = [1, 2, 3];
+let b = a.mapi(|i, a| i + a * 2);
+assert_eq(b, [2, 5, 8]);
+
+
+
pub fn for_each<Env>(self, f: fn[Env](T)) + +
+

Applies a function to each element of this array.

+

Example:

+
let a = [1, 2, 3];
+let mut b = [0; 3];
+let mut i = 0;
+a.for_each(|x| {
+    b[i] = x;
+    i += 1;
+});
+assert_eq(a, b);
+
+
+
pub fn for_eachi<Env>(self, f: fn[Env](u32, T)) + +
+

Applies a function to each element of this array along with its index.

+

Example:

+
let a = [1, 2, 3];
+let mut b = [0; 3];
+a.for_eachi(|i, x| {
+    b[i] = x;
+});
+assert_eq(a, b);
+
+
+
pub fn fold<U, Env>(self, accumulator: U, f: fn[Env](U, T) -> U) -> U + +
+

Applies a function to each element of the array, returning the final accumulated value. The first +parameter is the initial value.

+

This is a left fold, so the given function will be applied to the accumulator and first element of +the array, then the second, and so on. For a given call the expected result would be equivalent to:

+
let a1 = [1];
+let a2 = [1, 2];
+let a3 = [1, 2, 3];
+
+let f = |a, b| a - b;
+a1.fold(10, f); //=> f(10, 1)
+a2.fold(10, f); //=> f(f(10, 1), 2)
+a3.fold(10, f); //=> f(f(f(10, 1), 2), 3)
+
+assert_eq(a3.fold(10, f), 10 - 1 - 2 - 3);
+
+
+
pub fn reduce<Env>(self, f: fn[Env](T, T) -> T) -> T + +
+

Same as fold, but uses the first element as the starting element.

+

Requires the input array to be non-empty.

+

Example:

+
fn main() {
+    let arr = [1, 2, 3, 4];
+    let reduced = arr.reduce(|a, b| a + b);
+    assert(reduced == 10);
+}
+
+
+
pub fn all<Env>(self, predicate: fn[Env](T) -> bool) -> bool + +
+

Returns true if all the elements in this array satisfy the given predicate.

+

Example:

+
fn main() {
+    let arr = [2, 2, 2, 2, 2];
+    let all = arr.all(|a| a == 2);
+    assert(all);
+}
+
+
+
pub fn any<Env>(self, predicate: fn[Env](T) -> bool) -> bool + +
+

Returns true if any of the elements in this array satisfy the given predicate.

+

Example:

+
fn main() {
+    let arr = [2, 2, 2, 2, 5];
+    let any = arr.any(|a| a == 5);
+    assert(any);
+}
+
+
+
pub fn concat<let M: u32>(self, array2: [T; M]) -> [T; N + M] + +
+

Concatenates this array with another array.

+

Example:

+
fn main() {
+    let arr1 = [1, 2, 3, 4];
+    let arr2 = [6, 7, 8, 9, 10, 11];
+    let concatenated_arr = arr1.concat(arr2);
+    assert(concatenated_arr == [1, 2, 3, 4, 6, 7, 8, 9, 10, 11]);
+}
+
+
+

impl<let N: u32> [u8; N]

+ +
pub fn as_str_unchecked(self) -> str<N> + +
+

Converts a byte array of type [u8; N] to a string. Note that this performs no UTF-8 validation - +the given array is interpreted as-is as a string.

+

Example:

+
fn main() {
+    let hi = [104, 105].as_str_unchecked();
+    assert_eq(hi, "hi");
+}
+
+
+

impl<let N: u32, T> [T; N]

+ +
pub fn sort(self) -> Self +
where + T: Ord, + T: Eq
+ +
+

Returns a new sorted array. The original array remains untouched. Notice that this function will +only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting +logic it uses internally is optimized specifically for these values. If you need a sort function to +sort any type, you should use the sort_via function.

+

Example:

+
fn main() {
+    let arr = [42, 32];
+    let sorted = arr.sort();
+    assert(sorted == [32, 42]);
+}
+
+
+
+ + diff --git a/noir_stdlib/docs/std/primitive.bool.html b/noir_stdlib/docs/std/primitive.bool.html new file mode 100644 index 00000000000..1b20d4ee9f0 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.bool.html @@ -0,0 +1,185 @@ + + + + + +Primitive type bool documentation + + + +
+ +

Primitive type bool

+

Trait implementations

+

impl AsPrimitive<Field> for bool

+ +
pub fn as_(self) -> Field + +

impl AsPrimitive<bool> for bool

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<i16> for bool

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for bool

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for bool

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for bool

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for bool

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for bool

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for bool

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for bool

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for bool

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for bool

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for bool

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for bool

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for bool

+ +
pub fn default() -> Self + +

impl Eq for bool

+ +
pub fn eq(self, other: Self) -> Self + +

impl Hash for bool

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Not for bool

+ +
pub fn not(self) -> Self + +

impl Ord for bool

+ +
pub fn cmp(self, other: Self) -> Ordering + +
+ + diff --git a/noir_stdlib/docs/std/primitive.fmtstr.html b/noir_stdlib/docs/std/primitive.fmtstr.html new file mode 100644 index 00000000000..daf956680b5 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.fmtstr.html @@ -0,0 +1,102 @@ + + + + + +Primitive type fmtstr documentation + + + +
+ +

Primitive type fmtstr

+

Implementations

+

impl<let N: u32, T> fmtstr<N, T>

+ +
pub comptime fn quoted_contents(self) -> Quoted + +
+

Returns the format string contents (that is, without the leading and trailing double quotes) as a Quoted value.

+
+
pub comptime fn as_quoted_str(self) -> Quoted + +
+

Returns the format string contents (with the leading and trailing double quotes) as a Quoted string literal (not a format string literal).

+
+
+ + diff --git a/noir_stdlib/docs/std/primitive.i16.html b/noir_stdlib/docs/std/primitive.i16.html new file mode 100644 index 00000000000..93275f32431 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.i16.html @@ -0,0 +1,245 @@ + + + + + +Primitive type i16 documentation + + + +
+ +

Primitive type i16

+

Trait implementations

+

impl Add for i16

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<bool> for i16

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for i16

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<i32> for i16

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for i16

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for i16

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for i16

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for i16

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for i16

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for i16

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for i16

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for i16

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for i16

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for i16

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for i16

+ +
pub fn default() -> Self + +

impl Div for i16

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for i16

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for i16

+ +
pub fn from(value: bool) -> Self + +

impl From<i8> for i16

+ +
pub fn from(value: i8) -> Self + +

impl Hash for i16

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for i16

+ +
pub fn mul(self, other: Self) -> Self + +

impl Neg for i16

+ +
pub fn neg(self) -> Self + +

impl Not for i16

+ +
pub fn not(self) -> Self + +

impl Ord for i16

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for i16

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for i16

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for i16

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for i16

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for i16

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for i16

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for i16

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.i32.html b/noir_stdlib/docs/std/primitive.i32.html new file mode 100644 index 00000000000..0f2e5b2c927 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.i32.html @@ -0,0 +1,250 @@ + + + + + +Primitive type i32 documentation + + + +
+ +

Primitive type i32

+

Trait implementations

+

impl Add for i32

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<bool> for i32

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for i32

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for i32

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<i64> for i32

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for i32

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for i32

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for i32

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for i32

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for i32

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for i32

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for i32

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for i32

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for i32

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for i32

+ +
pub fn default() -> Self + +

impl Div for i32

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for i32

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for i32

+ +
pub fn from(value: bool) -> Self + +

impl From<i16> for i32

+ +
pub fn from(value: i16) -> Self + +

impl From<i8> for i32

+ +
pub fn from(value: i8) -> Self + +

impl Hash for i32

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for i32

+ +
pub fn mul(self, other: Self) -> Self + +

impl Neg for i32

+ +
pub fn neg(self) -> Self + +

impl Not for i32

+ +
pub fn not(self) -> Self + +

impl Ord for i32

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for i32

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for i32

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for i32

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for i32

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for i32

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for i32

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for i32

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.i64.html b/noir_stdlib/docs/std/primitive.i64.html new file mode 100644 index 00000000000..e73f2cbde42 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.i64.html @@ -0,0 +1,255 @@ + + + + + +Primitive type i64 documentation + + + +
+ +

Primitive type i64

+

Trait implementations

+

impl Add for i64

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<bool> for i64

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for i64

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for i64

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for i64

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<i8> for i64

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for i64

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for i64

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for i64

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for i64

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for i64

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for i64

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for i64

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for i64

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for i64

+ +
pub fn default() -> Self + +

impl Div for i64

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for i64

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for i64

+ +
pub fn from(value: bool) -> Self + +

impl From<i16> for i64

+ +
pub fn from(value: i16) -> Self + +

impl From<i32> for i64

+ +
pub fn from(value: i32) -> Self + +

impl From<i8> for i64

+ +
pub fn from(value: i8) -> Self + +

impl Hash for i64

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for i64

+ +
pub fn mul(self, other: Self) -> Self + +

impl Neg for i64

+ +
pub fn neg(self) -> Self + +

impl Not for i64

+ +
pub fn not(self) -> Self + +

impl Ord for i64

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for i64

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for i64

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for i64

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for i64

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for i64

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for i64

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for i64

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.i8.html b/noir_stdlib/docs/std/primitive.i8.html new file mode 100644 index 00000000000..5e500e6cfb6 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.i8.html @@ -0,0 +1,240 @@ + + + + + +Primitive type i8 documentation + + + +
+ +

Primitive type i8

+

Trait implementations

+

impl Add for i8

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<bool> for i8

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for i8

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for i8

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for i8

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for i8

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<u128> for i8

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for i8

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for i8

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for i8

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for i8

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for i8

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for i8

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for i8

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for i8

+ +
pub fn default() -> Self + +

impl Div for i8

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for i8

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for i8

+ +
pub fn from(value: bool) -> Self + +

impl Hash for i8

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for i8

+ +
pub fn mul(self, other: Self) -> Self + +

impl Neg for i8

+ +
pub fn neg(self) -> Self + +

impl Not for i8

+ +
pub fn not(self) -> Self + +

impl Ord for i8

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for i8

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for i8

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for i8

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for i8

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for i8

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for i8

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for i8

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.slice.html b/noir_stdlib/docs/std/primitive.slice.html new file mode 100644 index 00000000000..fb2afd31298 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.slice.html @@ -0,0 +1,183 @@ + + + + + +Primitive type slice documentation + + + +
+ +

Primitive type slice

+

Implementations

+

impl<T> [T]

+ +
pub fn len(self) -> u32 + +
+

Returns the length of the slice.

+
+
pub fn push_back(self, elem: T) -> Self + +
+

Push a new element to the end of the slice, returning a +new slice with a length one greater than the +original unmodified slice.

+
+
pub fn push_front(self, elem: T) -> Self + +
+

Push a new element to the front of the slice, returning a +new slice with a length one greater than the +original unmodified slice.

+
+
pub fn pop_back(self) -> (Self, T) + +
+

Remove the last element of the slice, returning the +popped slice and the element in a tuple

+
+
pub fn pop_front(self) -> (T, Self) + +
+

Remove the first element of the slice, returning the +element and the popped slice in a tuple

+
+
pub fn insert(self, index: u32, elem: T) -> Self + +
+

Insert an element at a specified index, shifting all elements +after it to the right

+
+
pub fn remove(self, index: u32) -> (Self, T) + +
+

Remove an element at a specified index, shifting all elements +after it to the left, returning the altered slice and +the removed element

+
+
pub fn append(self, other: Self) -> Self + +
+

Append each element of the other slice to the end of self. +This returns a new slice and leaves both input slices unchanged.

+
+
pub fn as_array<let N: u32>(self) -> [T; N] + +pub fn map<U, Env>(self, f: fn[Env](T) -> U) -> [U] + +pub fn mapi<U, Env>(self, f: fn[Env](u32, T) -> U) -> [U] + +pub fn for_each<Env>(self, f: fn[Env](T)) + +pub fn for_eachi<Env>(self, f: fn[Env](u32, T)) + +pub fn fold<U, Env>(self, accumulator: U, f: fn[Env](U, T) -> U) -> U + +pub fn reduce<Env>(self, f: fn[Env](T, T) -> T) -> T + +pub fn filter<Env>(self, predicate: fn[Env](T) -> bool) -> Self + +pub fn join(self, separator: T) -> T +
where + T: Append
+ +pub fn all<Env>(self, predicate: fn[Env](T) -> bool) -> bool + +pub fn any<Env>(self, predicate: fn[Env](T) -> bool) -> bool + +
+ + diff --git a/noir_stdlib/docs/std/primitive.str.html b/noir_stdlib/docs/std/primitive.str.html new file mode 100644 index 00000000000..edb5f09a0ed --- /dev/null +++ b/noir_stdlib/docs/std/primitive.str.html @@ -0,0 +1,102 @@ + + + + + +Primitive type str documentation + + + +
+ +

Primitive type str

+

Implementations

+

impl<let N: u32> str<N>

+ +
pub fn as_bytes(self) -> [u8; N] + +
+

Converts the given string into a byte array

+
+
pub fn as_bytes_vec(self) -> Vec<u8> + +
+

return a byte vector of the str content

+
+
+ + diff --git a/noir_stdlib/docs/std/primitive.u1.html b/noir_stdlib/docs/std/primitive.u1.html new file mode 100644 index 00000000000..98c778dff66 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.u1.html @@ -0,0 +1,175 @@ + + + + + +Primitive type u1 documentation + + + +
+ +

Primitive type u1

+

Trait implementations

+

impl Add for u1

+ +
pub fn add(self, other: Self) -> Self + +

impl BitAnd for u1

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for u1

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for u1

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for u1

+ +
pub fn default() -> Self + +

impl Div for u1

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for u1

+ +
pub fn eq(self, other: Self) -> bool + +

impl Hash for u1

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for u1

+ +
pub fn mul(self, other: Self) -> Self + +

impl Not for u1

+ +
pub fn not(self) -> Self + +

impl Rem for u1

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for u1

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for u1

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for u1

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for u1

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for u1

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for u1

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.u128.html b/noir_stdlib/docs/std/primitive.u128.html new file mode 100644 index 00000000000..158cdd19e5c --- /dev/null +++ b/noir_stdlib/docs/std/primitive.u128.html @@ -0,0 +1,260 @@ + + + + + +Primitive type u128 documentation + + + +
+ +

Primitive type u128

+

Trait implementations

+

impl Add for u128

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<Field> for u128

+ +
pub fn as_(self) -> Field + +

impl AsPrimitive<bool> for u128

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for u128

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for u128

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for u128

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for u128

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for u128

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<u16> for u128

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for u128

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for u128

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for u128

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for u128

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for u128

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for u128

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for u128

+ +
pub fn default() -> Self + +

impl Div for u128

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for u128

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for u128

+ +
pub fn from(value: bool) -> Self + +

impl From<u16> for u128

+ +
pub fn from(value: u16) -> Self + +

impl From<u32> for u128

+ +
pub fn from(value: u32) -> Self + +

impl From<u64> for u128

+ +
pub fn from(value: u64) -> Self + +

impl From<u8> for u128

+ +
pub fn from(value: u8) -> Self + +

impl Hash for u128

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for u128

+ +
pub fn mul(self, other: Self) -> Self + +

impl Not for u128

+ +
pub fn not(self) -> Self + +

impl Ord for u128

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for u128

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for u128

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for u128

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for u128

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for u128

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for u128

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for u128

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.u16.html b/noir_stdlib/docs/std/primitive.u16.html new file mode 100644 index 00000000000..2d9fbab3ca9 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.u16.html @@ -0,0 +1,245 @@ + + + + + +Primitive type u16 documentation + + + +
+ +

Primitive type u16

+

Trait implementations

+

impl Add for u16

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<Field> for u16

+ +
pub fn as_(self) -> Field + +

impl AsPrimitive<bool> for u16

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for u16

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for u16

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for u16

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for u16

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for u16

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for u16

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<u32> for u16

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for u16

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for u16

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for u16

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for u16

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for u16

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for u16

+ +
pub fn default() -> Self + +

impl Div for u16

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for u16

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for u16

+ +
pub fn from(value: bool) -> Self + +

impl From<u8> for u16

+ +
pub fn from(value: u8) -> Self + +

impl Hash for u16

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for u16

+ +
pub fn mul(self, other: Self) -> Self + +

impl Not for u16

+ +
pub fn not(self) -> Self + +

impl Ord for u16

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for u16

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for u16

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for u16

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for u16

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for u16

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for u16

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for u16

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.u32.html b/noir_stdlib/docs/std/primitive.u32.html new file mode 100644 index 00000000000..7f29d535746 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.u32.html @@ -0,0 +1,250 @@ + + + + + +Primitive type u32 documentation + + + +
+ +

Primitive type u32

+

Trait implementations

+

impl Add for u32

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<Field> for u32

+ +
pub fn as_(self) -> Field + +

impl AsPrimitive<bool> for u32

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for u32

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for u32

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for u32

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for u32

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for u32

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for u32

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for u32

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<u64> for u32

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for u32

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for u32

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for u32

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for u32

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for u32

+ +
pub fn default() -> Self + +

impl Div for u32

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for u32

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for u32

+ +
pub fn from(value: bool) -> Self + +

impl From<u16> for u32

+ +
pub fn from(value: u16) -> Self + +

impl From<u8> for u32

+ +
pub fn from(value: u8) -> Self + +

impl Hash for u32

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for u32

+ +
pub fn mul(self, other: Self) -> Self + +

impl Not for u32

+ +
pub fn not(self) -> Self + +

impl Ord for u32

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for u32

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for u32

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for u32

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for u32

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for u32

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for u32

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for u32

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.u64.html b/noir_stdlib/docs/std/primitive.u64.html new file mode 100644 index 00000000000..ac84fd1bb5d --- /dev/null +++ b/noir_stdlib/docs/std/primitive.u64.html @@ -0,0 +1,255 @@ + + + + + +Primitive type u64 documentation + + + +
+ +

Primitive type u64

+

Trait implementations

+

impl Add for u64

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<Field> for u64

+ +
pub fn as_(self) -> Field + +

impl AsPrimitive<bool> for u64

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for u64

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for u64

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for u64

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for u64

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for u64

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for u64

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for u64

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for u64

+ +
pub fn as_(self) -> Self + +

impl AsPrimitive<u8> for u64

+ +
pub fn as_(self) -> u8 + +

impl BitAnd for u64

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for u64

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for u64

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for u64

+ +
pub fn default() -> Self + +

impl Div for u64

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for u64

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for u64

+ +
pub fn from(value: bool) -> Self + +

impl From<u16> for u64

+ +
pub fn from(value: u16) -> Self + +

impl From<u32> for u64

+ +
pub fn from(value: u32) -> Self + +

impl From<u8> for u64

+ +
pub fn from(value: u8) -> Self + +

impl Hash for u64

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for u64

+ +
pub fn mul(self, other: Self) -> Self + +

impl Not for u64

+ +
pub fn not(self) -> Self + +

impl Ord for u64

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for u64

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for u64

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for u64

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for u64

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for u64

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for u64

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for u64

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/primitive.u8.html b/noir_stdlib/docs/std/primitive.u8.html new file mode 100644 index 00000000000..117dec83c14 --- /dev/null +++ b/noir_stdlib/docs/std/primitive.u8.html @@ -0,0 +1,248 @@ + + + + + +Primitive type u8 documentation + + + +
+ +

Primitive type u8

+

Trait implementations

+

impl Add for u8

+ +
pub fn add(self, other: Self) -> Self + +

impl AsPrimitive<Field> for u8

+ +
pub fn as_(self) -> Field + +

impl AsPrimitive<bool> for u8

+ +
pub fn as_(self) -> bool + +

impl AsPrimitive<i16> for u8

+ +
pub fn as_(self) -> i16 + +

impl AsPrimitive<i32> for u8

+ +
pub fn as_(self) -> i32 + +

impl AsPrimitive<i64> for u8

+ +
pub fn as_(self) -> i64 + +

impl AsPrimitive<i8> for u8

+ +
pub fn as_(self) -> i8 + +

impl AsPrimitive<u128> for u8

+ +
pub fn as_(self) -> u128 + +

impl AsPrimitive<u16> for u8

+ +
pub fn as_(self) -> u16 + +

impl AsPrimitive<u32> for u8

+ +
pub fn as_(self) -> u32 + +

impl AsPrimitive<u64> for u8

+ +
pub fn as_(self) -> u64 + +

impl AsPrimitive<u8> for u8

+ +
pub fn as_(self) -> Self + +

impl BitAnd for u8

+ +
pub fn bitand(self, other: Self) -> Self + +

impl BitOr for u8

+ +
pub fn bitor(self, other: Self) -> Self + +

impl BitXor for u8

+ +
pub fn bitxor(self, other: Self) -> Self + +

impl Default for u8

+ +
pub fn default() -> Self + +

impl Div for u8

+ +
pub fn div(self, other: Self) -> Self + +

impl Eq for u8

+ +
pub fn eq(self, other: Self) -> bool + +

impl From<bool> for u8

+ +
pub fn from(value: bool) -> Self + +

impl<let N: u32> From<str<N>> for [u8; N]

+ +
pub fn from(s: str<N>) -> Self + +
+

Returns an array of the string bytes.

+
+

impl Hash for u8

+ +
pub fn hash<H>(self, state: &mut H) +
where + H: Hasher
+ +

impl Mul for u8

+ +
pub fn mul(self, other: Self) -> Self + +

impl Not for u8

+ +
pub fn not(self) -> Self + +

impl Ord for u8

+ +
pub fn cmp(self, other: Self) -> Ordering + +

impl Rem for u8

+ +
pub fn rem(self, other: Self) -> Self + +

impl Shl for u8

+ +
pub fn shl(self, other: Self) -> Self + +

impl Shr for u8

+ +
pub fn shr(self, other: Self) -> Self + +

impl Sub for u8

+ +
pub fn sub(self, other: Self) -> Self + +

impl WrappingAdd for u8

+ +
pub fn wrapping_add(self, y: Self) -> Self + +

impl WrappingMul for u8

+ +
pub fn wrapping_mul(self, y: Self) -> Self + +

impl WrappingSub for u8

+ +
pub fn wrapping_sub(self, y: Self) -> Self + +
+ + diff --git a/noir_stdlib/docs/std/runtime/fn.is_unconstrained.html b/noir_stdlib/docs/std/runtime/fn.is_unconstrained.html new file mode 100644 index 00000000000..f14e969f87a --- /dev/null +++ b/noir_stdlib/docs/std/runtime/fn.is_unconstrained.html @@ -0,0 +1,24 @@ + + + + + +Function is_unconstrained documentation + + + +
+ +

Function is_unconstrained

+
pub fn is_unconstrained() -> bool
+ +
+ + diff --git a/noir_stdlib/docs/std/runtime/index.html b/noir_stdlib/docs/std/runtime/index.html new file mode 100644 index 00000000000..15581029d8a --- /dev/null +++ b/noir_stdlib/docs/std/runtime/index.html @@ -0,0 +1,91 @@ + + + + + +Module runtime documentation + + + +
+
noir_stdlib - std::runtime
+

Module runtime

+

Functions

+
+ + diff --git a/noir_stdlib/docs/std/slice/index.html b/noir_stdlib/docs/std/slice/index.html new file mode 100644 index 00000000000..6ec55f24a1c --- /dev/null +++ b/noir_stdlib/docs/std/slice/index.html @@ -0,0 +1,84 @@ + + + + + +Module slice documentation + + + +
+
noir_stdlib - std::slice
+

Module slice

+
+ + diff --git a/noir_stdlib/docs/std/string/index.html b/noir_stdlib/docs/std/string/index.html new file mode 100644 index 00000000000..158930e9b89 --- /dev/null +++ b/noir_stdlib/docs/std/string/index.html @@ -0,0 +1,84 @@ + + + + + +Module string documentation + + + +
+
noir_stdlib - std::string
+

Module string

+
+ + diff --git a/noir_stdlib/docs/std/test/index.html b/noir_stdlib/docs/std/test/index.html new file mode 100644 index 00000000000..3c145798ca8 --- /dev/null +++ b/noir_stdlib/docs/std/test/index.html @@ -0,0 +1,91 @@ + + + + + +Module test documentation + + + +
+ +

Module test

+

Structs

+
+ + diff --git a/noir_stdlib/docs/std/test/struct.OracleMock.html b/noir_stdlib/docs/std/test/struct.OracleMock.html new file mode 100644 index 00000000000..e44119746f4 --- /dev/null +++ b/noir_stdlib/docs/std/test/struct.OracleMock.html @@ -0,0 +1,53 @@ + + + + + +Struct OracleMock documentation + + + +
+ +

Struct OracleMock

+
pub struct OracleMock
+{ /* private fields */ }
+
+

Implementations

+

impl OracleMock

+ +
pub unconstrained fn mock<let N: u32>(name: str<N>) -> Self + +pub unconstrained fn with_params<P>(self, params: P) -> Self + +pub unconstrained fn get_last_params<P>(self) -> P + +pub unconstrained fn returns<R>(self, returns: R) -> Self + +pub unconstrained fn times(self, times: u64) -> Self + +pub unconstrained fn clear(self) + +pub unconstrained fn times_called(self) -> Field + +
+ + diff --git a/noir_stdlib/docs/styles.css b/noir_stdlib/docs/styles.css new file mode 100644 index 00000000000..47c21694fe9 --- /dev/null +++ b/noir_stdlib/docs/styles.css @@ -0,0 +1,198 @@ +:root { + --main-color: black; + --code-color: #f5f5f5; + --link-color: #3873ad; + --header-border-color: #ddd; + --crate-color: var(--link-color); + --module-color: var(--link-color); + --struct-color: #ad378a; + --trait-color: #6e4fc9; + --type-color: var(--struct-color); + --global-color: var(--link-color); + --fn-color: #ad7c37; + --primitive-color: var(--struct-color); + --sidebar-color: #f5f5f5; + --comment-color: #8e908c; +} + +body { + font-family: "Fira Sans", Arial, NanumBarunGothic, sans-serif; + font-weight: 500; + margin: 0; + display: flex; + flex-direction: row; + flex-wrap: nowrap; +} + +main { + padding: 28px 15px 40px 45px; + max-width: 960px; + position: relative; + flex-grow: 1; +} + +a { + color: var(--link-color); + text-decoration: none; +} + +pre { + padding: 14px; + background-color: var(--code-color); +} + +code { + font-family: "Source Code Pro",monospace; + text-wrap: auto; + white-space: pre-wrap; +} + +.code-header { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +h1, h2 { + line-height: 1.25; + padding-top: 3px; + padding-bottom: 9px; +} + +h1, h2, h3, h4 { + margin: 25px 0 15px 0; +} + +h2 { + font-size: 1.375rem; + border-bottom: 1px solid var(--header-border-color); +} + +ul { + list-style-type: none; + width: 100%; + margin: 0; + padding: 0; +} + +.item-list { + display: table; +} + +.item-list>li { + display: table-row; + width: 100%; + line-height: 2em; +} + +.item-list>li>.item-name { + width: 33%; + display: table-cell; + padding-right: 1.25rem; +} + +.item-list>li>.item-description { + display: table-cell; + font-family: "Source Serif 4", NanumBarunGothic, serif; +} + +.comments { + font-family: "Source Serif 4", NanumBarunGothic, serif; +} + +.comments code, .item-description code { + background-color: var(--code-color); + border-radius: 6px; + padding: 0 0.125em; + font-weight: 400; + font-size: 0.94em; +} + +.crate { + color: var(--crate-color); +} + +.module { + color: var(--module-color); +} + +.struct { + color: var(--struct-color); +} + +.trait { + color: var(--trait-color); +} + +.type { + color: var(--type-color); +} + +.global { + color: var(--global-color); +} + +.fn { + color: var(--fn-color); +} + +.primitive { + color: var(--primitive-color); +} + +.padded-methods { + padding-left: 2em; +} + +.padded-description { + padding-left: 2em; +} + +.sidebar { + scrollbar-width: thin; + background-color: var(--sidebar-color); + font-size: 0.875rem; + overflow-y: scroll; + overscroll-behavior: contain; + position: sticky; + height: 100vh; + top: 0; + left: 0; + width: 306px; + padding: 16px 15px 10px 24px; +} + +.sidebar h1 { + border-bottom: 0; + margin: 0; +} + +.sidebar h2 { + border-bottom: 0; + margin: 0; + margin-top: 30px; +} + +.sidebar h1 a, .sidebar h2 a { + color: var(--main-color); +} + +.sidebar h3 { + border-bottom: 0; + margin: 0; + margin-top: 15px; + margin-bottom: 15px; +} + +.sidebar li { + line-height: 2em; +} + +.comment { + color: var(--comment-color); +} + +.where-clause { + font-size: 0.875rem; + white-space: pre-wrap; +} \ No newline at end of file diff --git a/tooling/nargo_cli/Cargo.toml b/tooling/nargo_cli/Cargo.toml index fc27807fceb..e9311df8a81 100644 --- a/tooling/nargo_cli/Cargo.toml +++ b/tooling/nargo_cli/Cargo.toml @@ -39,6 +39,7 @@ iter-extended.workspace = true # and that is a different target, and for that the feature # aren't unified with this one. nargo = { workspace = true, features = ["rpc"] } +nargo_doc.workspace = true nargo_expand.workspace = true nargo_fmt.workspace = true nargo_toml.workspace = true diff --git a/tooling/nargo_cli/src/cli/doc_cmd.rs b/tooling/nargo_cli/src/cli/doc_cmd.rs new file mode 100644 index 00000000000..07d461e543f --- /dev/null +++ b/tooling/nargo_cli/src/cli/doc_cmd.rs @@ -0,0 +1,142 @@ +use std::{collections::HashMap, fs}; + +use clap::Args; +use fm::FileManager; +use nargo::{ + errors::CompileError, insert_all_files_for_workspace_into_file_manager, + ops::check_crate_and_report_errors, package::Package, parse_all, prepare_package, + workspace::Workspace, +}; +use nargo_doc::{ItemIds, crate_module, items::Crate}; +use nargo_toml::PackageSelection; +use noirc_driver::{CompileOptions, CrateId}; +use noirc_frontend::hir::{Context, ParsedFiles}; + +use crate::errors::CliError; + +use super::{LockType, PackageOptions, WorkspaceCommand}; + +/// Builds documentation for the specified package or workspace. +/// +/// Note: this command is in development and functionality may change greatly with no warning. +#[derive(Debug, Clone, Args, Default)] +pub(crate) struct DocCommand { + #[clap(flatten)] + pub(super) package_options: PackageOptions, + + #[clap(flatten)] + compile_options: CompileOptions, +} + +impl WorkspaceCommand for DocCommand { + fn package_selection(&self) -> PackageSelection { + self.package_options.package_selection() + } + fn lock_type(&self) -> LockType { + // Creates a `Prover.toml` template if it doesn't exist, otherwise only writes if `allow_overwrite` is true, + // so it shouldn't lead to accidental conflicts. Doesn't produce compilation artifacts. + LockType::None + } +} + +pub(crate) fn run(args: DocCommand, workspace: Workspace) -> Result<(), CliError> { + let mut workspace_file_manager = workspace.new_file_manager(); + insert_all_files_for_workspace_into_file_manager(&workspace, &mut workspace_file_manager); + let parsed_files = parse_all(&workspace_file_manager); + + let mut crates = Vec::new(); + // Maps a crate's root file to its crate + let mut all_dependencies = HashMap::new(); + let mut ids = HashMap::new(); + for package in &workspace { + let (krate, dependencies) = package_crate( + &workspace_file_manager, + &parsed_files, + package, + &args.compile_options, + &mut ids, + )?; + crates.push(krate); + all_dependencies.extend(dependencies); + } + // Crates in the workspace might depend on other crates in the workspace. + // Remove them from `all_dependencies`. + for krate in &crates { + all_dependencies.remove(&krate.root_file); + } + let dependencies = all_dependencies.into_values().collect::>(); + + let name = workspace.root_dir.file_name().unwrap().to_string_lossy().to_string(); + let crates = nargo_doc::items::Workspace { crates, name, dependencies }; + + let files = nargo_doc::to_html(&crates); + let target_dir = workspace.target_directory_path(); + let docs_dir = target_dir.join("docs"); + if let Ok(true) = fs::exists(&docs_dir) { + fs::remove_dir_all(&docs_dir).map_err(|err| { + CliError::Generic(format!("Failed to remove existing docs directory: {err}")) + })?; + } + for (path, contents) in files { + let full_path = docs_dir.join(path); + fs::create_dir_all(full_path.parent().unwrap()) + .map_err(|err| CliError::Generic(format!("Failed to create directory: {err}")))?; + fs::write(full_path, contents) + .map_err(|err| CliError::Generic(format!("Failed to write file: {err}")))?; + } + println!("Generated {}", docs_dir.join("index.html").display()); + Ok(()) +} + +/// Returns the Crate item for the given package, together with all of +/// its dependencies in a HashMap that maps a dependency's root file to +/// its crate. +fn package_crate( + file_manager: &FileManager, + parsed_files: &ParsedFiles, + package: &Package, + compile_options: &CompileOptions, + ids: &mut ItemIds, +) -> Result<(Crate, HashMap), CompileError> { + let (mut context, crate_id) = prepare_package(file_manager, parsed_files, package); + + check_crate_and_report_errors(&mut context, crate_id, compile_options)?; + + let module = + crate_module(crate_id, &context.crate_graph, &context.def_maps, &context.def_interner, ids); + + let mut dependencies = HashMap::new(); + collect_dependencies(&context, crate_id, file_manager, &mut dependencies, ids)?; + + let root_file = &context.crate_graph[crate_id].root_file_id; + let root_file = file_manager.path(*root_file).unwrap().display().to_string(); + + let krate = Crate { name: package.name.to_string(), root_module: module, root_file }; + Ok((krate, dependencies)) +} + +fn collect_dependencies( + context: &Context, + crate_id: CrateId, + file_manager: &FileManager, + dependencies: &mut HashMap, + ids: &mut ItemIds, +) -> Result<(), CompileError> { + for dependency in &context.crate_graph[crate_id].dependencies { + let crate_id = dependency.crate_id; + let root_file = &context.crate_graph[crate_id].root_file_id; + let root_file = file_manager.path(*root_file).unwrap().display().to_string(); + let module = crate_module( + crate_id, + &context.crate_graph, + &context.def_maps, + &context.def_interner, + ids, + ); + let name = dependency.name.to_string(); + dependencies.insert(root_file.clone(), Crate { name, root_module: module, root_file }); + + collect_dependencies(context, crate_id, file_manager, dependencies, ids)?; + } + Ok(()) +} diff --git a/tooling/nargo_cli/src/cli/mod.rs b/tooling/nargo_cli/src/cli/mod.rs index a567c907fd4..2e44a91aa40 100644 --- a/tooling/nargo_cli/src/cli/mod.rs +++ b/tooling/nargo_cli/src/cli/mod.rs @@ -22,6 +22,7 @@ mod check_cmd; pub mod compile_cmd; mod dap_cmd; mod debug_cmd; +mod doc_cmd; mod execute_cmd; mod expand_cmd; mod export_cmd; @@ -116,6 +117,7 @@ enum NargoCommand { #[command(hide = true)] Dap(dap_cmd::DapCommand), Expand(expand_cmd::ExpandCommand), + Doc(doc_cmd::DocCommand), GenerateCompletionScript(generate_completion_script_cmd::GenerateCompletionScriptCommand), } @@ -160,6 +162,7 @@ pub(crate) fn start_cli() -> eyre::Result<()> { NargoCommand::Dap(args) => dap_cmd::run(args), NargoCommand::Fmt(args) => with_workspace(args, config, fmt_cmd::run), NargoCommand::Expand(args) => with_workspace(args, config, expand_cmd::run), + NargoCommand::Doc(args) => with_workspace(args, config, doc_cmd::run), NargoCommand::GenerateCompletionScript(args) => generate_completion_script_cmd::run(args), }?; diff --git a/tooling/nargo_doc/Cargo.toml b/tooling/nargo_doc/Cargo.toml new file mode 100644 index 00000000000..580a9a662d1 --- /dev/null +++ b/tooling/nargo_doc/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "nargo_doc" +version.workspace = true +authors.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +iter-extended.workspace = true +serde.workspace = true +noirc_driver.workspace = true +noirc_frontend.workspace = true +noirc_errors.workspace = true +markdown = "1.0.0" + +[dev-dependencies] diff --git a/tooling/nargo_doc/src/html.rs b/tooling/nargo_doc/src/html.rs new file mode 100644 index 00000000000..569284f1c94 --- /dev/null +++ b/tooling/nargo_doc/src/html.rs @@ -0,0 +1,1795 @@ +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + path::PathBuf, +}; + +use noirc_frontend::ast::ItemVisibility; + +use crate::{ + html::{ + all_items::AllItems, + has_class::HasClass, + has_uri::HasUri, + id_to_info::{ItemInfo, compute_id_to_info}, + markdown_utils::{fix_markdown, markdown_summary}, + trait_impls::gather_all_trait_impls, + }, + items::{ + Crate, Function, FunctionParam, Generic, Global, HasNameAndComments, Id, Impl, Item, + Module, PrimitiveType, PrimitiveTypeKind, Reexport, Struct, StructField, Trait, TraitBound, + TraitConstraint, TraitImpl, Type, TypeAlias, Workspace, + }, +}; + +mod all_items; +mod has_class; +mod has_uri; +mod id_to_info; +mod markdown_utils; +mod trait_impls; + +/// Returns a list of (path, contents) representing the HTML files for the given crates. +/// The paths are relative paths that can be joined to a base directory. +/// +/// Not all returned files are linked to items. For example, there's an "all.html" file +/// that lists all items, and a "styles.css" file for styling. +pub fn to_html(workspace: &Workspace) -> Vec<(PathBuf, String)> { + let mut creator = HTMLCreator::new(workspace); + creator.process_workspace(workspace); + creator.files +} + +/// Builds all the files for the HTML documentation. +struct HTMLCreator { + output: String, + files: Vec<(PathBuf, String)>, + current_path: Vec, + workspace_name: String, + id_to_info: HashMap, + /// Maps a trait ID to all its implementations across all crates. + all_trait_impls: HashMap>, + self_type: Option, +} + +// Implementation details: +// - there's a single `output: String` buffer. Content is written there as HTML is generated +// and, once a new page needs to be "written", the buffer is moved to `files` and `output` is +// emptied. +// - `create_*` methods create new files by writing to `output`, pushing to `files`, then +// clearing `output`. +// - `render_*` methods just write to `output`. + +impl HTMLCreator { + fn new(workspace: &Workspace) -> Self { + let output = String::new(); + let files = Vec::new(); + let current_path = Vec::new(); + let workspace_name = workspace.name.clone(); + let id_to_info = compute_id_to_info(workspace); + + // Each trait in each create will have trait impls that are found in that crate. + // When showing a trait we want to show all impls across all crates, so we gather + // them now. + let all_trait_impls = gather_all_trait_impls(workspace); + Self { + output, + files, + current_path, + workspace_name, + id_to_info, + all_trait_impls, + self_type: None, + } + } + + fn process_workspace(&mut self, workspace: &Workspace) { + self.create_styles(); + self.create_all_items(workspace); + self.create_index(workspace); + + for krate in workspace.all_crates() { + if !krate.root_module.has_public_items() { + continue; + } + + self.create_crate(workspace, krate); + } + } + + fn create_styles(&mut self) { + let contents = include_str!("styles.css"); + self.output.push_str(contents); + self.push_file(PathBuf::from("styles.css")); + } + + fn create_all_items(&mut self, workspace: &Workspace) { + let all_items = all_items::compute_all_items(workspace); + self.html_start(&format!("All items in {}", workspace.name)); + self.sidebar_start(); + self.render_all_items_sidebar(&all_items); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(false); + self.h1(&format!("All items in {}", workspace.name)); + self.render_all_items_list("Structs", "struct", &all_items.structs); + self.render_all_items_list("Traits", "trait", &all_items.traits); + self.render_all_items_list("Type aliases", "type", &all_items.type_aliases); + self.render_all_items_list("Primitive types", "primitive", &all_items.primitive_types); + self.render_all_items_list("Globals", "global", &all_items.globals); + self.render_all_items_list("Functions", "fn", &all_items.functions); + self.main_end(); + self.html_end(); + + self.push_file(PathBuf::from("all.html")); + } + + fn render_all_items_list(&mut self, title: &str, class: &str, items: &[(Vec, String)]) { + if items.is_empty() { + return; + } + + self.output.push_str(&format!("")); + self.h2(title); + self.output.push_str("
    \n"); + for (path, name) in items { + let url_path = path.join("/"); + let module = path.join("::"); + self.output.push_str("
  • "); + self.output.push_str(&format!( + "{module}::{name}", + )); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + fn render_all_items_sidebar(&mut self, all_items: &AllItems) { + self.h2("Workspace items"); + self.output.push_str("
    \n"); + if !all_items.structs.is_empty() { + self.output.push_str("
  • Structs
  • \n"); + } + if !all_items.traits.is_empty() { + self.output.push_str("
  • Traits
  • \n"); + } + if !all_items.type_aliases.is_empty() { + self.output.push_str("
  • Type aliases
  • \n"); + } + if !all_items.primitive_types.is_empty() { + self.output.push_str("
  • Primitive types
  • \n"); + } + if !all_items.functions.is_empty() { + self.output.push_str("
  • Functions
  • \n"); + } + if !all_items.globals.is_empty() { + self.output.push_str("
  • Globals
  • \n"); + } + self.output.push_str("
\n"); + } + + fn create_index(&mut self, workspace: &Workspace) { + let crates = workspace + .crates + .iter() + .filter(|krate| krate.root_module.has_public_items()) + .collect::>(); + let redirect = + if crates.len() == 1 { Some(format!("{}/index.html", crates[0].name)) } else { None }; + self.html_start_with_redirect(&format!("{} documentation", workspace.name), redirect); + + // This sidebar is empty because there's not much we can list here. + // It's here so that every page has a sidebar. + self.sidebar_start(); + self.sidebar_end(); + + self.main_start(); + self.h1(&format!("{} documentation", workspace.name)); + self.render_list("Crates", "crates", false, 0, &crates); + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from("index.html")); + } + + fn create_crate(&mut self, workspace: &Workspace, krate: &Crate) { + self.current_path.push(krate.name.clone()); + + self.html_start(&format!("Crate {}", krate.name)); + self.sidebar_start(); + self.render_crate_sidebar(workspace, krate); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(false); + self.h1(&format!("Crate {}", krate.name)); + self.render_comments(&krate.root_module.comments, 1); + self.render_items(&krate.root_module.items, false, 0); + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from("index.html")); + + self.create_items(&krate.root_module, &krate.root_module.items); + + self.current_path.pop(); + } + + fn render_crate_sidebar(&mut self, workspace: &Workspace, krate: &Crate) { + self.render_module_items_sidebar("Crate items", &krate.root_module); + + self.h3("Crates"); + self.output.push_str("
    \n"); + for krate in &workspace.crates { + if !krate.root_module.has_public_items() { + continue; + } + + self.output.push_str("
  • "); + self.output.push_str(&format!( + "{}", + krate.uri(), + krate.class(), + krate.name(), + )); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + fn render_items(&mut self, items: &[(ItemVisibility, Item)], sidebar: bool, nesting: usize) { + if !sidebar { + self.render_reexports(items); + } + self.render_modules(items, sidebar, nesting); + self.render_structs(items, sidebar, nesting); + self.render_traits(items, sidebar, nesting); + self.render_type_aliases(items, sidebar, nesting); + self.render_primitive_types(items, sidebar, nesting); + self.render_functions(items, sidebar, nesting); + self.render_globals(items, sidebar, nesting); + } + + fn render_reexports(&mut self, items: &[(ItemVisibility, Item)]) { + let reexports = get_reexports(items); + if !reexports.is_empty() { + self.render_reexports_list("Re-exports", "re-exports", &reexports); + } + } + + fn render_modules(&mut self, items: &[(ItemVisibility, Item)], sidebar: bool, nesting: usize) { + let modules = get_modules(items); + if !modules.is_empty() { + self.render_list("Modules", "modules", sidebar, nesting, &modules); + } + } + + fn render_structs(&mut self, items: &[(ItemVisibility, Item)], sidebar: bool, nesting: usize) { + let structs = get_structs(items); + if !structs.is_empty() { + self.render_list("Structs", "structs", sidebar, nesting, &structs); + } + } + + fn render_traits(&mut self, items: &[(ItemVisibility, Item)], sidebar: bool, nesting: usize) { + let traits = get_traits(items); + if !traits.is_empty() { + self.render_list("Traits", "traits", sidebar, nesting, &traits); + } + } + + fn render_type_aliases( + &mut self, + items: &[(ItemVisibility, Item)], + sidebar: bool, + nesting: usize, + ) { + let type_aliases = get_type_aliases(items); + if !type_aliases.is_empty() { + self.render_list("Type aliases", "type-aliases", sidebar, nesting, &type_aliases); + } + } + + fn render_primitive_types( + &mut self, + items: &[(ItemVisibility, Item)], + sidebar: bool, + nesting: usize, + ) { + let primitive_types = get_primitive_types(items); + if !primitive_types.is_empty() { + self.render_list( + "Primitive types", + "primitive-types", + sidebar, + nesting, + &primitive_types, + ); + } + } + + fn render_globals(&mut self, items: &[(ItemVisibility, Item)], sidebar: bool, nesting: usize) { + let globals = get_globals(items); + if !globals.is_empty() { + self.render_list("Globals", "globals", sidebar, nesting, &globals); + } + } + + fn render_functions( + &mut self, + items: &[(ItemVisibility, Item)], + sidebar: bool, + nesting: usize, + ) { + let functions = get_functions(items); + if !functions.is_empty() { + self.render_list("Functions", "functions", sidebar, nesting, &functions); + } + } + + fn render_list( + &mut self, + title: &str, + anchor: &str, + sidebar: bool, + nesting: usize, + items: &[&T], + ) { + if sidebar { + self.output.push_str(&format!("

{title}

")); + } else { + self.output.push_str(&format!("

{title}

")); + } + self.output.push_str("
    \n"); + + let mut items = items.to_vec(); + items.sort_by_key(|item| item.name().to_lowercase()); + + for item in items { + self.output.push_str("
  • "); + if !sidebar { + self.output.push_str("
    "); + } + self.output.push_str(&format!( + "{}", + "../".repeat(nesting), + item.uri(), + item.class(), + item.name(), + )); + if !sidebar { + self.output.push_str("
    "); + self.output.push_str("
    "); + if let Some(comments) = item.comments() { + let summary = markdown_summary(comments); + self.output.push_str(&summary); + } + } + self.output.push_str("
    "); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + fn render_reexports_list(&mut self, title: &str, anchor: &str, reexports: &[&Reexport]) { + let nesting = self.current_path.len(); + + self.output.push_str(&format!("

{title}

")); + self.output.push_str("
    \n"); + + for reexport in reexports { + if !self.id_to_info.contains_key(&reexport.id) { + println!("{} {} {}", reexport.id, reexport.name, reexport.item_name); + } + + let info = &self.id_to_info[&reexport.id]; + let path = info.path.join("::"); + let path = if path.is_empty() { String::new() } else { format!("{path}::") }; + let uri = &info.uri; + let class = info.class; + self.output.push_str("
  • "); + self.output.push_str("
    "); + self.output.push_str(""); + self.output.push_str(&format!( + "pub use {}{}{};", + path, + "../".repeat(nesting), + uri, + class, + reexport.item_name, + if reexport.name != reexport.item_name { + format!(" as {}", reexport.name) + } else { + String::new() + }, + )); + self.output.push_str(""); + self.output.push_str("
    "); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + fn create_items(&mut self, parent_module: &Module, items: &[(ItemVisibility, Item)]) { + for (visibility, item) in items { + if visibility == &ItemVisibility::Public { + self.create_item(parent_module, item); + } + } + } + + fn create_item(&mut self, parent_module: &Module, item: &Item) { + match item { + Item::Module(module) => self.create_module(parent_module, module), + Item::Struct(struct_) => self.create_struct(parent_module, struct_), + Item::Trait(trait_) => self.create_trait(parent_module, trait_), + Item::TypeAlias(alias) => self.create_alias(parent_module, alias), + Item::Function(function) => self.create_function(parent_module, function), + Item::Global(global) => self.create_global(parent_module, global), + Item::PrimitiveType(primitive) => self.create_primitive_type(parent_module, primitive), + Item::Reexport(_) => { /* Re-exports don't have their own pages */ } + } + } + + fn create_module(&mut self, parent_module: &Module, module: &Module) { + self.current_path.push(module.name.clone()); + + self.html_start(&format!("Module {}", module.name)); + self.sidebar_start(); + self.render_module_sidebar(parent_module, module); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(false); + self.h1(&format!("Module {}", module.name)); + self.render_comments(&module.comments, 1); + self.render_items(&module.items, false, 0); + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from("index.html")); + + self.create_items(module, &module.items); + + self.current_path.pop(); + } + + fn render_module_sidebar(&mut self, parent_module: &Module, module: &Module) { + self.h2(&format!("Module {}", module.name)); + self.render_module_items_sidebar("Module items", module); + self.render_module_contents_sidebar(parent_module, 1); + } + + fn render_module_items_sidebar(&mut self, title: &str, module: &Module) { + if !module.has_public_items() { + return; + } + self.h3(title); + self.output.push_str("
    \n"); + if !get_reexports(&module.items).is_empty() { + self.output.push_str("
  • Re-exports
  • \n"); + } + if !get_modules(&module.items).is_empty() { + self.output.push_str("
  • Modules
  • \n"); + } + if !get_structs(&module.items).is_empty() { + self.output.push_str("
  • Structs
  • \n"); + } + if !get_traits(&module.items).is_empty() { + self.output.push_str("
  • Traits
  • \n"); + } + if !get_type_aliases(&module.items).is_empty() { + self.output.push_str("
  • Type aliases
  • \n"); + } + if !get_functions(&module.items).is_empty() { + self.output.push_str("
  • Functions
  • \n"); + } + if !get_globals(&module.items).is_empty() { + self.output.push_str("
  • Globals
  • \n"); + } + self.output.push_str("
\n"); + } + + fn render_module_contents_sidebar(&mut self, module: &Module, nesting: usize) { + if module.name.is_empty() { + let crate_name = self.current_path.last().unwrap(); + self.h2(&format!("In crate {crate_name}")); + } else { + self.h2(&format!("In module {}", module.name)); + } + self.render_items(&module.items, true, nesting); + } + + fn create_struct(&mut self, parent_module: &Module, struct_: &Struct) { + self.html_start(&format!("Struct {}", struct_.name)); + self.sidebar_start(); + self.render_struct_sidebar(struct_); + self.render_module_contents_sidebar(parent_module, 0); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(true); + self.h1(&format!("Struct {}", struct_.name)); + self.render_struct_code(struct_); + self.render_comments(&struct_.comments, 1); + self.render_struct_fields(&struct_.fields); + self.render_impls(&struct_.impls); + + let mut trait_impls = struct_.trait_impls.clone(); + trait_impls.sort_by_key(|trait_impl| { + (trait_impl_trait_to_string(trait_impl), trait_impl_anchor(trait_impl)) + }); + let show_methods = true; + self.render_trait_impls(&trait_impls, "Trait implementations", show_methods); + + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from(struct_.uri())); + } + + fn render_struct_sidebar(&mut self, struct_: &Struct) { + self.h2(&format!("Struct {}", struct_.name)); + + if !struct_.fields.is_empty() { + let mut fields = struct_.fields.clone(); + fields.sort_by_key(|field| field.name.clone()); + + self.h3("Fields"); + self.output.push_str("
    \n"); + for field in fields { + self.output.push_str("
  • "); + self.output.push_str(&format!("{}", field.name, field.name)); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + let mut methods = struct_.impls.iter().flat_map(|iter| &iter.methods).collect::>(); + methods.sort_by_key(|method| method.name.clone()); + + if !methods.is_empty() { + self.h3("Methods"); + self.output.push_str("
    \n"); + for method in methods { + self.output.push_str("
  • "); + self.output.push_str(&format!("{}", method.name, method.name)); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + self.render_sidebar_trait_impls("Trait implementations", true, &struct_.trait_impls); + } + + fn create_trait(&mut self, parent_module: &Module, trait_: &Trait) { + self.html_start(&format!("Trait {}", trait_.name)); + self.sidebar_start(); + self.render_trait_sidebar(trait_); + self.render_module_contents_sidebar(parent_module, 0); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(true); + self.h1(&format!("Trait {}", trait_.name)); + self.render_trait_code(trait_); + self.render_comments(&trait_.comments, 1); + self.render_trait_methods("Required methods", &trait_.required_methods); + self.render_trait_methods("Provided methods", &trait_.provided_methods); + + let mut trait_impls = self.get_all_trait_impls(trait_); + trait_impls.sort_by_key(|trait_impl| { + (self.type_to_string(&trait_impl.r#type), trait_impl_anchor(trait_impl)) + }); + let show_methods = false; + self.render_trait_impls(&trait_impls, "Implementors", show_methods); + + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from(trait_.uri())); + } + + fn render_trait_sidebar(&mut self, trait_: &Trait) { + self.h2(&format!("Trait {}", trait_.name)); + + self.render_trait_sidebar_methods("Required methods", &trait_.required_methods); + self.render_trait_sidebar_methods("Provided methods", &trait_.provided_methods); + + let trait_impls = self.get_all_trait_impls(trait_); + self.render_sidebar_trait_impls("Implementors", false, &trait_impls); + } + + fn render_trait_sidebar_methods(&mut self, title: &str, methods: &[Function]) { + let mut methods = methods.iter().collect::>(); + methods.sort_by_key(|method| method.name.clone()); + + if !methods.is_empty() { + self.h3(title); + self.output.push_str("
    \n"); + for method in methods { + self.output.push_str("
  • "); + self.output.push_str(&format!("{}", method.name, method.name)); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + } + + fn render_sidebar_trait_impls( + &mut self, + title: &str, + display_trait: bool, + trait_impls: &[TraitImpl], + ) { + if trait_impls.is_empty() { + return; + } + + let mut trait_impls = trait_impls.to_vec(); + if display_trait { + trait_impls.sort_by_key(|trait_impl| { + (trait_impl_trait_to_string(trait_impl), trait_impl_anchor(trait_impl)) + }); + } else { + trait_impls.sort_by_key(|trait_impl| { + (self.type_to_string(&trait_impl.r#type), trait_impl_anchor(trait_impl)) + }); + } + + self.h3(title); + self.output.push_str("
    \n"); + for trait_impl in trait_impls { + self.output.push_str("
  • "); + self.output.push_str(&format!( + "{}", + trait_impl_anchor(&trait_impl), + if display_trait { + trait_impl_trait_to_string(&trait_impl) + } else { + self.type_to_string(&trait_impl.r#type) + }, + )); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + fn create_alias(&mut self, parent_module: &Module, alias: &TypeAlias) { + self.html_start(&format!("Type alias {}", alias.name)); + self.sidebar_start(); + self.render_module_contents_sidebar(parent_module, 0); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(true); + self.h1(&format!("Type alias {}", alias.name)); + self.render_type_alias_code(alias); + self.render_comments(&alias.comments, 1); + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from(alias.uri())); + } + + fn create_function(&mut self, parent_module: &Module, function: &Function) { + self.html_start(&format!("Function {}", function.name)); + self.sidebar_start(); + self.render_module_contents_sidebar(parent_module, 0); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(true); + self.h1(&format!("Function {}", function.name)); + let as_header = false; + let output_id = false; + self.render_function(function, 1, as_header, output_id); + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from(function.uri())); + } + + fn create_global(&mut self, parent_module: &Module, global: &Global) { + self.html_start(&format!("Global {}", global.name)); + self.sidebar_start(); + self.render_module_contents_sidebar(parent_module, 0); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(true); + self.h1(&format!("Global {}", global.name)); + self.render_global_code(global); + self.render_comments(&global.comments, 1); + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from(global.uri())); + } + + fn create_primitive_type(&mut self, parent_module: &Module, primitive: &PrimitiveType) { + self.html_start(&format!("Primitive type {}", primitive.kind)); + self.sidebar_start(); + self.render_primitive_sidebar(primitive); + self.render_module_contents_sidebar(parent_module, 0); + self.sidebar_end(); + self.main_start(); + self.render_breadcrumbs(true); + self.h1(&format!( + "Primitive type {}", + primitive.kind + )); + self.render_impls(&primitive.impls); + + let mut trait_impls = primitive.trait_impls.clone(); + trait_impls.sort_by_key(|trait_impl| { + (trait_impl_trait_to_string(trait_impl), trait_impl_anchor(trait_impl)) + }); + let show_methods = true; + self.render_trait_impls(&trait_impls, "Trait implementations", show_methods); + + self.main_end(); + self.html_end(); + self.push_file(PathBuf::from(primitive.kind.uri())); + } + + fn render_primitive_sidebar(&mut self, primitive: &PrimitiveType) { + self.h2(&format!("Primitive type {}", primitive.kind)); + + let mut methods = primitive.impls.iter().flat_map(|iter| &iter.methods).collect::>(); + methods.sort_by_key(|method| method.name.clone()); + + if !methods.is_empty() { + self.h3("Methods"); + self.output.push_str("
    \n"); + for method in methods { + self.output.push_str("
  • "); + self.output.push_str(&format!("{}", method.name, method.name)); + self.output.push_str("
  • \n"); + } + self.output.push_str("
\n"); + } + + self.render_sidebar_trait_impls("Trait implementations", true, &primitive.trait_impls); + } + + fn render_struct_code(&mut self, struct_: &Struct) { + self.output.push_str("
");
+        self.output.push_str(&format!("pub struct {}", struct_.name));
+        self.render_generics(&struct_.generics);
+        if struct_.fields.is_empty() {
+            if struct_.has_private_fields {
+                self.output.push_str("\n{ /* private fields */ }\n");
+            } else {
+                self.output.push_str(" {}\n");
+            }
+        } else {
+            self.output.push_str(" {\n");
+            for field in &struct_.fields {
+                self.output.push_str(&format!("    pub {}: ", field.name,));
+                self.render_type(&field.r#type);
+                self.output.push_str(",\n");
+            }
+            if struct_.has_private_fields {
+                self.output.push_str("    /* private fields */\n");
+            }
+            self.output.push_str("}\n");
+        }
+        self.output.push_str("
\n"); + } + + fn render_struct_fields(&mut self, fields: &[StructField]) { + if fields.is_empty() { + return; + } + + self.h2("Fields"); + + for field in fields { + self.output.push_str(&format!( + "
", + field.name + )); + self.output.push_str(&field.name); + self.output.push_str(": "); + self.render_type(&field.r#type); + self.output.push_str("
\n"); + self.output.push_str("
"); + self.render_comments(&field.comments, 3); + self.output.push_str("
"); + } + } + + fn render_impls(&mut self, impls: &[Impl]) { + if impls.is_empty() { + return; + } + + self.h2("Implementations"); + + for impl_ in impls { + self.render_impl(impl_); + } + } + + fn render_impl(&mut self, impl_: &Impl) { + self.output.push_str("

"); + self.output.push_str("impl"); + self.render_generics(&impl_.generics); + self.output.push(' '); + self.render_type(&impl_.r#type); + self.output.push_str("

\n\n"); + let output_id = true; + + self.self_type = Some(impl_.r#type.clone()); + self.render_methods(&impl_.methods, 3, output_id); + self.self_type = None; + } + + fn render_trait_impls(&mut self, trait_impls: &[TraitImpl], title: &str, show_methods: bool) { + if trait_impls.is_empty() { + return; + } + + self.h2(title); + + for trait_impl in trait_impls { + self.render_trait_impl(trait_impl, show_methods); + } + } + + fn render_trait_impl(&mut self, trait_impl: &TraitImpl, show_methods: bool) { + let anchor = trait_impl_anchor(trait_impl); + self.output.push_str(&format!("

")); + self.output.push_str("impl"); + self.render_generics(&trait_impl.generics); + self.output.push(' '); + self.render_id_reference(trait_impl.trait_id, &trait_impl.trait_name); + self.render_generic_types(&trait_impl.trait_generics); + self.output.push_str(" for "); + self.render_type(&trait_impl.r#type); + let indent = 0; + self.render_where_clause(&trait_impl.where_clause, indent); + self.output.push_str("

\n\n"); + + if show_methods { + self.self_type = Some(trait_impl.r#type.clone()); + let output_id = false; + self.render_methods(&trait_impl.methods, 3, output_id); + self.self_type = None; + } + } + + fn render_trait_code(&mut self, trait_: &Trait) { + self.output.push_str("
");
+        self.output.push_str(&format!("pub trait {}", trait_.name));
+        self.render_generics(&trait_.generics);
+        if !trait_.bounds.is_empty() {
+            self.output.push(':');
+            for (index, bound) in trait_.bounds.iter().enumerate() {
+                if trait_.bounds.len() == 1 {
+                    self.output.push(' ');
+                } else {
+                    self.output.push_str("\n    ");
+                }
+                if index > 0 {
+                    self.output.push_str("+ ");
+                }
+                self.render_trait_bound(bound);
+            }
+        }
+        let indent = 0;
+        self.render_where_clause(&trait_.where_clause, indent);
+        if trait_.where_clause.is_empty() {
+            if trait_.bounds.len() <= 1 {
+                self.output.push_str(" {\n");
+            } else {
+                self.output.push_str("\n{\n");
+            }
+        } else {
+            self.output.push_str("{\n");
+        }
+
+        let color_name = true;
+        let link = true;
+        let indent = 1;
+        let mut printed_member = false;
+
+        if !trait_.associated_types.is_empty() {
+            for associated_type in &trait_.associated_types {
+                self.output.push_str("    type ");
+                self.output.push_str(&associated_type.name);
+                if !associated_type.bounds.is_empty() {
+                    self.output.push_str(": ");
+                    for (index, bound) in associated_type.bounds.iter().enumerate() {
+                        if index > 0 {
+                            self.output.push_str(" + ");
+                        }
+                        self.render_trait_bound(bound);
+                    }
+                }
+                self.output.push_str(";\n");
+            }
+
+            printed_member = true;
+        }
+
+        if !trait_.associated_constants.is_empty() {
+            for associated_constant in &trait_.associated_constants {
+                self.output.push_str("    let ");
+                self.output.push_str(&associated_constant.name);
+                self.output.push_str(": ");
+                self.render_type(&associated_constant.r#type);
+                self.output.push_str(";\n");
+            }
+
+            printed_member = true;
+        }
+
+        if !trait_.required_methods.is_empty() {
+            if printed_member {
+                self.output.push('\n');
+            }
+            self.output.push_str("    // Required methods\n");
+            for method in &trait_.required_methods {
+                self.output.push_str("    ");
+                self.render_function_signature_inner(method, color_name, link, indent);
+                self.output.push_str(";\n");
+            }
+            printed_member = true;
+        }
+
+        if !trait_.provided_methods.is_empty() {
+            if printed_member {
+                self.output.push('\n');
+            }
+            self.output.push_str("    // Provided methods\n");
+            for method in &trait_.provided_methods {
+                self.output.push_str("    ");
+                self.render_function_signature_inner(method, color_name, link, indent);
+                self.output.push_str(" { ... }\n");
+            }
+        }
+        self.output.push('}');
+        self.output.push_str("
\n\n"); + } + + fn render_trait_methods(&mut self, title: &str, methods: &[Function]) { + if methods.is_empty() { + return; + } + + self.h2(title); + let output_id = true; + self.render_methods(methods, 2, output_id); + } + + fn render_type_alias_code(&mut self, alias: &TypeAlias) { + self.output.push_str("
");
+        self.output.push_str(&format!("pub type {}", alias.name));
+        self.render_generics(&alias.generics);
+        self.output.push_str(" = ");
+        self.render_type(&alias.r#type);
+        self.output.push(';');
+        self.output.push_str("
\n\n"); + } + + fn render_global_code(&mut self, global: &Global) { + self.output.push_str("
");
+        self.output.push_str("pub ");
+        if global.mutable {
+            self.output.push_str("mut ");
+        }
+        if global.comptime {
+            self.output.push_str("comptime ");
+        }
+        self.output.push_str("global ");
+        self.output.push_str(&global.name);
+        self.output.push_str(": ");
+        self.render_type(&global.r#type);
+        self.output.push(';');
+        self.output.push_str("
\n\n"); + } + + fn render_methods( + &mut self, + methods: &[Function], + current_heading_level: usize, + output_id: bool, + ) { + self.output.push_str("
"); + for method in methods { + self.render_function(method, current_heading_level, true, output_id); + } + self.output.push_str("
"); + } + + fn render_function( + &mut self, + function: &Function, + current_heading_level: usize, + as_header: bool, + output_id: bool, + ) { + self.render_function_signature(function, as_header, output_id); + if function.comments.is_some() { + if as_header { + self.output.push_str("
"); + } + self.render_comments(&function.comments, current_heading_level); + if as_header { + self.output.push_str("
"); + } + } + } + + fn render_function_signature(&mut self, function: &Function, as_header: bool, output_id: bool) { + if as_header { + if output_id { + self.output + .push_str(&format!("", function.name)); + } else { + self.output.push_str(""); + } + } else { + self.output.push_str("
");
+            self.output.push_str("");
+        }
+        let color_name = as_header;
+        let link = false;
+        let indent = 0;
+        self.render_function_signature_inner(function, color_name, link, indent);
+        self.output.push_str("");
+        if !as_header {
+            self.output.push_str("
"); + } + self.output.push_str("\n\n"); + } + + fn render_function_signature_inner( + &mut self, + function: &Function, + color_name: bool, + link: bool, + indent: usize, + ) { + self.output.push_str("pub "); + if function.unconstrained { + self.output.push_str("unconstrained "); + } + if function.comptime { + self.output.push_str("comptime "); + } + self.output.push_str("fn "); + if link { + self.output.push_str(&format!("", function.name)); + } + if color_name { + self.output.push_str(""); + self.output.push_str(&function.name); + self.output.push_str(""); + } else { + self.output.push_str(&function.name); + } + if link { + self.output.push_str(""); + } + self.render_generics(&function.generics); + self.output.push('('); + + // Split params into multiple lines if the signature will likely be too long + // to fit in one line. + let use_newlines = + function_signature_to_string(function, self.self_type.as_ref()).len() >= 90; + for (index, param) in function.params.iter().enumerate() { + if index > 0 && !use_newlines { + self.output.push_str(", "); + } + if use_newlines { + self.output.push('\n'); + self.output.push_str(&" ".repeat(4 * (indent + 1))); + } + if param.mut_ref { + self.output.push_str("&mut "); + } + self.output.push_str(¶m.name); + + if !is_self_param(param, self.self_type.as_ref()) { + self.output.push_str(": "); + self.render_type(¶m.r#type); + } + + if use_newlines { + self.output.push(','); + } + } + if use_newlines { + self.output.push('\n'); + self.output.push_str(&" ".repeat(4 * indent)); + } + self.output.push(')'); + if !matches!(function.return_type, Type::Unit) { + self.output.push_str(" -> "); + self.render_type(&function.return_type); + } + self.render_where_clause(&function.where_clause, indent); + } + + fn render_generics(&mut self, generics: &[Generic]) { + if generics.is_empty() { + return; + } + + self.output.push_str("<"); + for (index, generic) in generics.iter().enumerate() { + if index > 0 { + self.output.push_str(", "); + } + if let Some(numeric) = &generic.numeric { + self.output.push_str("let "); + self.output.push_str(&generic.name); + self.output.push_str(": "); + self.render_type(numeric); + } else { + self.output.push_str(&generic.name); + } + } + self.output.push_str(">"); + } + + fn render_where_clause(&mut self, where_clause: &[TraitConstraint], indent: usize) { + if where_clause.is_empty() { + return; + } + + self.output.push('\n'); + self.output.push_str("
"); + self.output.push_str(&" ".repeat(4 * indent)); + self.output.push_str("where\n"); + for (index, constraint) in where_clause.iter().enumerate() { + self.output.push_str(&" ".repeat(4 * (indent + 1))); + self.render_type(&constraint.r#type); + self.output.push_str(": "); + self.render_trait_bound(&constraint.bound); + if index != where_clause.len() - 1 { + self.output.push_str(",\n"); + } + } + self.output.push_str("
"); + } + + fn render_trait_bound(&mut self, bound: &TraitBound) { + self.render_id_reference(bound.trait_id, &bound.trait_name); + self.render_trait_generics(&bound.ordered_generics, &bound.named_generics); + } + + fn render_id_reference(&mut self, id: Id, name: &str) { + if let Some(ItemInfo { path: _, uri, class, visibility: ItemVisibility::Public }) = + self.id_to_info.get(&id) + { + let nesting = self.current_path.len(); + self.output.push_str(&format!( + "{name}", + "../".repeat(nesting), + uri, + )); + } else { + self.output.push_str(name); + } + } + + fn render_type(&mut self, typ: &Type) { + if let Some(self_type) = &self.self_type { + if self_type == typ { + self.output.push_str("Self"); + return; + } + } + + match typ { + Type::Unit => self.output.push_str("()"), + Type::Primitive(primitive) => { + let nesting = self.current_path.len(); + self.output.push_str(&format!( + "{}", + "../".repeat(nesting), + primitive.uri(), + primitive + )); + } + Type::Array { length, element } => { + self.output.push('['); + self.render_type(element); + self.output.push_str("; "); + self.render_type(length); + self.output.push(']'); + } + Type::Slice { element } => { + self.output.push('['); + self.render_type(element); + self.output.push(']'); + } + Type::String { length } => { + let nesting = self.current_path.len(); + let primitive = PrimitiveTypeKind::Str; + self.output.push_str(&format!( + "{}", + "../".repeat(nesting), + primitive.uri(), + primitive + )); + self.output.push_str("<"); + self.render_type(length); + self.output.push_str(">"); + } + Type::FmtString { length, element } => { + let nesting = self.current_path.len(); + let primitive = PrimitiveTypeKind::Fmtstr; + self.output.push_str(&format!( + "{}", + "../".repeat(nesting), + primitive.uri(), + primitive + )); + self.output.push_str("<"); + self.render_type(length); + self.output.push_str(", "); + self.render_type(element); + self.output.push_str(">"); + } + Type::Tuple(items) => { + self.output.push('('); + for (index, item) in items.iter().enumerate() { + if index > 0 { + self.output.push_str(", "); + } + self.render_type(item); + } + if items.len() == 1 { + self.output.push(','); + } + self.output.push(')'); + } + Type::Reference { r#type, mutable } => { + self.output.push('&'); + if *mutable { + self.output.push_str("mut "); + } + self.render_type(r#type); + } + Type::Struct { id, name, generics } => { + self.render_id_reference(*id, name); + self.render_generic_types(generics); + } + Type::TypeAlias { id, name, generics } => { + self.render_id_reference(*id, name); + self.render_generic_types(generics); + } + Type::Function { params, return_type, env, unconstrained } => { + if *unconstrained { + self.output.push_str("unconstrained "); + } + self.output.push_str("fn"); + if !matches!(env.as_ref(), &Type::Unit) { + self.output.push('['); + self.render_type(env); + self.output.push(']'); + } + self.output.push('('); + for (index, param) in params.iter().enumerate() { + if index > 0 { + self.output.push_str(", "); + } + self.render_type(param); + } + self.output.push(')'); + if !matches!(return_type.as_ref(), &Type::Unit) { + self.output.push_str(" -> "); + self.render_type(return_type); + } + } + Type::Constant(value) => { + self.output.push_str(value); + } + Type::Generic(name) => { + self.output.push_str(&escape_html(name)); + } + Type::InfixExpr { lhs, operator, rhs } => { + self.render_type(lhs); + self.output.push(' '); + self.output.push_str(operator); + self.output.push(' '); + self.render_type(rhs); + } + Type::TraitAsType { trait_id, trait_name, ordered_generics, named_generics } => { + self.output.push_str("impl "); + self.render_id_reference(*trait_id, trait_name); + self.render_trait_generics(ordered_generics, named_generics); + } + } + } + + fn type_to_string(&self, typ: &Type) -> String { + type_to_string(typ, self.self_type.as_ref()) + } + + fn render_generic_types(&mut self, generics: &[Type]) { + if generics.is_empty() { + return; + } + + self.output.push_str("<"); + for (index, generic) in generics.iter().enumerate() { + if index > 0 { + self.output.push_str(", "); + } + self.render_type(generic); + } + self.output.push_str(">"); + } + + fn render_trait_generics(&mut self, ordered: &[Type], named: &BTreeMap) { + if ordered.is_empty() && named.is_empty() { + return; + } + + self.output.push_str("<"); + let mut first = true; + for generic in ordered { + if !first { + self.output.push_str(", "); + } + first = false; + self.render_type(generic); + } + for (name, typ) in named { + if !first { + self.output.push_str(", "); + } + first = false; + self.output.push_str(name); + self.output.push_str(" = "); + self.render_type(typ); + } + self.output.push_str(">"); + } + + /// Renders the given comments, if any. + /// Markdown headers that are less or equal than `current_heading_level` will be rendered + /// as smaller headers (i.e., `###` becomes `####` if `current_heading_level` is 3) + /// to ensure proper nesting. + fn render_comments(&mut self, comments: &Option, current_heading_level: usize) { + let Some(comments) = comments else { + return; + }; + + let comments = fix_markdown(comments, current_heading_level); + let html = markdown::to_html(&comments); + self.output.push_str("
\n"); + self.output.push_str(&html); + self.output.push_str("
\n"); + } + + fn render_breadcrumbs(&mut self, last_is_link: bool) { + self.output.push_str("
"); + let mut nesting = self.current_path.len(); + self.output.push_str( + format!("{}", "../".repeat(nesting), self.workspace_name) + .as_str(), + ); + if !self.current_path.is_empty() { + self.output.push_str(" - "); + for (index, item) in self.current_path.iter().enumerate() { + if index > 0 { + self.output.push_str("::"); + } + nesting -= 1; + if !last_is_link && index == self.current_path.len() - 1 { + self.output.push_str(item); + } else { + self.output.push_str( + format!("{}", "../".repeat(nesting), item) + .as_str(), + ); + } + } + } + self.output.push_str("
\n"); + } + + fn get_all_trait_impls(&self, trait_: &Trait) -> Vec { + self.all_trait_impls + .get(&trait_.id) + .map(|impls| impls.iter().cloned().collect()) + .unwrap_or_else(|| trait_.trait_impls.clone()) + } + + fn html_start(&mut self, title: &str) { + self.html_start_with_redirect(title, None); + } + + fn html_start_with_redirect(&mut self, title: &str, redirect: Option) { + self.output.push_str("\n"); + self.output.push_str("\n"); + self.output.push_str("\n"); + self.output.push_str("\n"); + if let Some(redirect) = redirect { + self.output.push_str(&format!( + "\n", + )); + } + + let nesting = self.current_path.len(); + self.output.push_str(&format!( + "\n", + "../".repeat(nesting) + )); + self.output.push_str(&format!("{title} documentation\n")); + self.output.push_str("\n"); + self.output.push_str("\n"); + } + + fn html_end(&mut self) { + self.output.push_str("\n"); + self.output.push_str("\n"); + } + + fn main_start(&mut self) { + self.output.push_str("
\n"); + } + + fn main_end(&mut self) { + self.output.push_str("
\n"); + } + + fn sidebar_start(&mut self) { + self.output.push_str("\n"); + } + + fn h1(&mut self, text: &str) { + self.output.push_str(&format!("

{text}

\n")); + } + + fn h2(&mut self, text: &str) { + self.output.push_str(&format!("

{text}

\n")); + } + + fn h3(&mut self, text: &str) { + self.output.push_str(&format!("

{text}

\n")); + } + + fn push_file(&mut self, path: PathBuf) { + let mut full_path = PathBuf::new(); + for item in &self.current_path { + full_path = full_path.join(item); + } + + let contents = std::mem::take(&mut self.output); + let path = full_path.join(path); + self.files.push((path, contents)); + } +} + +fn get_reexports(items: &[(ItemVisibility, Item)]) -> Vec<&Reexport> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::Reexport(reexport) = item { + return Some(reexport); + } + } + None + }) + .collect() +} + +fn get_modules(items: &[(ItemVisibility, Item)]) -> Vec<&Module> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::Module(module) = item { + if module.has_public_items() { + return Some(module); + } + } + } + None + }) + .collect() +} + +fn get_structs(items: &[(ItemVisibility, Item)]) -> Vec<&Struct> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::Struct(struct_) = item { + return Some(struct_); + } + } + None + }) + .collect() +} + +fn get_traits(items: &[(ItemVisibility, Item)]) -> Vec<&Trait> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::Trait(trait_) = item { + return Some(trait_); + } + } + None + }) + .collect() +} + +fn get_type_aliases(items: &[(ItemVisibility, Item)]) -> Vec<&TypeAlias> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::TypeAlias(alias) = item { + return Some(alias); + } + } + None + }) + .collect() +} + +fn get_primitive_types(items: &[(ItemVisibility, Item)]) -> Vec<&PrimitiveType> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::PrimitiveType(primitive_type) = item { + return Some(primitive_type); + } + } + None + }) + .collect() +} + +fn get_globals(items: &[(ItemVisibility, Item)]) -> Vec<&Global> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::Global(global) = item { + return Some(global); + } + } + None + }) + .collect() +} + +fn get_functions(items: &[(ItemVisibility, Item)]) -> Vec<&Function> { + items + .iter() + .filter_map(|(visibility, item)| { + if visibility == &ItemVisibility::Public { + if let Item::Function(function) = item { + return Some(function); + } + } + None + }) + .collect() +} + +fn trait_impl_anchor(trait_impl: &TraitImpl) -> String { + let mut string = String::new(); + string.push_str("impl-"); + string.push_str(&trait_impl_trait_to_string(trait_impl)); + string.push_str("-for-"); + string.push_str(&type_to_string(&trait_impl.r#type, None)); + string +} + +fn trait_impl_trait_to_string(trait_impl: &TraitImpl) -> String { + let mut string = String::new(); + string.push_str(&trait_impl.trait_name); + if !trait_impl.trait_generics.is_empty() { + string.push_str("<"); + for (index, typ) in trait_impl.trait_generics.iter().enumerate() { + if index > 0 { + string.push_str(", "); + } + string.push_str(&type_to_string(typ, None)); + } + string.push_str(">"); + } + string +} + +fn function_signature_to_string(function: &Function, self_type: Option<&Type>) -> String { + let mut string = String::new(); + string.push_str("pub "); + if function.unconstrained { + string.push_str("unconstrained "); + } + if function.comptime { + string.push_str("comptime "); + } + string.push_str("fn "); + string.push_str(&function.name); + string.push_str(&generics_to_string(&function.generics)); + string.push('('); + for (index, param) in function.params.iter().enumerate() { + if index > 0 { + string.push_str(", "); + } + if param.mut_ref { + string.push_str("&mut "); + } + string.push_str(¶m.name); + if !is_self_param(param, self_type) { + string.push_str(": "); + string.push_str(&type_to_string(¶m.r#type, self_type)); + } + } + string.push(')'); + if !matches!(function.return_type, Type::Unit) { + string.push_str(" -> "); + string.push_str(&type_to_string(&function.return_type, self_type)); + } + string +} + +fn generics_to_string(generics: &[Generic]) -> String { + if generics.is_empty() { + return String::new(); + } + + let mut string = String::new(); + string.push('<'); + for (index, generic) in generics.iter().enumerate() { + if index > 0 { + string.push_str(", "); + } + if let Some(numeric) = &generic.numeric { + string.push_str(&format!("let {}: {}", generic.name, &type_to_string(numeric, None))); + } else { + string.push_str(&generic.name); + } + } + string.push('>'); + string +} + +fn type_to_string(typ: &Type, self_type: Option<&Type>) -> String { + if let Some(self_type) = self_type { + if self_type == typ { + return "Self".to_string(); + } + } + + match typ { + Type::Unit => "()".to_string(), + Type::Primitive(primitive) => primitive.to_string(), + Type::Array { length, element } => { + format!( + "[{}; {}]", + type_to_string(element, self_type), + type_to_string(length, self_type) + ) + } + Type::Slice { element } => format!("[{}]", type_to_string(element, self_type)), + Type::String { length } => format!("str<{}>", type_to_string(length, self_type)), + Type::FmtString { length, element } => { + format!( + "fmtstr<{}, {}>", + type_to_string(length, self_type), + type_to_string(element, self_type) + ) + } + Type::Tuple(items) => { + let items: Vec = + items.iter().map(|typ| type_to_string(typ, self_type)).collect(); + format!("({}{})", items.join(", "), if items.len() == 1 { "," } else { "" }) + } + Type::Reference { r#type, mutable } => { + if *mutable { + format!("&mut {}", type_to_string(r#type, self_type)) + } else { + format!("&{}", type_to_string(r#type, self_type)) + } + } + Type::Struct { name, generics, id: _ } | Type::TypeAlias { name, generics, id: _ } => { + let mut string = String::new(); + string.push_str(name); + if !generics.is_empty() { + let generic_strings: Vec = + generics.iter().map(|typ| type_to_string(typ, self_type)).collect(); + string.push_str(&format!("<{}>", generic_strings.join(", "))); + } + string + } + Type::Function { params, return_type, env, unconstrained } => { + let mut string = String::new(); + if *unconstrained { + string.push_str("unconstrained "); + } + string.push_str("fn"); + if !matches!(env.as_ref(), &Type::Unit) { + string.push_str(&format!("[{}]", type_to_string(env, self_type))); + } + string.push('('); + let param_strings: Vec = + params.iter().map(|typ| type_to_string(typ, self_type)).collect(); + string.push_str(¶m_strings.join(", ")); + string.push(')'); + if !matches!(return_type.as_ref(), &Type::Unit) { + string.push_str(" -> "); + string.push_str(&type_to_string(return_type, self_type)); + } + string + } + Type::Constant(value) => value.clone(), + Type::Generic(name) => escape_html(name), + Type::InfixExpr { lhs, operator, rhs } => { + format!( + "{}{}{}", + type_to_string(lhs, self_type), + operator, + type_to_string(rhs, self_type) + ) + } + Type::TraitAsType { trait_name, ordered_generics, named_generics, trait_id: _ } => { + let mut string = String::new(); + string.push_str("impl "); + string.push_str(trait_name); + if !ordered_generics.is_empty() || !named_generics.is_empty() { + string.push('<'); + let mut first = true; + for generic in ordered_generics { + if !first { + string.push_str(", "); + } + first = false; + string.push_str(&type_to_string(generic, self_type)); + } + for (name, typ) in named_generics { + if !first { + string.push_str(", "); + } + first = false; + string.push_str(name); + string.push_str(" = "); + string.push_str(&type_to_string(typ, self_type)); + } + string.push('>'); + } + string + } + } +} + +fn is_self_param(param: &FunctionParam, self_type: Option<&Type>) -> bool { + if param.name != "self" { + return false; + } + + let Some(self_type) = self_type else { + if let Type::Generic(generic) = ¶m.r#type { + return generic == "Self"; + } + return false; + }; + + if param.mut_ref { + let Type::Reference { r#type, mutable: true } = ¶m.r#type else { + return false; + }; + r#type.as_ref() == self_type + } else { + ¶m.r#type == self_type + } +} + +fn escape_html(input: &str) -> String { + input.replace('<', "<").replace('>', ">") +} diff --git a/tooling/nargo_doc/src/html/all_items.rs b/tooling/nargo_doc/src/html/all_items.rs new file mode 100644 index 00000000000..1ba8e0f52ba --- /dev/null +++ b/tooling/nargo_doc/src/html/all_items.rs @@ -0,0 +1,78 @@ +use noirc_frontend::ast::ItemVisibility; + +use crate::items::{Item, Workspace}; + +/// All items in a workspace. +/// Each field is a list of (path, name) tuples. +pub(super) struct AllItems { + pub(super) structs: Vec<(Vec, String)>, + pub(super) traits: Vec<(Vec, String)>, + pub(super) type_aliases: Vec<(Vec, String)>, + pub(super) primitive_types: Vec<(Vec, String)>, + pub(super) functions: Vec<(Vec, String)>, + pub(super) globals: Vec<(Vec, String)>, +} + +pub(super) fn compute_all_items(workspace: &Workspace) -> AllItems { + let mut all_items = AllItems { + structs: Vec::new(), + traits: Vec::new(), + type_aliases: Vec::new(), + primitive_types: Vec::new(), + globals: Vec::new(), + functions: Vec::new(), + }; + + let mut current_path = Vec::new(); + for krate in &workspace.crates { + current_path.push(krate.name.clone()); + for (visibility, item) in &krate.root_module.items { + if visibility == &ItemVisibility::Public { + gather_all_items_in_item(item, &mut current_path, &mut all_items); + } + } + current_path.pop(); + } + + all_items.structs.sort(); + all_items.traits.sort(); + all_items.type_aliases.sort(); + all_items.primitive_types.sort(); + all_items.functions.sort(); + all_items.globals.sort(); + + all_items +} + +fn gather_all_items_in_item(item: &Item, current_path: &mut Vec, all_items: &mut AllItems) { + match item { + Item::Module(module) => { + current_path.push(module.name.clone()); + for (visibility, item) in &module.items { + if visibility == &ItemVisibility::Public { + gather_all_items_in_item(item, current_path, all_items); + } + } + current_path.pop(); + } + Item::Struct(struct_) => { + all_items.structs.push((current_path.clone(), struct_.name.clone())); + } + Item::Trait(trait_) => { + all_items.traits.push((current_path.clone(), trait_.name.clone())); + } + Item::TypeAlias(type_alias) => { + all_items.type_aliases.push((current_path.clone(), type_alias.name.clone())); + } + Item::PrimitiveType(primitive_type) => { + all_items.primitive_types.push((current_path.clone(), primitive_type.kind.to_string())); + } + Item::Global(global) => { + all_items.globals.push((current_path.clone(), global.name.clone())); + } + Item::Function(function) => { + all_items.functions.push((current_path.clone(), function.name.clone())); + } + Item::Reexport(_) => {} + } +} diff --git a/tooling/nargo_doc/src/html/has_class.rs b/tooling/nargo_doc/src/html/has_class.rs new file mode 100644 index 00000000000..4ab4abdd83f --- /dev/null +++ b/tooling/nargo_doc/src/html/has_class.rs @@ -0,0 +1,54 @@ +use crate::items::{Crate, Function, Global, Module, PrimitiveType, Struct, Trait, TypeAlias}; + +/// A trait that associated a CSS class name with an item. +pub(super) trait HasClass { + fn class(&self) -> &'static str; +} + +impl HasClass for Crate { + fn class(&self) -> &'static str { + "crate" + } +} + +impl HasClass for Module { + fn class(&self) -> &'static str { + "module" + } +} + +impl HasClass for Struct { + fn class(&self) -> &'static str { + "struct" + } +} + +impl HasClass for Trait { + fn class(&self) -> &'static str { + "trait" + } +} + +impl HasClass for TypeAlias { + fn class(&self) -> &'static str { + "type" + } +} + +impl HasClass for Global { + fn class(&self) -> &'static str { + "global" + } +} + +impl HasClass for Function { + fn class(&self) -> &'static str { + "fn" + } +} + +impl HasClass for PrimitiveType { + fn class(&self) -> &'static str { + "primitive" + } +} diff --git a/tooling/nargo_doc/src/html/has_uri.rs b/tooling/nargo_doc/src/html/has_uri.rs new file mode 100644 index 00000000000..ed472c3741c --- /dev/null +++ b/tooling/nargo_doc/src/html/has_uri.rs @@ -0,0 +1,64 @@ +use crate::items::{ + Crate, Function, Global, Module, PrimitiveType, PrimitiveTypeKind, Struct, Trait, TypeAlias, +}; + +/// A trait that associates an HTML uri with an item. +/// The uri is relative to the page where the item is typically shown +/// (for example, a crate is shown in the workspace, a struct is shown in its module, etc.). +pub(super) trait HasUri { + fn uri(&self) -> String; +} + +impl HasUri for Crate { + fn uri(&self) -> String { + format!("{}/index.html", self.name) + } +} + +impl HasUri for Module { + fn uri(&self) -> String { + format!("{}/index.html", self.name) + } +} + +impl HasUri for Struct { + fn uri(&self) -> String { + format!("struct.{}.html", self.name) + } +} + +impl HasUri for Trait { + fn uri(&self) -> String { + format!("trait.{}.html", self.name) + } +} + +impl HasUri for TypeAlias { + fn uri(&self) -> String { + format!("type.{}.html", self.name) + } +} + +impl HasUri for Global { + fn uri(&self) -> String { + format!("global.{}.html", self.name) + } +} + +impl HasUri for Function { + fn uri(&self) -> String { + format!("fn.{}.html", self.name) + } +} + +impl HasUri for PrimitiveType { + fn uri(&self) -> String { + self.kind.uri() + } +} + +impl HasUri for PrimitiveTypeKind { + fn uri(&self) -> String { + format!("primitive.{self}.html") + } +} diff --git a/tooling/nargo_doc/src/html/id_to_info.rs b/tooling/nargo_doc/src/html/id_to_info.rs new file mode 100644 index 00000000000..079e35937f8 --- /dev/null +++ b/tooling/nargo_doc/src/html/id_to_info.rs @@ -0,0 +1,91 @@ +use std::collections::HashMap; + +use noirc_frontend::ast::ItemVisibility; + +use crate::{ + html::{HasClass, has_uri::HasUri}, + items::{Id, Item, Workspace}, +}; + +pub(super) struct ItemInfo { + pub(super) path: Vec, + pub(super) uri: String, + pub(super) class: &'static str, + /// Overall visibility of this item, including parent modules. + /// For example, if this is a public item inside a private module, + /// its visibility will be private. + pub(super) visibility: ItemVisibility, +} + +/// Computes an ItemInfo for every item in the workspace, indexed by its Id. +pub(super) fn compute_id_to_info(workspace: &Workspace) -> HashMap { + let mut id_to_info = HashMap::new(); + let mut path = Vec::new(); + + for krate in workspace.all_crates() { + let module = &krate.root_module; + let uri = krate.uri(); + let class = module.class(); + let visibility = ItemVisibility::Public; + id_to_info.insert(module.id, ItemInfo { path: Vec::new(), uri, class, visibility }); + + path.push(krate.name.to_string()); + + for (visibility, item) in &krate.root_module.items { + compute_id_to_info_in_item(item, *visibility, &mut id_to_info, &mut path); + } + + path.pop(); + } + + id_to_info +} + +fn compute_id_to_info_in_item( + item: &Item, + visibility: ItemVisibility, + id_to_info: &mut HashMap, + path: &mut Vec, +) { + match item { + Item::Module(module) => { + let uri = format!("{}/{}", path.join("/"), module.uri()); + let class = module.class(); + id_to_info.insert(module.id, ItemInfo { path: path.clone(), uri, class, visibility }); + + path.push(module.name.clone()); + for (item_visibility, item) in &module.items { + let visibility = visibility.min(*item_visibility); + compute_id_to_info_in_item(item, visibility, id_to_info, path); + } + path.pop(); + } + Item::Struct(struct_) => { + let uri = format!("{}/{}", path.join("/"), struct_.uri()); + let class = struct_.class(); + id_to_info.insert(struct_.id, ItemInfo { path: path.clone(), uri, class, visibility }); + } + Item::Trait(trait_) => { + let uri = format!("{}/{}", path.join("/"), trait_.uri()); + let class = trait_.class(); + id_to_info.insert(trait_.id, ItemInfo { path: path.clone(), uri, class, visibility }); + } + Item::TypeAlias(type_alias) => { + let uri = format!("{}/{}", path.join("/"), type_alias.uri()); + let class = type_alias.class(); + id_to_info + .insert(type_alias.id, ItemInfo { path: path.clone(), uri, class, visibility }); + } + Item::Function(function) => { + let uri = format!("{}/{}", path.join("/"), function.uri()); + let class = function.class(); + id_to_info.insert(function.id, ItemInfo { path: path.clone(), uri, class, visibility }); + } + Item::Global(global) => { + let uri = format!("{}/{}", path.join("/"), global.uri()); + let class = global.class(); + id_to_info.insert(global.id, ItemInfo { path: path.clone(), uri, class, visibility }); + } + Item::PrimitiveType(_) | Item::Reexport(_) => {} + } +} diff --git a/tooling/nargo_doc/src/html/markdown_utils.rs b/tooling/nargo_doc/src/html/markdown_utils.rs new file mode 100644 index 00000000000..505c475d3d9 --- /dev/null +++ b/tooling/nargo_doc/src/html/markdown_utils.rs @@ -0,0 +1,94 @@ +/// Fixes a Markdown string by: +/// - adjusting headers that exceed `current_heading_level` by making them smaller, +/// so headers in user comments aren't larger than the surrounding document's headers. +/// - ensures code blocks are properly closed. +pub(super) fn fix_markdown(markdown: &str, current_heading_level: usize) -> String { + // Track occurrences of "```" to see if the user forgot to close a code block. + // If so, we'll close it to prevent ruining the docs. + let mut open_code_comment = false; + let mut fixed_comment = String::new(); + + 'outer_loop: for line in markdown.lines() { + let trimmed_line = line.trim_start(); + + if trimmed_line.starts_with('#') { + for level in 1..=current_heading_level { + if trimmed_line.starts_with(&format!("{} ", "#".repeat(level))) { + fixed_comment.push_str(&format!( + "{} {}", + "#".repeat(current_heading_level + 1), + &trimmed_line[level + 1..] + )); + fixed_comment.push('\n'); + continue 'outer_loop; + } + } + } + + if trimmed_line.starts_with("```") { + open_code_comment = !open_code_comment; + } + + fixed_comment.push_str(line); + fixed_comment.push('\n'); + } + + if open_code_comment { + fixed_comment.push_str("```"); + fixed_comment.push('\n'); + } + + fixed_comment +} + +/// Returns a summary of the given markdown (up to the first blank line). +pub(super) fn markdown_summary(markdown: &str) -> String { + let mut string = String::new(); + for line in markdown.lines() { + if line.trim().is_empty() { + break; + } + string.push_str(line); + string.push('\n'); + } + let string = string.trim().to_string(); + // Avoid having a header as a summary + let string = string.trim_start_matches('#'); + let markdown = markdown::to_html(string); + let markdown = markdown.trim_start_matches("

"); + markdown.trim_end_matches("

").trim().to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_fix_markdown_adjusts_headers() { + let input = "# Header 1\n## Header 2\n### Header 3\n#### Header 4\nNormal text"; + let expected = "### Header 1\n### Header 2\n### Header 3\n#### Header 4\nNormal text\n"; + assert_eq!(fix_markdown(input, 2), expected); + } + + #[test] + fn test_fix_markdown_closes_code_block_one_block() { + let input = "Here is some code:\n```\nlet x = 10;\n"; + let expected = "Here is some code:\n```\nlet x = 10;\n```\n"; + assert_eq!(fix_markdown(input, 1), expected); + } + + #[test] + fn test_fix_markdown_closes_code_block_two_blocks() { + let input = "Here is some code:\n```\nlet x = 10;\n```\nMore text.\n```\nlet y = 20;\n"; + let expected = + "Here is some code:\n```\nlet x = 10;\n```\nMore text.\n```\nlet y = 20;\n```\n"; + assert_eq!(fix_markdown(input, 1), expected); + } + + #[test] + fn test_markdown_summary() { + let input = "# Title\nThis is a summary.\n\nThis part should be ignored."; + let expected = "Title\nThis is a summary."; + assert_eq!(markdown_summary(input), expected); + } +} diff --git a/tooling/nargo_doc/src/html/trait_impls.rs b/tooling/nargo_doc/src/html/trait_impls.rs new file mode 100644 index 00000000000..5e3543e5a75 --- /dev/null +++ b/tooling/nargo_doc/src/html/trait_impls.rs @@ -0,0 +1,48 @@ +use std::collections::{HashMap, HashSet}; + +use noirc_frontend::ast::ItemVisibility; + +use crate::items::{Id, Item, TraitImpl, Workspace}; + +/// Gather all trait impls in the workspace, grouped by the trait they implement. +pub(super) fn gather_all_trait_impls(workspace: &Workspace) -> HashMap> { + let mut trait_impls = HashMap::new(); + + for krate in workspace.all_crates() { + for (visibility, item) in &krate.root_module.items { + if visibility == &ItemVisibility::Public { + gather_trait_impls_in_item(item, &mut trait_impls); + } + } + } + + trait_impls +} + +fn gather_trait_impls_in_item(item: &Item, trait_impls: &mut HashMap>) { + match item { + Item::Module(module) => { + for (visibility, item) in &module.items { + if visibility == &ItemVisibility::Public { + gather_trait_impls_in_item(item, trait_impls); + } + } + } + Item::Struct(struct_) => { + for impl_ in &struct_.trait_impls { + trait_impls.entry(impl_.trait_id).or_default().insert(impl_.clone()); + } + } + Item::Trait(trait_) => { + for impl_ in &trait_.trait_impls { + trait_impls.entry(impl_.trait_id).or_default().insert(impl_.clone()); + } + } + Item::PrimitiveType(primitive_type) => { + for impl_ in &primitive_type.trait_impls { + trait_impls.entry(impl_.trait_id).or_default().insert(impl_.clone()); + } + } + Item::TypeAlias(_) | Item::Function(_) | Item::Global(_) | Item::Reexport(_) => {} + } +} diff --git a/tooling/nargo_doc/src/items.rs b/tooling/nargo_doc/src/items.rs new file mode 100644 index 00000000000..5f7cbaf6c71 --- /dev/null +++ b/tooling/nargo_doc/src/items.rs @@ -0,0 +1,439 @@ +//! Contains the data structures that represent items to be shown by the documentation generator. + +use std::collections::BTreeMap; + +use noirc_frontend::{ast::ItemVisibility, hir::def_map::ModuleId}; + +pub trait HasNameAndComments { + fn name(&self) -> String; + fn comments(&self) -> Option<&str>; +} + +pub type Id = usize; + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Workspace { + pub name: String, + /// Crates directly defined in this workspace. + pub crates: Vec, + /// All unique dependencies of `crates`. + pub dependencies: Vec, +} + +impl Workspace { + pub fn all_crates(&self) -> impl Iterator { + self.crates.iter().chain(self.dependencies.iter()) + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Crate { + pub name: String, + pub root_module: Module, + pub root_file: String, +} + +impl HasNameAndComments for Crate { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.root_module.comments() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum Item { + Module(Module), + Struct(Struct), + Trait(Trait), + TypeAlias(TypeAlias), + Function(Function), + Global(Global), + PrimitiveType(PrimitiveType), + Reexport(Reexport), +} + +impl Item { + pub fn set_name(&mut self, new_name: String) { + match self { + Item::Module(module) => module.name = new_name, + Item::Struct(struct_) => struct_.name = new_name, + Item::Trait(trait_) => trait_.name = new_name, + Item::TypeAlias(type_alias) => type_alias.name = new_name, + Item::Function(function) => function.name = new_name, + Item::Global(global) => global.name = new_name, + Item::PrimitiveType(_) => {} + Item::Reexport(reexport) => reexport.name = new_name, + } + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Module { + pub id: Id, + pub module_id: ModuleId, + pub name: String, + pub items: Vec<(ItemVisibility, Item)>, + pub comments: Option, +} + +impl Module { + pub fn has_public_items(&self) -> bool { + self.items.iter().any(|(visibility, _)| *visibility == ItemVisibility::Public) + } +} + +impl HasNameAndComments for Module { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Struct { + pub id: Id, + pub name: String, + pub generics: Vec, + /// All `pub` fields of the struct. + pub fields: Vec, + /// `true` if the struct has any private fields, besides the public ones listed in `fields`. + pub has_private_fields: bool, + pub impls: Vec, + pub trait_impls: Vec, + pub comments: Option, +} + +impl HasNameAndComments for Struct { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct StructField { + pub name: String, + pub r#type: Type, + pub comments: Option, +} + +impl HasNameAndComments for StructField { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Impl { + pub generics: Vec, + pub r#type: Type, + pub methods: Vec, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct TraitImpl { + pub generics: Vec, + pub trait_id: Id, + pub trait_name: String, + pub trait_generics: Vec, + pub r#type: Type, + pub where_clause: Vec, + pub methods: Vec, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Global { + pub id: Id, + pub name: String, + pub comptime: bool, + pub mutable: bool, + pub r#type: Type, + pub comments: Option, +} + +impl HasNameAndComments for Global { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Function { + pub id: Id, + pub unconstrained: bool, + pub comptime: bool, + pub name: String, + pub generics: Vec, + pub params: Vec, + pub return_type: Type, + pub where_clause: Vec, + pub comments: Option, +} + +impl HasNameAndComments for Function { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct FunctionParam { + pub name: String, + pub r#type: Type, + pub mut_ref: bool, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Trait { + pub id: Id, + pub name: String, + pub generics: Vec, + pub bounds: Vec, + pub where_clause: Vec, + pub associated_types: Vec, + pub associated_constants: Vec, + pub required_methods: Vec, + pub provided_methods: Vec, + pub trait_impls: Vec, + pub comments: Option, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct AssociatedType { + pub name: String, + pub bounds: Vec, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct AssociatedConstant { + pub name: String, + pub r#type: Type, +} + +impl HasNameAndComments for Trait { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct TypeAlias { + pub id: Id, + pub name: String, + pub generics: Vec, + pub r#type: Type, + pub comments: Option, +} + +impl HasNameAndComments for TypeAlias { + fn name(&self) -> String { + self.name.clone() + } + + fn comments(&self) -> Option<&str> { + self.comments.as_deref() + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Generic { + pub name: String, + pub numeric: Option, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct TraitConstraint { + pub r#type: Type, + pub bound: TraitBound, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct TraitBound { + pub trait_id: Id, + pub trait_name: String, + pub ordered_generics: Vec, + pub named_generics: BTreeMap, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum Type { + Unit, + Primitive(PrimitiveTypeKind), + Array { + length: Box, + element: Box, + }, + Slice { + element: Box, + }, + String { + length: Box, + }, + FmtString { + length: Box, + element: Box, + }, + Tuple(Vec), + Reference { + r#type: Box, + mutable: bool, + }, + Struct { + id: Id, + name: String, + generics: Vec, + }, + TypeAlias { + id: Id, + name: String, + generics: Vec, + }, + Function { + params: Vec, + return_type: Box, + env: Box, + unconstrained: bool, + }, + Constant(String), + Generic(String), + InfixExpr { + lhs: Box, + operator: String, + rhs: Box, + }, + TraitAsType { + trait_id: Id, + trait_name: String, + ordered_generics: Vec, + named_generics: BTreeMap, + }, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct PrimitiveType { + pub kind: PrimitiveTypeKind, + pub impls: Vec, + pub trait_impls: Vec, +} + +impl HasNameAndComments for PrimitiveType { + fn name(&self) -> String { + self.kind.to_string() + } + + fn comments(&self) -> Option<&str> { + None + } +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Reexport { + pub id: Id, + pub item_name: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum ItemKind { + Module, + Struct, + Trait, + TypeAlias, + Function, + Global, + PrimitiveType, + Reexport, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub enum PrimitiveTypeKind { + Bool, + U1, + U8, + U16, + U32, + U64, + U128, + I8, + I16, + I32, + I64, + Field, + Str, + Fmtstr, + Array, + Slice, + Expr, + Quoted, + Type, + TypedExpr, + TypeDefinition, + TraitConstraint, + TraitDefinition, + TraitImpl, + UnresolvedType, + FunctionDefinition, + Module, + CtString, +} + +impl std::fmt::Display for PrimitiveTypeKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let name = match self { + PrimitiveTypeKind::Bool => "bool", + PrimitiveTypeKind::U1 => "u1", + PrimitiveTypeKind::U8 => "u8", + PrimitiveTypeKind::U16 => "u16", + PrimitiveTypeKind::U32 => "u32", + PrimitiveTypeKind::U64 => "u64", + PrimitiveTypeKind::U128 => "u128", + PrimitiveTypeKind::I8 => "i8", + PrimitiveTypeKind::I16 => "i16", + PrimitiveTypeKind::I32 => "i32", + PrimitiveTypeKind::I64 => "i64", + PrimitiveTypeKind::Field => "Field", + PrimitiveTypeKind::Str => "str", + PrimitiveTypeKind::Fmtstr => "fmtstr", + PrimitiveTypeKind::Array => "array", + PrimitiveTypeKind::Slice => "slice", + PrimitiveTypeKind::Expr => "Expr", + PrimitiveTypeKind::Quoted => "Quoted", + PrimitiveTypeKind::Type => "Type", + PrimitiveTypeKind::TypedExpr => "TypedExpr", + PrimitiveTypeKind::TypeDefinition => "TypeDefinition", + PrimitiveTypeKind::TraitConstraint => "TraitConstraint", + PrimitiveTypeKind::TraitDefinition => "TraitDefinition", + PrimitiveTypeKind::TraitImpl => "TraitImpl", + PrimitiveTypeKind::UnresolvedType => "UnresolvedType", + PrimitiveTypeKind::FunctionDefinition => "FunctionDefinition", + PrimitiveTypeKind::Module => "Module", + PrimitiveTypeKind::CtString => "CtString", + }; + write!(f, "{name}") + } +} diff --git a/tooling/nargo_doc/src/lib.rs b/tooling/nargo_doc/src/lib.rs new file mode 100644 index 00000000000..41a4dd4bea1 --- /dev/null +++ b/tooling/nargo_doc/src/lib.rs @@ -0,0 +1,755 @@ +use std::collections::HashMap; + +use iter_extended::vecmap; +use noirc_driver::CrateId; +use noirc_errors::Location; +use noirc_frontend::ast::{IntegerBitSize, ItemVisibility}; +use noirc_frontend::hir::def_map::{ModuleDefId, ModuleId}; +use noirc_frontend::hir::printer::items as expand_items; +use noirc_frontend::hir_def::stmt::{HirLetStatement, HirPattern}; +use noirc_frontend::hir_def::traits::ResolvedTraitBound; +use noirc_frontend::node_interner::{FuncId, GlobalId, ReferenceId, TraitId, TypeAliasId, TypeId}; +use noirc_frontend::shared::Signedness; +use noirc_frontend::{Kind, NamedGeneric, ResolvedGeneric, TypeBinding}; +use noirc_frontend::{graph::CrateGraph, hir::def_map::DefMaps, node_interner::NodeInterner}; + +use crate::items::{ + AssociatedConstant, AssociatedType, Function, FunctionParam, Generic, Global, Id, Impl, Item, + ItemKind, Module, PrimitiveType, PrimitiveTypeKind, Reexport, Struct, StructField, Trait, + TraitBound, TraitConstraint, TraitImpl, Type, TypeAlias, +}; + +mod html; +pub mod items; +pub use html::to_html; + +/// Returns the root module in a crate. +pub fn crate_module( + crate_id: CrateId, + _crate_graph: &CrateGraph, + def_maps: &DefMaps, + interner: &NodeInterner, + ids: &mut ItemIds, +) -> Module { + let module = noirc_frontend::hir::printer::crate_to_module(crate_id, def_maps, interner); + let mut builder = DocItemBuilder::new(interner, ids); + let mut module = builder.convert_module(module); + builder.process_module_reexports(&mut module); + module +} + +struct DocItemBuilder<'a> { + interner: &'a NodeInterner, + ids: &'a mut ItemIds, + /// The minimum visibility of the current module. For example, + /// if the visibilities of parents modules are [pub, pub(crate), pub] then + /// this will be `pub(crate)`. + visibility: ItemVisibility, + /// Maps a ModuleDefId to the item it converted to. + /// This is needed because if an item is publicly exported, but the item + /// isn't publicly visible (because its parent module is private) then we'll + /// include the item directly undert the module that publicly exports it. + /// We do this by looking up the item in this map. + module_def_id_to_item: HashMap, + module_imports: HashMap>, + /// Trait constraints in scope. + /// These are set when a trait or trait impl is visited. + trait_constraints: Vec, +} + +impl<'a> DocItemBuilder<'a> { + fn new(interner: &'a NodeInterner, ids: &'a mut ItemIds) -> Self { + Self { + interner, + ids, + visibility: ItemVisibility::Public, + module_def_id_to_item: HashMap::new(), + module_imports: HashMap::new(), + trait_constraints: Vec::new(), + } + } +} + +struct ConvertedItem { + item: Item, + // This is the maximum visibility the item has considering it's nested + // in modules. For example, in `pub(crate) mod a { pub struct B {} }`, + // struct B will have `pub(crate)` visibility here as it can't be publicly + // reached. + visibility: ItemVisibility, +} + +/// Maps an ItemId to a unique identifier. +pub type ItemIds = HashMap; + +/// Uniquely identifies an item. +/// This is done by using a type's name, location in source code and kind. +/// With macros, two types might end up being defined in the same location but they will likely +/// have different names. +/// This is just a temporary solution until we have a better way to uniquely identify items +/// across crates. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ItemId { + pub location: Location, + pub kind: ItemKind, + pub name: String, +} + +impl DocItemBuilder<'_> { + fn convert_item(&mut self, item: expand_items::Item, visibility: ItemVisibility) -> Item { + let module_def_id = if let expand_items::Item::PrimitiveType(..) = item { + None + } else { + Some(item.module_def_id()) + }; + let converted_item = match item { + expand_items::Item::Module(module) => { + let old_visibility = self.visibility; + self.visibility = old_visibility.min(visibility); + + let module = self.convert_module(module); + + self.visibility = old_visibility; + + Item::Module(module) + } + expand_items::Item::DataType(item_data_type) => { + let type_id = item_data_type.id; + let shared_data_type = self.interner.get_type(type_id); + let data_type = shared_data_type.borrow(); + if data_type.is_enum() { + panic!("Enums are not supported yet"); + } + let comments = self.doc_comments(ReferenceId::Type(type_id)); + let mut has_private_fields = false; + let fields = data_type + .get_fields_as_written() + .unwrap() + .iter() + .enumerate() + .filter(|(_, field)| { + if field.visibility == ItemVisibility::Public { + true + } else { + has_private_fields = true; + false + } + }) + .map(|(index, field)| { + let comments = self.doc_comments(ReferenceId::StructMember(type_id, index)); + let r#type = self.convert_type(&field.typ); + StructField { name: field.name.to_string(), r#type, comments } + }) + .collect(); + let generics = vecmap(&data_type.generics, |generic| self.convert_generic(generic)); + let impls = vecmap(item_data_type.impls, |impl_| self.convert_impl(impl_)); + let trait_impls = + vecmap(item_data_type.trait_impls, |impl_| self.convert_trait_impl(impl_)); + let id = self.get_type_id(type_id); + Item::Struct(Struct { + id, + name: data_type.name.to_string(), + generics, + fields, + has_private_fields, + impls, + trait_impls, + comments, + }) + } + expand_items::Item::Trait(item_trait) => { + let trait_id = item_trait.id; + let trait_ = self.interner.get_trait(trait_id); + let name = trait_.name.to_string(); + let comments = self.doc_comments(ReferenceId::Trait(trait_id)); + let generics = vecmap(&trait_.generics, |generic| self.convert_generic(generic)); + let where_clause = vecmap(&trait_.where_clause, |constraint| { + self.convert_trait_constraint(constraint) + }); + self.trait_constraints = where_clause.clone(); + let mut required_methods = Vec::new(); + let mut provided_methods = Vec::new(); + for func_id in &item_trait.methods { + let has_body = self.interner.function(func_id).try_as_expr().is_some(); + let function = self.convert_function(*func_id); + if has_body { + provided_methods.push(function); + } else { + required_methods.push(function); + } + } + self.trait_constraints.clear(); + let trait_impls = vecmap(item_trait.trait_impls, |trait_impl| { + self.convert_trait_impl(trait_impl) + }); + let parents = vecmap(&trait_.trait_bounds, |bound| self.convert_trait_bound(bound)); + + let mut associated_types = Vec::new(); + let mut associated_constants = Vec::new(); + + for associated_type in &trait_.associated_types { + let name = associated_type.name.to_string(); + + if let Kind::Numeric(numeric_type) = associated_type.kind() { + let r#type = self.convert_type(&numeric_type); + associated_constants.push(AssociatedConstant { name, r#type }); + } else { + let bounds = if let Some(trait_bounds) = + trait_.associated_type_bounds.get(associated_type.name.as_str()) + { + vecmap(trait_bounds, |trait_bound| { + self.convert_trait_bound(trait_bound) + }) + } else { + Vec::new() + }; + associated_types.push(AssociatedType { name, bounds }); + } + } + + let id = self.get_trait_id(trait_id); + Item::Trait(Trait { + id, + name, + generics, + bounds: parents, + where_clause, + associated_types, + associated_constants, + comments, + required_methods, + provided_methods, + trait_impls, + }) + } + expand_items::Item::TypeAlias(type_alias_id) => { + let type_alias = self.interner.get_type_alias(type_alias_id); + let type_alias = type_alias.borrow(); + let name = type_alias.name.to_string(); + let r#type = self.convert_type(&type_alias.typ); + let comments = self.doc_comments(ReferenceId::Alias(type_alias_id)); + let generics = + vecmap(&type_alias.generics, |generic| self.convert_generic(generic)); + let id = self.get_type_alias_id(type_alias_id); + Item::TypeAlias(TypeAlias { id, name, comments, r#type, generics }) + } + expand_items::Item::PrimitiveType(primitive_type) => { + let kind = match &primitive_type.typ { + noirc_frontend::Type::String(..) => PrimitiveTypeKind::Str, + noirc_frontend::Type::FmtString(..) => PrimitiveTypeKind::Fmtstr, + noirc_frontend::Type::Array(..) => PrimitiveTypeKind::Array, + noirc_frontend::Type::Slice(..) => PrimitiveTypeKind::Slice, + _ => { + let Type::Primitive(kind) = self.convert_type(&primitive_type.typ) else { + panic!("Expected primitive type"); + }; + kind + } + }; + let impls = vecmap(primitive_type.impls, |impl_| self.convert_impl(impl_)); + let trait_impls = + vecmap(primitive_type.trait_impls, |impl_| self.convert_trait_impl(impl_)); + Item::PrimitiveType(PrimitiveType { kind, impls, trait_impls }) + } + expand_items::Item::Global(global_id) => { + let global_info = self.interner.get_global(global_id); + let definition_id = global_info.definition_id; + let definition = self.interner.definition(definition_id); + let comptime = matches!( + self.interner.get_global_let_statement(global_id), + Some(HirLetStatement { comptime: true, .. }) + ); + let mutable = definition.mutable; + let name = global_info.ident.to_string(); + let typ = self.interner.definition_type(definition_id); + let r#type = self.convert_type(&typ); + let comments = self.doc_comments(ReferenceId::Global(global_id)); + let id = self.get_global_id(global_id); + Item::Global(Global { id, name, comments, comptime, mutable, r#type }) + } + expand_items::Item::Function(func_id) => Item::Function(self.convert_function(func_id)), + }; + if let Some(module_def_id) = module_def_id { + self.module_def_id_to_item.insert( + module_def_id, + ConvertedItem { item: converted_item.clone(), visibility: self.visibility }, + ); + } + converted_item + } + + fn convert_module(&mut self, module: expand_items::Module) -> Module { + let name = module.name.unwrap_or_default(); + let comments = self.doc_comments(ReferenceId::Module(module.id)); + let items = module + .items + .into_iter() + .map(|(visibility, item)| (visibility, self.convert_item(item, visibility))) + .collect(); + self.module_imports.insert(module.id, module.imports); + let id = self.get_module_id(module.id); + Module { id, module_id: module.id, name, comments, items } + } + + fn convert_impl(&mut self, impl_: expand_items::Impl) -> Impl { + let generics = vecmap(impl_.generics, |(name, kind)| { + let numeric = self.kind_to_numeric(kind); + Generic { name, numeric } + }); + let r#type = self.convert_type(&impl_.typ); + let methods = impl_ + .methods + .into_iter() + .filter(|(visibility, _)| visibility == &ItemVisibility::Public) + .map(|(_, func_id)| self.convert_function(func_id)) + .collect(); + Impl { generics, r#type, methods } + } + + fn convert_trait_impl(&mut self, item_trait_impl: expand_items::TraitImpl) -> TraitImpl { + let trait_impl_id = item_trait_impl.id; + + let trait_impl = self.interner.get_trait_implementation(trait_impl_id); + let trait_impl = trait_impl.borrow(); + + let generics = vecmap(item_trait_impl.generics, |(name, kind)| { + let numeric = self.kind_to_numeric(kind); + Generic { name, numeric } + }); + let where_clause = vecmap(&trait_impl.where_clause, |constraint| { + self.convert_trait_constraint(constraint) + }); + self.trait_constraints = where_clause.clone(); + let methods = vecmap(item_trait_impl.methods, |func_id| self.convert_function(func_id)); + self.trait_constraints.clear(); + + let trait_ = self.interner.get_trait(trait_impl.trait_id); + let trait_name = trait_.name.to_string(); + let trait_id = self.get_trait_id(trait_.id); + let trait_generics = vecmap(&trait_impl.trait_generics, |typ| self.convert_type(typ)); + let r#type = self.convert_type(&trait_impl.typ); + TraitImpl { r#type, generics, methods, trait_id, trait_name, trait_generics, where_clause } + } + + fn convert_trait_constraint( + &mut self, + constraint: &noirc_frontend::hir_def::traits::TraitConstraint, + ) -> TraitConstraint { + let r#type = self.convert_type(&constraint.typ); + let bound = self.convert_trait_bound(&constraint.trait_bound); + TraitConstraint { r#type, bound } + } + + fn convert_trait_bound(&mut self, trait_bound: &ResolvedTraitBound) -> TraitBound { + let trait_ = self.interner.get_trait(trait_bound.trait_id); + let trait_name = trait_.name.to_string(); + let trait_id = self.get_trait_id(trait_.id); + let (ordered_generics, named_generics) = + self.convert_trait_generics(&trait_bound.trait_generics); + TraitBound { trait_id, trait_name, ordered_generics, named_generics } + } + + fn convert_type(&mut self, typ: &noirc_frontend::Type) -> Type { + match typ { + noirc_frontend::Type::Unit => Type::Unit, + noirc_frontend::Type::FieldElement => Type::Primitive(PrimitiveTypeKind::Field), + noirc_frontend::Type::Bool => Type::Primitive(PrimitiveTypeKind::Bool), + noirc_frontend::Type::Integer(signedness, bit_size) => match signedness { + Signedness::Unsigned => match bit_size { + IntegerBitSize::One => Type::Primitive(PrimitiveTypeKind::U1), + IntegerBitSize::Eight => Type::Primitive(PrimitiveTypeKind::U8), + IntegerBitSize::Sixteen => Type::Primitive(PrimitiveTypeKind::U16), + IntegerBitSize::ThirtyTwo => Type::Primitive(PrimitiveTypeKind::U32), + IntegerBitSize::SixtyFour => Type::Primitive(PrimitiveTypeKind::U64), + IntegerBitSize::HundredTwentyEight => Type::Primitive(PrimitiveTypeKind::U128), + }, + Signedness::Signed => match bit_size { + IntegerBitSize::One => panic!("There is no signed 1-bit integer"), + IntegerBitSize::Eight => Type::Primitive(PrimitiveTypeKind::I8), + IntegerBitSize::Sixteen => Type::Primitive(PrimitiveTypeKind::I16), + IntegerBitSize::ThirtyTwo => Type::Primitive(PrimitiveTypeKind::I32), + IntegerBitSize::SixtyFour => Type::Primitive(PrimitiveTypeKind::I64), + IntegerBitSize::HundredTwentyEight => { + panic!("There is no signed 128-bit integer") + } + }, + }, + noirc_frontend::Type::Quoted(quoted) => match quoted { + noirc_frontend::QuotedType::Expr => Type::Primitive(PrimitiveTypeKind::Expr), + noirc_frontend::QuotedType::Quoted => Type::Primitive(PrimitiveTypeKind::Quoted), + noirc_frontend::QuotedType::Type => Type::Primitive(PrimitiveTypeKind::Type), + noirc_frontend::QuotedType::TypedExpr => { + Type::Primitive(PrimitiveTypeKind::TypedExpr) + } + noirc_frontend::QuotedType::TypeDefinition => { + Type::Primitive(PrimitiveTypeKind::TypeDefinition) + } + noirc_frontend::QuotedType::TraitConstraint => { + Type::Primitive(PrimitiveTypeKind::TraitConstraint) + } + noirc_frontend::QuotedType::TraitDefinition => { + Type::Primitive(PrimitiveTypeKind::TraitDefinition) + } + noirc_frontend::QuotedType::TraitImpl => { + Type::Primitive(PrimitiveTypeKind::TraitImpl) + } + noirc_frontend::QuotedType::UnresolvedType => { + Type::Primitive(PrimitiveTypeKind::UnresolvedType) + } + noirc_frontend::QuotedType::FunctionDefinition => { + Type::Primitive(PrimitiveTypeKind::FunctionDefinition) + } + noirc_frontend::QuotedType::Module => Type::Primitive(PrimitiveTypeKind::Module), + noirc_frontend::QuotedType::CtString => { + Type::Primitive(PrimitiveTypeKind::CtString) + } + }, + noirc_frontend::Type::Array(length, element) => Type::Array { + length: Box::new(self.convert_type(length)), + element: Box::new(self.convert_type(element)), + }, + noirc_frontend::Type::Slice(element) => { + Type::Slice { element: Box::new(self.convert_type(element)) } + } + noirc_frontend::Type::String(length) => { + Type::String { length: Box::new(self.convert_type(length)) } + } + noirc_frontend::Type::FmtString(length, element) => Type::FmtString { + length: Box::new(self.convert_type(length)), + element: Box::new(self.convert_type(element)), + }, + noirc_frontend::Type::Tuple(types) => { + Type::Tuple(vecmap(types, |typ| self.convert_type(typ))) + } + noirc_frontend::Type::DataType(data_type, generics) => { + let data_type = data_type.borrow(); + if data_type.is_enum() { + panic!("Enums are not supported yet"); + } + let id = self.get_type_id(data_type.id); + let name = data_type.name.to_string(); + let generics = vecmap(generics, |typ| self.convert_type(typ)); + Type::Struct { id, name, generics } + } + noirc_frontend::Type::Alias(type_alias, generics) => { + let type_alias = type_alias.borrow(); + let id = self.get_type_alias_id(type_alias.id); + let name = type_alias.name.to_string(); + let generics = vecmap(generics, |typ| self.convert_type(typ)); + Type::TypeAlias { id, name, generics } + } + noirc_frontend::Type::TypeVariable(type_var) => { + if let TypeBinding::Bound(typ) = &*type_var.borrow() { + self.convert_type(typ) + } else { + Type::Generic("_".to_string()) + } + } + noirc_frontend::Type::TraitAsType(trait_id, _, trait_generics) => { + let trait_ = self.interner.get_trait(*trait_id); + let trait_id = self.get_trait_id(trait_.id); + let trait_name = trait_.name.to_string(); + let (ordered_generics, named_generics) = + self.convert_trait_generics(trait_generics); + Type::TraitAsType { trait_id, trait_name, ordered_generics, named_generics } + } + noirc_frontend::Type::NamedGeneric(NamedGeneric { name, type_var, .. }) => { + if let TypeBinding::Bound(typ) = &*type_var.borrow() { + self.convert_type(typ) + } else { + Type::Generic(name.to_string()) + } + } + noirc_frontend::Type::CheckedCast { from: _, to } => self.convert_type(to), + noirc_frontend::Type::Function(args, return_type, env, unconstrained) => { + Type::Function { + params: vecmap(args, |typ| self.convert_type(typ)), + return_type: Box::new(self.convert_type(return_type)), + env: Box::new(self.convert_type(env)), + unconstrained: *unconstrained, + } + } + noirc_frontend::Type::Reference(typ, mutable) => { + Type::Reference { r#type: Box::new(self.convert_type(typ)), mutable: *mutable } + } + noirc_frontend::Type::Constant(signed_field, _kind) => { + Type::Constant(signed_field.to_string()) + } + noirc_frontend::Type::InfixExpr(lhs, operator, rhs, _) => Type::InfixExpr { + lhs: Box::new(self.convert_type(lhs)), + operator: operator.to_string(), + rhs: Box::new(self.convert_type(rhs)), + }, + noirc_frontend::Type::Forall(..) => { + panic!("Should not need to print Type::Forall") + } + noirc_frontend::Type::Error => { + panic!("Should not need to print Type::Error") + } + } + } + + fn convert_trait_generics( + &mut self, + trait_generics: &noirc_frontend::hir::type_check::generics::TraitGenerics, + ) -> (Vec, std::collections::BTreeMap) { + let ordered_generics = vecmap(&trait_generics.ordered, |typ| self.convert_type(typ)); + let named_generics = trait_generics + .named + .iter() + .filter(|named_type| { + if let noirc_frontend::Type::NamedGeneric(NamedGeneric { implicit: true, .. }) = + &named_type.typ + { + return false; + } + true + }) + .map(|named_type| (named_type.name.to_string(), self.convert_type(&named_type.typ))) + .collect(); + (ordered_generics, named_generics) + } + + fn convert_function(&mut self, func_id: FuncId) -> Function { + let modifiers = self.interner.function_modifiers(&func_id); + let func_meta = self.interner.function_meta(&func_id); + let unconstrained = modifiers.is_unconstrained; + let comptime = modifiers.is_comptime; + let name = modifiers.name.to_string(); + let comments = self.doc_comments(ReferenceId::Function(func_id)); + let generics = vecmap(&func_meta.direct_generics, |generic| self.convert_generic(generic)); + let params = vecmap(func_meta.parameters.iter(), |(pattern, typ, _visibility)| { + let is_self = self.pattern_is_self(pattern); + + // `&mut self` is represented as a mutable reference type, not as a mutable pattern + let mut mut_ref = false; + let name = if is_self && matches!(typ, noirc_frontend::Type::Reference(..)) { + mut_ref = true; + "self".to_string() + } else { + self.pattern_to_string(pattern) + }; + + let r#type = self.convert_type(typ); + FunctionParam { name, r#type, mut_ref } + }); + let return_type = self.convert_type(func_meta.return_type()); + let trait_constraints = func_meta.trait_constraints.clone(); + let where_clause = + vecmap(trait_constraints, |constraint| self.convert_trait_constraint(&constraint)); + + // Only keep trait constraints if they aren't already present because they exist in the + // parent trait/impl. + let where_clause = where_clause + .iter() + .filter(|trait_constraint| !self.trait_constraints.contains(trait_constraint)) + .cloned() + .collect::>(); + + let id = self.get_function_id(func_id); + + Function { + id, + name, + comments, + unconstrained, + comptime, + generics, + params, + return_type, + where_clause, + } + } + + fn convert_generic(&mut self, generic: &ResolvedGeneric) -> Generic { + let numeric = self.kind_to_numeric(generic.kind()); + let name = generic.name.to_string(); + Generic { name, numeric } + } + + fn kind_to_numeric(&mut self, kind: Kind) -> Option { + match kind { + Kind::Any | Kind::Normal | Kind::IntegerOrField | Kind::Integer => None, + Kind::Numeric(typ) => Some(self.convert_type(&typ)), + } + } + + /// Goes over a module's imports. If an import is a re-export of a private item, + /// the item is added to the module's items. + fn process_module_reexports(&mut self, module: &mut Module) { + let imports = self.module_imports.remove(&module.module_id).unwrap(); + for import in imports { + if import.visibility == ItemVisibility::Private { + continue; + } + + if let Some(converted_item) = self.module_def_id_to_item.get(&import.id) { + if converted_item.visibility < import.visibility { + // This is a re-export of a private item. The private item won't show up in + // its module docs (because it's private) so it's included directly under + // the module that re-exports it (this is how rustdoc works too). + let mut item = converted_item.item.clone(); + item.set_name(import.name.to_string()); + + module.items.push((import.visibility, item)); + continue; + } + } + + // This is an internal or external re-export + let id = self.get_module_def_id(import.id); + module.items.push(( + import.visibility, + Item::Reexport(Reexport { + id, + item_name: self.get_module_def_id_name(import.id), + name: import.name.to_string(), + }), + )); + } + + for (_visibility, item) in &mut module.items { + if let Item::Module(sub_module) = item { + self.process_module_reexports(sub_module); + } + } + } + + fn doc_comments(&self, id: ReferenceId) -> Option { + self.interner.doc_comments(id).map(|comments| comments.join("\n").trim().to_string()) + } + + fn pattern_to_string(&self, pattern: &HirPattern) -> String { + match pattern { + HirPattern::Identifier(ident) => { + let definition = self.interner.definition(ident.id); + definition.name.to_string() + } + HirPattern::Mutable(inner_pattern, _) => self.pattern_to_string(inner_pattern), + HirPattern::Tuple(..) | HirPattern::Struct(..) => "_".to_string(), + } + } + + fn pattern_is_self(&self, pattern: &HirPattern) -> bool { + match pattern { + HirPattern::Identifier(ident) => { + let definition = self.interner.definition(ident.id); + definition.name == "self" + } + HirPattern::Mutable(pattern, _) => self.pattern_is_self(pattern), + HirPattern::Tuple(..) | HirPattern::Struct(..) => false, + } + } + + fn get_module_def_id_name(&mut self, id: ModuleDefId) -> String { + match id { + ModuleDefId::ModuleId(module_id) => { + let attributes = self.interner.try_module_attributes(module_id); + attributes.map(|attributes| &attributes.name).cloned().unwrap_or_else(String::new) + } + ModuleDefId::FunctionId(func_id) => self.interner.function_name(&func_id).to_string(), + ModuleDefId::TypeId(type_id) => { + let data_type = self.interner.get_type(type_id); + let data_type = data_type.borrow(); + data_type.name.to_string() + } + ModuleDefId::TypeAliasId(type_alias_id) => { + let type_alias = self.interner.get_type_alias(type_alias_id); + let type_alias = type_alias.borrow(); + type_alias.name.to_string() + } + ModuleDefId::TraitId(trait_id) => { + let trait_ = self.interner.get_trait(trait_id); + trait_.name.to_string() + } + ModuleDefId::TraitAssociatedTypeId(id) => { + let associated_type = self.interner.get_trait_associated_type(id); + associated_type.name.to_string() + } + ModuleDefId::GlobalId(global_id) => { + let global_info = self.interner.get_global(global_id); + global_info.ident.to_string() + } + } + } + + fn get_module_def_id(&mut self, id: ModuleDefId) -> Id { + match id { + ModuleDefId::ModuleId(id) => self.get_module_id(id), + ModuleDefId::FunctionId(id) => self.get_function_id(id), + ModuleDefId::TypeId(id) => self.get_type_id(id), + ModuleDefId::TypeAliasId(id) => self.get_type_alias_id(id), + ModuleDefId::TraitId(id) => self.get_trait_id(id), + ModuleDefId::GlobalId(id) => self.get_global_id(id), + ModuleDefId::TraitAssociatedTypeId(_) => { + panic!("Trait associated types cannot be re-exported") + } + } + } + + fn get_module_id(&mut self, id: ModuleId) -> Id { + let module = self.interner.module_attributes(id); + let location = module.location; + let name = module.name.clone(); + let kind = ItemKind::Module; + let id = ItemId { location, kind, name }; + self.get_id(id) + } + + fn get_type_id(&mut self, id: TypeId) -> Id { + let data_type = self.interner.get_type(id); + let data_type = data_type.borrow(); + let location = data_type.location; + let name = data_type.name.to_string(); + let kind = ItemKind::Struct; + let id = ItemId { location, kind, name }; + self.get_id(id) + } + + fn get_trait_id(&mut self, id: TraitId) -> Id { + let trait_ = self.interner.get_trait(id); + let location = trait_.location; + let name = trait_.name.to_string(); + let kind = ItemKind::Trait; + let id = ItemId { location, kind, name }; + self.get_id(id) + } + + fn get_type_alias_id(&mut self, id: TypeAliasId) -> Id { + let alias = self.interner.get_type_alias(id); + let alias = alias.borrow(); + let location = alias.location; + let name = alias.name.to_string(); + let kind = ItemKind::TypeAlias; + let id = ItemId { location, kind, name }; + self.get_id(id) + } + + fn get_function_id(&mut self, id: FuncId) -> Id { + let func_meta = self.interner.function_meta(&id); + let name = self.interner.function_name(&id).to_owned(); + let location = func_meta.location; + let kind = ItemKind::Function; + let id = ItemId { location, kind, name }; + self.get_id(id) + } + + fn get_global_id(&mut self, id: GlobalId) -> Id { + let global_info = self.interner.get_global(id); + let location = global_info.location; + let name = global_info.ident.to_string(); + let kind = ItemKind::Global; + let id = ItemId { location, kind, name }; + self.get_id(id) + } + + fn get_id(&mut self, key: ItemId) -> Id { + if let Some(existing_id) = self.ids.get(&key) { + *existing_id + } else { + let new_id = self.ids.len(); + self.ids.insert(key, new_id); + new_id + } + } +} diff --git a/tooling/nargo_doc/src/styles.css b/tooling/nargo_doc/src/styles.css new file mode 100644 index 00000000000..47c21694fe9 --- /dev/null +++ b/tooling/nargo_doc/src/styles.css @@ -0,0 +1,198 @@ +:root { + --main-color: black; + --code-color: #f5f5f5; + --link-color: #3873ad; + --header-border-color: #ddd; + --crate-color: var(--link-color); + --module-color: var(--link-color); + --struct-color: #ad378a; + --trait-color: #6e4fc9; + --type-color: var(--struct-color); + --global-color: var(--link-color); + --fn-color: #ad7c37; + --primitive-color: var(--struct-color); + --sidebar-color: #f5f5f5; + --comment-color: #8e908c; +} + +body { + font-family: "Fira Sans", Arial, NanumBarunGothic, sans-serif; + font-weight: 500; + margin: 0; + display: flex; + flex-direction: row; + flex-wrap: nowrap; +} + +main { + padding: 28px 15px 40px 45px; + max-width: 960px; + position: relative; + flex-grow: 1; +} + +a { + color: var(--link-color); + text-decoration: none; +} + +pre { + padding: 14px; + background-color: var(--code-color); +} + +code { + font-family: "Source Code Pro",monospace; + text-wrap: auto; + white-space: pre-wrap; +} + +.code-header { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +h1, h2 { + line-height: 1.25; + padding-top: 3px; + padding-bottom: 9px; +} + +h1, h2, h3, h4 { + margin: 25px 0 15px 0; +} + +h2 { + font-size: 1.375rem; + border-bottom: 1px solid var(--header-border-color); +} + +ul { + list-style-type: none; + width: 100%; + margin: 0; + padding: 0; +} + +.item-list { + display: table; +} + +.item-list>li { + display: table-row; + width: 100%; + line-height: 2em; +} + +.item-list>li>.item-name { + width: 33%; + display: table-cell; + padding-right: 1.25rem; +} + +.item-list>li>.item-description { + display: table-cell; + font-family: "Source Serif 4", NanumBarunGothic, serif; +} + +.comments { + font-family: "Source Serif 4", NanumBarunGothic, serif; +} + +.comments code, .item-description code { + background-color: var(--code-color); + border-radius: 6px; + padding: 0 0.125em; + font-weight: 400; + font-size: 0.94em; +} + +.crate { + color: var(--crate-color); +} + +.module { + color: var(--module-color); +} + +.struct { + color: var(--struct-color); +} + +.trait { + color: var(--trait-color); +} + +.type { + color: var(--type-color); +} + +.global { + color: var(--global-color); +} + +.fn { + color: var(--fn-color); +} + +.primitive { + color: var(--primitive-color); +} + +.padded-methods { + padding-left: 2em; +} + +.padded-description { + padding-left: 2em; +} + +.sidebar { + scrollbar-width: thin; + background-color: var(--sidebar-color); + font-size: 0.875rem; + overflow-y: scroll; + overscroll-behavior: contain; + position: sticky; + height: 100vh; + top: 0; + left: 0; + width: 306px; + padding: 16px 15px 10px 24px; +} + +.sidebar h1 { + border-bottom: 0; + margin: 0; +} + +.sidebar h2 { + border-bottom: 0; + margin: 0; + margin-top: 30px; +} + +.sidebar h1 a, .sidebar h2 a { + color: var(--main-color); +} + +.sidebar h3 { + border-bottom: 0; + margin: 0; + margin-top: 15px; + margin-bottom: 15px; +} + +.sidebar li { + line-height: 2em; +} + +.comment { + color: var(--comment-color); +} + +.where-clause { + font-size: 0.875rem; + white-space: pre-wrap; +} \ No newline at end of file