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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright 2020 Branan Riley <me@branan.info>

//! Support macros for Cntrlr

#![deny(missing_docs)]

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse::{Error as ParseError, Parse, ParseStream, Result},
    parse_macro_input,
    punctuated::Punctuated,
    spanned::Spanned,
    token::Comma,
    FnArg, Ident, ItemFn, ItemUse, Pat, ReturnType, Type,
};

struct IdentList {
    boards: Punctuated<Ident, Comma>,
}

impl Parse for IdentList {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(IdentList {
            boards: input.parse_terminated(Ident::parse)?,
        })
    }
}

/// Add a function to the prelude
///
/// This macro generates the appropriate attributes for a function to
/// be added to the Cntrlr prelude.
#[proc_macro_attribute]
pub fn prelude_fn(args: TokenStream, input: TokenStream) -> TokenStream {
    let input_use = parse_macro_input!(input as ItemUse);
    let boards = parse_macro_input!(args as IdentList);

    let cfgs = boards
        .boards
        .iter()
        .map(|board| {
            let board_name = format!("{}", board);
            quote!(board = #board_name)
        })
        .collect::<Vec<_>>();

    quote!(
        #[cfg(any(#(#cfgs),*, doc))]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(any(#(#cfgs),*))))]
        #input_use
    )
    .into()
}

/// Add a board function to a module
///
/// This macro generates an implementation of the marked function,
/// which defers to the appropriate board implementation based on
/// compile-time configuration.
#[proc_macro_attribute]
pub fn board_fn(args: TokenStream, input: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(input as ItemFn);
    let attrs = &input_fn.attrs;
    let vis = &input_fn.vis;
    let sig = &input_fn.sig;
    let fn_name = &sig.ident;
    let boards = parse_macro_input!(args as IdentList);
    let module = &boards.boards[0];

    let cfgs = boards
        .boards
        .iter()
        .skip(1)
        .map(|board| {
            let board_name = format!("{}", board);
            quote!(board = #board_name)
        })
        .collect::<Vec<_>>();

    // This isn't super robust, but good enough for what we need to do.
    let args = sig
        .inputs
        .iter()
        .filter_map(|input| match input {
            FnArg::Receiver(_) => None,
            FnArg::Typed(pat) => match *pat.pat {
                Pat::Ident(ref ident) => Some(ident.clone()),
                _ => None,
            },
        })
        .collect::<Vec<_>>();

    let impls = boards
        .boards
        .iter()
        .skip(1)
        .map(|board| {
            let board_name = format!("{}", board);
            quote!(
            #[cfg(board = #board_name)]
            {
                crate::hw::board::#board::#module::#fn_name(#(#args),*)
            }
            )
        })
        .collect::<Vec<_>>();

    quote!(
        #[cfg(any(#(#cfgs),*, doc))]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(any(#(#cfgs),*))))]
        #(#attrs)*
        #vis #sig {
            #(#impls)*
        }
    )
    .into()
}

/// The main task of a Cntrlr application
///
/// This macro defines a startup routine named which creates an
/// executor and adds the marked function as a task. If any enabled
/// Cntrlr features require background tasks (such as USB), those
/// tasks will also be added to the executor.
#[proc_macro_attribute]
pub fn entry(_args: TokenStream, input: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(input as ItemFn);
    let sig = &input_fn.sig;
    let fn_name = &sig.ident;

    let main_is_valid = sig.asyncness.is_some()
        && sig.generics.params.is_empty()
        && sig.generics.where_clause.is_none()
        && sig.inputs.is_empty()
        && match sig.output {
            ReturnType::Type(_, ref typ) => matches!(**typ, Type::Never(_)),
            ReturnType::Default => false,
        };
    if !main_is_valid {
        return ParseError::new(
            input_fn.sig.span(),
            format!(
                "Cntrlr entry function must be of the form `async fn {}() -> !`",
                fn_name
            ),
        )
        .to_compile_error()
        .into();
    }

    quote!(
        #[export_name = "__cntrlr_main"]
        // This is flagged as unsafe just in case the input_fn is
        // unsafe, so that we can call it.
        pub unsafe extern "C" fn #fn_name() -> ! {
            #input_fn

            let mut executor =  ::cntrlr::task::Executor::new();
            executor.add_task(#fn_name());
            // TODO: Add tasks for device drivers as needed.
            executor.run()
        }
    )
    .into()
}

/// Override the default task initialization
///
/// This allows you control of Cntrlr application startup, including
/// whether or not to use an async executor and which tasks are added
/// to it.
#[proc_macro_attribute]
pub fn raw_entry(_args: TokenStream, input: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(input as ItemFn);
    let sig = &input_fn.sig;
    let fn_name = &sig.ident;

    let main_is_valid = sig.asyncness.is_none()
        && match sig.abi {
            None => false,
            Some(ref abi) => match abi.name {
                None => true,
                Some(ref abi) => abi.value() == "C",
            },
        }
        && sig.generics.params.is_empty()
        && sig.generics.where_clause.is_none()
        && sig.inputs.is_empty()
        && match sig.output {
            ReturnType::Type(_, ref typ) => matches!(**typ, Type::Never(_)),
            ReturnType::Default => false,
        };
    if !main_is_valid {
        return ParseError::new(
            input_fn.sig.span(),
            format!(
                "Cntrlr entry function must be of the form `extern \"C\" fn {}() -> !`",
                fn_name
            ),
        )
        .to_compile_error()
        .into();
    }

    quote!(
        #[export_name = "__cntrlr_main"]
        #input_fn
    )
    .into()
}

/// Override the default reset vector
///
/// When you implement the reset vector, you are responsible for all
/// chip and runtime initialization, including such things as loading
/// the data segment and clearing bss. You probably don't want to do
/// this. See [`macro@raw_entry`] if you want to take over after minimal
/// board init has been completed.
#[proc_macro_attribute]
pub fn reset(_args: TokenStream, input: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(input as ItemFn);
    let sig = &input_fn.sig;
    let fn_name = &sig.ident;

    let reset_is_valid = sig.asyncness.is_none()
        && match sig.abi {
            None => false,
            Some(ref abi) => match abi.name {
                None => true,
                Some(ref abi) => abi.value() == "C",
            },
        }
        && sig.generics.params.is_empty()
        && sig.generics.where_clause.is_none()
        && sig.inputs.is_empty()
        && match sig.output {
            ReturnType::Type(_, ref typ) => matches!(**typ, Type::Never(_)),
            ReturnType::Default => false,
        };
    if !reset_is_valid {
        return ParseError::new(
            input_fn.sig.span(),
            format!(
                "Cntrlr reset function must be of the form `extern \"C\" fn {}() -> !`",
                fn_name
            ),
        )
        .to_compile_error()
        .into();
    }

    quote!(
        #[link_section = ".__CNTRLR_START"]
        #[export_name = "__cntrlr_reset"]
        #input_fn
    )
    .into()
}