Files
marine/crates/it-parser/src/embedder.rs

62 lines
1.7 KiB
Rust
Raw Normal View History

2020-06-04 12:46:12 +03:00
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2021-03-12 20:04:47 +03:00
use super::custom::ITCustomSection;
2021-05-10 12:51:22 +03:00
use super::errors::ITParserError;
2021-03-12 20:04:47 +03:00
use crate::Result;
2020-06-04 12:46:12 +03:00
use walrus::ModuleConfig;
2021-05-10 12:51:22 +03:00
use wasmer_it::{
2020-07-07 23:11:42 +03:00
ast::Interfaces,
2020-06-04 12:46:12 +03:00
decoders::wat::{parse, Buffer},
};
2021-05-10 12:51:22 +03:00
use wasmer_it::ToBytes;
2020-06-04 12:46:12 +03:00
2021-03-16 13:51:59 +03:00
use std::path::Path;
2020-06-04 12:46:12 +03:00
2021-05-10 12:51:22 +03:00
/// Embed provided IT to a Wasm file by path.
pub fn embed_text_it<I, O>(in_wasm_path: I, out_wasm_path: O, it: &str) -> Result<()>
2021-03-16 13:51:59 +03:00
where
I: AsRef<Path>,
O: AsRef<Path>,
{
2020-07-09 15:55:58 +03:00
let module = ModuleConfig::new()
2021-03-16 13:51:59 +03:00
.parse_file(in_wasm_path)
2021-05-10 12:51:22 +03:00
.map_err(ITParserError::CorruptedWasmFile)?;
2020-06-04 12:46:12 +03:00
2021-05-10 12:51:22 +03:00
let buffer = Buffer::new(it)?;
2020-06-04 12:46:12 +03:00
let ast = parse(&buffer)?;
2021-05-10 12:51:22 +03:00
let mut module = embed_it(module, &ast);
2020-06-04 12:46:12 +03:00
module
2021-03-16 13:51:59 +03:00
.emit_wasm_file(out_wasm_path)
2021-05-10 12:51:22 +03:00
.map_err(ITParserError::WasmEmitError)?;
2020-06-04 12:46:12 +03:00
Ok(())
}
2020-07-07 23:11:42 +03:00
2021-05-10 12:51:22 +03:00
/// Embed provided IT to a Wasm module.
pub fn embed_it(mut wasm_module: walrus::Module, interfaces: &Interfaces<'_>) -> walrus::Module {
2020-07-07 23:11:42 +03:00
let mut bytes = vec![];
2020-07-09 15:55:58 +03:00
// TODO: think about possible errors here
interfaces.to_bytes(&mut bytes).unwrap();
2020-07-07 23:11:42 +03:00
2021-03-12 20:04:47 +03:00
let custom = ITCustomSection(bytes);
2020-07-09 15:55:58 +03:00
wasm_module.customs.add(custom);
2020-07-07 23:11:42 +03:00
2020-07-09 15:55:58 +03:00
wasm_module
2020-07-07 23:11:42 +03:00
}