Debian Codegraph @

src/parsing/bitfield_field.rs

raw symbols SCIP
1 use std::str::FromStr;
2
3 use proc_macro2::TokenStream;
4 use syn::Token;
5 use syn::parse::{Parse, ParseStream};
6
7 use crate::create_syn_error;
8
9 /// Represents a field in a bitfield struct.
10 #[derive(Clone)]
11 pub(crate) struct BitfieldField {
12 /// The name of the field.
13 pub(crate) name: syn::Ident,
14 /// The type of the field.
15 pub(crate) ty: syn::Type,
16 /// The visibility of the field.
17 pub(crate) vis: Option<syn::Visibility>,
18 /// The number of bits the field occupies.
19 pub(crate) bits: u8,
20 /// The offset of the field.
21 pub(crate) offset: u8,
22 /// The default value of the field as a token stream. This allows us to
23 /// insert the default value in any token stream without complicated
24 /// conversions or parsing.
25 pub(crate) default_value_tokens: Option<TokenStream>,
26 /// Whether the field is unsigned.
27 pub(crate) unsigned: bool,
28 /// Whether the field is padding.
29 pub(crate) padding: bool,
30 /// The access of the field.
31 pub(crate) access: FieldAccess,
32 /// The type of the field.
33 pub(crate) field_type: FieldType,
34 /// Whether the field is ignored.
35 pub(crate) ignore: bool,
36 }
37
38 /// Represents the type of field.
39 #[derive(Clone, PartialEq)]
40 pub(crate) enum FieldType {
41 IntegerFieldType,
42 CustomFieldType,
43 }
44
45 /// Represents the `#[bits]` attribute.
46 #[derive(Clone)]
47 pub(crate) struct BitsAttribute {
48 pub(crate) bits: Option<u8>,
49 pub(crate) default_value_expr: Option<syn::Expr>,
50 pub(crate) access: Option<FieldAccess>,
51 pub(crate) ignore: bool,
52 }
53
54 /// Represents the access of a field.
55 #[derive(Clone, PartialEq)]
56 pub(crate) enum FieldAccess {
57 /// The field is read-only.
58 ReadOnly,
59 /// The field is write-only.
60 WriteOnly,
61 /// The field is read-write.
62 ReadWrite,
63 /// The field is inaccessible.
64 None,
65 }
66
67 impl FromStr for FieldAccess {
68 type Err = ();
69
70 fn from_str(s: &str) -> Result<Self, Self::Err> {
71 match s.to_ascii_lowercase().as_str() {
72 "ro" => Ok(FieldAccess::ReadOnly),
73 "wo" => Ok(FieldAccess::WriteOnly),
74 "rw" => Ok(FieldAccess::ReadWrite),
75 "none" => Ok(FieldAccess::None),
76 _ => Err(()),
77 }
78 }
79 }
80
81 impl Parse for BitsAttribute {
82 /// Parser a field with the '#[bits]' attribute.
83 fn parse(input: ParseStream) -> syn::Result<Self> {
84 let mut bitfield_attribute_args =
85 BitsAttribute { bits: None, default_value_expr: None, access: None, ignore: false };
86
87 // First check for the number of bits.
88 if input.peek(syn::LitInt) {
89 let num_bits = match input.parse::<syn::LitInt>() {
90 Ok(lit_int) => lit_int.base10_parse::<u8>()?,
91 Err(_) => {
92 return Err(syn::Error::new(input.span(), "Unable to parse field bits"));
93 }
94 };
95
96 // Move to the next argument.
97 if !input.is_empty() {
98 <Token![,]>::parse(input)?;
99 }
100
101 bitfield_attribute_args.bits = Some(num_bits)
102 };
103
104 // Parse the remaining arguments which is in the form of `[key] = [val]`.
105 while !input.is_empty() {
106 // Parse the argument key.
107 let arg_ident = syn::Ident::parse(input)?;
108
109 // Move to the key part of the argument.
110 <Token![=]>::parse(input)?;
111
112 match arg_ident.to_string().as_str() {
113 "default" => {
114 let default_value_tokens = match input.parse::<syn::Expr>() {
115 Ok(expr) => expr,
116 Err(_) => {
117 return Err(syn::Error::new(
118 input.span(),
119 "Unable to parse default value",
120 ));
121 }
122 };
123 bitfield_attribute_args.default_value_expr = Some(default_value_tokens);
124 }
125 "access" => {
126 let access_str = match input.parse::<syn::Ident>() {
127 Ok(ident) => ident.to_string(),
128 Err(_) => {
129 return Err(syn::Error::new(
130 input.span(),
131 "Unable to parse access value, expected 'ro', 'wo', 'rw', or 'none'",
132 ));
133 }
134 };
135 let access = match FieldAccess::from_str(&access_str) {
136 Ok(access) => access,
137 Err(_) => {
138 return Err(syn::Error::new(
139 input.span(),
140 "Unable to parse access value, expected 'ro', 'wo', 'rw', or 'none'",
141 ));
142 }
143 };
144 bitfield_attribute_args.access = Some(access);
145 }
146 "ignore" => {
147 bitfield_attribute_args.ignore = match input.parse::<syn::LitBool>() {
148 Ok(val) => val.value,
149 Err(err) => {
150 return Err(create_syn_error(
151 input.span(),
152 format!(
153 "Failed to parse the 'ignore' arg '{}', must be either 'true' or 'false'.",
154 err
155 ),
156 ));
157 }
158 };
159 }
160 _ => {}
161 }
162
163 // Move to the next argument.
164 if !input.is_empty() {
165 <Token![,]>::parse(input)?;
166 }
167 }
168
169 Ok(bitfield_attribute_args)
170 }
171 }
172
173 #[cfg(test)]
174 mod tests {
175 use quote::quote;
176
177 use super::*;
178
179 #[test]
180 fn parse_bits_attributes() {
181 let args = quote!(8);
182 let args = syn::parse2::<BitsAttribute>(args).unwrap();
183
184 assert_eq!(args.bits, Some(8));
185 }
186
187 #[test]
188 fn parse_bits_attributes_no_bits() {
189 let args = quote!();
190 let args = syn::parse2::<BitsAttribute>(args).unwrap();
191
192 assert_eq!(args.bits, None);
193 }
194 }