rtic_core/parser/
ast.rs

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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use std::sync::atomic::Ordering;

use heck::ToSnakeCase;
use proc_macro2::Span;
use quote::{format_ident, ToTokens};
use syn::{
    parse::Parser, spanned::Spanned, Expr, ExprArray, ExprLit, Ident, ItemFn, ItemImpl, ItemStruct,
    Lit, LitInt, Meta,
};

use crate::{
    errors::ParseError, parse_utils::RticAttr, rtic_traits::HWT_TRAIT_TY, DEFAULT_TASK_PRIORITY,
};

#[derive(Debug)]
pub struct InitTask {
    pub args: InitTaskArgs,
    pub ident: Ident,
    pub body: ItemFn,
}

#[derive(Debug, Clone, Default)]
pub struct InitTaskArgs {
    pub core: u32,
}

impl InitTaskArgs {
    pub fn parse(args: Meta) -> syn::Result<Self> {
        let mut core: Option<syn::LitInt> = None;
        let Meta::List(args) = args else {
            return Ok(Self::default());
        };

        syn::meta::parser(|meta| {
            if meta.path.is_ident("core") {
                core = Some(meta.value()?.parse()?)
            } else {
                // this is needed to advance the values iterator
                let _ = meta.value()?.parse::<Expr>();
            }
            Ok(())
        })
        .parse2(args.tokens)?;

        let core = core
            .and_then(|core| core.base10_parse().ok())
            .unwrap_or_default();

        Ok(Self { core })
    }
}

#[derive(Debug)]
pub struct TaskArgs {
    pub interrupt_handler_name: Option<syn::Ident>,
    pub priority: u16,
    // list of identifiers for shared resources
    pub shared_idents: Vec<Ident>,
    pub core: u32,
    // tells whether a task is native to this compilation pass or if another compilation pass handles its trait implementation
    pub task_trait: Ident,
}

impl TaskArgs {
    pub fn parse(args: Meta) -> syn::Result<Self> {
        let Meta::List(args) = args else {
            return Ok(TaskArgs {
                interrupt_handler_name: None,
                priority: DEFAULT_TASK_PRIORITY.load(Ordering::Relaxed),
                shared_idents: Default::default(),
                core: 0,
                task_trait: format_ident!("{HWT_TRAIT_TY}"),
            });
        };

        let mut interrupt_handler_name: Option<syn::Path> = None;
        let mut task_trait: Option<Ident> = None;
        let mut priority: Option<LitInt> = None;
        let mut shared: Option<ExprArray> = None;
        let mut core: Option<LitInt> = None;

        syn::meta::parser(|meta| {
            if meta.path.is_ident("binds") {
                interrupt_handler_name = Some(meta.value()?.parse()?);
            } else if meta.path.is_ident("priority") {
                priority = Some(meta.value()?.parse()?);
            } else if meta.path.is_ident("shared") {
                shared = Some(meta.value()?.parse()?);
            } else if meta.path.is_ident("core") {
                core = Some(meta.value()?.parse()?);
            } else if meta.path.is_ident("task_trait") {
                task_trait = Some(meta.value()?.parse()?);
            } else {
                // this is needed to advance the values iterator
                let _: syn::Result<Expr> = meta.value()?.parse();
            }
            Ok(())
        })
        .parse2(args.tokens)?;

        let interrupt_handler_name = interrupt_handler_name
            .map(|i| Ident::new(&i.to_token_stream().to_string(), Span::call_site()));

        let priority = priority
            .and_then(|p| p.base10_parse().ok())
            .unwrap_or(DEFAULT_TASK_PRIORITY.load(Ordering::Relaxed));

        let core = core
            .and_then(|core| core.base10_parse().ok())
            .unwrap_or_default();
        let task_trait = task_trait.unwrap_or(format_ident!("{HWT_TRAIT_TY}"));

        let shared_idents = if let Some(shared) = shared {
            let mut elements = Vec::with_capacity(shared.elems.len());
            for element in shared.elems {
                let element = Ident::new(&element.to_token_stream().to_string(), Span::call_site());
                elements.push(element);
            }
            elements
        } else {
            Vec::new()
        };

        Ok(Self {
            interrupt_handler_name,
            priority,
            shared_idents,
            core,
            task_trait,
        })
    }
}

/// Alias for hardware task
pub type HardwareTask = RticTask;

/// Alias for idle tasks. idle task has `interrupt_handler_name` set to None and priority 0
pub type IdleTask = RticTask;

#[derive(Debug)]
pub struct RticTask {
    pub args: TaskArgs,
    pub task_struct: ItemStruct,
    pub struct_impl: Option<ItemImpl>,
    pub user_initializable: bool, // whether user should manually initialize this task during init
}

impl RticTask {
    pub fn name(&self) -> &Ident {
        &self.task_struct.ident
    }

    /// By convention, this method is used to generate the name of the static task instance
    pub fn name_uppercase(&self) -> Ident {
        let name = self
            .task_struct
            .ident
            .to_string()
            .to_snake_case()
            .to_uppercase();
        Ident::new(&name, Span::call_site())
    }

    pub fn name_snakecase(&self) -> Ident {
        let name = self.task_struct.ident.to_string().to_snake_case();
        Ident::new(&name, Span::call_site())
    }
}

#[derive(Debug, Clone)]
pub struct SharedElement {
    pub ident: Ident,
    pub ty: syn::Type,
    pub priority: u16,
}

#[derive(Debug, Clone, Default)]
pub struct SharedResourcesArgs {
    pub core: u32,
}

impl SharedResourcesArgs {
    pub fn parse(args: Meta) -> syn::Result<Self> {
        let mut core: Option<syn::LitInt> = None;
        let Meta::List(args) = args else {
            return Ok(Self::default());
        };

        syn::meta::parser(|meta| {
            if meta.path.is_ident("core") {
                core = Some(meta.value()?.parse()?)
            } else {
                // this is needed to advance the values iterator
                let _ = meta.value()?.parse::<Expr>();
            }
            Ok(())
        })
        .parse2(args.tokens)?;

        let core = core
            .and_then(|core| core.base10_parse().ok())
            .unwrap_or_default();

        Ok(Self { core })
    }
}

#[derive(Debug, Clone)]
pub struct SharedResources {
    pub args: SharedResourcesArgs,
    pub strct: ItemStruct,
    pub resources: Vec<SharedElement>,
}

impl SharedResources {
    pub fn get_field_mut(&mut self, field_name: &Ident) -> Option<&mut SharedElement> {
        self.resources
            .iter_mut()
            .find(|field| &field.ident == field_name)
    }

    pub fn get_field(&self, field_name: &Ident) -> Option<&SharedElement> {
        self.resources
            .iter()
            .find(|field| &field.ident == field_name)
    }
    pub fn name_uppercase(&self) -> Ident {
        let name = self.strct.ident.to_string().to_snake_case().to_uppercase();
        Ident::new(&name, Span::call_site())
    }
}

/// Arguments provided to the #[app(...)] macro attribute, this includes paths to PACs, number of cores, and peripherals option.
#[derive(Debug)]
pub struct AppArgs {
    // path to peripheral crate
    pub pacs: Vec<syn::Path>,
    pub peripherals: bool,
    pub cores: u32,
}

impl AppArgs {
    pub fn parse(args: proc_macro2::TokenStream) -> syn::Result<Self> {
        let args_span = args.span();

        let mut args = RticAttr::parse_from_tokens(&args)?;

        // parse the number of cores
        let cores = args.elements.remove("cores");
        let cores = match cores {
            Some(Expr::Lit(ExprLit {
                lit: Lit::Int(lit_int),
                ..
            })) => lit_int.base10_parse()?,
            _ => 1_u32,
        };

        // parse the path(s) to PAC(s)
        let device = args
            .elements
            .remove("device")
            .ok_or(ParseError::DeviceArg.to_syn(args_span))?;

        let pacs = match device {
            Expr::Array(array_exp) => {
                if array_exp.elems.len() != cores as usize {
                    return Err(ParseError::DevicesCoresMismatch.to_syn(args_span));
                }

                let mut devices = Vec::with_capacity(cores as usize);
                for exp in array_exp.elems {
                    if let Expr::Path(p) = exp {
                        devices.push(p.path)
                    } else {
                        return Err(ParseError::DeviceNotPath.to_syn(args_span));
                    }
                }
                devices
            }
            Expr::Path(path_to_pac) => {
                let mut devices = Vec::with_capacity(cores as usize);
                for _ in 0..cores {
                    devices.push(path_to_pac.path.clone())
                }
                devices
            }
            _ => return Err(ParseError::DeviceNotPath.to_syn(args_span)),
        };

        Ok(Self {
            pacs,
            peripherals: false, // TODO: not supported yet
            cores,
        })
    }
}