Skip to content

Commit c086c49

Browse files
committed
feature(frontend): parse AccountComponentMetadata in the frontend
and pass it through the pipeline.
1 parent 80c769a commit c086c49

File tree

15 files changed

+1353
-1227
lines changed

15 files changed

+1353
-1227
lines changed

frontend/wasm/src/code_translator/tests.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ fn check_op(wat_op: &str, expected_ir: expect_test::ExpectFile) {
2424
)"#,
2525
);
2626
let wasm = wat::parse_str(wat).unwrap();
27-
let world_ref = translate(&wasm, &WasmTranslationConfig::default(), context.clone())
27+
let output = translate(&wasm, &WasmTranslationConfig::default(), context.clone())
2828
.map_err(|e| {
2929
if let Some(labels) = e.labels() {
3030
for label in labels {
@@ -36,9 +36,9 @@ fn check_op(wat_op: &str, expected_ir: expect_test::ExpectFile) {
3636
})
3737
.unwrap();
3838

39-
let world = world_ref.borrow();
39+
let component = output.component.borrow();
4040
let mut w = String::new();
41-
world
41+
component
4242
.as_operation()
4343
.prewalk(|op: &Operation| {
4444
if let Some(_function) = op.downcast_ref::<builtin::Function>() {

frontend/wasm/src/component/build_ir.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use midenc_session::{diagnostics::Report, Session};
66
use super::{translator::ComponentTranslator, ComponentTypesBuilder, ParsedRootComponent};
77
use crate::{
88
component::ComponentParser, error::WasmResult, supported_component_model_features,
9-
WasmTranslationConfig,
9+
FrontendOutput, WasmTranslationConfig,
1010
};
1111

1212
fn parse<'data>(
@@ -28,7 +28,7 @@ pub fn translate_component(
2828
wasm: &[u8],
2929
config: &WasmTranslationConfig,
3030
context: Rc<Context>,
31-
) -> WasmResult<midenc_hir::dialects::builtin::ComponentRef> {
31+
) -> WasmResult<FrontendOutput> {
3232
let (mut component_types_builder, mut parsed_root_component) =
3333
parse(config, wasm, context.session())?;
3434
let dialect = context.get_or_register_dialect::<BuiltinDialect>();

frontend/wasm/src/component/parser.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,10 @@ impl<'a, 'data> ComponentParser<'a, 'data> {
434434
// debug.
435435
other => {
436436
self.validator.payload(&other).into_diagnostic()?;
437-
unsupported_diag!(&self.session.diagnostics, "unsupported section {other:?}");
437+
unsupported_diag!(
438+
&self.session.diagnostics,
439+
"unsupported component section {other:?}"
440+
);
438441
}
439442
}
440443

@@ -606,12 +609,16 @@ impl<'a, 'data> ComponentParser<'a, 'data> {
606609
// module and actual function translation is deferred until this
607610
// entire process has completed.
608611
self.validator.module_section(&range).into_diagnostic()?;
609-
let parsed_module = ModuleEnvironment::new(
612+
let module_environment = ModuleEnvironment::new(
610613
self.config,
611614
self.validator,
612615
self.types.module_types_builder_mut(),
613-
)
614-
.parse(parser, &component[range.start..range.end], &self.session.diagnostics)?;
616+
);
617+
let parsed_module = module_environment.parse(
618+
parser,
619+
&component[range.start..range.end],
620+
&self.session.diagnostics,
621+
)?;
615622
let static_idx = self.static_modules.push(parsed_module);
616623
self.result.initializers.push(LocalInitializer::ModuleStatic(static_idx));
617624
// Set a fallback name for the newly added parsed module to be used if

frontend/wasm/src/component/translator.rs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use cranelift_entity::PrimaryMap;
44
use midenc_hir::{
55
self as hir2,
66
diagnostics::Report,
7-
dialects::builtin::{self, ComponentBuilder, ComponentRef, ModuleBuilder, World, WorldBuilder},
7+
dialects::builtin::{self, ComponentBuilder, ModuleBuilder, World, WorldBuilder},
88
interner::Symbol,
99
Abi, BuilderExt, Context, FunctionIdent, FunctionType, FxHashMap, Ident, SourceSpan,
1010
};
@@ -32,7 +32,7 @@ use crate::{
3232
module_translation_state::ModuleTranslationState,
3333
types::{EntityIndex, FuncIndex},
3434
},
35-
unsupported_diag, WasmTranslationConfig,
35+
unsupported_diag, FrontendOutput, WasmTranslationConfig,
3636
};
3737

3838
/// A translator from the linearized Wasm component model to the Miden IR component
@@ -100,14 +100,30 @@ impl<'a> ComponentTranslator<'a> {
100100
mut self,
101101
root_component: &'a ParsedComponent,
102102
types: &mut ComponentTypesBuilder,
103-
) -> WasmResult<ComponentRef> {
103+
) -> WasmResult<FrontendOutput> {
104104
let mut frame = ComponentFrame::new(root_component.types_ref(), FxHashMap::default());
105105

106106
for init in &root_component.initializers {
107107
self.initializer(&mut frame, types, init)?;
108108
}
109109

110-
Ok(self.result.component)
110+
let mut account_component_metadata_bytes_vec: Vec<Vec<u8>> = self
111+
.nested_modules
112+
.into_iter()
113+
.flat_map(|t| t.1.account_component_metadata_bytes.map(|slice| slice.to_vec()))
114+
.collect();
115+
assert_eq!(
116+
account_component_metadata_bytes_vec.len(),
117+
1,
118+
"expected only one core Wasm module to have account component metadata section",
119+
);
120+
let account_component_metadata_bytes = account_component_metadata_bytes_vec.remove(0);
121+
122+
let output = FrontendOutput {
123+
component: self.result.component,
124+
account_component_metadata_bytes: Some(account_component_metadata_bytes),
125+
};
126+
Ok(output)
111127
}
112128

113129
fn initializer(

frontend/wasm/src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,29 @@ use wasmparser::WasmFeatures;
2929

3030
pub use self::{config::*, error::WasmError};
3131

32+
/// The output of the frontend Wasm translation stage
33+
pub struct FrontendOutput {
34+
/// The IR component translated from the Wasm
35+
pub component: builtin::ComponentRef,
36+
/// The serialized AccountComponentMetadata (name, description, storage layout, etc.)
37+
pub account_component_metadata_bytes: Option<Vec<u8>>,
38+
}
39+
3240
/// Translate a valid Wasm core module or Wasm Component Model binary into Miden
3341
/// IR Component
3442
pub fn translate(
3543
wasm: &[u8],
3644
config: &WasmTranslationConfig,
3745
context: Rc<Context>,
38-
) -> WasmResult<builtin::ComponentRef> {
46+
) -> WasmResult<FrontendOutput> {
3947
if wasm[4..8] == [0x01, 0x00, 0x00, 0x00] {
4048
// Wasm core module
4149
// see https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
42-
translate_module_as_component(wasm, config, context)
50+
let component = translate_module_as_component(wasm, config, context)?;
51+
Ok(FrontendOutput {
52+
component,
53+
account_component_metadata_bytes: None,
54+
})
4355
} else {
4456
translate_component(wasm, config, context)
4557
}

frontend/wasm/src/module/module_env.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ pub struct ParsedModule<'data> {
7474
/// When we're parsing the code section this will be incremented so we know
7575
/// which function is currently being defined.
7676
code_index: u32,
77+
78+
/// The serialized AccountComponentMetadata (name, description, storage layout, etc.)
79+
pub account_component_metadata_bytes: Option<&'data [u8]>,
7780
}
7881

7982
/// Contains function data: byte code and its offset in the module.
@@ -208,13 +211,24 @@ impl<'a, 'data> ModuleEnvironment<'a, 'data> {
208211
log::warn!("failed to parse name section {:?}", e);
209212
}
210213
}
211-
Payload::CustomSection(s) => self.dwarf_section(&s),
214+
Payload::CustomSection(s) if s.name().starts_with(".debug_") => self.dwarf_section(&s),
215+
Payload::CustomSection(s) if s.name() == "miden_account_component_metadata" => {
216+
self.result.account_component_metadata_bytes = Some(s.data());
217+
}
218+
Payload::CustomSection { .. } => {
219+
// ignore any other custom sections
220+
}
221+
212222
// It's expected that validation will probably reject other
213223
// payloads such as `UnknownSection` or those related to the
214224
// component model.
215225
other => {
216226
self.validator.payload(&other).into_diagnostic()?;
217-
unsupported_diag!(diagnostics, "wasm error: unsupported section {:?}", other);
227+
unsupported_diag!(
228+
diagnostics,
229+
"wasm error: unsupported module section {:?}",
230+
other
231+
);
218232
}
219233
}
220234
Ok(())
@@ -716,9 +730,6 @@ impl<'a, 'data> ModuleEnvironment<'a, 'data> {
716730

717731
fn dwarf_section(&mut self, section: &CustomSectionReader<'data>) {
718732
let name = section.name();
719-
if !name.starts_with(".debug_") {
720-
return;
721-
}
722733
if !self.config.generate_native_debuginfo && !self.config.parse_wasm_debuginfo {
723734
self.result.has_unparsed_debuginfo = true;
724735
return;

midenc-compile/src/stages/assemble.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ fn build_package(mast: MastArtifact, outputs: &CodegenOutput, session: &Session)
8686
}
8787
}
8888

89+
todo!("store outputs.account_component_metadata to the Package");
90+
8991
miden_mast_package::Package {
9092
name,
9193
mast,

midenc-compile/src/stages/codegen.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ pub struct CodegenOutput {
1818
pub component: Arc<MasmComponent>,
1919
pub link_libraries: Vec<Arc<Library>>,
2020
pub link_packages: BTreeMap<Symbol, Arc<Package>>,
21+
/// The serialized AccountComponentMetadata (name, description, storage layout, etc.)
22+
pub account_component_metadata_bytes: Option<Vec<u8>>,
2123
}
2224

2325
/// Perform code generation on the possibly-linked output of previous stages
@@ -76,6 +78,7 @@ impl Stage for CodegenStage {
7678
component: Arc::from(masm_component),
7779
link_libraries,
7880
link_packages,
81+
account_component_metadata_bytes: linker_output.account_component_metadata_bytes,
7982
})
8083
}
8184
}

midenc-compile/src/stages/link.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use alloc::{borrow::ToOwned, collections::BTreeMap, sync::Arc, vec::Vec};
22

3+
use midenc_frontend_wasm::FrontendOutput;
34
use midenc_hir::{interner::Symbol, BuilderExt, OpBuilder, SourceSpan};
45
#[cfg(feature = "std")]
56
use midenc_session::Path;
@@ -16,6 +17,8 @@ pub struct LinkOutput {
1617
pub world: builtin::WorldRef,
1718
/// The IR component which is the primary input being compiled
1819
pub component: builtin::ComponentRef,
20+
/// The serialized AccountComponentMetadata (name, description, storage layout, etc.)
21+
pub account_component_metadata_bytes: Option<Vec<u8>>,
1922
/// The set of Miden Assembly sources to be provided to the assembler to satisfy link-time
2023
/// dependencies
2124
pub masm: Vec<Arc<miden_assembly::ast::Module>>,
@@ -109,7 +112,10 @@ impl Stage for LinkStage {
109112
// Parse and translate the component WebAssembly using the constructed World
110113
let component_wasm =
111114
component_wasm.ok_or_else(|| Report::msg("expected at least one wasm input"))?;
112-
let component = match component_wasm {
115+
let FrontendOutput {
116+
component,
117+
account_component_metadata_bytes,
118+
} = match component_wasm {
113119
#[cfg(feature = "std")]
114120
InputType::Real(path) => parse_hir_from_wasm_file(&path, world, context.clone())?,
115121
#[cfg(not(feature = "std"))]
@@ -138,6 +144,7 @@ impl Stage for LinkStage {
138144
Ok(LinkOutput {
139145
world,
140146
component,
147+
account_component_metadata_bytes,
141148
masm,
142149
mast,
143150
packages,
@@ -150,7 +157,7 @@ fn parse_hir_from_wasm_file(
150157
path: &Path,
151158
world: builtin::WorldRef,
152159
context: Rc<Context>,
153-
) -> CompilerResult<builtin::ComponentRef> {
160+
) -> CompilerResult<FrontendOutput> {
154161
use std::io::Read;
155162

156163
log::debug!("parsing hir from wasm at {}", path.display());
@@ -172,12 +179,12 @@ fn parse_hir_from_wasm_bytes(
172179
bytes: &[u8],
173180
context: Rc<Context>,
174181
config: &wasm::WasmTranslationConfig,
175-
) -> CompilerResult<builtin::ComponentRef> {
176-
let component = wasm::translate(bytes, config, context.clone())?;
182+
) -> CompilerResult<FrontendOutput> {
183+
let outpub = wasm::translate(bytes, config, context.clone())?;
177184
log::debug!(
178185
"parsed hir component from wasm bytes with first module name: {}",
179-
component.borrow().id()
186+
outpub.component.borrow().id()
180187
);
181188

182-
Ok(component)
189+
Ok(outpub)
183190
}

sdk/base-macros/src/account_component_metadata.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,6 @@ impl AccountComponentMetadataBuilder {
3535
}
3636
}
3737

38-
pub fn name(&self) -> String {
39-
self.name.clone()
40-
}
41-
4238
pub fn build(self) -> AccountComponentMetadata {
4339
AccountComponentMetadata::new(
4440
self.name,

0 commit comments

Comments
 (0)