marine_macro_impl/
utils.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
17#[macro_export]
18/// Crates new syn::Ident with the given string and new call span
19macro_rules! new_ident {
20    ($string: expr) => {
21        syn::Ident::new(&$string, proc_macro2::Span::call_site())
22    };
23}
24
25#[macro_export]
26macro_rules! prepare_global_data {
27    ($mtype: ident, $self: ident, $name: expr, $data: ident, $data_size: ident, $global_static_name: ident, $section_name: ident) => {
28        // TODO: change serialization protocol
29        let mtype = $crate::export_ast_types::SDKAst::$mtype($self.clone().into());
30        let $data = serde_json::to_vec(&mtype).unwrap();
31        let $data_size = $data.len();
32        let $data = syn::LitByteStr::new(&$data, proc_macro2::Span::call_site());
33
34        let $global_static_name = $crate::new_ident!(format!(
35            "{}{}",
36            $crate::token_stream_generator::GENERATED_GLOBAL_PREFIX,
37            $name.replace(".", "_"),
38        ));
39        let $section_name = format!(
40            "{}{}",
41            $crate::token_stream_generator::GENERATED_SECTION_PREFIX,
42            $name.replace(".", "_"),
43        );
44    };
45}
46
47#[macro_export]
48macro_rules! syn_error {
49    ($span:expr, $message:expr) => {
50        Err(syn::Error::new($span, $message))
51    };
52}
53
54/// Calculate record size in an internal serialized view.
55pub fn get_record_size<'a>(
56    fields: impl Iterator<Item = &'a crate::parsed_type::ParsedType>,
57) -> usize {
58    use crate::parsed_type::ParsedType;
59
60    let mut size = 0;
61
62    for field in fields {
63        size += match field {
64            ParsedType::U8(_) | ParsedType::I8(_) | ParsedType::Boolean(_) => 1,
65            ParsedType::U16(_) | ParsedType::I16(_) => 2,
66            ParsedType::U32(_) | ParsedType::I32(_) | ParsedType::F32(_) => 4,
67            ParsedType::U64(_) | ParsedType::I64(_) | ParsedType::F64(_) => 8,
68            ParsedType::Record(..) => 4,
69            ParsedType::Vector(..) | ParsedType::Utf8Str(_) | ParsedType::Utf8String(_) => 2 * 4,
70        };
71    }
72
73    size
74}
75
76pub(crate) fn prepare_ident(str: String) -> String {
77    str.chars()
78        .map(|c| match c {
79            '<' => '_',
80            '&' => '_',
81            '>' => '_',
82            c => c,
83        })
84        .collect()
85}