zamm_yang 0.1.8

A basic, experimental code generator
Documentation
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use crate::codegen::StructConfig;
use crate::tao::perspective::{BuildInfo, BuildInfoExtension, KnowledgeGraphNode};
use heck::{CamelCase, SnakeCase};
use itertools::Itertools;
use std::rc::Rc;
use zamm_yin::node_wrappers::CommonNodeTrait;
use zamm_yin::tao::archetype::{Archetype, ArchetypeFormTrait, ArchetypeTrait};
use zamm_yin::tao::form::FormTrait;
use zamm_yin::tao::Tao;

/// Whether or not this is the root node, or marked as an analogous root node.
pub fn root_node_or_equivalent(target: &Archetype) -> bool {
    target.id() == Tao::TYPE_ID || KnowledgeGraphNode::from(target.id()).is_root_analogue()
}

/// Whether or not the given archetype belongs in its own submodule.
pub fn in_own_submodule(target: &Archetype) -> bool {
    // todo: filter by type, once Yin has that functionality
    BuildInfo::from(target.id()).is_own_module()
        || root_node_or_equivalent(target)
        || !target.child_archetypes().is_empty()
}

/// The import path for concepts, starting from Tao and leading to the given archetype.
pub fn ancestor_path(target: &Archetype, separator: &str) -> String {
    let build_info = BuildInfo::from(target.id());
    match build_info.import_path() {
        Some(existing_path) => {
            let modules = existing_path.split("::").collect::<Vec<&str>>();
            modules
                .iter()
                .skip(1)
                .take(modules.len() - 2)
                .format(separator)
                .to_string()
        }
        None => {
            // parent path matters because we want to follow whatever convention the parent is
            // following
            let parent_path = if root_node_or_equivalent(target) {
                None
            } else {
                Some(ancestor_path(&target.parents().first().unwrap(), separator))
            };

            let target_name = target
                .internal_name_str()
                .unwrap()
                .to_snake_case()
                .to_ascii_lowercase();
            if in_own_submodule(target) {
                match parent_path {
                    Some(actual_parent_path) => {
                        format!("{}{}{}", actual_parent_path, separator, target_name)
                    }
                    None => target_name,
                }
            } else {
                parent_path.unwrap() // if not in own module, then parent must be it
            }
        }
    }
}

fn snake_name(target: &Archetype) -> String {
    target
        .internal_name_str()
        .unwrap()
        .to_snake_case()
        .to_ascii_lowercase()
}

/// Get the output path for a given concept.
pub fn archetype_file_path(target: &Archetype) -> String {
    // append _form to filename to avoid
    // https://rust-lang.github.io/rust-clippy/master/index.html#module_inception
    format!(
        "src/{}/{}_form.rs",
        ancestor_path(target, "/"),
        snake_name(target)
    )
}

/// Get the output path for a given concept.
pub fn module_file_path(target: &Archetype) -> String {
    // module path should always be forced if mod.rs is being generated for it
    assert!(in_own_submodule(target));
    format!("src/{}/mod.rs", ancestor_path(target, "/"))
}

/// Returns the full import path, including the crate itself.
///
/// `yin_override` needed for now because Yin is not yet fully described by its own yin.md.
/// todo: remove once Yin supports that
pub fn import_path(target: &KnowledgeGraphNode, yin_override: bool) -> String {
    let build_info = BuildInfo::from(target.id());
    match build_info.import_path() {
        Some(existing_path) => (*existing_path).to_owned(),
        None => {
            let yin_crate = if build_info.crate_name().is_some() {
                (*build_info.crate_name().unwrap()).to_owned()
            } else if yin_override || target.is_newly_defined() {
                assert!(
                    !target.is_imported(),
                    "{:?} is both newly defined and imported",
                    target
                );
                "crate".to_owned()
            } else {
                "zamm_yin".to_owned()
            };
            let struct_name = target.internal_name_str().unwrap().to_camel_case();
            format!(
                "{}::{}::{}",
                yin_crate,
                ancestor_path(&Archetype::from(target.id()), "::"),
                struct_name
            )
        }
    }
}

/// Turns a concept into a struct to be imported.
pub fn concept_to_struct(target: &Archetype, yin_override: bool) -> StructConfig {
    let build_info = BuildInfo::from(target.id());
    let name = build_info.implementation_name().unwrap_or_else(|| {
        Rc::from(
            target
                .internal_name_str()
                .unwrap_or_else(|| panic!("{:?} has no internal name", target))
                .to_camel_case()
                .as_str(),
        )
    });
    StructConfig {
        name: (*name).to_owned(),
        import: import_path(&KnowledgeGraphNode::from(target.id()), yin_override),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tao::initialize_kb;
    use zamm_yin::tao::archetype::ArchetypeTrait;
    use zamm_yin::tao::relation::attribute::{Attribute, Owner};
    use zamm_yin::tao::Tao;

    #[test]
    fn own_submodule_tao() {
        initialize_kb();
        assert!(in_own_submodule(&Tao::archetype()));
    }

    #[test]
    fn own_submodule_parent() {
        initialize_kb();
        let mut parent = Tao::archetype().individuate_as_archetype();
        parent.set_internal_name_str("parent");
        let mut child = parent.individuate_as_archetype();
        child.set_internal_name_str("child");
        assert!(in_own_submodule(&parent));
    }

    #[test]
    fn own_submodule_nested() {
        initialize_kb();
        let mut parent = Tao::archetype().individuate_as_archetype();
        parent.set_internal_name_str("parent");
        let mut child = parent.individuate_as_archetype();
        child.set_internal_name_str("child");
        assert!(!in_own_submodule(&child));
    }

    #[test]
    fn own_submodule_forced() {
        initialize_kb();
        let mut parent = Tao::archetype().individuate_as_archetype();
        parent.set_internal_name_str("parent");
        let mut child = parent.individuate_as_archetype();
        child.set_internal_name_str("child");
        // these are individuals, not subtypes, so don't count towards a submodule
        child.individuate_as_form();
        child.individuate_as_form();
        assert!(!in_own_submodule(&child));
    }

    #[test]
    fn folder_path_tao() {
        initialize_kb();
        assert_eq!(
            archetype_file_path(&Tao::archetype()),
            "src/tao/tao_form.rs"
        );
    }

    #[test]
    fn folder_path_attributes() {
        initialize_kb();
        assert_eq!(
            archetype_file_path(&Attribute::archetype().into()),
            "src/tao/relation/attribute/attribute_form.rs"
        );
    }

    #[test]
    fn folder_path_nested() {
        initialize_kb();
        assert_eq!(
            archetype_file_path(&Owner::archetype().into()),
            "src/tao/relation/attribute/owner_form.rs"
        );
    }

    #[test]
    fn folder_path_forced_own_module() {
        initialize_kb();
        let owner = Owner::archetype();
        BuildInfo::from(owner.id()).mark_own_module();
        assert_eq!(
            archetype_file_path(&owner.into()),
            "src/tao/relation/attribute/owner/owner_form.rs"
        );
    }

    #[test]
    fn folder_path_custom_module() {
        initialize_kb();
        BuildInfo::from(Attribute::TYPE_ID)
            .set_import_path("zamm_yin::tao::newfangled::module::attribute::Attribute".to_owned());
        let owner = Owner::archetype();
        BuildInfo::from(owner.id()).mark_own_module();
        assert_eq!(
            archetype_file_path(&owner.into()),
            "src/tao/newfangled/module/attribute/owner/owner_form.rs"
        );
    }

    #[test]
    fn module_path_tao() {
        initialize_kb();
        assert_eq!(module_file_path(&Tao::archetype()), "src/tao/mod.rs");
    }

    #[test]
    fn module_path_attributes() {
        initialize_kb();
        assert_eq!(
            module_file_path(&Attribute::archetype().into()),
            "src/tao/relation/attribute/mod.rs"
        );
    }

    #[test]
    fn module_path_forced_own_module() {
        initialize_kb();
        let owner = Owner::archetype();
        BuildInfo::from(owner.id()).mark_own_module();
        assert_eq!(
            module_file_path(&owner.into()),
            "src/tao/relation/attribute/owner/mod.rs"
        );
    }

    #[test]
    fn import_path_tao() {
        initialize_kb();
        assert_eq!(
            import_path(&KnowledgeGraphNode::from(Tao::TYPE_ID), false),
            "zamm_yin::tao::Tao"
        );
    }

    #[test]
    fn import_path_attributes() {
        initialize_kb();
        assert_eq!(
            import_path(&KnowledgeGraphNode::from(Attribute::TYPE_ID), false),
            "zamm_yin::tao::relation::attribute::Attribute"
        );
    }

    #[test]
    fn import_path_nested() {
        initialize_kb();
        assert_eq!(
            import_path(&KnowledgeGraphNode::from(Owner::TYPE_ID), false),
            "zamm_yin::tao::relation::attribute::Owner"
        );
    }

    #[test]
    fn import_path_forced_own_module() {
        initialize_kb();
        BuildInfo::from(Owner::TYPE_ID).mark_own_module();
        assert_eq!(
            import_path(&KnowledgeGraphNode::from(Owner::TYPE_ID), false),
            "zamm_yin::tao::relation::attribute::owner::Owner"
        );
    }

    #[test]
    fn import_path_newly_defined() {
        initialize_kb();
        let mut owner = KnowledgeGraphNode::from(Owner::TYPE_ID);
        owner.mark_newly_defined();
        assert_eq!(
            import_path(&owner, false),
            "crate::tao::relation::attribute::Owner"
        );
    }

    #[test]
    fn import_path_custom_module() {
        initialize_kb();
        BuildInfo::from(Attribute::TYPE_ID)
            .set_import_path("zamm_yin::tao::newfangled::module::attribute::Attribute".to_owned());
        let mut owner = KnowledgeGraphNode::from(Owner::TYPE_ID);
        BuildInfo::from(Owner::TYPE_ID).mark_own_module();
        owner.mark_newly_defined();
        assert_eq!(
            import_path(&owner, false),
            "crate::tao::newfangled::module::attribute::owner::Owner"
        );
    }

    #[test]
    fn import_path_custom_crate() {
        initialize_kb();
        BuildInfo::from(Attribute::TYPE_ID)
            .set_import_path("zamm_yin::tao::newfangled::module::attribute::Attribute".to_owned());
        let mut owner = KnowledgeGraphNode::from(Owner::TYPE_ID);
        BuildInfo::from(Owner::TYPE_ID).mark_own_module();
        owner.mark_newly_defined();
        // possible if we've defined a new type, but we did so only to tell yang that it's already
        // been implemented as part of a dependency
        BuildInfo::from(owner.id()).set_crate_name("mycrate");
        assert_eq!(
            import_path(&owner, false),
            "mycrate::tao::newfangled::module::attribute::owner::Owner"
        );
    }

    #[test]
    fn import_path_multiple_descendants() {
        initialize_kb();
        let type1 = Tao::archetype().individuate_as_archetype();
        let mut type1_node = KnowledgeGraphNode::from(type1.id());
        type1_node.set_internal_name_str("hello");
        type1_node.mark_newly_defined();
        let type2 = type1.individuate_as_archetype();
        let mut type2_node = KnowledgeGraphNode::from(type2.id());
        type2_node.set_internal_name_str("world");
        type2_node.mark_newly_defined();
        BuildInfo::from(type2.id()).mark_own_module();
        assert_eq!(
            import_path(&type2_node, false),
            "crate::tao::hello::world::World"
        );
    }

    #[test]
    fn import_path_custom_root() {
        initialize_kb();
        let root = Tao::archetype().individuate_as_archetype();
        let mut root_node = KnowledgeGraphNode::from(root.id());
        root_node.set_internal_name_str("my-root");
        root_node.mark_newly_defined();
        root_node.mark_root_analogue();
        assert_eq!(import_path(&root_node, false), "crate::my_root::MyRoot");
    }

    #[test]
    fn struct_config_tao() {
        initialize_kb();
        assert_eq!(
            concept_to_struct(&Tao::archetype(), false),
            StructConfig {
                name: "Tao".to_owned(),
                import: "zamm_yin::tao::Tao".to_owned(),
            }
        );
    }

    #[test]
    fn struct_config_attributes() {
        initialize_kb();
        assert_eq!(
            concept_to_struct(&Attribute::archetype().into(), false),
            StructConfig {
                name: "Attribute".to_owned(),
                import: "zamm_yin::tao::relation::attribute::Attribute".to_owned(),
            }
        );
    }

    #[test]
    fn struct_config_nested() {
        initialize_kb();
        assert_eq!(
            concept_to_struct(&Owner::archetype().into(), false),
            StructConfig {
                name: "Owner".to_owned(),
                import: "zamm_yin::tao::relation::attribute::Owner".to_owned(),
            }
        );
    }

    #[test]
    fn struct_config_forced_own_module() {
        initialize_kb();
        BuildInfo::from(Owner::TYPE_ID).mark_own_module();
        assert_eq!(
            concept_to_struct(&Owner::archetype().into(), false),
            StructConfig {
                name: "Owner".to_owned(),
                import: "zamm_yin::tao::relation::attribute::owner::Owner".to_owned(),
            }
        );
    }

    #[test]
    fn struct_config_newly_defined() {
        initialize_kb();
        let owner = Owner::archetype();
        KnowledgeGraphNode::from(owner.id()).mark_newly_defined();
        assert_eq!(
            concept_to_struct(&owner.into(), false),
            StructConfig {
                name: "Owner".to_owned(),
                import: "crate::tao::relation::attribute::Owner".to_owned(),
            }
        );
    }

    #[test]
    fn struct_config_override() {
        initialize_kb();
        let mut tao_build = BuildInfo::from(Tao::TYPE_ID);
        tao_build.set_implementation_name("TaoStruct");
        tao_build.set_import_path("crate::TaoStruct".to_owned());
        assert_eq!(
            concept_to_struct(&Tao::archetype(), false),
            StructConfig {
                name: "TaoStruct".to_owned(),
                import: "crate::TaoStruct".to_owned(),
            }
        );
    }
}