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
use std::fmt;
use crate::setup::*;

/// Indentation generator
/// 
/// This struct will use the context of the generator to decide how to generate
/// 
/// When using this generator you should assume that any necessary indentation
/// before your generator has already been created. i.e. generate indentation
/// for all lines except the first since that indentation would be generated by
/// the parent generator. You will only need to use this when you create a
/// multiline generator which does not use the existing code structure
/// generators.
#[derive(Clone, Copy)]
pub struct Indentation {
}

impl Indentation {
    /// Creates an indentation generator
    /// 
    /// This should not be used if you want a specific amount/type of indentation
    /// 
    /// ```
    /// # use code_generator::CodeStyle;
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::Indentation;
    /// # use code_generator::DisplayExt;
    /// #
    /// let indent = Indentation::new();
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR).indent();
    /// assert_eq!("    ", format!("{}", indent.display(info)));
    /// ```
    pub fn new() -> Indentation {
        Indentation { }
    }
}

impl CodeGenerate for Indentation {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let indent ;
        match info.indent_type {
            IndentationType::Spaces => indent = " ".repeat(info.indent_amount*info.indent_level),
            IndentationType::Tabs => indent = "	".repeat(
                ((info.indent_amount+3) / 4) * info.indent_level
            ),
        }
        
        write!(f, "{}", indent)
    }
}

/// The name type allows the struct to use the generation info to decide the
/// case type of the name based on the type of name.
/// 
/// The FixedCase variant is used to override the CaseType discovery of normal
/// code generation.
/// 
/// The Bypass variant is used to provide a name without having the generator
/// use any sort of formatting on it.
#[derive(Clone, Copy)]
pub enum NameType {
    Default,
    ConstDefine,
    Type,
    Member,
    Function,
    File,
    FixedCase(CaseType),
    Bypass,
}

#[derive(Clone)]
pub struct Name {
    parts: Vec<String>,
    name_type: NameType
}

impl Name {
    fn is_separator(char: char, prev: Option<char>) -> bool {
        char.is_uppercase() 
        && prev.is_some_and(
            |char| char.is_lowercase()
        )
    }

    /// Creates a Name generator
    /// 
    /// This struct makes it easy to change the name format based on the
    /// context of the generator.
    /// 
    /// ```
    /// # use code_generator::CaseType;
    /// # use code_generator::CodeStyle;
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::Name;
    /// # use code_generator::NameType;
    /// # use code_generator::DisplayExt;
    /// #
    /// let cc = NameType::FixedCase(CaseType::CamelCase);
    /// let name = Name::new("test_name1").with_type(cc);
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("test_Name1", format!("{}", name.display(info)));
    ///
    /// let ssc = NameType::FixedCase(CaseType::ScreamingSnakeCase);
    /// let name = Name::new("test_name2").with_type(ssc);
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("TEST__NAME2", format!("{}", name.display(info)));
    ///
    /// let ssc = NameType::FixedCase(CaseType::SnakeCase);
    /// let name = Name::new("testNameThree").with_type(ssc);
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("test_name_three", format!("{}", name.display(info)));
    ///
    /// let ssc = NameType::FixedCase(CaseType::FlatCase);
    /// let name = Name::new("test_four").with_type(ssc);
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("test_four", format!("{}", name.display(info)));
    /// ```
    pub fn new(name: &str) -> Name {
        let mut parts: Vec<String> = Vec::new();
        let mut current_part = String::new();
        let mut is_first = true;
        let mut prev = None;
        for char in name.chars() {
            if Self::is_separator(char, prev) && !is_first {
                parts.push(current_part.clone());
                current_part.clear();
            }

            current_part.extend(char.to_lowercase());
            if char == '_' {
                parts.push(current_part.clone());
                current_part.clear();
            }
            is_first = false;
            prev = Some(char);
        }
        // push last part
        if !current_part.is_empty() {
            parts.push(current_part);
        }

        Name {
            parts: parts,
            name_type: NameType::Default
        }
    }

    pub fn new_with_type(snake_case_name: &str, name_type: NameType) -> Name {
        if let NameType::Bypass = name_type {
            Name {
                parts: vec![snake_case_name.into()],
                name_type: NameType::Bypass
            }
        } else {
            Name::new(snake_case_name).with_type(name_type)
        }
    }

    pub fn with_type(mut self, name_type: NameType) -> Name {
        match self.name_type {
            // Fixed/Bypass case bypasses the name type specialization
            NameType::Bypass => (),
            NameType::FixedCase(_) => (),
            _ => self.name_type = name_type,
        }

        self
    }

    /// Creates a Name generator
    /// 
    /// This struct makes it easy to change the name format based on the
    /// context of the generator.
    /// 
    /// ```
    /// # use code_generator::CaseType;
    /// # use code_generator::CodeStyle;
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::Name;
    /// # use code_generator::NameType;
    /// # use code_generator::DisplayExt;
    /// # use code_generator::CaseTypes;
    /// #
    /// let name = Name::new("test_name1").as_include_guard();
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR)
    ///     .with_case_types(
    ///         CaseTypes::new().with_const_define(CaseType::ScreamingSnakeCase)
    ///     );
    /// assert_eq!("TEST__NAME1_H", format!("{}", name.display(info)));
    pub fn as_include_guard(&self) -> Name {
        let mut parts = self.parts.clone();
        parts.push(String::from("h"));
        Name { parts: parts, name_type: NameType::ConstDefine }
    }

    fn caps_first_letter(string: String) -> String {
        let mut result = String::new();

        let mut iter = string.chars();
        if let Some(char) = iter.next() {
            result.push(char.to_ascii_uppercase());
        }

        for char in iter {
            result.push(char);
        }

        result
    }

    fn casify(&self, case: CaseType) -> String {
        if let NameType::Bypass = self.name_type {
            return self.parts.join("");
        }

        let mut parts = Vec::new();
        let mut is_first = true;
        for part in self.parts.iter() {
            parts.push (match case {
                CaseType::CamelCase => if is_first {part.clone()} else {Self::caps_first_letter(part.clone())},
                CaseType::FlatCase => part.clone(),
                CaseType::PascalCase => Self::caps_first_letter(part.clone()),
                CaseType::ScreamingCase => part.to_ascii_uppercase(),
                CaseType::ScreamingSnakeCase => part.to_ascii_uppercase(),
                CaseType::SnakeCase => part.clone(),
            });
            is_first = false;
        }
        match case {
            CaseType::CamelCase => parts.join(""),
            CaseType::FlatCase => parts.join(""),
            CaseType::PascalCase => parts.join(""),
            CaseType::ScreamingCase => parts.join(""),
            CaseType::ScreamingSnakeCase => parts.join("_"),
            CaseType::SnakeCase => parts.join("_"),
        }
    }

    fn get_case_type(&self, info: CaseTypes) -> CaseType {
        match self.name_type {
            NameType::Default => info.default_case,
            NameType::ConstDefine => info.const_define_case,
            NameType::Function => info.function_name_case,
            NameType::Member => info.member_name_case,
            NameType::Type => info.type_name_case,
            NameType::File => info.file_name_case,
            NameType::FixedCase(case) => case,
            NameType::Bypass => info.default_case,
        }
    }
}

impl CodeGenerate for Name {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let case_type = self.get_case_type(info.case_types);
        write!(f, "{}", self.casify(case_type))
    }
}

pub struct Include {
    file_name: Name,
    is_sys_inc: bool,
}

impl Include {
    
    /// Creates an Include generator
    /// 
    /// This struct allows includes to be adapted to the naming of the config
    /// 
    /// ```
    /// # use code_generator::CaseType;
    /// # use code_generator::CodeStyle;
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::Name;
    /// # use code_generator::NameType;
    /// # use code_generator::DisplayExt;
    /// # use code_generator::Include;
    /// #
    /// let inc = Include::new(Name::new_with_type("my_testFile", NameType::File));
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("#include \"My_TestFile.h\"", format!("{}", inc.display(info)));
    /// ```
    pub fn new(file_name: Name) -> Include {
        Include {
            file_name,
            is_sys_inc: false
        }
    }

    /// Creates an Include generator
    /// 
    /// This struct allows includes to be adapted to the naming of the config
    /// 
    /// ```
    /// # use code_generator::CaseType;
    /// # use code_generator::CodeStyle;
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::Name;
    /// # use code_generator::NameType;
    /// # use code_generator::DisplayExt;
    /// # use code_generator::Include;
    /// #
    /// let inc = Include::new_sys("my_testFile.h");
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("#include <my_testFile.h>", format!("{}", inc.display(info)));
    /// ```
    pub fn new_sys(file_name: &str) -> Include {
        Include {
            file_name: Name::new_with_type(
                file_name,
                NameType::Bypass
            ),
            is_sys_inc: true
        }
    }
}

impl CodeGenerate for Include {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        match self.is_sys_inc {
            true => write!(f, "#include <{}>", self.file_name.display(info)),
            false => write!(f, "#include \"{}.h\"", self.file_name.display(info))
        }
    }
}

/// The NewLine struct allows the generation info to decide the new line format
#[derive(Clone, Copy)]
pub struct NewLine {
}

impl NewLine {
    /// Creates a NewLine generator
    /// 
    /// This struct makes it easy to change the new line format based on the
    /// context of the generator.
    /// 
    /// ```
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::NewLineType;
    /// # use code_generator::NewLine;
    /// # use code_generator::DisplayExt;
    /// #
    /// let new_line = NewLine::new();
    /// let mut info = CodeGenerationInfo::new();
    /// info.set_new_line_type(NewLineType::CrNl);
    /// assert_eq!("\r\n", format!("{}", new_line.display(info)));
    /// ```
    pub fn new() -> NewLine {
        NewLine { }
    }
}

impl CodeGenerate for NewLine {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        match info.new_line_type {
            NewLineType::Cr => write!(f, "\r"),
            NewLineType::Nl => write!(f, "\n"),
            NewLineType::CrNl => write!(f, "\r\n"),
            NewLineType::None => write!(f, ""),
        }
    }
}

pub struct CodeSet {
    code_set: Vec<Box<dyn CodeGenerate>>,
    is_separated: bool,
}

impl CodeSet {
    pub fn new(set: Vec<Box<dyn CodeGenerate>>) -> CodeSet {
        CodeSet { code_set: set, is_separated: false }
    }

    pub fn new_separated(set: Vec<Box<dyn CodeGenerate>>) -> CodeSet {
        CodeSet { code_set: set, is_separated: true }
    }
}

impl CodeGenerate for CodeSet {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result = fmt::Result::Ok(());
        let mut iter = self.code_set.iter();
        if let Some(item) = iter.next() {
            result = result.and(item.generate(f, info));

            for item in iter {
                result = result.and(NewLine::new().generate(f, info));
                if self.is_separated {
                    result = result.and(NewLine::new().generate(f, info));
                }
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(item.generate(f, info));
            }
        }
        result
    }
}

/// The JoinedCode struct joins multiple sections of code with no further
/// formatting, or configuration done outside, inside, or between units.
pub struct JoinedCode {
    code_set: Vec<Box<dyn CodeGenerate>>,
}

impl JoinedCode {
    /// Creates a JoinedCode generator
    /// 
    /// This struct makes it easy to join multiple generators without any separation
    /// 
    /// ```
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::DisplayExt;
    /// # use code_generator::JoinedCode;
    /// #
    /// let joined = JoinedCode::new(vec![
    ///     Box::new(String::from("This")),
    ///     Box::new(String::from(":")),
    ///     Box::new(String::from("Is")),
    ///     Box::new(String::from(":")),
    ///     Box::new(String::from("Joined"))
    /// ]);
    /// let mut info = CodeGenerationInfo::new();
    /// assert_eq!("This:Is:Joined", format!("{}", joined.display(info)));
    /// ```
    pub fn new(set: Vec<Box<dyn CodeGenerate>>) -> JoinedCode {
        JoinedCode { code_set: set }
    }
}

impl CodeGenerate for JoinedCode {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result = fmt::Result::Ok(());

        for item in self.code_set.iter() {
            result = result.and(item.generate(f, info));
        }

        result
    }
}

/// Creates a JoinedCode generator
/// 
/// This macro makes it easy to create a JoinedCode struct
/// 
/// ```
/// # use code_generator::CodeGenerationInfo;
/// # use code_generator::DisplayExt;
/// # use code_generator::JoinedCode;
/// # use code_generator::CodeGenerate;
/// # use code_generator::join_code;
/// #
/// let joined = join_code!(
///     String::from("This"),
///     String::from("Is"),
///     String::from("Joined")
/// );
///
/// let mut info = CodeGenerationInfo::new();
/// assert_eq!("ThisIsJoined", format!("{}", JoinedCode::new(joined).display(info)));
/// ```
#[macro_export]
macro_rules! join_code {
    ($($args:expr),*) => {{
        let temp: Vec<Box<dyn CodeGenerate>> = vec![
            $(Box::new($args)),*
        ];

        temp
    }}
}

/// Raw code with no formatting besides injecting newlines, and
/// indentation based on the context
impl CodeGenerate for String {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result: fmt::Result = fmt::Result::Ok(());
        // First line doesn't print indentation
        let mut iter = self.lines();
        if let Some(line) = iter.next() {
            result = result.and(result.and(write!(f, "{}", line)));
        }
        for line in iter {
            result = result.and(NewLine::new().generate(f, info));
            result = result.and(Indentation::new().generate(f, info));
            result = result.and(write!(f, "{}", line));
        }
        return result;
    }
}

/// Raw code with no formatting besides injecting newlines, and
/// indentation based on the context/// Creates a JoinedCode generator
/// ```
/// # use code_generator::CodeGenerationInfo;
/// # use code_generator::DisplayExt;
/// # use code_generator::JoinedCode;
/// # use code_generator::CodeGenerate;
/// # use code_generator::join_code;
/// #
/// let text = "Testing123";
///
/// let mut info = CodeGenerationInfo::new();
/// assert_eq!("Testing123", format!("{}", text.display(info)));
/// ```
impl CodeGenerate for &str {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result: fmt::Result = fmt::Result::Ok(());
        // First line doesn't print indentation
        let mut iter = self.lines();
        if let Some(line) = iter.next() {
            result = result.and(result.and(write!(f, "{}", line)));
        }
        for line in iter {
            result = result.and(NewLine::new().generate(f, info));
            result = result.and(Indentation::new().generate(f, info));
            result = result.and(write!(f, "{}", line));
        }
        return result;
    }
}

pub struct SeparatedCode {
    items: Vec<Box<dyn CodeGenerate>>,
    separator: Box<dyn CodeGenerate>,
    // TODO: newlines in GeneratorInfo?
}

impl SeparatedCode {
    pub fn new(items: Vec<Box<dyn CodeGenerate>>, separator: Box<dyn CodeGenerate>) -> SeparatedCode {
        SeparatedCode { items: items, separator: separator }
    }
}

impl CodeGenerate for SeparatedCode {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result: fmt::Result = fmt::Result::Ok(());

        let mut iterator = self.items.iter();

        if let Some(item) = iterator.next() {
            result = result.and(item.generate(f, info));
        }

        for item in iterator {
            result = result.and(self.separator.generate(f, info));
            result = result.and(item.generate(f, info));
        }

        result
    }
}

pub struct CodeBody {
    raw_code: CodeSet,
}

impl CodeBody {
    /// Creates a CodeBody generator
    /// 
    /// This struct is used for code bodies. Think the body to an if statement,
    /// function, or struct. This handles the brace/newline format of that body
    /// 
    /// ```
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::CodeStyle;
    /// # use code_generator::DisplayExt;
    /// # use code_generator::CodeBody;
    /// #
    /// let code_body = CodeBody::new(vec![
    ///     Box::new(String::from("Body"))
    /// ]);
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!("{\r\n    Body\r\n}", format!("{}", code_body.display(info)));
    /// 
    /// let info = CodeGenerationInfo::from_style(CodeStyle::Horstmann);
    /// assert_eq!("{   Body\r\n}", format!("{}", code_body.display(info)));
    /// ```
    pub fn new(code: Vec<Box<dyn CodeGenerate>>) -> CodeBody {
        CodeBody {raw_code: CodeSet::new(code)}
    }
}

impl CodeGenerate for CodeBody {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result: fmt::Result = fmt::Result::Ok(());
        match info.indent_style {
            IndentationStyle::Allman => {
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, "{{"));
                result = result.and(NewLine::new().generate(f, info));
                result = result.and(Indentation::new().generate(f, info.indent()));
                result = result.and(self.raw_code.generate(f, info.indent()));
                result = result.and(NewLine::new().generate(f, info));
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, "}}"));
            }
            IndentationStyle::GNU => {
                result = result.and(write!(f, "{{"));
                result = result.and(NewLine::new().generate(f, info));
                result = result.and(Indentation::new().generate(f, info.indent().indent()));
                result = result.and(self.raw_code.generate(f, info.indent().indent()));
                result = result.and(NewLine::new().generate(f, info));
                if info.context != GeneratorContext::Function {
                    result = result.and(Indentation::new().generate(f, info.indent()));
                }
                result = result.and(write!(f, "}}"));
            }
            IndentationStyle::Horstmann => {
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, "{{"));
                let mut temp_info = info;
                temp_info.indent_level = 1;
                temp_info.indent_amount -= 1;// to account for '{' if using spaces
                result = result.and(Indentation::new().generate(f, temp_info));
                result = result.and(self.raw_code.generate(f, info.indent()));
                result = result.and(NewLine::new().generate(f, info));
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, "}}"));
            }
            IndentationStyle::KnR => {
                result = result.and(write!(f, "{{"));
                result = result.and(NewLine::new().generate(f, info));
                result = result.and(Indentation::new().generate(f, info.indent()));
                result = result.and(self.raw_code.generate(f, info.indent()));
                result = result.and(NewLine::new().generate(f, info));
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, "}}"));
            }
            IndentationStyle::Pico => {
                result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, "{{"));
                let mut temp_info = info;
                temp_info.indent_level = 1;
                temp_info.indent_amount -= 1;// to account for '{' if using spaces
                result = result.and(Indentation::new().generate(f, temp_info));
                result = result.and(self.raw_code.generate(f, info.indent()));
                //result = result.and(Indentation::new().generate(f, info));
                result = result.and(write!(f, " }}"));
            }
            IndentationStyle::None => {
                result = result.and(write!(f, "{{"));
                result = result.and(self.raw_code.generate(f, info.indent()));
                result = result.and(write!(f, "}}"));
            }
            _ => result = result.and(write!(f, "NOT SUPPORTED YET!")),
        }

        result
    }
}

pub struct HeaderPlusBody<HT> {
    header: HT,
    body: CodeBody,
}

impl<HT> HeaderPlusBody<HT> {
    /// Creates a HeaderPlusBody generator
    /// 
    /// This struct is used for joining headers and bodies. For example joining
    /// the "if(condition)" to the "{body}"
    /// 
    /// ```
    /// # use code_generator::CodeGenerationInfo;
    /// # use code_generator::CodeStyle;
    /// # use code_generator::DisplayExt;
    /// # use code_generator::CodeBody;
    /// # use code_generator::HeaderPlusBody;
    /// #
    /// let header_plus_body = HeaderPlusBody::new(
    ///     String::from("header"),
    ///     CodeBody::new(vec![Box::new(String::from("Body"))])
    /// );
    /// let info = CodeGenerationInfo::from_style(CodeStyle::KnR);
    /// assert_eq!(
    ///     "header {\r\n    Body\r\n}",
    ///     format!("{}", header_plus_body.display(info))
    /// );
    /// 
    /// let info = CodeGenerationInfo::from_style(CodeStyle::Allman);
    /// assert_eq!(
    ///     "header\r\n{\r\n    Body\r\n}",
    ///     format!("{}", header_plus_body.display(info))
    /// );
    /// ```
    pub fn new(header: HT, body: CodeBody) -> HeaderPlusBody<HT>{
        HeaderPlusBody {header: header, body: body}
    }
}

impl<HT> CodeGenerate for HeaderPlusBody<HT>
where HT: CodeGenerate,{
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result {
        let mut result: fmt::Result = fmt::Result::Ok(());
        result = result.and(self.header.generate(f, info));
        match info.indent_style {
            IndentationStyle::Allman |
            IndentationStyle::Horstmann |
            IndentationStyle::Pico => {
                result = result.and(NewLine::new().generate(f, info));
            },
            IndentationStyle::GNU => {
                result = result.and(NewLine::new().generate(f, info));
                if info.context != GeneratorContext::Function {
                    result = result.and(Indentation::new().generate(f, info.indent()));
                }
            }
            IndentationStyle::KnR => {
                result = result.and(write!(f, " "));
            }
            _ => (),
        }
        result = result.and(self.body.generate(f, info));
        result
    }
}