Skip to main content

emc230x_macros/
lib.rs

1// Copyright (c) 2024 Jake Swensen
2// SPDX-License-Identifier: MPL-2.0
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8use darling::FromDeriveInput;
9use proc_macro::{self, TokenStream};
10use quote::quote;
11use syn::{parse_macro_input, DeriveInput};
12
13#[derive(Debug, Default, FromDeriveInput)]
14#[darling(attributes(register), forward_attrs(allow, doc, cfg))]
15struct RegisterAddressMacroArgs {
16    address: u8,
17    default: u8,
18}
19
20#[proc_macro_derive(RegisterAddress, attributes(register))]
21pub fn derive_register_address(input: TokenStream) -> TokenStream {
22    let input = parse_macro_input!(input);
23    let args = RegisterAddressMacroArgs::from_derive_input(&input).expect("Invalid arguments");
24    let DeriveInput { ident, .. } = input;
25
26    let default_value = args.default;
27    let address_value = args.address;
28    let address = quote! {
29        const ADDRESS: u8 = #address_value;
30    };
31
32    let output = quote! {
33        impl RegisterAddress for #ident {
34            #address
35        }
36
37        impl Default for #ident {
38            fn default() -> Self {
39                Self(#default_value)
40            }
41        }
42
43        impl From<#ident> for u8 {
44            fn from(val: #ident) -> u8 {
45                val.0
46            }
47        }
48
49        impl From<u8> for #ident {
50            fn from(val: u8) -> Self {
51                Self(val)
52            }
53        }
54    };
55
56    output.into()
57}
58
59#[derive(Debug, Default, FromDeriveInput)]
60#[darling(attributes(register), forward_attrs(allow, doc, cfg))]
61struct RegisterFanMacroArgs {
62    offset: u8,
63    default: u8,
64}
65
66#[proc_macro_derive(RegisterOffset, attributes(register))]
67pub fn derive_register_offset(input: TokenStream) -> TokenStream {
68    let input = parse_macro_input!(input);
69    let args = RegisterFanMacroArgs::from_derive_input(&input).expect("Invalid arguments");
70    let DeriveInput { ident, .. } = input;
71
72    let default_value = args.default;
73    let offset_value = args.offset;
74    let offset = quote! {
75        const OFFSET: u8 = #offset_value;
76    };
77
78    let output = quote! {
79        impl RegisterOffset for #ident {
80            #offset
81        }
82
83        impl Default for #ident {
84            fn default() -> Self {
85                Self(#default_value)
86            }
87        }
88
89        impl From<#ident> for u8 {
90            fn from(val: #ident) -> u8 {
91                val.0
92            }
93        }
94
95        impl From<u8> for #ident {
96            fn from(val: u8) -> Self {
97                Self(val)
98            }
99        }
100    };
101
102    output.into()
103}