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}
29
30/// Writes a value as a literal of `ty`.
31pub fn typed(
32    ws: &CheckedWorkspace,
33    profile: &LanguageProfile,
34    how: &Constructors,
35    value: &Value,
36    ty: &Type,
37) -> String {
38    let ty = ws.expand_alias(ty);
39
40    match (&ty, value) {
41        // Absence is whatever this language writes for nothing, which the
42        // untyped writer already knows.
43        (_, Value::Null) => (how.plain)(value),
44
45        (Type::Optional { of }, present) => typed(ws, profile, how, present, of),
46
47        (Type::List { of }, Value::List(items)) => {
48            let parts: Vec<String> = items
49                .iter()
50                .map(|i| typed(ws, profile, how, i, of))
51                .collect();
52            wrap_list(how, &parts)
53        }
54
55        (Type::Tuple { items: types }, Value::Tuple(items)) if types.len() == items.len() => {
56            let parts: Vec<String> = types
57                .iter()
58                .zip(items)
59                .map(|(t, i)| typed(ws, profile, how, i, t))
60                .collect();
61            (how.plain)(&Value::Tuple(
62                // Rebuilt so the untyped writer supplies this language's
63                // bracketing, with the parts already written.
64                parts.iter().map(|p| Value::Str(p.clone())).collect(),
65            ))
66            .replace('"', "")
67        }
68
69        // Whichever alternative it actually is decides how it is written, which
70        // is what makes a discriminated union come out as the right thing.
71        (Type::Union { members }, _) => {
72            for member in members {
73                if ws.validate(value, member).is_ok() {
74                    return typed(ws, profile, how, value, member);
75                }
76            }
77            (how.plain)(value)
78        }
79
80        (Type::Record { fields }, Value::Record(entries)) => {
81            // An anonymous record has no name to construct, so it stays a map.
82            let parts: Vec<String> = entries
83                .iter()
84                .map(|(name, entry)| {
85                    let declared = fields.iter().find(|f| f.name.as_str() == name);
86                    let written = match declared {
87                        Some(field) => typed(ws, profile, how, entry, &field.ty),
88                        None => (how.plain)(entry),
89                    };
90                    format!("{}: {written}", (how.plain)(&Value::Str(name.clone())))
91                })
92                .collect();
93            format!("{{{}}}", parts.join(", "))
94        }
95
96        (Type::Ref(r), _) => {
97            let Some(def) = ws.ref_target_of(r).and_then(|q| ws.def(&q).cloned()) else {
98                return (how.plain)(value);
99            };
100            match (&def, value) {
101                (TypeDef::Struct(_) | TypeDef::Interface(_), Value::Record(entries)) => {
102                    let declared = ws.fields_of(r).unwrap_or_default();
103                    // Declaration order, not whatever order the value arrived
104                    // in: generated code should look the way the declaration
105                    // does.
106                    let parts: Vec<(String, String)> = declared
107                        .iter()
108                        .filter_map(|field| {
109                            let entry = entries.get(field.name.as_str())?;
110                            // A field that is absent is left out, the same way
111                            // it is left out of the wire form.
112                            if matches!(entry, Value::Null) {
113                                return None;
114                            }
115                            Some((
116                                profile.name(&field.name),
117                                typed(ws, profile, how, entry, &field.ty),
118                            ))
119                        })
120                        .collect();
121                    (how.record)(&profile.name(&r.name), &parts)
122                }
123                (
124                    TypeDef::Enum(d),
125                    Value::Variant {
126                        tag,
127                        value: payload,
128                    },
129                ) => {
130                    let carried = d
131                        .variants
132                        .iter()
133                        .find(|v| v.name.as_str() == tag)
134                        .filter(|v| !matches!(v.payload, Type::Unit))
135                        .map(|v| typed(ws, profile, how, payload, &v.payload));
136                    (how.variant)(&profile.name(&r.name), tag, carried.as_deref())
137                }
138                _ => (how.plain)(value),
139            }
140        }
141
142        _ => (how.plain)(value),
143    }
144}
145
146/// This language's brackets for a list, borrowed from its untyped writer.
147fn wrap_list(how: &Constructors, parts: &[String]) -> String {
148    // Written as a list of placeholders and then filled in, so the brackets
149    // come from the same place they would for any other list.
150    let shape = (how.plain)(&Value::List(parts.iter().map(|_| Value::Null).collect()));
151    let mut out = String::with_capacity(shape.len() + parts.iter().map(String::len).sum::<usize>());
152    let mut parts = parts.iter();
153    let mut rest = shape.as_str();
154    // The placeholder is whatever this language writes for nothing.
155    let nothing = (how.plain)(&Value::Null);
156    while let Some(at) = rest.find(&nothing) {
157        out.push_str(&rest[..at]);
158        match parts.next() {
159            Some(part) => out.push_str(part),
160            None => out.push_str(&nothing),
161        }
162        rest = &rest[at + nothing.len()..];
163    }
164    out.push_str(rest);
165    out
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use unitype_core::Workspace;
172    use unitype_core::check::check_workspace;
173    use unitype_core::ir::TypeRef;
174    use unitype_core::lang::profile;
175    use unitype_core::{Ident, QualifiedName};
176
177    const WS: &str = r#"{"universes":[{"name":"demo","types":[
178        {"k":"struct","name":"Shape","fields":[{"name":"id","ty":"str"}]},
179        {"k":"struct","name":"Circle","extends":"Shape","fields":[
180            {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
181            {"name":"radius","ty":"float"},
182            {"name":"note","ty":"str?"}]},
183        {"k":"enum","name":"Colour","variants":[
184            {"name":"Red"},{"name":"Custom","payload":"str"}]},
185        {"k":"struct","name":"Bag","fields":[{"name":"items","ty":"[Circle]"}]}]}]}"#;
186
187    fn ws() -> CheckedWorkspace {
188        check_workspace(Workspace::from_json(WS).expect("reads")).expect("checks")
189    }
190
191    fn named(name: &str) -> Type {
192        Type::Ref(TypeRef::qualified(
193            Ident::new("demo").unwrap(),
194            Ident::new(name).unwrap(),
195        ))
196    }
197
198    fn write(lang: &str, json: &str, ty: &Type) -> String {
199        let ws = ws();
200        let value = ws.read_json(json, ty).expect("a real value");
201        let profile = profile(lang).expect("ships");
202        let how = crate::constructors(lang).expect("has constructors");
203        typed(&ws, &profile, &how, &value, ty)
204    }
205
206    #[test]
207    fn a_struct_becomes_the_way_that_language_builds_one() {
208        let json = r#"{"id":"c-1","kind":"circle","radius":2.5}"#;
209        assert_eq!(
210            write("python", json, &named("Circle")),
211            r#"Circle(id="c-1", kind="circle", radius=2.5)"#
212        );
213        assert_eq!(
214            write("rust", json, &named("Circle")),
215            r#"Circle { id: "c-1".to_string(), kind: "circle".to_string(), radius: 2.5 }"#
216        );
217        assert_eq!(
218            write("typescript", json, &named("Circle")),
219            r#"{ id: "c-1", kind: "circle", radius: 2.5 }"#
220        );
221    }
222
223    #[test]
224    fn fields_come_out_in_the_order_they_were_declared() {
225        // The value arrived with its fields in a different order; generated
226        // code should still look the way the declaration does.
227        let scrambled = r#"{"radius":2.5,"kind":"circle","id":"c-1"}"#;
228        assert_eq!(
229            write("python", scrambled, &named("Circle")),
230            r#"Circle(id="c-1", kind="circle", radius=2.5)"#
231        );
232    }
233
234    #[test]
235    fn a_field_that_is_absent_is_left_out_of_the_literal_too() {
236        let with_null = r#"{"id":"c-1","kind":"circle","radius":2.5,"note":null}"#;
237        let written = write("python", with_null, &named("Circle"));
238        assert!(!written.contains("note"), "{written}");
239    }
240
241    #[test]
242    fn a_nested_struct_is_built_rather_than_flattened_into_a_map() {
243        let json = r#"{"items":[{"id":"c-1","kind":"circle","radius":1.0}]}"#;
244        let written = write("rust", json, &named("Bag"));
245        assert!(
246            written.contains("Circle {"),
247            "the element is a Circle, so it should be built as one: {written}"
248        );
249        assert!(written.starts_with("Bag {"), "{written}");
250    }
251
252    #[test]
253    fn a_variant_is_named_the_way_that_language_names_one() {
254        assert_eq!(write("rust", r#""Red""#, &named("Colour")), "Colour::Red");
255        assert_eq!(
256            write(
257                "rust",
258                r#"{"$tag":"Custom","value":"teal"}"#,
259                &named("Colour")
260            ),
261            r#"Colour::Custom("teal".to_string())"#
262        );
263        assert_eq!(
264            write("python", r#""Red""#, &named("Colour")),
265            r#"{"$tag": "Red"}"#
266        );
267    }
268
269    #[test]
270    fn a_list_gets_that_language_brackets_with_the_parts_filled_in() {
271        let json = r#"{"items":[{"id":"a","kind":"circle","radius":1.0},
272                                {"id":"b","kind":"circle","radius":2.0}]}"#;
273        let written = write("python", json, &named("Bag"));
274        assert!(written.contains("items=[Circle("), "{written}");
275        assert_eq!(written.matches("Circle(").count(), 2, "{written}");
276    }
277
278    #[test]
279    fn without_a_type_to_go_on_a_record_stays_a_map() {
280        let ws = ws();
281        let value = ws
282            .read_json(r#"{"whatever":1}"#, &Type::Any)
283            .expect("reads");
284        let profile = profile("python").expect("ships");
285        let how = crate::constructors("python").expect("has constructors");
286        assert_eq!(
287            typed(&ws, &profile, &how, &value, &Type::Any),
288            r#"{"whatever": 1}"#
289        );
290    }
291
292    #[test]
293    fn every_shipped_language_has_constructors() {
294        for lang in unitype_core::LANGUAGES {
295            assert!(crate::constructors(lang).is_some(), "{lang}");
296        }
297        let _ = QualifiedName::new(Ident::new("a").unwrap(), Ident::new("b").unwrap());
298    }
299}