hyperlight_component_util/
util.rs

1/*
2Copyright 2025 The Hyperlight Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15 */
16
17//! General utilities for bindgen macros
18use crate::etypes;
19
20/// Read and parse a WIT type encapsulated in a wasm file from the
21/// given filename, relative to the cargo manifest directory.
22pub fn read_wit_type_from_file<R, F: FnMut(String, &etypes::Component) -> R>(
23    filename: impl AsRef<std::ffi::OsStr>,
24    mut cb: F,
25) -> R {
26    let path = std::path::Path::new(&filename);
27    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
28    let manifest_dir = std::path::Path::new(&manifest_dir);
29    let path = manifest_dir.join(path);
30
31    let bytes = std::fs::read(path).unwrap();
32    let i = wasmparser::Parser::new(0).parse_all(&bytes);
33    let ct = crate::component::read_component_single_exported_type(i);
34
35    // because of the two-level encapsulation scheme, we need to look
36    // for the single export of the component type that we just read
37    if !ct.uvars.is_empty()
38        || !ct.imports.is_empty()
39        || !ct.instance.evars.is_empty()
40        || ct.instance.unqualified.exports.len() != 1
41    {
42        panic!("malformed component type container for wit type");
43    };
44    let export = &ct.instance.unqualified.exports[0];
45    use etypes::ExternDesc;
46    let ExternDesc::Component(ct) = &export.desc else {
47        panic!("malformed component type container: does not contain component type");
48    };
49    log::debug!("hcm: considering component type {:?}", ct);
50    cb(export.kebab_name.to_string(), ct)
51}
52
53/// Deal with `$HYPERLIGHT_COMPONENT_MACRO_DEBUG`: if it is present,
54/// save the given token stream (representing the result of
55/// macroexpansion) to the debug file and include that file instead of
56/// directly returning the given token stream.
57pub fn emit_decls(decls: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
58    if let Ok(dbg_out) = std::env::var("HYPERLIGHT_COMPONENT_MACRO_DEBUG") {
59        if let Ok(file) = syn::parse2(decls.clone()) {
60            std::fs::write(&dbg_out, prettyplease::unparse(&file)).unwrap();
61        } else {
62            let decls = format!("{}", &decls);
63            std::fs::write(&dbg_out, &decls).unwrap();
64        }
65        quote::quote! { include!(#dbg_out); }
66    } else {
67        decls
68    }
69}