Skip to main content

unitype_codegen/
literal.rs

1//! Writing a value out as a literal, in a language, against its type.
2//!
3//! Without a type, a record is only a bag of names and there is nothing better
4//! to write than a map. With one, it is a `Circle`, and what should come out is
5//! whatever that language says for constructing one.
6//!
7//! This is the half of "move a value between languages" that the reading side
8//! already had: text goes in and becomes a value of a known type, and here that
9//! value goes back out as something you can paste into a source file.
10
11use unitype_core::check::CheckedWorkspace;
12use unitype_core::ir::{Type, TypeDef};
13use unitype_core::lang::LanguageProfile;
14use unitype_core::value::Value;
15
16/// How one language writes the parts a value is made of.
17///
18/// Only the pieces that differ. What a float or a string looks like is already
19/// each backend's untyped literal writer; what differs once a type is known is
20/// how a struct is built and how a variant is named.
21pub struct Constructors {
22    /// Builds a named struct from `name` and its `field = value` parts.
23    pub record: fn(&str, &[(String, String)]) -> String,
24    /// Builds one alternative of a named enum.
25    pub variant: fn(&str, &str, Option<&str>) -> String,
26    /// Writes a value with no type to guide it.
27    pub plain: fn(&Value) -> String,
28    /// Brackets parts that are already written as this language's tuple.
29    pub tuple: fn(&[String]) -> String,
30    /// Writes a whole value against its type, for a language where the shared
31    /// walk below is not enough: one that names a field after the type that
32    /// declares it, or has to say that a value is present before it is
33    /// allowed where one that may be absent is wanted.
34    pub typed: Option<fn(&CheckedWorkspace, &Value, &Type) -> String>,
35}
36
37/// A tuple in the languages that write one with parentheses, which need a
38/// trailing comma to tell a one-element tuple from a parenthesised value.
39pub(crate) fn parenthesised(parts: &[String]) -> String {
40    match parts {
41        [only] => format!("({only},)"),
42        _ => format!("({})", parts.join(", ")),
43    }
44}
45
46/// Writes a value as a literal of `ty`.
47pub fn typed(
48    ws: &CheckedWorkspace,
49    profile: &LanguageProfile,
50    how: &Constructors,
51    value: &Value,
52    ty: &Type,
53) -> String {
54    if let Some(own) = how.typed {
55        return own(ws, value, ty);
56    }
57    let ty = ws.expand_alias(ty);
58
59    match (&ty, value) {
60        // Absence is whatever this language writes for nothing, which the
61        // untyped writer already knows.
62        (_, Value::Null) => (how.plain)(value),
63
64        (Type::Optional { of }, present) => typed(ws, profile, how, present, of),
65
66        // Bounds change nothing about how a value is written.
67        (Type::Bounded { of, .. }, _) => typed(ws, profile, how, value, of),
68
69        (Type::List { of }, Value::List(items)) => {
70            let parts: Vec<String> = items
71                .iter()
72                .map(|i| typed(ws, profile, how, i, of))
73                .collect();
74            wrap_list(how, &parts)
75        }
76
77        (Type::Tuple { items: types }, Value::Tuple(items)) if types.len() == items.len() => {
78            let parts: Vec<String> = types
79                .iter()
80                .zip(items)
81                .map(|(t, i)| typed(ws, profile, how, i, t))
82                .collect();
83            (how.tuple)(&parts)
84        }
85
86        // Whichever alternative it actually is decides how it is written, which
87        // is what makes a discriminated union come out as the right thing.
88        (Type::Union { members }, _) => {
89            for member in members {
90                if ws.validate(value, member).is_ok() {
91                    return typed(ws, profile, how, value, member);
92                }
93            }
94            (how.plain)(value)
95        }
96
97        (Type::Record { fields }, Value::Record(entries)) => {
98            // An anonymous record has no name to construct, so it stays a map.
99            let parts: Vec<String> = entries
100                .iter()
101                .map(|(name, entry)| {
102                    let declared = fields.iter().find(|f| f.name.as_str() == name);
103                    let written = match declared {
104                        Some(field) => typed(ws, profile, how, entry, &field.ty),
105                        None => (how.plain)(entry),
106                    };
107                    format!("{}: {written}", (how.plain)(&Value::Str(name.clone())))
108                })
109                .collect();
110            format!("{{{}}}", parts.join(", "))
111        }
112
113        (Type::Ref(r), _) => {
114            let Some(def) = ws.ref_target_of(r).and_then(|q| ws.def(&q).cloned()) else {
115                return (how.plain)(value);
116            };
117            match (&def, value) {
118                (TypeDef::Struct(_) | TypeDef::Interface(_), Value::Record(entries)) => {
119                    let declared = ws.fields_of(r).unwrap_or_default();
120                    // Declaration order, not whatever order the value arrived
121                    // in: generated code should look the way the declaration
122                    // does.
123                    let parts: Vec<(String, String)> = declared
124                        .iter()
125                        .filter_map(|field| {
126                            let entry = entries.get(field.name.as_str())?;
127                            // A field that is absent is left out, the same way
128                            // it is left out of the wire form.
129                            if matches!(entry, Value::Null) {
130                                return None;
131                            }
132                            Some((
133                                profile.name(&field.name),
134                                typed(ws, profile, how, entry, &field.ty),
135                            ))
136                        })
137                        .collect();
138                    (how.record)(&profile.name(&r.name), &parts)
139                }
140                (
141                    TypeDef::Enum(d),
142                    Value::Variant {
143                        tag,
144                        value: payload,
145                    },
146                ) => {
147                    let carried = d
148                        .variants
149                        .iter()
150                        .find(|v| v.name.as_str() == tag)
151                        .filter(|v| !matches!(v.payload, Type::Unit))
152                        .map(|v| typed(ws, profile, how, payload, &v.payload));
153                    (how.variant)(&profile.name(&r.name), tag, carried.as_deref())
154                }
155                _ => (how.plain)(value),
156            }
157        }
158
159        _ => (how.plain)(value),
160    }
161}
162
163/// This language's brackets for a list, borrowed from its untyped writer.
164fn wrap_list(how: &Constructors, parts: &[String]) -> String {
165    // Written as a list of placeholders and then filled in, so the brackets
166    // come from the same place they would for any other list.
167    let shape = (how.plain)(&Value::List(parts.iter().map(|_| Value::Null).collect()));
168    let mut out = String::with_capacity(shape.len() + parts.iter().map(String::len).sum::<usize>());
169    let mut parts = parts.iter();
170    let mut rest = shape.as_str();
171    // The placeholder is whatever this language writes for nothing.
172    let nothing = (how.plain)(&Value::Null);
173    while let Some(at) = rest.find(&nothing) {
174        out.push_str(&rest[..at]);
175        match parts.next() {
176            Some(part) => out.push_str(part),
177            None => out.push_str(&nothing),
178        }
179        rest = &rest[at + nothing.len()..];
180    }
181    out.push_str(rest);
182    out
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use unitype_core::Workspace;
189    use unitype_core::check::check_workspace;
190    use unitype_core::ir::TypeRef;
191    use unitype_core::lang::profile;
192    use unitype_core::{Ident, QualifiedName};
193
194    const WS: &str = r#"{"universes":[{"name":"demo","types":[
195        {"k":"struct","name":"Shape","fields":[{"name":"id","ty":"str"}]},
196        {"k":"struct","name":"Circle","extends":"Shape","fields":[
197            {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
198            {"name":"radius","ty":"float"},
199            {"name":"note","ty":"str?"}]},
200        {"k":"enum","name":"Colour","variants":[
201            {"name":"Red"},{"name":"Custom","payload":"str"}]},
202        {"k":"struct","name":"Bag","fields":[{"name":"items","ty":"[Circle]"}]},
203        {"k":"struct","name":"Pairs","fields":[
204            {"name":"named","ty":{"k":"tuple","items":["i64","str"]}},
205            {"name":"point","ty":{"k":"tuple","items":["i64","i64"]}}]}]}]}"#;
206
207    fn ws() -> CheckedWorkspace {
208        check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks")
209    }
210
211    fn named(name: &str) -> Type {
212        Type::Ref(TypeRef::qualified(
213            Ident::new("demo").unwrap(),
214            Ident::new(name).unwrap(),
215        ))
216    }
217
218    fn write(lang: &str, json: &str, ty: &Type) -> String {
219        let ws = ws();
220        let value = ws.read_json(json, ty).expect("a real value");
221        let profile = profile(lang).expect("ships");
222        let how = crate::constructors(lang).expect("has constructors");
223        typed(&ws, &profile, &how, &value, ty)
224    }
225
226    #[test]
227    fn a_struct_becomes_the_way_that_language_builds_one() {
228        let json = r#"{"id":"c-1","kind":"circle","radius":2.5}"#;
229        assert_eq!(
230            write("python", json, &named("Circle")),
231            r#"Circle(id="c-1", kind="circle", radius=2.5)"#
232        );
233        assert_eq!(
234            write("rust", json, &named("Circle")),
235            r#"Circle { id: "c-1".to_string(), kind: "circle".to_string(), radius: 2.5 }"#
236        );
237        assert_eq!(
238            write("typescript", json, &named("Circle")),
239            r#"{ id: "c-1", kind: "circle", radius: 2.5 }"#
240        );
241    }
242
243    #[test]
244    fn fields_come_out_in_the_order_they_were_declared() {
245        // The value arrived with its fields in a different order; generated
246        // code should still look the way the declaration does.
247        let scrambled = r#"{"radius":2.5,"kind":"circle","id":"c-1"}"#;
248        assert_eq!(
249            write("python", scrambled, &named("Circle")),
250            r#"Circle(id="c-1", kind="circle", radius=2.5)"#
251        );
252    }
253
254    #[test]
255    fn a_field_that_is_absent_is_left_out_of_the_literal_too() {
256        let with_null = r#"{"id":"c-1","kind":"circle","radius":2.5,"note":null}"#;
257        let written = write("python", with_null, &named("Circle"));
258        assert!(!written.contains("note"), "{written}");
259    }
260
261    #[test]
262    fn a_nested_struct_is_built_rather_than_flattened_into_a_map() {
263        let json = r#"{"items":[{"id":"c-1","kind":"circle","radius":1.0}]}"#;
264        let written = write("rust", json, &named("Bag"));
265        assert!(
266            written.contains("Circle {"),
267            "the element is a Circle, so it should be built as one: {written}"
268        );
269        assert!(written.starts_with("Bag {"), "{written}");
270    }
271
272    #[test]
273    fn a_variant_is_named_the_way_that_language_names_one() {
274        assert_eq!(write("rust", r#""Red""#, &named("Colour")), "Colour::Red");
275        assert_eq!(
276            write(
277                "rust",
278                r#"{"$tag":"Custom","value":"teal"}"#,
279                &named("Colour")
280            ),
281            r#"Colour::Custom("teal".to_string())"#
282        );
283        assert_eq!(
284            write("python", r#""Red""#, &named("Colour")),
285            r#"{"$tag": "Red"}"#
286        );
287    }
288
289    #[test]
290    fn a_list_gets_that_language_brackets_with_the_parts_filled_in() {
291        let json = r#"{"items":[{"id":"a","kind":"circle","radius":1.0},
292                                {"id":"b","kind":"circle","radius":2.0}]}"#;
293        let written = write("python", json, &named("Bag"));
294        assert!(written.contains("items=[Circle("), "{written}");
295        assert_eq!(written.matches("Circle(").count(), 2, "{written}");
296    }
297
298    #[test]
299    fn a_tuple_with_a_string_in_it_keeps_the_quotes_around_the_string() {
300        let json = r#"{"named":[1,"a"],"point":[1,2]}"#;
301        assert_eq!(
302            write("python", json, &named("Pairs")),
303            r#"Pairs(named=(1, "a"), point=(1, 2))"#
304        );
305        assert_eq!(
306            write("typescript", json, &named("Pairs")),
307            r#"{ named: [1, "a"], point: [1, 2] }"#
308        );
309        assert_eq!(
310            write("rust", json, &named("Pairs")),
311            r#"Pairs { named: (1, "a".to_string()), point: (1, 2) }"#
312        );
313    }
314
315    #[test]
316    fn a_tuple_of_numbers_is_not_rewritten_as_strings() {
317        let json = r#"{"named":[7,"x"],"point":[3,4]}"#;
318        let rust = write("rust", json, &named("Pairs"));
319        assert!(rust.contains("point: (3, 4)"), "{rust}");
320        assert!(!rust.contains("3.to_string()"), "{rust}");
321    }
322
323    #[test]
324    fn a_one_element_tuple_keeps_its_trailing_comma_where_it_needs_one() {
325        // A schema cannot declare one — canonical form collapses a one-element
326        // tuple to its element — so the type and value are built by hand.
327        let ty = Type::Tuple {
328            items: vec![Type::String],
329        };
330        let value = Value::Tuple(vec![Value::Str("only".into())]);
331        let ws = ws();
332        let write = |lang: &str| {
333            let profile = profile(lang).expect("ships");
334            let how = crate::constructors(lang).expect("has constructors");
335            typed(&ws, &profile, &how, &value, &ty)
336        };
337        assert_eq!(write("python"), r#"("only",)"#);
338        assert_eq!(write("rust"), r#"("only".to_string(),)"#);
339        assert_eq!(write("typescript"), r#"["only"]"#);
340    }
341
342    #[test]
343    fn without_a_type_to_go_on_a_record_stays_a_map() {
344        let ws = ws();
345        let value = ws
346            .read_json(r#"{"whatever":1}"#, &Type::Any)
347            .expect("reads");
348        let profile = profile("python").expect("ships");
349        let how = crate::constructors("python").expect("has constructors");
350        assert_eq!(
351            typed(&ws, &profile, &how, &value, &Type::Any),
352            r#"{"whatever": 1}"#
353        );
354    }
355
356    #[test]
357    fn every_shipped_language_has_constructors() {
358        for lang in unitype_core::LANGUAGES {
359            assert!(crate::constructors(lang).is_some(), "{lang}");
360        }
361        let _ = QualifiedName::new(Ident::new("a").unwrap(), Ident::new("b").unwrap());
362    }
363}