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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{
    convert::Infallible,
    io::Read,
    num::ParseIntError,
    str::{FromStr, ParseBoolError},
};
use thiserror::Error;
use xml::{
    attribute::OwnedAttribute,
    reader::{
        EventReader,
        ParserConfig,
        XmlEvent::{self, *},
    },
};

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

#[derive(Error, Debug)]
pub enum Error {
    #[error("no protocol in file")]
    NoProtocol,
    #[error("xml parsing failed")]
    XmlParse(#[from] xml::reader::Error),
    #[error("unexpected xml event: {0:?}")]
    UnexpectedXmlEvent(XmlEvent),
    #[error("unexpected xml element: {0}")]
    UnexpectedXmlElement(String),
    #[error("parsing int failed")]
    ParseInt(#[from] ParseIntError),
    #[error("parsing bool failed")]
    ParseBool(#[from] ParseBoolError),
    #[error("missing required attribute: {0}")]
    MissingRequiredAttribute(String),
    #[error("invalid argument kind: {0}")]
    InvalidArgKind(String),
}

impl From<Infallible> for Error {
    fn from(i: Infallible) -> Self {
        match i {}
    }
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Protocol {
    pub name: String,
    pub copyright: String,
    pub description: Option<Description>,
    pub interfaces: Vec<Interface>,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Interface {
    pub name: String,
    pub version: u32,
    pub description: Option<Description>,
    pub requests: Vec<Request>,
    pub events: Vec<Event>,
    pub enums: Vec<Enum>,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Request {
    pub name: String,
    pub destructor: bool,
    pub since: u32,
    pub description: Option<Description>,
    pub args: Vec<Arg>,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Event {
    pub name: String,
    pub since: u32,
    pub description: Option<Description>,
    pub args: Vec<Arg>,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Arg {
    pub name: String,
    pub kind: ArgKind,
    pub summary: Option<String>,
    pub interface: Option<String>,
    pub allow_null: bool,
    pub enumeration: Option<String>,
    pub description: Option<Description>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ArgKind {
    NewId,
    Int,
    Uint,
    Fixed,
    String,
    Object,
    Array,
    Fd,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Enum {
    pub name: String,
    pub since: u32,
    pub bitfield: bool,
    pub description: Option<Description>,
    pub entries: Vec<Entry>,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Entry {
    pub name: String,
    pub value: u32,
    pub summary: Option<String>,
    pub since: u32,
    pub description: Option<Description>,
}

#[derive(Clone, Default, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Description {
    pub summary: String,
    pub body: String,
}

impl Default for ArgKind {
    fn default() -> Self {
        Self::NewId
    }
}

impl FromStr for ArgKind {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Ok(match s {
            "new_id" => ArgKind::NewId,
            "int" => ArgKind::Int,
            "uint" => ArgKind::Uint,
            "fixed" => ArgKind::Fixed,
            "string" => ArgKind::String,
            "object" => ArgKind::Object,
            "array" => ArgKind::Array,
            "fd" => ArgKind::Fd,
            _ => return Err(Error::InvalidArgKind(s.into())),
        })
    }
}

struct ParseContext<R: Read> {
    event_reader: EventReader<R>,
    attributes: Vec<OwnedAttribute>,
}

impl<R: Read> ParseContext<R> {
    fn next(&mut self) -> Result<XmlEvent> {
        Ok(self.event_reader.next()?)
    }

    fn attr<T>(&self, name: &str) -> Result<T>
    where
        T: FromStr,
        <T as FromStr>::Err: Into<Error>,
    {
        Ok(self
            .attributes
            .iter()
            .filter(|attr| attr.name.local_name == name)
            .map(|attr| attr.value.clone())
            .next()
            .ok_or_else(|| Error::MissingRequiredAttribute(name.into()))?
            .parse::<T>()
            .map_err(|err| err.into())?)
    }

    fn parse(&mut self) -> Result<Protocol> {
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } if name.local_name == "protocol" => {
                    self.attributes = attributes;
                    break self.protocol()?;
                },
                EndDocument => return Err(Error::NoProtocol),
                _ => {},
            }
        })
    }

    fn protocol(&mut self) -> Result<Protocol> {
        let mut protocol = Protocol::default();
        protocol.name = self.attr("name")?;
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } => {
                    self.attributes = attributes;
                    match &*name.local_name {
                        "copyright" => protocol.copyright = self.copyright()?,
                        "description" => protocol.description = self.description()?.into(),
                        "interface" => protocol.interfaces.push(self.interface()?),
                        other => return Err(Error::UnexpectedXmlElement(other.into())),
                    }
                },
                EndElement { name } if name.local_name == "protocol" => break protocol,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn copyright(&mut self) -> Result<String> {
        let mut body = None;
        Ok(loop {
            match self.next()? {
                Characters(data) => body = Some(data),
                EndElement { name } if name.local_name == "copyright" => {
                    break body.unwrap_or_default();
                },
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn interface(&mut self) -> Result<Interface> {
        let mut interface = Interface::default();
        interface.name = self.attr("name")?;
        interface.version = self.attr("version")?;
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } => {
                    self.attributes = attributes;
                    match &*name.local_name {
                        "description" => interface.description = self.description()?.into(),
                        "request" => interface.requests.push(self.request()?),
                        "event" => interface.events.push(self.event()?),
                        "enum" => interface.enums.push(self.enumeration()?),
                        other => return Err(Error::UnexpectedXmlElement(other.into())),
                    }
                },
                EndElement { name } if name.local_name == "interface" => break interface,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn request(&mut self) -> Result<Request> {
        let mut request = Request::default();
        request.name = self.attr("name")?;
        request.destructor = self
            .attr("type")
            .map(|t: String| t == "destructor")
            .unwrap_or(false);
        request.since = self.attr("since").unwrap_or(1);
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } => {
                    self.attributes = attributes;
                    match &*name.local_name {
                        "description" => request.description = self.description()?.into(),
                        "arg" => request.args.push(self.arg()?),
                        other => return Err(Error::UnexpectedXmlElement(other.into())),
                    }
                },
                EndElement { name } if name.local_name == "request" => break request,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn event(&mut self) -> Result<Event> {
        let mut event = Event::default();
        event.name = self.attr("name")?;
        event.since = self.attr("since").unwrap_or(1);
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } => {
                    self.attributes = attributes;
                    match &*name.local_name {
                        "description" => event.description = self.description()?.into(),
                        "arg" => event.args.push(self.arg()?),
                        other => return Err(Error::UnexpectedXmlElement(other.into())),
                    }
                },
                EndElement { name } if name.local_name == "event" => break event,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn arg(&mut self) -> Result<Arg> {
        let mut arg = Arg::default();
        arg.name = self.attr("name")?;
        arg.kind = self.attr("type")?;
        arg.summary = self.attr("summary").ok();
        arg.interface = self.attr("interface").ok();
        arg.allow_null = self.attr("allow-null").unwrap_or(false);
        arg.enumeration = self.attr("enum").ok();
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } if name.local_name == "description" => {
                    self.attributes = attributes;
                    arg.description = self.description()?.into();
                },
                EndElement { name } if name.local_name == "arg" => break arg,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn enumeration(&mut self) -> Result<Enum> {
        let mut enumeration = Enum::default();
        enumeration.name = self.attr("name")?;
        enumeration.since = self.attr("since").unwrap_or(1);
        enumeration.bitfield = self.attr("bitfield").unwrap_or(false);
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } => {
                    self.attributes = attributes;
                    match &*name.local_name {
                        "description" => enumeration.description = self.description()?.into(),
                        "entry" => enumeration.entries.push(self.entry()?),
                        other => return Err(Error::UnexpectedXmlElement(other.into())),
                    }
                },
                EndElement { name } if name.local_name == "enum" => break enumeration,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn entry(&mut self) -> Result<Entry> {
        let mut entry = Entry::default();
        entry.name = self.attr("name")?;
        entry.value = {
            let value: String = self.attr("value")?;
            let (str, radix) = if value.starts_with("0x") {
                (&value[2..], 16)
            } else {
                (&value[..], 10)
            };
            u32::from_str_radix(str, radix)?
        };
        entry.summary = self.attr("summary").ok();
        entry.since = self.attr("since").unwrap_or(1);
        Ok(loop {
            match self.next()? {
                StartElement {
                    name, attributes, ..
                } if name.local_name == "description" => {
                    self.attributes = attributes;
                    entry.description = self.description()?.into();
                },
                EndElement { name } if name.local_name == "entry" => break entry,
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }

    fn description(&mut self) -> Result<Description> {
        let mut description = Description::default();
        description.summary = self.attr("summary")?;
        Ok(loop {
            match self.next()? {
                Characters(data) => description.body = data,
                EndElement { name } if name.local_name == "description" => {
                    break description;
                },
                other => return Err(Error::UnexpectedXmlEvent(other)),
            }
        })
    }
}

pub fn parse<R: Read>(reader: R) -> std::result::Result<Protocol, Error> {
    let event_reader = EventReader::new_with_config(
        reader,
        ParserConfig::new()
            .trim_whitespace(true)
            .cdata_to_characters(true),
    );
    ParseContext {
        event_reader,
        attributes: Vec::new(),
    }
    .parse()
}