aboutsummaryrefslogtreecommitdiff
path: root/src/backends/rust/types.rs
blob: 5b1767ddfbbfde06de90e821679d9b6531ab1b50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// Copyright 2023 Google LLC
//
// 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
//
//     https://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.

//! Utility functions for dealing with Rust integer types.

use crate::analyzer::ast as analyzer_ast;
use crate::{ast, lint};
use quote::{format_ident, quote};

/// A Rust integer type such as `u8`.
#[derive(Copy, Clone)]
pub struct Integer {
    pub width: usize,
}

impl Integer {
    /// Get the Rust integer type for the given bit width.
    ///
    /// This will round up the size to the nearest Rust integer size.
    /// PDL supports integers up to 64 bit, so it is an error to call
    /// this with a width larger than 64.
    pub fn new(width: usize) -> Integer {
        for integer_width in [8, 16, 32, 64] {
            if width <= integer_width {
                return Integer { width: integer_width };
            }
        }
        panic!("Cannot construct Integer with width: {width}")
    }
}

impl quote::ToTokens for Integer {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let t: syn::Type = syn::parse_str(&format!("u{}", self.width))
            .expect("Could not parse integer, unsupported width?");
        t.to_tokens(tokens);
    }
}

pub fn rust_type(field: &analyzer_ast::Field) -> proc_macro2::TokenStream {
    match &field.desc {
        ast::FieldDesc::Scalar { width, .. } => {
            let field_type = Integer::new(*width);
            quote!(#field_type)
        }
        ast::FieldDesc::Typedef { type_id, .. } => {
            let field_type = format_ident!("{type_id}");
            quote!(#field_type)
        }
        ast::FieldDesc::Array { width: Some(width), size: Some(size), .. } => {
            let field_type = Integer::new(*width);
            let size = proc_macro2::Literal::usize_unsuffixed(*size);
            quote!([#field_type; #size])
        }
        ast::FieldDesc::Array { width: Some(width), size: None, .. } => {
            let field_type = Integer::new(*width);
            quote!(Vec<#field_type>)
        }
        ast::FieldDesc::Array { type_id: Some(type_id), size: Some(size), .. } => {
            let field_type = format_ident!("{type_id}");
            let size = proc_macro2::Literal::usize_unsuffixed(*size);
            quote!([#field_type; #size])
        }
        ast::FieldDesc::Array { type_id: Some(type_id), size: None, .. } => {
            let field_type = format_ident!("{type_id}");
            quote!(Vec<#field_type>)
        }
        //ast::Field::Size { .. } | ast::Field::Count { .. } => quote!(),
        _ => todo!("{field:?}"),
    }
}

pub fn rust_borrow(
    field: &analyzer_ast::Field,
    scope: &lint::Scope<'_>,
) -> proc_macro2::TokenStream {
    match &field.desc {
        ast::FieldDesc::Scalar { .. } => quote!(),
        ast::FieldDesc::Typedef { type_id, .. } => match &scope.typedef[type_id].desc {
            ast::DeclDesc::Enum { .. } => quote!(),
            ast::DeclDesc::Struct { .. } => quote!(&),
            ast::DeclDesc::CustomField { .. } => quote!(),
            desc => unreachable!("unexpected declaration: {desc:?}"),
        },
        ast::FieldDesc::Array { .. } => quote!(&),
        _ => todo!(),
    }
}

/// Suffix for `Buf::get_*` and `BufMut::put_*` methods when reading a
/// value with the given `width`.
fn endianness_suffix(endianness: ast::EndiannessValue, width: usize) -> &'static str {
    if width > 8 && endianness == ast::EndiannessValue::LittleEndian {
        "_le"
    } else {
        ""
    }
}

/// Parse an unsigned integer with the given `width`.
///
/// The generated code requires that `span` is a mutable `bytes::Buf`
/// value.
pub fn get_uint(
    endianness: ast::EndiannessValue,
    width: usize,
    span: &proc_macro2::Ident,
) -> proc_macro2::TokenStream {
    let suffix = endianness_suffix(endianness, width);
    let value_type = Integer::new(width);
    if value_type.width == width {
        let get_u = format_ident!("get_u{}{}", value_type.width, suffix);
        quote! {
            #span.get_mut().#get_u()
        }
    } else {
        let get_uint = format_ident!("get_uint{}", suffix);
        let value_nbytes = proc_macro2::Literal::usize_unsuffixed(width / 8);
        let cast = (value_type.width < 64).then(|| quote!(as #value_type));
        quote! {
            #span.get_mut().#get_uint(#value_nbytes) #cast
        }
    }
}

/// Write an unsigned integer `value` to `span`.
///
/// The generated code requires that `span` is a mutable
/// `bytes::BufMut` value.
pub fn put_uint(
    endianness: ast::EndiannessValue,
    value: &proc_macro2::TokenStream,
    width: usize,
    span: &proc_macro2::Ident,
) -> proc_macro2::TokenStream {
    let suffix = endianness_suffix(endianness, width);
    let value_type = Integer::new(width);
    if value_type.width == width {
        let put_u = format_ident!("put_u{}{}", width, suffix);
        quote! {
            #span.#put_u(#value)
        }
    } else {
        let put_uint = format_ident!("put_uint{}", suffix);
        let value_nbytes = proc_macro2::Literal::usize_unsuffixed(width / 8);
        let cast = (value_type.width < 64).then(|| quote!(as u64));
        quote! {
            #span.#put_uint(#value #cast, #value_nbytes)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_integer_new() {
        assert_eq!(Integer::new(0).width, 8);
        assert_eq!(Integer::new(8).width, 8);
        assert_eq!(Integer::new(9).width, 16);
        assert_eq!(Integer::new(64).width, 64);
    }

    #[test]
    #[should_panic]
    fn test_integer_new_panics_on_large_width() {
        Integer::new(65);
    }
}