marine_it_parser/
embedder.rs

1/*
2 * Copyright 2020 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use super::custom::ITCustomSection;
18use super::errors::ITParserError;
19use crate::ParserResult;
20
21use walrus::ModuleConfig;
22use wasmer_it::ast::Interfaces;
23use wasmer_it::decoders::wat::parse;
24use wasmer_it::decoders::wat::Buffer;
25use wasmer_it::ToBytes;
26
27use std::path::Path;
28
29/// Embed provided IT to a Wasm file by path.
30pub fn embed_text_it<I, O>(in_wasm_path: I, out_wasm_path: O, it: &str) -> ParserResult<()>
31where
32    I: AsRef<Path>,
33    O: AsRef<Path>,
34{
35    let module = ModuleConfig::new()
36        .parse_file(in_wasm_path)
37        .map_err(ITParserError::CorruptedWasmFile)?;
38
39    let buffer = Buffer::new(it)?;
40    let ast = parse(&buffer)?;
41
42    let mut module = embed_it(module, &ast);
43    module
44        .emit_wasm_file(out_wasm_path)
45        .map_err(ITParserError::WasmEmitError)?;
46
47    Ok(())
48}
49
50/// Embed provided IT to a Wasm module.
51pub fn embed_it(mut wasm_module: walrus::Module, interfaces: &Interfaces<'_>) -> walrus::Module {
52    let mut bytes = vec![];
53    // TODO: think about possible errors here
54    interfaces.to_bytes(&mut bytes).unwrap();
55
56    let custom = ITCustomSection(bytes);
57    wasm_module.customs.add(custom);
58
59    wasm_module
60}