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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! # zbus-lockstep-macros
//!
//! This provides the `validate` macro that builds on `zbus-lockstep`.
#![doc(html_root_url = "https://docs.rs/zbus-lockstep-macros/0.4.4")]

type Result<T> = std::result::Result<T, syn::Error>;

use std::{collections::HashMap, path::PathBuf};

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse::ParseStream, parse_macro_input, Ident, ItemStruct, LitStr, Token};

/// Validate a struct's type signature against XML signal body type.
///
/// Retrieves the signal body type from a (collection of) XML file(s) and compares it to the
/// struct's type signature.
///
/// If the XML file(s) are found in the default location, `xml/` or `XML/` of the crate root,
/// or provided as environment variable, `LOCKSTEP_XML_PATH`, the macro can be used without
/// arguments.
///
///
/// # Arguments
///
/// `#[validate]` can take three optional arguments:
///
/// * `xml`: Path to XML file(s) containing the signal definition.
/// * `interface`: Interface name of the signal.
/// * `signal`: Signal name.
///
/// `#[validate(xml: <xml_path>, interface: <interface_name>, member: <member_name>)]`
///
/// ## `xml_path`
///
/// Without an argument, the macro looks for XML file(s) in `xml/` or `XML/` of the crate root.
/// If the definitions are to be found elsewhere, there are two options:
///
/// Use the `xml` argument:
///
/// ```ignore
/// #[validate(xml: "xml")]
/// #[derive(Type)]
/// struct RemoveNodeSignal {
///    name: String,
///    path: OwnedObjectPath,
/// }
/// ```
///
///
/// Alternatively, you can provide the XML directory path as environment variable,
/// `LOCKSTEP_XML_PATH`, which will override both default and the path argument.
///
/// ## `interface`
///
/// If more than one signal with the same name is defined in the XML file(s),
/// the macro will fail and you can provide an interface name to disambiguate.
///
/// ```ignore
/// #[validate(interface: "org.example.Node")]
/// #[derive(Type)]
/// struct RemoveNodeSignal {
///    name: String,
///    path: OwnedObjectPath,
/// }
/// ```
///
///
/// ## `signal`
///
/// If a custom signal name is desired, you can be provided using `signal:`.
///
/// ```ignore
/// #[validate(signal: "RemoveNode")]
/// #[derive(Type)]
/// struct RemoveNodeSignal {
///    name: String,
///    path: OwnedObjectPath,
/// }
/// ```
///
/// ## Multiple arguments
///
/// You can provide multiple arguments with a comma separated list.
///
/// # Examples
///
/// ```ignore
/// #[validate(xml: "xml", interface: "org.example.Node", signal: "RemoveNode")]
/// #[derive(Type)]
/// struct RemoveNodeSignal {
///    name: String,
///    path: OwnedObjectPath,
/// }
/// ```
#[proc_macro_attribute]
pub fn validate(args: TokenStream, input: TokenStream) -> TokenStream {
    // Parse the macro arguments.
    let args = parse_macro_input!(args as ValidateArgs);

    // Parse the item struct.
    let item_struct = parse_macro_input!(input as ItemStruct);
    let item_name = item_struct.ident.to_string();

    let xml_str = args.xml.as_ref().and_then(|p| p.to_str());

    let xml = match zbus_lockstep::resolve_xml_path(xml_str) {
        Ok(xml) => xml,
        Err(e) => {
            return syn::Error::new(
                proc_macro2::Span::call_site(),
                format!("Failed to resolve XML path: {e}"),
            )
            .to_compile_error()
            .into();
        }
    };

    // Store each file's XML as a string in a with the XML's file path as key.
    let mut xml_files: HashMap<PathBuf, String> = HashMap::new();
    let read_dir = std::fs::read_dir(xml);

    // If the path does not exist, the process lacks permissions to read the path,
    // or the path is not a directory, return an error.
    if let Err(e) = read_dir {
        return syn::Error::new(
            proc_macro2::Span::call_site(),
            format!("Failed to read XML directory: {e}"),
        )
        .to_compile_error()
        .into();
    }

    // Iterate over the directory and store each XML file as a string.
    for entry in read_dir.expect("Failed to read XML directory") {
        let entry = entry.expect("Failed to read XML file");

        // Skip directories.
        if entry.path().is_dir() {
            continue;
        }

        if entry.path().extension().expect("File has no extension.") == "xml" {
            let xml =
                std::fs::read_to_string(entry.path()).expect("Unable to read XML file to string");
            xml_files.insert(entry.path().clone(), xml);
        }
    }

    // These are later needed to call `get_signal_body_type`.
    let mut xml_file_path = None;
    let mut interface_name = None;
    let mut signal_name = None;

    // Iterate over `xml_files` and find the signal that is contained in the struct's name.
    // Or if `signal_arg` is provided, use that.
    for (path_key, xml_string) in xml_files {
        let node = zbus_xml::Node::try_from(xml_string.as_str());

        if node.is_err() {
            return syn::Error::new(
                proc_macro2::Span::call_site(),
                format!(
                    "Failed to parse XML file: \"{}\" Err: {}",
                    path_key.to_str().unwrap(),
                    node.err().unwrap()
                ),
            )
            .to_compile_error()
            .into();
        }

        let node = node.unwrap();

        for interface in node.interfaces() {
            // We were called with an interface argument, so if the interface name does not match,
            // skip it.
            if args.interface.is_some()
                && interface.name().as_str() != args.interface.as_ref().unwrap()
            {
                continue;
            }

            for signal in interface.signals() {
                if args.signal.is_some() && signal.name().as_str() != args.signal.as_ref().unwrap()
                {
                    continue;
                }

                let xml_signal_name = signal.name();

                if args.signal.is_some()
                    && xml_signal_name.as_str() == args.signal.as_ref().unwrap()
                {
                    interface_name = Some(interface.name().to_string());
                    signal_name = Some(xml_signal_name.to_string());
                    xml_file_path = Some(path_key.clone());
                    continue;
                }

                if item_name.contains(xml_signal_name.as_str()) {
                    // If we have found a signal with the same name in an earlier iteration:
                    if interface_name.is_some() && signal_name.is_some() {
                        return syn::Error::new(
                            proc_macro2::Span::call_site(),
                            "Multiple interfaces with the same signal name. Please disambiguate.",
                        )
                        .to_compile_error()
                        .into();
                    }
                    interface_name = Some(interface.name().to_string());
                    signal_name = Some(xml_signal_name.to_string());
                    xml_file_path = Some(path_key.clone());
                }
            }
        }
    }

    // Lets be nice and provide a informative compiler error message.

    // We searched all XML files and did not find a match.
    if interface_name.is_none() {
        return syn::Error::new(
            proc_macro2::Span::call_site(),
            format!(
                "No interface matching signal name '{}' found.",
                args.signal.unwrap_or_else(|| item_name.clone())
            ),
        )
        .to_compile_error()
        .into();
    }

    // If we did find a matching interface we have also set `xml_file_path` and `signal_name`.

    let interface_name = interface_name.expect("Interface should have been found in search loop.");
    let signal_name = signal_name.expect("Signal should have been found in search loop.");

    let xml_file_path = xml_file_path.expect("XML file path should be found in search loop.");
    let xml_file_path = xml_file_path
        .to_str()
        .expect("XML file path should be valid UTF-8");

    // Create a block to return the item struct with a uniquely named validation test.
    let test_name = format!("test_{item_name}_type_signature");
    let test_name = Ident::new(&test_name, proc_macro2::Span::call_site());

    let item_struct_name = item_struct.ident.clone();
    let item_struct_name = Ident::new(
        &item_struct_name.to_string(),
        proc_macro2::Span::call_site(),
    );

    let item_plus_validation_test = quote! {
        #item_struct

        #[cfg(test)]
        #[test]
        fn #test_name() {
            use zvariant::Type;

            let xml_file = std::fs::File::open(#xml_file_path).expect("\"#xml_file_path\" expected to be a valid file path." );
            let item_signature_from_xml = zbus_lockstep::get_signal_body_type(
                xml_file,
                #interface_name,
                #signal_name,
                None
            ).expect("Failed to get signal body type from XML file.");
            let item_signature_from_struct = <#item_struct_name as Type>::signature();

            assert_eq!(&item_signature_from_xml, &item_signature_from_struct);
        }
    };

    item_plus_validation_test.into()
}

struct ValidateArgs {
    // Optional path to XML file
    xml: Option<PathBuf>,

    // Optional interface name
    interface: Option<String>,

    // Optional signal name
    signal: Option<String>,
}

impl syn::parse::Parse for ValidateArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut xml = None;
        let mut interface = None;
        let mut signal = None;

        while !input.is_empty() {
            let ident = input.parse::<Ident>()?;
            match ident.to_string().as_str() {
                "xml" => {
                    input.parse::<Token![:]>()?;
                    let lit = input.parse::<LitStr>()?;
                    xml = Some(PathBuf::from(lit.value()));
                }
                "interface" => {
                    input.parse::<Token![:]>()?;
                    let lit = input.parse::<LitStr>()?;
                    interface = Some(lit.value());
                }
                "signal" => {
                    input.parse::<Token![:]>()?;
                    let lit = input.parse::<LitStr>()?;
                    signal = Some(lit.value());
                }
                _ => {
                    return Err(syn::Error::new(
                        ident.span(),
                        format!("Unexpected argument: {ident}"),
                    ))
                }
            }

            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(ValidateArgs {
            xml,
            interface,
            signal,
        })
    }
}