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
extern crate xml;

use std::fmt;
use xml::attribute::OwnedAttribute;
use xml::reader::{EventReader, XmlEvent};

const TAB1: &str = "    ";
const TAB2: &str = "        ";
const TAB3: &str = "            ";
const TAB4: &str = "                ";

#[derive(Debug)]
struct FdbScope {
    name: String,
    options: Vec<FdbOption>,
}
impl FdbScope {
    fn gen_ty<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
        let with_ty = self.with_ty();

        if with_ty {
            writeln!(w, "#[derive(Clone, Debug)]")?;
        } else {
            writeln!(w, "#[derive(Clone, Copy, Debug)]")?;
        }
        writeln!(w, "#[non_exhaustive]")?;
        writeln!(w, "pub enum {name} {{", name = self.name)?;

        let with_ty = self.with_ty();
        for option in self.options.iter() {
            option.gen_ty(w, with_ty)?;
        }
        writeln!(w, "}}")
    }

    fn gen_impl<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
        writeln!(w, "impl {name} {{", name = self.name)?;
        self.gen_code(w)?;
        self.gen_apply(w)?;
        writeln!(w, "}}")
    }

    fn gen_code<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
        writeln!(
            w,
            "{t}pub fn code(&self) -> fdb_sys::FDB{name} {{",
            t = TAB1,
            name = self.name,
        )?;
        writeln!(w, "{t}match *self {{", t = TAB2)?;

        let enum_prefix = self.c_enum_prefix();
        let with_ty = self.with_ty();

        for option in self.options.iter() {
            writeln!(
                w,
                "{t}{scope}::{name}{param} => fdb_sys::{enum_prefix}{code},",
                t = TAB3,
                scope = self.name,
                name = option.name,
                param = if let (true, Some(..)) = (with_ty, option.get_ty()) {
                    "(..)"
                } else {
                    ""
                },
                enum_prefix = enum_prefix,
                code = option.c_name,
            )?;
        }

        writeln!(w, "{t}}}", t = TAB2)?;
        writeln!(w, "{t}}}", t = TAB1)
    }

    fn gen_apply<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
        let fn_name = match self.apply_fn_name() {
            Some(name) => name,
            _ => return Ok(()),
        };

        let first_arg = match self.apply_arg_name() {
            Some(name) => format!(", target: *mut fdb_sys::{}", name),
            None => String::new(),
        };

        writeln!(
            w,
            "{t}pub unsafe fn apply(&self{args}) -> FdbResult<()> {{",
            t = TAB1,
            args = first_arg
        )?;
        writeln!(w, "{t}let code = self.code();", t = TAB2)?;
        writeln!(w, "{t}let err = match *self {{", t = TAB2)?;

        let args = if first_arg.is_empty() {
            "code"
        } else {
            "target, code"
        };

        for option in self.options.iter() {
            write!(w, "{}{}::{}", TAB3, self.name, option.name)?;
            match option.param_type {
                FdbOptionTy::Empty => {
                    writeln!(
                        w,
                        " => fdb_sys::{}({}, std::ptr::null(), 0),",
                        fn_name, args
                    )?;
                }
                FdbOptionTy::Int => {
                    writeln!(w, "(v) => {{")?;
                    writeln!(
                        w,
                        "{}let data: [u8;8] = std::mem::transmute(v as i64);",
                        TAB4,
                    )?;
                    writeln!(
                        w,
                        "{}fdb_sys::{}({}, data.as_ptr() as *const u8, 8)",
                        TAB4, fn_name, args
                    )?;
                    writeln!(w, "{t}}}", t = TAB3)?;
                }
                FdbOptionTy::Bytes => {
                    writeln!(w, "(ref v) => {{")?;
                    writeln!(
                        w,
                        "{}fdb_sys::{}({}, v.as_ptr() as *const u8, \
                         i32::try_from(v.len()).expect(\"len to fit in i32\"))\n",
                        TAB4, fn_name, args
                    )?;
                    writeln!(w, "{t}}}", t = TAB3)?;
                }
                FdbOptionTy::Str => {
                    writeln!(w, "(ref v) => {{")?;
                    writeln!(
                        w,
                        "{}fdb_sys::{}({}, v.as_ptr() as *const u8, \
                         i32::try_from(v.len()).expect(\"len to fit in i32\"))\n",
                        TAB4, fn_name, args
                    )?;
                    writeln!(w, "{t}}}", t = TAB3)?;
                }
            }
        }

        writeln!(w, "{t}}};", t = TAB2)?;
        writeln!(
            w,
            "{t}if err != 0 {{ Err(FdbError::from_code(err)) }} else {{ Ok(()) }}",
            t = TAB2,
        )?;
        writeln!(w, "{t}}}", t = TAB1)
    }

    fn with_ty(&self) -> bool {
        self.apply_fn_name().is_some()
    }

    fn c_enum_prefix(&self) -> &'static str {
        match self.name.as_str() {
            "NetworkOption" => "FDBNetworkOption_FDB_NET_OPTION_",
            "ClusterOption" => "FDBClusterOption_FDB_CLUSTER_OPTION_",
            "DatabaseOption" => "FDBDatabaseOption_FDB_DB_OPTION_",
            "TransactionOption" => "FDBTransactionOption_FDB_TR_OPTION_",
            "StreamingMode" => "FDBStreamingMode_FDB_STREAMING_MODE_",
            "MutationType" => "FDBMutationType_FDB_MUTATION_TYPE_",
            "ConflictRangeType" => "FDBConflictRangeType_FDB_CONFLICT_RANGE_TYPE_",
            "ErrorPredicate" => "FDBErrorPredicate_FDB_ERROR_PREDICATE_",
            ty => panic!("unknown Scope name: `{}`", ty),
        }
    }

    fn apply_arg_name(&self) -> Option<&'static str> {
        let s = match self.name.as_str() {
            "ClusterOption" => "FDBCluster",
            "DatabaseOption" => "FDBDatabase",
            "TransactionOption" => "FDBTransaction",
            _ => return None,
        };
        Some(s)
    }

    fn apply_fn_name(&self) -> Option<&'static str> {
        let s = match self.name.as_str() {
            "NetworkOption" => "fdb_network_set_option",
            "ClusterOption" => "fdb_cluster_set_option",
            "DatabaseOption" => "fdb_database_set_option",
            "TransactionOption" => "fdb_transaction_set_option",
            _ => return None,
        };
        Some(s)
    }
}

#[derive(Clone, Copy, Debug)]
enum FdbOptionTy {
    Empty,
    Int,
    Str,
    Bytes,
}
impl std::default::Default for FdbOptionTy {
    fn default() -> Self {
        FdbOptionTy::Empty
    }
}

#[derive(Default, Debug)]
struct FdbOption {
    name: String,
    c_name: String,
    code: i32,
    param_type: FdbOptionTy,
    param_description: String,
    description: String,
    hidden: bool,
    default_for: Option<i32>,
    persistent: bool,
}

impl FdbOption {
    fn gen_ty<W: fmt::Write>(&self, w: &mut W, with_ty: bool) -> fmt::Result {
        if !self.param_description.is_empty() {
            writeln!(w, "{t}/// {desc}", t = TAB1, desc = self.param_description)?;
            writeln!(w, "{t}///", t = TAB1)?;
        }
        if !self.description.is_empty() {
            writeln!(w, "{t}/// {desc}", t = TAB1, desc = self.description)?;
        }

        if let (true, Some(ty)) = (with_ty, self.get_ty()) {
            writeln!(w, "{t}{name}({ty}),", t = TAB1, name = self.name, ty = ty)?;
        } else {
            writeln!(w, "{t}{name},", t = TAB1, name = self.name)?;
        }
        Ok(())
    }

    fn get_ty(&self) -> Option<&'static str> {
        match self.param_type {
            FdbOptionTy::Int => Some("i32"),
            FdbOptionTy::Str => Some("String"),
            FdbOptionTy::Bytes => Some("Vec<u8>"),
            FdbOptionTy::Empty => None,
        }
    }
}

fn to_rs_enum_name(v: &str) -> String {
    let mut is_start_of_word = true;
    v.chars()
        .filter_map(|c| {
            if c == '_' {
                is_start_of_word = true;
                None
            } else if is_start_of_word {
                is_start_of_word = false;
                Some(c.to_ascii_uppercase())
            } else {
                Some(c)
            }
        })
        .collect()
}

impl From<Vec<OwnedAttribute>> for FdbOption {
    fn from(attrs: Vec<OwnedAttribute>) -> Self {
        let mut opt = Self::default();
        for attr in attrs {
            let v = attr.value;
            match attr.name.local_name.as_str() {
                "name" => {
                    opt.name = to_rs_enum_name(v.as_str());
                    opt.c_name = v.to_uppercase();
                }
                "code" => {
                    opt.code = v.parse().expect("code to be a i32");
                }
                "paramType" => {
                    opt.param_type = match v.as_str() {
                        "Int" => FdbOptionTy::Int,
                        "String" => FdbOptionTy::Str,
                        "Bytes" => FdbOptionTy::Bytes,
                        "" => FdbOptionTy::Empty,
                        ty => panic!("unexpected param_type: {}", ty),
                    };
                }
                "paramDescription" => {
                    opt.param_description = v;
                }
                "description" => {
                    opt.description = v;
                }
                "hidden" => match v.as_str() {
                    "true" => opt.hidden = true,
                    "false" => opt.hidden = false,
                    _ => panic!("unexpected boolean value in 'hidden': {}", v),
                },
                "defaultFor" => {
                    opt.default_for = Some(v.parse().expect("defaultFor to be a i32"));
                }
                "persistent" => match v.as_str() {
                    "true" => opt.persistent = true,
                    "false" => opt.persistent = false,
                    _ => panic!("unexpected boolean value in 'persistent': {}", v),
                },
                attr => {
                    panic!("unexpected option attribute: {}", attr);
                }
            }
        }
        opt
    }
}

fn on_scope<I>(parser: &mut I) -> Vec<FdbOption>
where
    I: Iterator<Item = xml::reader::Result<XmlEvent>>,
{
    let mut options = Vec::new();
    for e in parser {
        let e = e.unwrap();
        match e {
            XmlEvent::StartElement {
                name, attributes, ..
            } => {
                assert_eq!(name.local_name, "Option", "unexpected token");

                let option = FdbOption::from(attributes.clone());
                if !option.hidden {
                    options.push(option);
                }
            }
            XmlEvent::EndElement { name, .. } => {
                if name.local_name == "Scope" {
                    return options;
                }
            }
            _ => {}
        }
    }

    panic!("unexpected end of token");
}

#[cfg(all(not(feature = "embedded-fdb-include"), target_os = "linux"))]
const OPTIONS_DATA: &[u8] = include_bytes!("/usr/include/foundationdb/fdb.options");

#[cfg(all(not(feature = "embedded-fdb-include"), target_os = "macos"))]
const OPTIONS_DATA: &[u8] = include_bytes!("/usr/local/include/foundationdb/fdb.options");

#[cfg(all(not(feature = "embedded-fdb-include"), target_os = "windows"))]
const OPTIONS_DATA: &[u8] =
    include_bytes!("C:/Program Files/foundationdb/include/foundationdb/fdb.options");

#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-5_1"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/510/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-5_2"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/520/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-6_0"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/600/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-6_1"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/610/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-6_2"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/620/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-6_3"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/630/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-7_0"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/700/fdb.options");
#[cfg(all(feature = "embedded-fdb-include", feature = "fdb-7_1"))]
const OPTIONS_DATA: &[u8] = include_bytes!("../include/710/fdb.options");

pub fn emit(w: &mut impl fmt::Write) -> fmt::Result {
    let mut reader = OPTIONS_DATA;
    let parser = EventReader::new(&mut reader);
    let mut iter = parser.into_iter();
    let mut scopes = Vec::new();

    while let Some(e) = iter.next() {
        match e.unwrap() {
            XmlEvent::StartElement {
                name, attributes, ..
            } => {
                if name.local_name == "Scope" {
                    let scope_name = attributes
                        .into_iter()
                        .find(|attr| attr.name.local_name == "name")
                        .unwrap();

                    let options = on_scope(&mut iter);
                    scopes.push(FdbScope {
                        name: scope_name.value,
                        options,
                    });
                }
            }
            XmlEvent::EndElement { .. } => {
                //
            }
            _ => {}
        }
    }

    writeln!(w, "use std::convert::TryFrom;")?;
    writeln!(w, "use crate::{{FdbError, FdbResult}};")?;
    writeln!(w, "use foundationdb_sys as fdb_sys;")?;
    for scope in scopes.iter() {
        scope.gen_ty(w)?;
        scope.gen_impl(w)?;
    }

    Ok(())
}