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
#[macro_use]
extern crate genco;
#[macro_use]
extern crate log;
extern crate reproto_backend as backend;
#[macro_use]
extern crate reproto_core as core;
#[macro_use]
extern crate reproto_manifest as manifest;
extern crate reproto_naming as naming;
extern crate reproto_trans as trans;
extern crate serde;
#[allow(unused)]
#[macro_use]
extern crate serde_derive;
extern crate toml;

mod compiler;
mod flavored;
mod module;

use backend::{Initializer, IntoBytes};
use compiler::Compiler;
use core::errors::Result;
use core::{Context, CoreFlavor};
use flavored::{RpEnumBody, RpField, RpInterfaceBody, RpPackage, SwiftName};
use genco::Tokens;
use genco::swift::Swift;
use manifest::{Lang, Manifest, NoModule, TryFromToml};
use std::any::Any;
use std::path::Path;
use std::rc::Rc;
use trans::Environment;

const EXT: &str = "swift";
const TYPE_SEP: &'static str = "_";

#[derive(Clone, Copy, Default, Debug)]
pub struct SwiftLang;

impl Lang for SwiftLang {
    lang_base!(SwiftModule, compile);

    fn comment(&self, input: &str) -> Option<String> {
        Some(format!("// {}", input))
    }

    fn package_naming(&self) -> Option<Box<naming::Naming>> {
        Some(Box::new(naming::to_upper_camel()))
    }

    fn safe_packages(&self) -> bool {
        true
    }

    fn keywords(&self) -> Vec<(&'static str, &'static str)> {
        vec![
            ("as", "as_"),
            ("associatedtype", "associatedtype_"),
            ("associativity", "associativity_"),
            ("break", "break_"),
            ("case", "case_"),
            ("catch", "catch_"),
            ("class", "class_"),
            ("continue", "continue_"),
            ("convenience", "convenience_"),
            ("default", "default_"),
            ("defer", "defer_"),
            ("deinit", "deinit_"),
            ("do", "do_"),
            ("dynamic", "dynamic_"),
            ("else", "else_"),
            ("enum", "enum_"),
            ("extension", "extension_"),
            ("fallthrough", "fallthrough_"),
            ("false", "false_"),
            ("fileprivate", "fileprivate_"),
            ("final", "final_"),
            ("for", "for_"),
            ("func", "func_"),
            ("get", "get_"),
            ("guard", "guard_"),
            ("if", "if_"),
            ("import", "import_"),
            ("in", "in_"),
            ("indirect", "indirect_"),
            ("infix", "infix_"),
            ("init", "init_"),
            ("inout", "inout_"),
            ("internal", "internal_"),
            ("is", "is_"),
            ("lazy", "lazy_"),
            ("left", "left_"),
            ("let", "let_"),
            ("mutating", "mutating_"),
            ("nil", "nil_"),
            ("none", "none_"),
            ("nonmutating", "nonmutating_"),
            ("open", "open_"),
            ("operator", "operator_"),
            ("optional", "optional_"),
            ("override", "override_"),
            ("postfix", "postfix_"),
            ("precedence", "precedence_"),
            ("prefix", "prefix_"),
            ("private", "private_"),
            ("protocol", "protocol_"),
            ("public", "public_"),
            ("repeat", "repeat_"),
            ("required", "required_"),
            ("rethrows", "rethrows_"),
            ("return", "return_"),
            ("right", "right_"),
            ("self", "self_"),
            ("set", "set_"),
            ("static", "static_"),
            ("struct", "struct_"),
            ("subscript", "subscript_"),
            ("super", "super_"),
            ("switch", "switch_"),
            ("throw", "throw_"),
            ("throws", "throws_"),
            ("true", "true_"),
            ("try", "try_"),
            ("typealias", "typealias_"),
            ("unowned", "unowned_"),
            ("var", "var_"),
            ("weak", "weak_"),
            ("where", "where_"),
            ("while", "while_"),
        ]
    }
}

#[derive(Debug)]
pub enum SwiftModule {
    Grpc,
    Simple,
    Codable,
}

impl TryFromToml for SwiftModule {
    fn try_from_string(path: &Path, id: &str, value: String) -> Result<Self> {
        use self::SwiftModule::*;

        let result = match id {
            "grpc" => Grpc,
            "simple" => Simple,
            "codable" => Codable,
            _ => return NoModule::illegal(path, id, value),
        };

        Ok(result)
    }

    fn try_from_value(path: &Path, id: &str, value: toml::Value) -> Result<Self> {
        use self::SwiftModule::*;

        let result = match id {
            "grpc" => Grpc,
            "simple" => Simple,
            "codable" => Codable,
            _ => return NoModule::illegal(path, id, value),
        };

        Ok(result)
    }
}

pub struct Options {
    /// All types that the struct model should extend.
    pub struct_model_extends: Tokens<'static, Swift<'static>>,
    pub type_gens: Vec<Box<TypeCodegen>>,
    pub tuple_gens: Vec<Box<TupleCodegen>>,
    pub struct_model_gens: Vec<Box<StructModelCodegen>>,
    pub enum_gens: Vec<Box<EnumCodegen>>,
    pub interface_gens: Vec<Box<InterfaceCodegen>>,
    pub interface_model_gens: Vec<Box<InterfaceModelCodegen>>,
    pub package_gens: Vec<Box<PackageCodegen>>,
    /// The provided Any type that should be used in structs.
    pub any_type: Vec<(&'static str, Swift<'static>)>,
}

impl Options {
    pub fn new() -> Options {
        Options {
            struct_model_extends: Tokens::new(),
            type_gens: Vec::new(),
            tuple_gens: Vec::new(),
            struct_model_gens: Vec::new(),
            interface_gens: Vec::new(),
            interface_model_gens: Vec::new(),
            enum_gens: Vec::new(),
            package_gens: Vec::new(),
            any_type: Vec::new(),
        }
    }
}

pub fn options(modules: Vec<SwiftModule>) -> Result<Options> {
    use self::SwiftModule::*;

    let mut options = Options::new();

    for m in modules {
        debug!("+module: {:?}", m);

        let initializer: Box<Initializer<Options = Options>> = match m {
            Grpc => Box::new(module::Grpc::new()),
            Simple => Box::new(module::Simple::new()),
            Codable => Box::new(module::Codable::new()),
        };

        initializer.initialize(&mut options)?;
    }

    Ok(options)
}

pub struct FileSpec<'a>(pub Tokens<'a, Swift<'a>>);

impl<'el> Default for FileSpec<'el> {
    fn default() -> Self {
        FileSpec(Tokens::new())
    }
}

impl<'el> IntoBytes<Compiler<'el>> for FileSpec<'el> {
    fn into_bytes(self, _: &Compiler<'el>, _: &RpPackage) -> Result<Vec<u8>> {
        let out = self.0.join_line_spacing().to_file()?;
        Ok(out.into_bytes())
    }
}

/// Build codegen hooks.
macro_rules! codegen {
    ($c:tt, $e:ty) => {
        pub trait $c {
            fn generate(&self, e: $e) -> Result<()>;
        }

        impl<T> $c for Rc<T>
        where
            T: $c,
        {
            fn generate(&self, e: $e) -> Result<()> {
                self.as_ref().generate(e)
            }
        }
    };
}

/// Event emitted when a struct has been added.
pub struct TypeAdded<'a, 'c: 'a, 'el: 'a> {
    pub container: &'a mut Tokens<'el, Swift<'el>>,
    pub compiler: &'a Compiler<'c>,
    pub name: &'el SwiftName,
    pub fields: &'a [&'el RpField],
}

codegen!(TypeCodegen, TypeAdded);

/// Event emitted when a struct has been added.
pub struct TupleAdded<'a, 'c: 'a, 'el: 'a> {
    pub container: &'a mut Tokens<'el, Swift<'el>>,
    pub compiler: &'a Compiler<'c>,
    pub name: &'el SwiftName,
    pub fields: &'a [&'el RpField],
}

codegen!(TupleCodegen, TupleAdded);

/// Event emitted when a struct has been added.
pub struct StructModelAdded<'a, 'el: 'a> {
    pub container: &'a mut Tokens<'el, Swift<'el>>,
    pub fields: &'a [&'el RpField],
}

codegen!(StructModelCodegen, StructModelAdded);

/// Event emitted when an enum has been added.
pub struct EnumAdded<'a, 'el: 'a> {
    pub container: &'a mut Tokens<'el, Swift<'el>>,
    pub name: &'el SwiftName,
    pub body: &'el RpEnumBody,
}

codegen!(EnumCodegen, EnumAdded);

/// Event emitted when an interface has been added.
pub struct InterfaceAdded<'a, 'c: 'a, 'el: 'a> {
    pub container: &'a mut Tokens<'el, Swift<'el>>,
    pub compiler: &'a Compiler<'c>,
    pub name: &'el SwiftName,
    pub body: &'el RpInterfaceBody,
}

codegen!(InterfaceCodegen, InterfaceAdded);

/// Event emitted when an interface model has been added.
pub struct InterfaceModelAdded<'a, 'el: 'a> {
    pub container: &'a mut Tokens<'el, Swift<'el>>,
    pub body: &'el RpInterfaceBody,
}

codegen!(InterfaceModelCodegen, InterfaceModelAdded);

/// Event emitted when an interface model has been added.
pub struct PackageAdded<'a, 'el: 'a> {
    pub files: &'a mut Vec<(RpPackage, FileSpec<'el>)>,
}

codegen!(PackageCodegen, PackageAdded);

fn compile(ctx: Rc<Context>, env: Environment<CoreFlavor>, manifest: Manifest) -> Result<()> {
    let modules = manifest::checked_modules(manifest.modules)?;
    let options = options(modules)?;

    let packages = env.packages()?;

    let translator = flavored::SwiftFlavorTranslator::new(packages.clone(), &options)?;

    let translator = env.translator(translator)?;

    let env = env.translate(translator)?;

    let handle = ctx.filesystem(manifest.output.as_ref().map(AsRef::as_ref))?;
    Compiler::new(&env, options, handle.as_ref())?.compile(&packages)
}