aboutsummaryrefslogtreecommitdiff
path: root/macros/src/syntax/parse/software_task.rs
blob: fb9b37c442ab310383c729256debbcfe5c180aa9 (plain) (blame)
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
use syn::{parse, ForeignItemFn, ItemFn, Stmt};

use crate::syntax::parse::util::FilterAttrs;
use crate::syntax::{
    ast::{SoftwareTask, SoftwareTaskArgs},
    parse::util,
};

impl SoftwareTask {
    pub(crate) fn parse(args: SoftwareTaskArgs, item: ItemFn) -> parse::Result<Self> {
        let valid_signature = util::check_fn_signature(&item, true)
            && util::type_is_unit(&item.sig.output)
            && item.sig.asyncness.is_some();

        let span = item.sig.ident.span();

        let name = item.sig.ident.to_string();

        if valid_signature {
            if let Some(context) = util::parse_inputs(item.sig.inputs, &name) {
                let FilterAttrs { cfgs, attrs, .. } = util::filter_attributes(item.attrs);

                return Ok(SoftwareTask {
                    args,
                    attrs,
                    cfgs,
                    context,
                    stmts: item.block.stmts,
                    is_extern: false,
                });
            }
        }

        Err(parse::Error::new(
            span,
            format!("this task handler must have type signature `async fn({name}::Context)`"),
        ))
    }
}

impl SoftwareTask {
    pub(crate) fn parse_foreign(
        args: SoftwareTaskArgs,
        item: ForeignItemFn,
    ) -> parse::Result<Self> {
        let valid_signature = util::check_foreign_fn_signature(&item, true)
            && util::type_is_unit(&item.sig.output)
            && item.sig.asyncness.is_some();

        let span = item.sig.ident.span();

        let name = item.sig.ident.to_string();

        if valid_signature {
            if let Some(context) = util::parse_inputs(item.sig.inputs, &name) {
                let FilterAttrs { cfgs, attrs, .. } = util::filter_attributes(item.attrs);

                return Ok(SoftwareTask {
                    args,
                    attrs,
                    cfgs,
                    context,
                    stmts: Vec::<Stmt>::new(),
                    is_extern: true,
                });
            }
        }

        Err(parse::Error::new(
            span,
            format!("this task handler must have type signature `async fn({name}::Context)`"),
        ))
    }
}