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
//! Specialization for Csharp code generation.

mod modifier;
mod utils;

pub use self::modifier::Modifier;
pub use self::utils::BlockComment;
use crate::{Cons, Formatter, Lang, LangItem};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt;

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

impl_type_basics!(Csharp, TypeEnum<'a>, TypeTrait, TypeBox, TypeArgs, {Simple, Optional, Type, Array, Void});

/// Trait implemented by all types
pub trait TypeTrait: 'static + fmt::Debug + LangItem<Csharp> {
    /// Coerce trait into an enum that can be used for type-specific operations
    fn as_enum(&self) -> TypeEnum<'_>;

    /// 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<(Cons<'static>, Cons<'static>)>) {}
}

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(());

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

    /// 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<Cons<'static>>,
    {
        Self {
            namespace: Some(namespace.into()),
            ..self
        }
    }
}

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

impl TypeTrait for Optional {
    fn as_enum(&self) -> TypeEnum<'_> {
        TypeEnum::Optional(self)
    }

    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<(Cons<'static>, Cons<'static>)>) {
        self.inner.type_imports(modules)
    }
}

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<Cons<'static>>,
    /// Name  of class.
    name: Cons<'static>,
    /// Path of class when nested.
    path: Vec<Cons<'static>>,
    /// 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<Cons<'static>>>(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 TypeTrait for Type {
    fn as_enum(&self) -> TypeEnum<'_> {
        TypeEnum::Type(self)
    }

    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<(Cons<'static>, Cons<'static>)>) {
        for argument in &self.arguments {
            argument.type_imports(modules);
        }

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

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 TypeTrait for Simple {
    fn as_enum(&self) -> TypeEnum<'_> {
        TypeEnum::Simple(self)
    }

    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<(Cons<'static>, Cons<'static>)>) {
        modules.insert((SYSTEM.into(), self.alias.into()));
    }
}

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 TypeTrait for Array {
    fn as_enum(&self) -> TypeEnum<'_> {
        TypeEnum::Array(self)
    }

    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<(Cons<'static>, Cons<'static>)>) {
        self.inner.type_imports(modules);
    }
}

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 TypeTrait for Void {
    fn as_enum(&self) -> TypeEnum<'_> {
        TypeEnum::Void(self)
    }

    fn name(&self) -> &str {
        "void"
    }

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

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<'el>(tokens: &Tokens<'el>, config: &mut Config) -> Option<Tokens<'el>> {
        let mut modules = BTreeSet::new();

        let file_namespace = config.namespace.as_ref().map(|p| p.as_ref());

        for custom in tokens.walk_custom() {
            if let Some(import) = custom.as_import() {
                import.type_imports(&mut modules);
            }
        }

        if modules.is_empty() {
            return None;
        }

        let mut out = Tokens::new();
        let mut imported = HashSet::new();

        for (namespace, name) in modules {
            if Some(&*namespace) == file_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) {
                out.push(toks!("using ", namespace.clone(), ";"));
                imported.insert(namespace.to_string());
            }

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

        Some(out)
    }
}

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();

        if let Some(imports) = Self::imports(&tokens, config) {
            toks.push(imports);
            toks.line_spacing();
        }

        if let Some(ref namespace) = config.namespace {
            toks.push(toks!["namespace ", namespace.clone(), " {"]);
            toks.indent();
            toks.append(tokens);
            toks.unindent();
            toks.push("}");
        } else {
            toks.append(tokens);
        }

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

/// Setup an imported element.
pub fn using<P: Into<Cons<'static>>, N: Into<Cons<'static>>>(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<Cons<'static>>>(name: N) -> Type {
    Type {
        namespace: None,
        name: name.into(),
        path: vec![],
        arguments: vec![],
        qualified: false,
        kind: Kind::Class,
    }
}

/// Setup an array type.
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(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate as genco;
    use crate::{quote, Csharp, Quoted, Tokens};

    #[test]
    fn test_string() {
        let mut toks: Tokens<Csharp> = Tokens::new();
        toks.append("hello \n world".quoted());
        assert_eq!("\"hello \\n world\"", toks.to_string().unwrap().as_str());
    }

    #[ignore]
    #[test]
    fn test_using() {
        let a = using("Foo.Bar", "A");
        let b = using("Foo.Bar", "B");
        let ob = 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()
        );
    }
}