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
use super::{ModuleEvent, ModuleEvents};
use crate::attrs::partition_attributes;
use anyhow::{Context, Result};
use proc_macro2::Ident;

use super::ModuleConfiguration;

/// Odra module struct.
///
/// Wraps up [syn::ItemStruct].
pub struct ModuleStruct {
    pub is_instantiable: bool,
    pub item: syn::ItemStruct,
    pub events: ModuleEvents,
    pub skip_instance: bool
}

impl ModuleStruct {
    pub fn with_config(mut self, mut config: ModuleConfiguration) -> Result<Self, syn::Error> {
        let submodules = self
            .item
            .fields
            .iter()
            .filter(|field| field.ident.is_some())
            .filter_map(filter_ident_excluding_variable_and_mapping)
            .map(|ident| ModuleEvent { name: ident })
            .collect::<Vec<_>>();

        let mut mappings = self
            .item
            .fields
            .iter()
            .filter(|field| field.ident.is_some())
            .filter_map(|f| match &f.ty {
                syn::Type::Path(path) => extract_mapping_value_ident_from_path(path).ok(),
                _ => None
            })
            .map(|ident| ModuleEvent { name: ident })
            .collect::<Vec<_>>();
        mappings.dedup();

        config.events.submodules_events.extend(submodules);
        config.events.mappings_events.extend(mappings);

        self.events = config.events;
        self.skip_instance = config.skip_instance;

        Ok(self)
    }
}

impl From<syn::ItemStruct> for ModuleStruct {
    fn from(item: syn::ItemStruct) -> Self {
        let (_, other_attrs) = partition_attributes(item.attrs).unwrap();
        Self {
            is_instantiable: true,
            item: syn::ItemStruct {
                attrs: other_attrs,
                ..item
            },
            events: Default::default(),
            skip_instance: false
        }
    }
}

fn extract_mapping_value_ident_from_path(path: &syn::TypePath) -> Result<Ident> {
    // Eg. odra::type::Mapping<String, Mapping<String, Mapping<u8, String>>>
    let mut segment = path
        .path
        .segments
        .last()
        .cloned()
        .context("At least one segment expected")?;
    if segment.ident != "Mapping" {
        return Err(anyhow::anyhow!(
            "Mapping expected but found {}",
            segment.ident
        ));
    }
    loop {
        let args = &segment.arguments;
        if args.is_empty() {
            break;
        }
        if let syn::PathArguments::AngleBracketed(args) = args {
            match args
                .args
                .last()
                .context("syn::GenericArgument expected but not found")?
            {
                syn::GenericArgument::Type(syn::Type::Path(path)) => {
                    let path = &path.path;
                    segment = path
                        .segments
                        .last()
                        .cloned()
                        .context("At least one segment expected")?;
                }
                other => {
                    return Err(anyhow::anyhow!(
                        "syn::TypePath expected but found {:?}",
                        other
                    ))
                }
            }
        } else {
            return Err(anyhow::anyhow!(
                "syn::AngleBracketedGenericArguments expected but found {:?}",
                args
            ));
        }
    }
    Ok(segment.ident)
}

fn filter_ident_excluding_variable_and_mapping(field: &syn::Field) -> Option<syn::Ident> {
    filter_ident(field, &["Variable", "Mapping", "List"])
}

fn filter_ident(field: &syn::Field, exclusions: &'static [&str]) -> Option<syn::Ident> {
    match &field.ty {
        syn::Type::Path(path) => {
            let path = &path.path;
            match &path.segments.last() {
                Some(segment) => {
                    if exclusions.contains(&segment.ident.to_string().as_str()) {
                        return None;
                    }
                    Some(segment.ident.clone())
                }
                _ => None
            }
        }
        _ => None
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test() {
        let path = syn::parse_str::<syn::TypePath>(
            "Mapping<String, Mapping<String, Mapping<u8, String>>>"
        )
        .unwrap();
        let ident = extract_mapping_value_ident_from_path(&path);
        assert_eq!(ident.unwrap().to_string(), "String");

        // Mapping expected but found String
        let path = syn::parse_str::<syn::TypePath>("String<i32, u8, u16>").unwrap();
        let ident = extract_mapping_value_ident_from_path(&path);
        assert!(ident.is_err());

        // Invalid Mapping - parenthesized arguments instead of angle bracketed
        let path = syn::parse_str::<syn::TypePath>(
            "Mapping<String, Mapping<String, Mapping(u8, String)>>"
        )
        .unwrap();
        let ident = extract_mapping_value_ident_from_path(&path);
        assert!(ident.is_err());

        // Invalid Mapping - function type instead of type
        let path = syn::parse_str::<syn::TypePath>(
            "Mapping<String, Mapping<String, Mapping<fn(usize) -> bool>>>"
        )
        .unwrap();
        let ident = extract_mapping_value_ident_from_path(&path);
        assert!(ident.is_err());
    }
}