fce_wit_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::WITParserError;
19use crate::Result;
20
21use walrus::ModuleConfig;
22use wasmer_wit::{
23    ast::Interfaces,
24    decoders::wat::{parse, Buffer},
25};
26use wasmer_wit::ToBytes;
27
28use std::path::Path;
29
30/// Embed provided WIT to a Wasm file by path.
31pub fn embed_text_wit<I, O>(in_wasm_path: I, out_wasm_path: O, wit: &str) -> Result<()>
32where
33    I: AsRef<Path>,
34    O: AsRef<Path>,
35{
36    let module = ModuleConfig::new()
37        .parse_file(in_wasm_path)
38        .map_err(WITParserError::CorruptedWasmFile)?;
39
40    let buffer = Buffer::new(wit)?;
41    let ast = parse(&buffer)?;
42
43    let mut module = embed_wit(module, &ast);
44    module
45        .emit_wasm_file(out_wasm_path)
46        .map_err(WITParserError::WasmEmitError)?;
47
48    Ok(())
49}
50
51/// Embed provided WIT to a Wasm module.
52pub fn embed_wit(mut wasm_module: walrus::Module, interfaces: &Interfaces<'_>) -> walrus::Module {
53    let mut bytes = vec![];
54    // TODO: think about possible errors here
55    interfaces.to_bytes(&mut bytes).unwrap();
56
57    let custom = ITCustomSection(bytes);
58    wasm_module.customs.add(custom);
59
60    wasm_module
61}