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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! Specialization for Rust code generation.
//!
//! # Examples
//!
//! ```rust
//! use genco::prelude::*;
//!
//! # fn main() -> genco::fmt::Result {
//! let toks: rust::Tokens = quote! {
//!     fn foo() -> u32 {
//!         42
//!     }
//! };
//!
//! assert_eq!(
//!     vec![
//!         "fn foo() -> u32 {",
//!         "    42",
//!         "}",
//!     ],
//!     toks.to_file_vec()?
//! );
//! # Ok(())
//! # }
//! ```
//!
//! # String Quoting in Rust
//!
//! Rust uses UTF-8 internally, string quoting is with the exception of escape
//! sequences a one-to-one translation.
//!
//! ```rust
//! use genco::prelude::*;
//!
//! # fn main() -> genco::fmt::Result {
//! let toks: rust::Tokens = quote!("start π 😊 \n \x7f ÿ $ end");
//! assert_eq!("\"start π 😊 \\n \\x7f ÿ $ end\"", toks.to_string()?);
//! # Ok(())
//! # }

use crate::fmt;
use crate::tokens::ItemStr;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt::Write as _;

const SEP: &str = "::";

/// Tokens container specialization for Rust.
pub type Tokens = crate::Tokens<Rust>;

impl_lang! {
    /// Language specialization for Rust.
    pub Rust {
        type Config = Config;
        type Format = Format;
        type Item = Import;

        fn write_quoted(out: &mut fmt::Formatter<'_>, input: &str) -> fmt::Result {
            // From: https://doc.rust-lang.org/reference/tokens.html#literals

            for c in input.chars() {
                match c {
                    // new line
                    '\n' => out.write_str("\\n")?,
                    // carriage return
                    '\r' => out.write_str("\\r")?,
                    // horizontal tab
                    '\t' => out.write_str("\\t")?,
                    // backslash
                    '\\' => out.write_str("\\\\")?,
                    // null
                    '\0' => out.write_str("\\0")?,
                    // Note: only relevant if we were to use single-quoted strings.
                    // '\'' => out.write_str("\\'")?,
                    '"' => out.write_str("\\\"")?,
                    c if !c.is_control() => out.write_char(c)?,
                    c if (c as u32) < 0x80 => {
                        write!(out, "\\x{:02x}", c as u32)?;
                    }
                    c => {
                        write!(out, "\\u{{{:04x}}}", c as u32)?;
                    }
                };
            }

            Ok(())
        }

        fn format_file(
            tokens: &Tokens,
            out: &mut fmt::Formatter<'_>,
            config: &Self::Config,
        ) -> fmt::Result {
            let mut imports: Tokens = Tokens::new();
            Self::imports(&mut imports, config, tokens);

            let format = Format::default();
            imports.format(out, config, &format)?;
            tokens.format(out, config, &format)?;
            Ok(())
        }
    }

    Import {
        fn format(&self, out: &mut fmt::Formatter<'_>, config: &Config, _: &Format) -> fmt::Result {
            match &self.module {
                Module::Module {
                    import: Some(ImportMode::Direct),
                    ..
                } => {
                    self.write_direct(out)?;
                }
                Module::Module {
                    import: Some(ImportMode::Qualified),
                    module,
                } => {
                    self.write_prefixed(out, module)?;
                }
                Module::Module {
                    import: None,
                    module,
                } => match &config.default_import {
                    ImportMode::Direct => self.write_direct(out)?,
                    ImportMode::Qualified => self.write_prefixed(out, module)?,
                },
                Module::Aliased {
                    alias: ref module, ..
                } => {
                    out.write_str(module)?;
                    out.write_str(SEP)?;
                    out.write_str(&self.name)?;
                }
            }

            Ok(())
        }
    }
}

/// Format state for Rust.
#[derive(Debug, Default)]
pub struct Format {}

/// Language configuration for Rust.
#[derive(Debug)]
pub struct Config {
    default_import: ImportMode,
}

impl Config {
    /// Configure the default import mode to use.
    ///
    /// See [Import] for more details.
    pub fn with_default_import(self, default_import: ImportMode) -> Self {
        Self { default_import }
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            default_import: ImportMode::Direct,
        }
    }
}

/// The import mode to use when generating import statements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImportMode {
    /// Import names without a module prefix.
    ///
    /// so for `std::fmt::Debug` it would import `std::fmt::Debug`, and use
    /// `Debug`.
    Direct,
    /// Import qualified names with a module prefix.
    ///
    /// so for `std::fmt::Debug` it would import `std::fmt`, and use
    /// `fmt::Debug`.
    Qualified,
}

#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
enum Module {
    /// Type imported directly from module with the specified mode.
    Module {
        import: Option<ImportMode>,
        module: ItemStr,
    },
    /// Prefixed with an alias.
    Aliased { module: ItemStr, alias: ItemStr },
}

impl Module {
    /// Convert into an aliased import, or keep as same in case that's not
    /// feasible.
    fn into_module_aliased<A>(self, alias: A) -> Self
    where
        A: Into<ItemStr>,
    {
        match self {
            Self::Module { module, .. } => Self::Aliased {
                module,
                alias: alias.into(),
            },
            other => other,
        }
    }

    /// Aliasing a type explicitly means you no longer want to import it by
    /// module. Set the correct import here.
    fn into_aliased(self) -> Self {
        match self {
            Self::Module { module, .. } => Self::Module {
                import: Some(ImportMode::Direct),
                module,
            },
            other => other,
        }
    }

    /// Switch to a direct import mode.
    ///
    /// See [ImportMode::Direct].
    fn direct(self) -> Self {
        match self {
            Self::Module { module, .. } => Self::Module {
                module,
                import: Some(ImportMode::Direct),
            },
            other => other,
        }
    }

    /// Switch into a qualified import mode.
    ///
    /// See [ImportMode::Qualified].
    fn qualified(self) -> Self {
        match self {
            Self::Module { module, .. } => Self::Module {
                module,
                import: Some(ImportMode::Qualified),
            },
            other => other,
        }
    }
}

/// The import of a Rust type `use std::collections::HashMap`.
///
/// Created through the [import()] function.
#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Import {
    /// How the type is imported.
    module: Module,
    /// Name of type.
    name: ItemStr,
    /// Alias to use for the type.
    alias: Option<ItemStr>,
}

impl Import {
    /// Alias the given type as it's imported.
    ///
    /// # Examples
    ///
    /// ```
    /// use genco::prelude::*;
    ///
    /// let ty = rust::import("std::fmt", "Debug").with_alias("FmtDebug");
    ///
    /// let toks = quote!($ty);
    ///
    /// assert_eq!(
    ///     vec![
    ///         "use std::fmt::Debug as FmtDebug;",
    ///         "",
    ///         "FmtDebug",
    ///     ],
    ///     toks.to_file_vec()?
    /// );
    /// # Ok::<_, genco::fmt::Error>(())
    /// ```
    pub fn with_alias<A: Into<ItemStr>>(self, alias: A) -> Self {
        Self {
            module: self.module.into_aliased(),
            alias: Some(alias.into()),
            ..self
        }
    }

    /// Alias the module being imported.
    ///
    /// This also implies that the import is [qualified()].
    ///
    /// # Examples
    ///
    /// ```
    /// use genco::prelude::*;
    ///
    /// let ty = rust::import("std::fmt", "Debug").with_module_alias("other");
    ///
    /// let toks = quote!($ty);
    ///
    /// assert_eq!(
    ///     vec![
    ///         "use std::fmt as other;",
    ///         "",
    ///         "other::Debug",
    ///     ],
    ///     toks.to_file_vec()?
    /// );
    /// # Ok::<_, genco::fmt::Error>(())
    /// ```
    ///
    /// [qualified()]: Self::qualified()
    pub fn with_module_alias<A: Into<ItemStr>>(self, alias: A) -> Self {
        Self {
            module: self.module.into_module_aliased(alias),
            ..self
        }
    }

    /// Switch to a qualified import mode.
    ///
    /// See [ImportMode::Qualified].
    ///
    /// So importing `std::fmt::Debug` will cause the module to be referenced as
    /// `fmt::Debug` instead of `Debug`.
    ///
    /// This is implied if [with_module_alias()][Self::with_module_alias()] is used.
    ///
    /// # Examples
    ///
    /// ```
    /// use genco::prelude::*;
    ///
    /// let ty = rust::import("std::fmt", "Debug").qualified();
    ///
    /// let toks = quote!($ty);
    ///
    /// assert_eq!(
    ///     vec![
    ///         "use std::fmt;",
    ///         "",
    ///         "fmt::Debug",
    ///     ],
    ///     toks.to_file_vec()?
    /// );
    /// # Ok::<_, genco::fmt::Error>(())
    /// ```
    pub fn qualified(self) -> Self {
        Self {
            module: self.module.qualified(),
            ..self
        }
    }

    /// Switch into a direct import mode.
    ///
    /// See [ImportMode::Direct].
    ///
    /// # Examples
    ///
    /// ```
    /// use genco::prelude::*;
    ///
    /// let ty = rust::import("std::fmt", "Debug").direct();
    ///
    /// let toks = quote!($ty);
    ///
    /// assert_eq!(
    ///     vec![
    ///         "use std::fmt::Debug;",
    ///         "",
    ///         "Debug",
    ///     ],
    ///     toks.to_file_vec()?
    /// );
    /// # Ok::<_, genco::fmt::Error>(())
    /// ```
    pub fn direct(self) -> Self {
        Self {
            module: self.module.direct(),
            ..self
        }
    }

    /// Write the direct name of the type.
    fn write_direct(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(alias) = &self.alias {
            out.write_str(alias)
        } else {
            out.write_str(&self.name)
        }
    }

    /// Write the prefixed name of the type.
    fn write_prefixed(&self, out: &mut fmt::Formatter<'_>, module: &ItemStr) -> fmt::Result {
        if let Some(module) = module.rsplit(SEP).next() {
            out.write_str(module)?;
            out.write_str(SEP)?;
        }

        out.write_str(&self.name)?;
        Ok(())
    }
}

impl Rust {
    fn imports(out: &mut Tokens, config: &Config, tokens: &Tokens) {
        use crate as genco;
        use crate::quote_in;
        use std::collections::btree_set;

        let mut modules = BTreeMap::<&ItemStr, Import>::new();

        let mut queue = VecDeque::new();

        for import in tokens.walk_imports() {
            queue.push_back(import);
        }

        while let Some(import) = queue.pop_front() {
            match &import.module {
                Module::Module {
                    module,
                    import: Some(ImportMode::Direct),
                } => {
                    let module = modules.entry(module).or_default();
                    module.names.insert((&import.name, import.alias.as_ref()));
                }
                Module::Module {
                    module,
                    import: Some(ImportMode::Qualified),
                } => {
                    let module = modules.entry(module).or_default();
                    module.self_import = true;
                }
                Module::Module {
                    module,
                    import: None,
                } => match config.default_import {
                    ImportMode::Direct => {
                        let module = modules.entry(module).or_default();
                        module.names.insert((&import.name, import.alias.as_ref()));
                    }
                    ImportMode::Qualified => {
                        let module = modules.entry(module).or_default();
                        module.self_import = true;
                    }
                },
                Module::Aliased { module, alias } => {
                    let module = modules.entry(module).or_default();
                    module.self_aliases.insert(alias);
                }
            }
        }

        let mut has_any = false;

        for (m, module) in modules {
            let mut render = module.iter(m);

            if let Some(first) = render.next() {
                has_any = true;
                out.push();

                // render as a group if there's more than one thing being
                // imported.
                if let Some(second) = render.next() {
                    quote_in! { *out =>
                        use $m::{$(ref o =>
                            first.render(o);
                            quote_in!(*o => , $(ref o => second.render(o)));

                            for item in render {
                                quote_in!(*o => , $(ref o => item.render(o)));
                            }
                        )};
                    };
                } else {
                    match first {
                        RenderItem::SelfImport => {
                            quote_in!(*out => use $m;);
                        }
                        RenderItem::SelfAlias { alias } => {
                            quote_in!(*out => use $m as $alias;);
                        }
                        RenderItem::Name {
                            name,
                            alias: Some(alias),
                        } => {
                            quote_in!(*out => use $m::$name as $alias;);
                        }
                        RenderItem::Name { name, alias: None } => {
                            quote_in!(*out => use $m::$name;);
                        }
                    }
                }
            }
        }

        if has_any {
            out.line();
        }

        return;

        /// An imported module.
        #[derive(Debug, Default)]
        struct Import<'a> {
            /// If we need the module (e.g. through an alias).
            self_import: bool,
            /// Aliases for the own module.
            self_aliases: BTreeSet<&'a ItemStr>,
            /// Set of imported names.
            names: BTreeSet<(&'a ItemStr, Option<&'a ItemStr>)>,
        }

        impl<'a> Import<'a> {
            fn iter(self, module: &'a str) -> ImportedIter<'a> {
                ImportedIter {
                    module,
                    self_import: self.self_import,
                    self_aliases: self.self_aliases.into_iter(),
                    names: self.names.into_iter(),
                }
            }
        }

        struct ImportedIter<'a> {
            module: &'a str,
            self_import: bool,
            self_aliases: btree_set::IntoIter<&'a ItemStr>,
            names: btree_set::IntoIter<(&'a ItemStr, Option<&'a ItemStr>)>,
        }

        impl<'a> Iterator for ImportedIter<'a> {
            type Item = RenderItem<'a>;

            fn next(&mut self) -> Option<Self::Item> {
                if std::mem::take(&mut self.self_import) {
                    // Only render self-import if it's not a top level module.
                    if self.module.split(SEP).count() > 1 {
                        return Some(RenderItem::SelfImport);
                    }
                }

                if let Some(alias) = self.self_aliases.next() {
                    return Some(RenderItem::SelfAlias { alias });
                }

                if let Some((name, alias)) = self.names.next() {
                    return Some(RenderItem::Name { name, alias });
                }

                None
            }
        }

        #[derive(Clone, Copy)]
        enum RenderItem<'a> {
            SelfImport,
            SelfAlias {
                alias: &'a ItemStr,
            },
            Name {
                name: &'a ItemStr,
                alias: Option<&'a ItemStr>,
            },
        }

        impl RenderItem<'_> {
            fn render(self, out: &mut Tokens) {
                match self {
                    Self::SelfImport => {
                        quote_in!(*out => self);
                    }
                    Self::SelfAlias { alias } => {
                        quote_in!(*out => self as $alias);
                    }
                    Self::Name {
                        name,
                        alias: Some(alias),
                    } => {
                        quote_in!(*out => $name as $alias);
                    }
                    Self::Name { name, alias: None } => {
                        quote_in!(*out => $name);
                    }
                }
            }
        }
    }
}

/// The import of a Rust type `use std::collections::HashMap`.
///
/// # Examples
///
/// ```
/// use genco::prelude::*;
///
/// let a = rust::import("std::fmt", "Debug").qualified();
/// let b = rust::import("std::fmt", "Debug").with_module_alias("fmt2");
/// let c = rust::import("std::fmt", "Debug");
/// let d = rust::import("std::fmt", "Debug").with_alias("FmtDebug");
///
/// let toks = quote!{
///     $a
///     $b
///     $c
///     $d
/// };
///
/// assert_eq!(
///     vec![
///         "use std::fmt::{self, self as fmt2, Debug, Debug as FmtDebug};",
///         "",
///         "fmt::Debug",
///         "fmt2::Debug",
///         "Debug",
///         "FmtDebug",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
///
/// # Example with an alias
///
/// ```
/// use genco::prelude::*;
///
/// let ty = rust::import("std::fmt", "Debug").with_alias("FmtDebug");
///
/// let toks = quote!{
///     $ty
/// };
///
/// assert_eq!(
///     vec![
///         "use std::fmt::Debug as FmtDebug;",
///         "",
///         "FmtDebug",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
///
/// # Example with a module alias
///
/// ```
/// use genco::prelude::*;
///
/// let ty = rust::import("std::fmt", "Debug").with_module_alias("fmt2");
///
/// let toks = quote!{
///     $ty
/// };
///
/// assert_eq!(
///     vec![
///         "use std::fmt as fmt2;",
///         "",
///         "fmt2::Debug",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
///
/// # Example with multiple aliases
///
/// ```
/// use genco::prelude::*;
///
/// let a = rust::import("std::fmt", "Debug").with_alias("FmtDebug");
/// let b = rust::import("std::fmt", "Debug").with_alias("FmtDebug2");
///
/// let toks = quote!{
///     $a
///     $b
/// };
///
/// assert_eq!(
///     vec![
///         "use std::fmt::{Debug as FmtDebug, Debug as FmtDebug2};",
///         "",
///         "FmtDebug",
///         "FmtDebug2",
///     ],
///     toks.to_file_vec()?
/// );
/// # Ok::<_, genco::fmt::Error>(())
/// ```
pub fn import<M, N>(module: M, name: N) -> Import
where
    M: Into<ItemStr>,
    N: Into<ItemStr>,
{
    Import {
        module: Module::Module {
            import: None,
            module: module.into(),
        },
        name: name.into(),
        alias: None,
    }
}