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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde;

pub mod spec {
    use std::collections::HashMap;
    use std::fmt;
    use serde::de::{Deserializer, Deserialize, Visitor, SeqAccess, Error};

    #[derive(Debug, Clone, Deserialize)]
    #[serde(untagged, rename_all = "lowercase")]
    pub enum Spec {
        Include(Include),
        Command(Command),
        Struct(Struct),
        Alternate(Alternate),
        Enum(Enum),
        Event(Event),
        CombinedUnion(CombinedUnion),
        Union(Union),
        PragmaWhitelist {
            pragma: PragmaWhitelist
        },
        PragmaDocRequired {
            pragma: PragmaDocRequired
        },
    }

    #[derive(Debug, Default, Clone)]
    pub struct Data {
        pub fields: Vec<Value>,
    }

    impl Data {
        pub fn is_empty(&self) -> bool {
            self.fields.is_empty() || self.fields.iter().all(|f| f.optional)
        }
    }

    impl<'de> Deserialize<'de> for Data {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            <HashMap<String, Type>>::deserialize(d).map(|h| Data {
                fields: h.into_iter().map(|(n, t)| Value::new(&n, t)).collect(),
            })
        }
    }

    #[derive(Debug, Clone)]
    pub struct Value {
        pub name: String,
        pub ty: Type,
        pub optional: bool,
    }

    impl Value {
        pub fn new(name: &str, ty: Type) -> Self {
            let (name, opt) = if name.starts_with("*") {
                (name[1..].into(), true)
            } else {
                (name.into(), false)
            };

            Value {
                name: name,
                ty: ty,
                optional: opt,
            }
        }
    }

    #[derive(Clone, PartialEq, Eq)]
    pub struct Type {
        pub name: String,
        pub is_array: bool,
    }

    impl fmt::Debug for Type {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            if self.is_array {
                write!(fmt, "[{}]", self.name)
            } else {
                write!(fmt, "{}", self.name)
            }
        }
    }

    impl<'de> Deserialize<'de> for Type {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            struct V;

            impl<'de> Visitor<'de> for V {
                type Value = Type;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    write!(formatter, "a Type of string or single element array")
                }

                fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
                    Ok(Type {
                        name: v.into(),
                        is_array: false,
                    })
                }

                fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
                    Ok(Type {
                        name: v,
                        is_array: false,
                    })
                }

                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
                    let v = seq.next_element::<String>()?;
                    if let Some(v) = v {
                        if seq.next_element::<String>()?.is_none() {
                            Ok(Type {
                                name: v,
                                is_array: true,
                            })
                        } else {
                            Err(A::Error::invalid_length(2, &"single array item"))
                        }
                    } else {
                        Err(A::Error::invalid_length(0, &"single array item"))
                    }
                }
            }

            d.deserialize_any(V)
        }
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Include {
        pub include: String,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Command {
        #[serde(rename = "command")]
        pub id: String,
        #[serde(default)]
        pub data: DataOrType,
        #[serde(default)]
        pub returns: Option<Type>,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Struct {
        #[serde(rename = "struct")]
        pub id: String,
        #[serde(default)]
        pub data: Data,
        #[serde(default)]
        pub base: DataOrType,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Alternate {
        #[serde(rename = "alternate")]
        pub id: String,
        #[serde(default)]
        pub data: Data,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Enum {
        #[serde(rename = "enum")]
        pub id: String,
        #[serde(default)]
        pub data: Vec<String>,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct CombinedUnion {
        #[serde(rename = "union")]
        pub id: String,
        pub base: DataOrType,
        #[serde(default)]
        pub discriminator: Option<String>,
        pub data: Data,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Union {
        #[serde(rename = "union")]
        pub id: String,
        #[serde(default)]
        pub discriminator: Option<String>,
        pub data: Data,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(untagged, rename_all = "kebab-case")]
    pub enum DataOrType {
        Data(Data),
        Type(Type),
    }

    impl Default for DataOrType {
        fn default() -> Self {
            DataOrType::Data(Default::default())
        }
    }

    impl DataOrType {
        pub fn is_empty(&self) -> bool {
            match self {
                &DataOrType::Data(ref data) => data.fields.is_empty(),
                &DataOrType::Type(..) => false,
            }
        }
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct Event {
        #[serde(rename = "event")]
        pub id: String,
        #[serde(default)]
        pub data: Data,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct PragmaWhitelist {
        pub returns_whitelist: Vec<String>,
        #[serde(default)]
        pub name_case_whitelist: Vec<String>,
    }

    #[derive(Debug, Clone, Deserialize)]
    #[serde(rename_all = "kebab-case")]
    pub struct PragmaDocRequired {
        pub doc_required: bool,
    }
}

pub use spec::Spec;

use std::path::{Path, PathBuf};
use std::ops::{Deref, DerefMut};
use std::io;

pub struct Parser {
    data: String,
    pos: usize,
    eof: bool,
}

impl Parser {
    pub fn from_string<S: Into<String>>(s: S) -> Self {
        Parser {
            data: s.into(),
            pos: 0,
            eof: false,
        }
    }

    pub fn strip_comments(s: &str) -> String {
        let lines: Vec<String> = s.lines()
            .filter(|l| !l.trim().starts_with("#") && !l.trim().is_empty())
            .map(|s| s.replace("'", "\""))
            .map(|s| if let Some(i) = s.find('#') {
                s[..i].to_owned()
            } else {
                s
            }).collect();
        lines.join("\n")
    }
}

impl Iterator for Parser {
    type Item = serde_json::Result<Spec>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.eof {
            None
        } else {
            Some(match serde_json::from_str(&self.data[self.pos..]) {
                Ok(res) => {
                    self.eof = true;
                    Ok(res)
                },
                Err(e) => {
                    let (line, col) = (e.line(), e.column());
                    if line == 0 || col == 0 {
                        Err(e)
                    } else {
                        let count: usize =  self.data[self.pos..].lines().map(|l| l.len() + 1).take(line - 1).sum();
                        let str = &self.data[self.pos .. (self.pos + count + col - 1)];
                        self.pos += count;
                        serde_json::from_str(str)
                    }
                },
            })
        }
    }
}

pub trait QemuRepo {
    type Error;

    fn push_context<P: AsRef<Path>>(&mut self, p: P);
    fn pop_context(&mut self);
    fn context(&self) -> &Path;

    fn include<P: AsRef<Path>>(&mut self, p: P) -> Result<(QemuRepoContext<Self>, String), Self::Error>;
}

#[derive(Debug, Clone)]
pub struct QemuFileRepo {
    paths: Vec<PathBuf>,
}

pub struct QemuRepoContext<'a, R: QemuRepo + ?Sized + 'a> {
    repo: &'a mut R,
}

impl<'a, R: QemuRepo + ?Sized + 'a> QemuRepoContext<'a, R> {
    pub fn from_include<P: AsRef<Path>>(repo: &'a mut R, path: P) -> (Self, PathBuf) {
        let path = path.as_ref();
        let include_path = repo.context().join(path);
        repo.push_context(include_path.parent().unwrap());

        (
            QemuRepoContext {
                repo: repo,
            },
            include_path,
        )
    }
}

impl<'a, R: QemuRepo + ?Sized + 'a> Deref for QemuRepoContext<'a, R> {
    type Target = R;

    fn deref(&self) -> &Self::Target {
        self.repo
    }
}

impl<'a, R: QemuRepo + ?Sized + 'a> DerefMut for QemuRepoContext<'a, R> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.repo
    }
}

impl<'a, R: QemuRepo + ?Sized + 'a> Drop for QemuRepoContext<'a, R> {
    fn drop(&mut self) {
        self.repo.pop_context();
    }
}

impl QemuFileRepo {
    pub fn new<P: Into<PathBuf>>(p: P) -> Self {
        QemuFileRepo {
            paths: vec![p.into()],
        }
    }
}

impl QemuRepo for QemuFileRepo {
    type Error = io::Error;

    fn push_context<P: AsRef<Path>>(&mut self, p: P) {
        self.paths.push(p.as_ref().to_owned());
    }

    fn pop_context(&mut self) {
        self.paths.pop();
        assert!(!self.paths.is_empty());
    }

    fn context(&self) -> &Path {
        self.paths.last().unwrap()
    }

    fn include<P: AsRef<Path>>(&mut self, p: P) -> Result<(QemuRepoContext<Self>, String), Self::Error> {
        use std::fs::File;
        use std::io::Read;

        let (context, path) = QemuRepoContext::from_include(self, p);
        let mut f = File::open(path)?;
        let mut str = String::new();
        f.read_to_string(&mut str)?;
        Ok((context, str))
    }
}

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

    fn parse_include<P: AsRef<Path>>(repo: &mut QemuFileRepo, include: P) {
        let include = include.as_ref();
        println!("including {}", include.display());

        let (mut context, schema) = repo.include(include).expect("include path not found");
        for item in Parser::from_string(Parser::strip_comments(&schema)) {
            match item.expect("schema parse failure") {
                Spec::Include(inc) => parse_include(&mut context, inc.include),
                item => println!("decoded {:?}", item),
            }
        }
    }

    fn parse_schema(mut repo: QemuFileRepo) {
        parse_include(&mut repo, "qapi-schema.json");
    }

    #[test]
    fn parse_qapi() {
        parse_schema(QemuFileRepo::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../schema/qapi/")));
    }

    #[test]
    fn parse_qga() {
        parse_schema(QemuFileRepo::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../schema/qga/")));
    }
}