nimbus_fml/backends/kotlin/gen_structs/
object.rs

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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use askama::Template;
use std::fmt::Display;

use crate::backends::{
    CodeDeclaration, CodeOracle, CodeType, LiteralRenderer, TypeIdentifier, VariablesType,
};
use crate::intermediate_representation::{FeatureManifest, Literal, ObjectDef};

use super::filters;

use super::common::{self, code_type};

pub struct ObjectRuntime;

impl CodeDeclaration for ObjectRuntime {}

pub struct ObjectCodeType {
    id: String,
}

impl ObjectCodeType {
    pub fn new(id: String) -> Self {
        Self { id }
    }
}

impl CodeType for ObjectCodeType {
    fn type_label(&self, _oracle: &dyn CodeOracle) -> String {
        common::class_name(&self.id)
    }

    fn property_getter(
        &self,
        oracle: &dyn CodeOracle,
        vars: &dyn Display,
        prop: &dyn Display,
        default: &dyn Display,
    ) -> String {
        code_type::property_getter(self, oracle, vars, prop, default)
    }

    fn value_getter(
        &self,
        oracle: &dyn CodeOracle,
        vars: &dyn Display,
        prop: &dyn Display,
    ) -> String {
        code_type::value_getter(self, oracle, vars, prop)
    }

    fn value_mapper(&self, oracle: &dyn CodeOracle) -> Option<String> {
        code_type::value_mapper(self, oracle)
    }

    /// The language specific expression that gets a value of the `prop` from the `vars` object.
    ///
    /// The name of the type as it's represented in the `Variables` object.
    /// The string return may be used to combine with an identifier, e.g. a `Variables` method name.
    fn variables_type(&self, _oracle: &dyn CodeOracle) -> VariablesType {
        VariablesType::Variables
    }

    fn create_transform(&self, oracle: &dyn CodeOracle) -> Option<String> {
        Some(format!("{}::create", self.type_label(oracle)))
    }

    fn merge_transform(&self, oracle: &dyn CodeOracle) -> Option<String> {
        Some(format!("{}::mergeWith", self.type_label(oracle)))
    }

    fn value_merger(&self, _oracle: &dyn CodeOracle, default: &dyn Display) -> Option<String> {
        Some(format!("_mergeWith({})", default))
    }

    fn as_json_transform(&self, _oracle: &dyn CodeOracle, prop: &dyn Display) -> Option<String> {
        Some(format!("{}.toJSONObject()", prop))
    }

    fn literal(
        &self,
        oracle: &dyn CodeOracle,
        ctx: &dyn Display,
        renderer: &dyn LiteralRenderer,
        literal: &Literal,
    ) -> String {
        renderer.literal(
            oracle,
            &TypeIdentifier::Object(self.id.clone()),
            literal,
            ctx,
        )
    }
}

#[derive(Template)]
#[template(syntax = "kt", escape = "none", path = "ObjectTemplate.kt")]
pub(crate) struct ObjectCodeDeclaration {
    inner: ObjectDef,
    fm: FeatureManifest,
}

impl ObjectCodeDeclaration {
    pub fn new(fm: &FeatureManifest, inner: &ObjectDef) -> Self {
        Self {
            fm: fm.clone(),
            inner: inner.clone(),
        }
    }
    pub fn inner(&self) -> ObjectDef {
        self.inner.clone()
    }
}

impl CodeDeclaration for ObjectCodeDeclaration {
    fn definition_code(&self, _oracle: &dyn CodeOracle) -> Option<String> {
        Some(self.render().unwrap())
    }

    fn imports(&self, _oracle: &dyn CodeOracle) -> Option<Vec<String>> {
        Some(vec![
            "org.mozilla.experiments.nimbus.internal.FMLObjectInterface".to_string(),
        ])
    }
}

impl LiteralRenderer for ObjectCodeDeclaration {
    fn literal(
        &self,
        oracle: &dyn CodeOracle,
        typ: &TypeIdentifier,
        value: &Literal,
        ctx: &dyn Display,
    ) -> String {
        object_literal(&self.fm, ctx, &self, oracle, typ, value)
    }
}

pub(crate) fn object_literal(
    fm: &FeatureManifest,
    ctx: &dyn Display,
    renderer: &dyn LiteralRenderer,
    oracle: &dyn CodeOracle,
    typ: &TypeIdentifier,
    value: &Literal,
) -> String {
    let id = if let TypeIdentifier::Object(id) = typ {
        id
    } else {
        return oracle.find(typ).literal(oracle, ctx, renderer, value);
    };
    let literal_map = if let Literal::Object(map) = value {
        map
    } else {
        unreachable!(
            "An JSON object is expected for {} object literal",
            oracle.find(typ).type_label(oracle)
        )
    };

    let def = fm.find_object(id).unwrap();

    let args: Vec<String> = literal_map
        .iter()
        .map(|(k, v)| {
            let prop = def.find_prop(k);

            format!(
                "{var_name} = {var_value}",
                var_name = common::var_name(k),
                var_value = oracle.find(&prop.typ).literal(oracle, ctx, renderer, v)
            )
        })
        .collect();

    format!(
        "{typelabel}({args})",
        typelabel = oracle.find(typ).type_label(oracle),
        args = args.join(", ")
    )
}

#[cfg(test)]
mod unit_tests {
    use serde_json::json;

    use crate::{backends::TypeIdentifier, intermediate_representation::Literal};

    use super::*;

    struct TestCodeOracle;
    impl CodeOracle for TestCodeOracle {
        fn find(&self, _type_: &TypeIdentifier) -> Box<dyn CodeType> {
            unreachable!()
        }
    }

    struct TestRenderer;
    impl LiteralRenderer for TestRenderer {
        fn literal(
            &self,
            _oracle: &dyn CodeOracle,
            typ: &TypeIdentifier,
            _value: &Literal,
            _ctx: &dyn Display,
        ) -> String {
            if let TypeIdentifier::Object(nm) = typ {
                format!("{}()", nm)
            } else {
                unreachable!()
            }
        }
    }

    fn oracle() -> Box<dyn CodeOracle> {
        Box::new(TestCodeOracle) as Box<dyn CodeOracle>
    }

    fn code_type(name: &str) -> Box<dyn CodeType> {
        Box::new(ObjectCodeType::new(name.to_string())) as Box<dyn CodeType>
    }

    fn getter_with_fallback(
        ct: &dyn CodeType,
        vars: &dyn Display,
        prop: &dyn Display,
        def: &dyn Display,
    ) -> String {
        let oracle = &*oracle();
        ct.property_getter(oracle, vars, prop, def)
    }

    #[test]
    fn test_type_label() {
        let ct = code_type("AnObject");
        let oracle = &*oracle();
        assert_eq!("AnObject".to_string(), ct.type_label(oracle))
    }

    #[test]
    fn test_literal() {
        let ct = code_type("AnObject");
        let oracle = &*oracle();
        let finder = &TestRenderer;
        let ctx = "ctx".to_string();
        assert_eq!(
            "AnObject()".to_string(),
            ct.literal(oracle, &ctx, finder, &json!({}))
        );
    }

    #[test]
    fn test_get_value() {
        let ct = code_type("AnObject");
        let oracle = &*oracle();

        assert_eq!(
            r#"v.getVariables("the-property")"#.to_string(),
            ct.value_getter(oracle, &"v", &"the-property")
        );
    }

    #[test]
    fn test_getter_with_fallback() {
        let ct = code_type("AnObject");
        assert_eq!(
            r#"vars.getVariables("the-property")?.let(AnObject::create)?._mergeWith(default) ?: default"#
            .to_string(),
            getter_with_fallback(&*ct, &"vars", &"the-property", &"default"));
    }
}