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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! Specialization for Csharp code generation.
//!
//! # Examples
//!
//! String quoting in Dart:
//!
//! ```rust
//! use genco::prelude::*;
//!
//! let toks: csharp::Tokens = quote!(#("hello \n world".quoted()));
//! assert_eq!("\"hello \\n world\"", toks.to_string().unwrap());
//! ```

mod block_comment;

use crate as genco;
use crate::{quote_in, Formatter, ItemStr, Lang, LangItem};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt;

pub use self::block_comment::BlockComment;

/// Tokens container specialization for C#.
pub type Tokens = crate::Tokens<Csharp>;

impl_dynamic_types! { Csharp =>
    pub trait TypeTrait {
        /// Get the name of the type.
        fn name(&self) -> &str;

        /// Get the namespace of the type, if available.
        fn namespace(&self) -> Option<&str> {
            None
        }

        /// Check if type is nullable.
        fn is_nullable(&self) -> bool;

        /// Handle imports recursively.
        fn type_imports(&self, _: &mut BTreeSet<(ItemStr, ItemStr)>) {}
    }

    pub trait TypeArgs;
    pub struct TypeBox;
    pub enum TypeEnum;

    impl TypeTrait for Simple {
        fn name(&self) -> &str {
            self.name
        }

        fn namespace(&self) -> Option<&str> {
            Some(SYSTEM)
        }

        fn is_nullable(&self) -> bool {
            false
        }

        fn type_imports(&self, modules: &mut BTreeSet<(ItemStr, ItemStr)>) {
            modules.insert((SYSTEM.into(), self.alias.into()));
        }
    }

    impl TypeTrait for Optional {
        fn name(&self) -> &str {
            self.inner.name()
        }

        fn namespace(&self) -> Option<&str> {
            self.inner.namespace()
        }

        fn is_nullable(&self) -> bool {
            false
        }

        fn type_imports(&self, modules: &mut BTreeSet<(ItemStr, ItemStr)>) {
            self.inner.type_imports(modules)
        }
    }

    impl TypeTrait for Type {
        fn name(&self) -> &str {
            &*self.name
        }

        fn namespace(&self) -> Option<&str> {
            self.namespace.as_deref()
        }

        fn is_nullable(&self) -> bool {
            match self.kind {
                Kind::Enum | Kind::Struct => false,
                _ => true,
            }
        }

        fn type_imports(&self, modules: &mut BTreeSet<(ItemStr, ItemStr)>) {
            for argument in &self.arguments {
                argument.type_imports(modules);
            }

            if let Some(namespace) = &self.namespace {
                modules.insert((namespace.clone(), self.name.clone()));
            }
        }
    }

    impl TypeTrait for Array {
        fn name(&self) -> &str {
            self.inner.name()
        }

        fn namespace(&self) -> Option<&str> {
            self.inner.namespace()
        }

        fn is_nullable(&self) -> bool {
            true
        }

        fn type_imports(&self, modules: &mut BTreeSet<(ItemStr, ItemStr)>) {
            self.inner.type_imports(modules);
        }
    }

    impl TypeTrait for Void {
        fn name(&self) -> &str {
            "void"
        }

        fn is_nullable(&self) -> bool {
            false
        }
    }
}

static SYSTEM: &'static str = "System";
static SEP: &'static str = ".";

/// Boolean type
pub const BOOLEAN: Simple = Simple {
    name: "bool",
    alias: "Boolean",
};

/// Byte type.
pub const BYTE: Simple = Simple {
    name: "byte",
    alias: "Byte",
};

/// Signed Byte type.
pub const SBYTE: Simple = Simple {
    name: "sbyte",
    alias: "SByte",
};

/// Decimal type
pub const DECIMAL: Simple = Simple {
    name: "decimal",
    alias: "Decimal",
};

/// Float type.
pub const SINGLE: Simple = Simple {
    name: "float",
    alias: "Single",
};

/// Double type.
pub const DOUBLE: Simple = Simple {
    name: "double",
    alias: "Double",
};

/// Int16 type.
pub const INT16: Simple = Simple {
    name: "short",
    alias: "Int16",
};

/// Uint16 type.
pub const UINT16: Simple = Simple {
    name: "ushort",
    alias: "UInt16",
};

/// Int32 type.
pub const INT32: Simple = Simple {
    name: "int",
    alias: "Int32",
};

/// Uint32 type.
pub const UINT32: Simple = Simple {
    name: "uint",
    alias: "UInt32",
};

/// Int64 type.
pub const INT64: Simple = Simple {
    name: "long",
    alias: "Int64",
};

/// UInt64 type.
pub const UINT64: Simple = Simple {
    name: "ulong",
    alias: "UInt64",
};

/// The `void` type.
pub const VOID: Void = Void(());

impl_modifier! {
    /// A Csharp modifier.
    ///
    /// A vector of modifiers have a custom implementation, allowing them to be
    /// formatted with a spacing between them in the language-recommended order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use genco::prelude::*;
    /// use csharp::Modifier::*;
    ///
    /// let toks: csharp::Tokens = quote!(#(vec![Async, Static, Public]));
    ///
    /// assert_eq!("public async static", toks.to_string().unwrap());
    /// ```
    pub enum Modifier<Csharp> {
        /// The `public` modifier.
        Public => "public",
        /// The `private` modifier.
        Private => "private",
        /// The `internal` modifier.
        Internal => "internal",
        /// The `protected` modifier.
        Protected => "protected",
        /// The `abstract` modifier.
        Abstract => "abstract",
        /// The `async` modifier.
        Async => "async",
        /// The `const` modifier.
        Const => "const",
        /// The `event` modifier.
        Event => "event",
        /// The `extern` modifier.
        Extern => "extern",
        /// The `new` modifier.
        New => "new",
        /// The `override` modifier.
        Override => "override",
        /// The `partial` modifier.
        Partial => "partial",
        /// The `readonly` modifier.
        Readonly => "readonly",
        /// The `sealed` modifier.
        Sealed => "sealed",
        /// The `static` modifier.
        Static => "static",
        /// The `unsafe` modifier.
        Unsafe => "unsafe",
        /// The `virtual` modifier.
        Virtual => "virtual",
        /// The `volatile` modifier.
        Volatile => "volatile",
    }
}

/// Config data for Csharp formatting.
#[derive(Debug, Default)]
pub struct Config {
    /// namespace to use.
    namespace: Option<ItemStr>,

    /// Names which have been imported (namespace + name).
    imported_names: HashMap<String, String>,
}

impl Config {
    /// Set the namespace name to build.
    pub fn with_namespace<N>(self, namespace: N) -> Self
    where
        N: Into<ItemStr>,
    {
        Self {
            namespace: Some(namespace.into()),
            ..self
        }
    }
}

/// An optional type.
#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Optional {
    inner: TypeBox,
}

impl_lang_item! {
    impl LangItem<Csharp> for Optional {
        fn format(&self, out: &mut Formatter, config: &mut Config, level: usize) -> fmt::Result {
            self.inner.format(out, config, level)?;

            if !self.inner.is_nullable() {
                out.write_str("?")?;
            }

            Ok(())
        }

        fn as_import(&self) -> Option<&dyn TypeTrait> {
            Some(self)
        }
    }
}

/// The kind of the pointed to type.
#[derive(Debug, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub enum Kind {
    /// The pointed to type is an enum.
    Enum,
    /// The pointed to type is a class.
    Class,
    /// The pointed to type is a struct.
    Struct,
}

/// A class.
#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Type {
    /// namespace of the class.
    namespace: Option<ItemStr>,
    /// Name  of class.
    name: ItemStr,
    /// Path of class when nested.
    path: Vec<ItemStr>,
    /// Arguments of the class.
    arguments: Vec<TypeBox>,
    /// Use as qualified type.
    qualified: bool,
    /// The kind of the type.
    kind: Kind,
}

impl Type {
    /// Extend the type with a nested path.
    ///
    /// This discards any arguments associated with it.
    pub fn path<P: Into<ItemStr>>(self, part: P) -> Self {
        let mut path = self.path;
        path.push(part.into());

        Self {
            path: path,
            arguments: vec![],
            ..self
        }
    }

    /// Add arguments to the given type.
    ///
    /// Only applies to classes, any other will return the same value.
    pub fn with_arguments(self, args: impl TypeArgs) -> Self {
        Self {
            arguments: args.into_args(),
            ..self
        }
    }

    /// Make this type into a qualified type that is always used with a namespace.
    pub fn qualified(self) -> Self {
        Self {
            qualified: true,
            ..self
        }
    }

    /// Convert this type into a struct.
    pub fn into_struct(self) -> Self {
        Self {
            kind: Kind::Struct,
            arguments: vec![],
            ..self
        }
    }

    /// Convert this type into an enum.
    pub fn into_enum(self) -> Self {
        Self {
            kind: Kind::Enum,
            arguments: vec![],
            ..self
        }
    }
}

impl_lang_item! {
    impl LangItem<Csharp> for Type {
        fn format(&self, out: &mut Formatter, config: &mut Config, level: usize) -> fmt::Result {
            {
                let qualified = match self.qualified {
                    true => true,
                    false => {
                        let file_namespace = config.namespace.as_ref().map(|p| p.as_ref());
                        let imported = config
                            .imported_names
                            .get(self.name.as_ref())
                            .map(String::as_str);
                        let pkg = self.namespace.as_deref();
                        imported != pkg && file_namespace != pkg
                    }
                };

                if let Some(namespace) = &self.namespace {
                    if qualified {
                        out.write_str(namespace)?;
                        out.write_str(SEP)?;
                    }
                }
            }

            {
                out.write_str(self.name.as_ref())?;

                let mut it = self.path.iter();

                while let Some(n) = it.next() {
                    out.write_str(".")?;
                    out.write_str(n.as_ref())?;
                }
            }

            if !self.arguments.is_empty() {
                out.write_str("<")?;

                let mut it = self.arguments.iter().peekable();

                while let Some(argument) = it.next() {
                    argument.format(out, config, level + 1usize)?;

                    if it.peek().is_some() {
                        out.write_str(", ")?;
                    }
                }

                out.write_str(">")?;
            }

            Ok(())
        }

        fn as_import(&self) -> Option<&dyn TypeTrait> {
            Some(self)
        }
    }
}

/// Simple type.
#[derive(Debug, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Simple {
    /// The name of the simple type.
    name: &'static str,
    /// Their .NET aliases.
    alias: &'static str,
}

impl_lang_item! {
    impl LangItem<Csharp> for Simple {
        fn format(&self, out: &mut Formatter, _: &mut Config, _: usize) -> fmt::Result {
            out.write_str(self.alias)?;
            Ok(())
        }

        fn as_import(&self) -> Option<&dyn TypeTrait> {
            Some(self)
        }
    }
}

/// An array type in C#.
#[derive(Debug, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Array {
    inner: TypeBox,
}

impl_lang_item! {
    impl LangItem<Csharp> for Array {
        fn format(&self, out: &mut Formatter, config: &mut Config, level: usize) -> fmt::Result {
            self.inner.format(out, config, level)?;
            out.write_str("[]")?;
            Ok(())
        }

        fn as_import(&self) -> Option<&dyn TypeTrait> {
            Some(self)
        }
    }
}

/// The special `void` type.
#[derive(Debug, Clone, Copy, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct Void(());

impl_lang_item! {
    impl LangItem<Csharp> for Void {
        fn format(&self, out: &mut Formatter, _: &mut Config, _: usize) -> fmt::Result {
            out.write_str("void")?;
            Ok(())
        }

        fn as_import(&self) -> Option<&dyn TypeTrait> {
            Some(self)
        }
    }
}

/// Language specialization for C#.
pub struct Csharp(());

impl Csharp {
    fn imports(tokens: &Tokens, output: &mut Tokens, config: &mut Config) {
        let mut modules = BTreeSet::new();

        for import in tokens.walk_imports() {
            import.type_imports(&mut modules);
        }

        if modules.is_empty() {
            return;
        }

        let mut imported = HashSet::new();

        for (namespace, name) in modules {
            if Some(&*namespace) == config.namespace.as_deref() {
                continue;
            }

            match config.imported_names.get(&*name) {
                // already imported...
                Some(existing) if existing == &*namespace => continue,
                // already imported, as something else...
                Some(_) => continue,
                _ => {}
            }

            if !imported.contains(&*namespace) {
                quote_in!(output => using #(&namespace););
                output.push();
                imported.insert(namespace.to_string());
            }

            config
                .imported_names
                .insert(name.to_string(), namespace.to_string());
        }

        output.line();
    }
}

impl Lang for Csharp {
    type Config = Config;
    type Import = dyn TypeTrait;

    fn quote_string(out: &mut Formatter, input: &str) -> fmt::Result {
        use std::fmt::Write as _;

        out.write_char('"')?;

        for c in input.chars() {
            match c {
                '\t' => out.write_str("\\t")?,
                '\u{0007}' => out.write_str("\\b")?,
                '\n' => out.write_str("\\n")?,
                '\r' => out.write_str("\\r")?,
                '\u{0014}' => out.write_str("\\f")?,
                '\'' => out.write_str("\\'")?,
                '"' => out.write_str("\\\"")?,
                '\\' => out.write_str("\\\\")?,
                c => out.write_char(c)?,
            }
        }

        out.write_char('"')?;

        Ok(())
    }

    fn write_file(
        tokens: Tokens,
        out: &mut Formatter,
        config: &mut Self::Config,
        level: usize,
    ) -> fmt::Result {
        let mut toks: Tokens = Tokens::new();

        Self::imports(&tokens, &mut toks, config);

        if let Some(namespace) = &config.namespace {
            quote_in! { toks =>
                namespace #namespace {
                    #tokens
                }
            }

            toks.push()
        } else {
            toks.append(tokens);
        }

        toks.format(out, config, level)
    }
}

/// Construct an imported type.
///
/// # Examples
///
/// ```rust
/// use genco::prelude::*;
///
/// let a = csharp::using("Foo.Bar", "A");
/// let b = csharp::using("Foo.Bar", "B");
/// let ob = csharp::using("Foo.Baz", "B");
/// let ob_a = ob.clone().with_arguments(a.clone());
///
/// let toks: Tokens<Csharp> = quote! {
///     #a
///     #b
///     #ob
///     #ob_a
/// };
///
/// assert_eq!(
///     vec![
///         "using Foo.Bar;",
///         "",
///         "A",
///         "B",
///         "Foo.Baz.B",
///         "Foo.Baz.B<A>",
///     ],
///     toks.to_file_vec().unwrap()
/// );
/// ```
pub fn using<P: Into<ItemStr>, N: Into<ItemStr>>(namespace: P, name: N) -> Type {
    Type {
        namespace: Some(namespace.into()),
        name: name.into(),
        path: vec![],
        arguments: vec![],
        qualified: false,
        kind: Kind::Class,
    }
}

/// Setup a local element from borrowed components.
pub fn local<N: Into<ItemStr>>(name: N) -> Type {
    Type {
        namespace: None,
        name: name.into(),
        path: vec![],
        arguments: vec![],
        qualified: false,
        kind: Kind::Class,
    }
}

/// Setup an array type.
///
/// # Examples
///
/// ```rust
/// use genco::prelude::*;
///
/// let ty = csharp::array(csharp::using("Foo.Bar", "A"));
///
/// let toks: Tokens<Csharp> = quote! {
///     #ty
/// };
///
/// assert_eq!(
///     vec![
///         "using Foo.Bar;",
///         "",
///         "A[]",
///     ],
///     toks.to_file_vec().unwrap()
/// );
/// ```
pub fn array<I: Into<TypeBox>>(value: I) -> Array {
    Array {
        inner: value.into(),
    }
}

/// Setup an optional type.
pub fn optional<I: Into<TypeBox>>(value: I) -> Optional {
    Optional {
        inner: value.into(),
    }
}

/// Format a doc comment where each line is preceeded by `///`.
///
/// # Examples
///
/// ```rust
/// use genco::prelude::*;
///
/// use std::iter;
///
/// let toks = quote! {
///     #(csharp::block_comment(vec!["Foo"]))
///     #(csharp::block_comment(iter::empty::<&str>()))
///     #(csharp::block_comment(vec!["Bar"]))
/// };
///
/// assert_eq!(
///     vec![
///         "/// Foo",
///         "/// Bar",
///     ],
///     toks.to_file_vec().unwrap()
/// );
/// ```
pub fn block_comment<T>(comment: T) -> BlockComment<T>
where
    T: IntoIterator,
    T::Item: Into<ItemStr>,
{
    BlockComment(comment)
}