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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use super::{
    AppendedFragment, AtomicFragment, CodeFragment, FileFragment, ItemDeclaration,
    ItemDeclarationAPI,
};
use crate::codegen::docstring::into_parent_docstring;
use crate::codegen::template::imports::{imports_as_str, re_exports_as_str};
use crate::codegen::CODE_WIDTH;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;

/// Fragment for a module declaration.
pub struct ModuleFragment {
    name: Option<String>,
    declaration: ItemDeclaration,
    test: bool,
    uses_entire_file: bool,
    re_exports: Vec<String>,
    submodules: Vec<Rc<RefCell<ModuleFragment>>>,
    content: Rc<RefCell<AppendedFragment>>,
    current_crate: Option<Rc<str>>,
}

impl ModuleFragment {
    /// Create a new module with the given name.
    pub fn new(name: String) -> Self {
        Self {
            name: Some(name),
            ..ModuleFragment::default()
        }
    }

    /// Create a new module that takes up an entire file.
    pub fn new_file_module() -> Self {
        Self {
            uses_entire_file: true,
            ..ModuleFragment::default()
        }
    }

    /// Create a new module with the name `tests`.
    pub fn new_test_module() -> Self {
        let mut new_self = Self::new("tests".to_owned());
        new_self.mark_as_test();
        new_self
    }

    /// Adds a submodule to the current module.
    pub fn add_submodule(&mut self, name: String) -> Rc<RefCell<ModuleFragment>> {
        let mut new_submodule = Self::new(name);
        // unlike the top-level module, submodules start out as declare-only. It is still possible
        // to add submodules manually via the `append` function instead.
        new_submodule.mark_as_declare_only();
        let module_rc = Rc::new(RefCell::new(new_submodule));
        self.submodules.push(module_rc.clone());
        module_rc
    }

    /// Mark a module as being a test module.
    pub fn mark_as_test(&mut self) {
        self.declaration.add_attribute("cfg(test)".to_owned());
        self.test = true;
    }

    /// Mark this for generation as an entire file. Skips generation of the mod preamble.
    pub fn mark_as_entire_file(&mut self) {
        self.uses_entire_file = true;
    }

    /// Re-export something so that it looks like it comes from this module.
    ///
    /// This usually, but not always, refers to something hidden within a submodule of this module.
    /// You can also re-export things from other modules, and they will also appear as if they came
    /// from this one.
    pub fn re_export(&mut self, export: String) {
        self.re_exports.push(export);
    }

    /// Add a fragment to the internals of this module.
    pub fn append(&mut self, fragment: Rc<RefCell<dyn CodeFragment>>) {
        self.content.borrow_mut().append(fragment);
    }

    fn submodules_by_publicity(&self, publicity: bool) -> AppendedFragment {
        let mut submodules_subset = self
            .submodules
            .iter()
            .filter(|s| s.borrow().is_public() == publicity)
            .collect::<Vec<&Rc<RefCell<ModuleFragment>>>>();
        submodules_subset.sort();
        // single newline separation between short module declarations
        // todo: separate by declaration-only versus full-impl as well
        let mut submodules_frag = AppendedFragment::new_with_separator("\n");
        for module in submodules_subset {
            submodules_frag.append(module.clone());
        }
        submodules_frag
    }

    /// Set the current crate for file imports.
    pub fn set_current_crate(&mut self, current_crate: Rc<str>) {
        self.current_crate = Some(current_crate);
    }
}

impl Default for ModuleFragment {
    fn default() -> Self {
        let mut declaration = ItemDeclaration::default();
        declaration.mark_for_full_implementation(); // opposite default for modules
        Self {
            name: None,
            declaration,
            test: false,
            uses_entire_file: false,
            re_exports: vec![],
            submodules: vec![],
            content: Rc::new(RefCell::new(AppendedFragment::default())),
            current_crate: None,
        }
    }
}

impl ItemDeclarationAPI for ModuleFragment {
    fn mark_as_public(&mut self) {
        self.declaration.mark_as_public();
    }

    fn is_public(&self) -> bool {
        self.declaration.is_public()
    }

    fn add_attribute(&mut self, attribute: String) {
        self.declaration.add_attribute(attribute);
    }

    fn document(&mut self, documentation: String) {
        self.declaration.document(documentation);
    }

    fn set_body(&mut self, body: Rc<RefCell<dyn CodeFragment>>) {
        self.declaration.set_body(body);
    }

    fn mark_as_declare_only(&mut self) {
        self.declaration.mark_as_declare_only();
    }

    fn mark_for_full_implementation(&mut self) {
        self.declaration.mark_for_full_implementation();
    }
}

impl Ord for ModuleFragment {
    fn cmp(&self, other: &Self) -> Ordering {
        self.name.cmp(&other.name)
    }
}

impl PartialOrd for ModuleFragment {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for ModuleFragment {
    fn eq(&self, other: &Self) -> bool {
        // in context, we'll only be comparing modules at the same level with each other
        self.name == other.name
    }
}

impl Eq for ModuleFragment {}

impl CodeFragment for ModuleFragment {
    fn body(&self, line_width: usize) -> String {
        let mut imports = self.content.borrow().imports();
        if self.test {
            imports.push("super::*".to_owned());
        }
        let mut imports_str = imports_as_str(
            &self
                .current_crate
                .as_ref()
                .cloned()
                .unwrap_or_else(|| Rc::from("DUMMY-TEST-CRATE")),
            imports,
            &[],
        );
        if !imports_str.is_empty() {
            imports_str += "\n\n";
        }

        let mut re_exports_str = re_exports_as_str(
            &self
                .re_exports
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<&str>>(),
        );
        if !re_exports_str.is_empty() {
            re_exports_str += "\n\n";
        }

        let mut submodules_frag = AppendedFragment::default();
        submodules_frag.append(Rc::new(RefCell::new(self.submodules_by_publicity(true))));
        submodules_frag.append(Rc::new(RefCell::new(self.submodules_by_publicity(false))));

        let mut internals = AppendedFragment::default();
        internals.append(Rc::new(RefCell::new(submodules_frag)));
        if !imports_str.is_empty() {
            internals.append(Rc::new(RefCell::new(AtomicFragment::new(imports_str))));
        }
        if !re_exports_str.is_empty() {
            internals.append(Rc::new(RefCell::new(AtomicFragment::new(re_exports_str))));
        }
        internals.append(self.content.clone());
        let internals_rc = Rc::new(RefCell::new(internals));

        if self.uses_entire_file {
            let mut f = FileFragment::new();
            if let Some(doc) = &self.declaration.doc {
                f.set_preamble(AtomicFragment::new(into_parent_docstring(&doc, CODE_WIDTH)));
            }
            f.append(internals_rc);
            f.generate_code()
        } else {
            let mut declaration = self.declaration.clone();
            // todo: try using FileFragment to generate the internals here too
            declaration.set_definition(Rc::new(RefCell::new(AtomicFragment::new(format!(
                "mod {name}",
                name = self.name.as_ref().unwrap()
            )))));
            if declaration.body.is_some() {
                // basically using that option as a boolean right now, because we need to
                // override with the imports
                declaration.set_body(internals_rc);
            }
            declaration.body(line_width) // declaration will take care of indent size
        }
    }

    fn imports(&self) -> Vec<String> {
        Vec::new() // module-level imports should never make it out of the module
    }
}

#[cfg(test)]
mod tests {
    use super::super::AtomicFragment;
    use super::*;
    use indoc::indoc;

    #[test]
    fn test_regular_module() {
        let mut test_mod = ModuleFragment::new("my_mod".to_owned());
        test_mod.append(Rc::new(RefCell::new(AtomicFragment {
            imports: Vec::new(),
            atom: indoc! {r#"
                fn a() {
                    println!("actually b");
                }"#}
            .to_string(),
        })));

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {r#"
                mod my_mod {
                    fn a() {
                        println!("actually b");
                    }
                }"#}
        );
    }

    #[test]
    fn test_documented_module() {
        let mut test_mod = ModuleFragment::new("my_mod".to_owned());
        test_mod.document("My amazing module.".to_owned());
        test_mod.append(Rc::new(RefCell::new(AtomicFragment {
            imports: Vec::new(),
            atom: indoc! {r#"
                fn a() {
                    println!("actually b");
                }"#}
            .to_string(),
        })));

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {r#"
                /// My amazing module.
                mod my_mod {
                    fn a() {
                        println!("actually b");
                    }
                }"#}
        );
    }

    #[test]
    fn test_public_module() {
        let mut test_mod = ModuleFragment::new("my_mod".to_owned());
        test_mod.mark_as_public();
        test_mod.append(Rc::new(RefCell::new(AtomicFragment {
            imports: Vec::new(),
            atom: indoc! {r#"
                fn a() {
                    println!("actually b");
                }"#}
            .to_string(),
        })));

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {r#"
                pub mod my_mod {
                    fn a() {
                        println!("actually b");
                    }
                }"#}
        );
    }

    #[test]
    fn test_declared_module() {
        let mut test_mod = ModuleFragment::new("my_mod".to_owned());
        test_mod.mark_as_declare_only();

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(test_mod.body(80), "mod my_mod;".to_owned());
    }

    #[test]
    fn test_publicly_declared_module() {
        let mut test_mod = ModuleFragment::new("my_mod".to_owned());
        test_mod.mark_as_declare_only();
        test_mod.mark_as_public();

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(test_mod.body(80), "pub mod my_mod;".to_owned());
    }

    #[test]
    fn test_submodules() {
        let mut test_mod = ModuleFragment::new("my_dom".to_owned());
        let test_sub = test_mod.add_submodule("my_sub".to_owned());
        test_sub.borrow_mut().mark_as_public();
        test_sub.borrow_mut().document("Subbed.".to_owned());

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {"
                mod my_dom {
                    /// Subbed.
                    pub mod my_sub;
                }"}
        );
    }

    #[test]
    fn test_implemented_submodules() {
        let mut test_mod = ModuleFragment::new("my_dom".to_owned());
        test_mod
            .add_submodule("my_sub".to_owned())
            .borrow_mut()
            .mark_for_full_implementation();

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {"
                mod my_dom {
                    mod my_sub {}
                }"}
        );
    }

    #[test]
    fn test_sorted_submodules() {
        let mut test_mod = ModuleFragment::new("my_dom".to_owned());
        test_mod
            .add_submodule("sub_d".to_owned())
            .borrow_mut()
            .mark_as_public();
        test_mod.add_submodule("sub_b".to_owned());
        test_mod.add_submodule("sub_c".to_owned());
        test_mod
            .add_submodule("sub_a".to_owned())
            .borrow_mut()
            .mark_as_public();

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {"
                mod my_dom {
                    pub mod sub_a;
                    pub mod sub_d;

                    mod sub_b;
                    mod sub_c;
                }"}
        );
    }

    #[test]
    fn test_re_exports() {
        let mut test_mod = ModuleFragment::new("my_dom".to_owned());
        test_mod.add_submodule("my_sub".to_owned());

        test_mod.re_export("my_sub::StructA".to_owned());
        test_mod.re_export("my_sub::StructB".to_owned());

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {"
                mod my_dom {
                    mod my_sub;

                    pub use my_sub::{StructA, StructB};
                }"}
        );
    }

    #[test]
    fn test_as_entire_file() {
        let mut test_mod = ModuleFragment::new_file_module();
        test_mod.document("This produces great things.".to_owned());
        test_mod.add_submodule("my_sub".to_owned());

        test_mod.re_export("my_sub::StructA".to_owned());
        test_mod.re_export("my_sub::StructB".to_owned());

        test_mod.append(Rc::new(RefCell::new(AtomicFragment {
            imports: Vec::new(),
            atom: indoc! {r#"
                fn a() {
                    println!("actually b");
                }"#}
            .to_string(),
        })));

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {r#"
                //! This produces great things.
                
                mod my_sub;

                pub use my_sub::{StructA, StructB};

                fn a() {
                    println!("actually b");
                }
                "#}
        );
    }

    #[test]
    fn test_test_module() {
        let mut test_mod = ModuleFragment::new_test_module();
        test_mod.append(Rc::new(RefCell::new(AtomicFragment {
            imports: Vec::new(),
            atom: indoc! {"
                #[test]
                fn test_big() {
                    Big {
                        a: Something {},
                        b: OrTheOther {},
                    }
                }"}
            .to_string(),
        })));

        assert_eq!(test_mod.imports(), Vec::<String>::new());
        assert_eq!(
            test_mod.body(80),
            indoc! {"
                #[cfg(test)]
                mod tests {
                    use super::*;

                    #[test]
                    fn test_big() {
                        Big {
                            a: Something {},
                            b: OrTheOther {},
                        }
                    }
                }"}
        );
    }
}