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
#[macro_use]
extern crate genco;
#[macro_use]
extern crate log;
#[macro_use]
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_trans as trans;
extern crate serde;
#[allow(unused)]
#[macro_use]
extern crate serde_derive;
extern crate toml;

mod compiler;
mod flavored;
mod module;
mod rust_file_spec;
mod utils;

use backend::Initializer;
use compiler::Compiler;
use core::errors::*;
use core::{Context, CoreFlavor};
use flavored::RpPackage;
use genco::{Cons, Rust, Tokens};
use manifest::{Lang, Manifest, NoModule, TryFromToml};
use rust_file_spec::RustFileSpec;
use std::any::Any;
use std::collections::BTreeMap;
use std::path::Path;
use std::rc::Rc;
use trans::{Environment, Packages};

const LIB: &str = "lib";
const MOD: &str = "mod";
const EXT: &str = "rs";
const TYPE_SEP: &'static str = "_";
const SCOPE_SEP: &'static str = "::";

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

impl Lang for RustLang {
    lang_base!(RustModule, compile);

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

    fn keywords(&self) -> Vec<(&'static str, &'static str)> {
        vec![
            ("as", "_as"),
            ("break", "_break"),
            ("const", "_const"),
            ("continue", "_continue"),
            ("crate", "_crate"),
            ("else", "_else"),
            ("enum", "_enum"),
            ("extern", "_extern"),
            ("false", "_false"),
            ("fn", "_fn"),
            ("for", "_for"),
            ("if", "_if"),
            ("impl", "_impl"),
            ("in", "_in"),
            ("let", "_let"),
            ("loop", "_loop"),
            ("match", "_match"),
            ("mod", "_mod"),
            ("move", "_move"),
            ("mut", "_mut"),
            ("pub", "_pub"),
            ("ref", "_ref"),
            ("return", "_return"),
            ("self", "_self"),
            ("static", "_static"),
            ("struct", "_struct"),
            ("super", "_super"),
            ("trait", "_trait"),
            ("true", "_true"),
            ("type", "_type"),
            ("unsafe", "_unsafe"),
            ("use", "_use"),
            ("where", "_where"),
            ("while", "_while"),
            ("abstract", "_abstract"),
            ("alignof", "_alignof"),
            ("become", "_become"),
            ("box", "_box"),
            ("do", "_do"),
            ("final", "_final"),
            ("macro", "_macro"),
            ("offsetof", "_offsetof"),
            ("override", "_override"),
            ("priv", "_priv"),
            ("proc", "_proc"),
            ("pure", "_pure"),
            ("sizeof", "_sizeof"),
            ("typeof", "_typeof"),
            ("unsized", "_unsized"),
            ("virtual", "_virtual"),
            ("yield", "_yield"),
        ]
    }
}

#[derive(Debug)]
pub enum RustModule {
    Chrono,
    Grpc,
    Reqwest,
}

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

        let result = match id {
            "chrono" => Chrono,
            "grpc" => Grpc,
            "reqwest" => Reqwest,
            _ => return NoModule::illegal(path, id, value),
        };

        Ok(result)
    }

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

        let result = match id {
            "chrono" => Chrono,
            "grpc" => Grpc,
            "reqwest" => Reqwest,
            _ => return NoModule::illegal(path, id, value),
        };

        Ok(result)
    }
}

pub struct Options {
    pub datetime: Option<Rust<'static>>,
    pub root: Vec<Box<RootCodegen>>,
    pub service: Vec<Box<ServiceCodegen>>,
    pub packages: Rc<Packages>,
}

pub struct Root<'a, 'el: 'a> {
    files: &'a mut BTreeMap<RpPackage, RustFileSpec<'el>>,
}

pub trait RootCodegen {
    /// Generate root code.
    fn generate(&self, root: Root) -> Result<()>;
}

pub struct Service<'a, 'el: 'a> {
    body: &'el flavored::RpServiceBody,
    container: &'a mut Tokens<'el, Rust<'el>>,
    name: Cons<'el>,
    attributes: &'a Tokens<'el, Rust<'el>>,
}

pub trait ServiceCodegen {
    /// Generate service code.
    fn generate(&self, service: Service) -> Result<()>;
}

fn options(modules: Vec<RustModule>, packages: Rc<Packages>) -> Result<Options> {
    use self::RustModule::*;

    let mut options = Options {
        datetime: None,
        root: Vec::new(),
        service: Vec::new(),
        packages: packages,
    };

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

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

        initializer.initialize(&mut options)?;
    }

    Ok(options)
}

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

    let translator = env.translator(flavored::RustFlavorTranslator::new(
        packages.clone(),
        options.datetime.clone(),
    ))?;
    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()
}