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
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.
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.
pub enum NameType {
    Default,
    Type,
    Member,
    Function,
    File,
    FixedCase(CaseType),
    Bypass,
}

pub struct Name {
    parts: Vec<String>,
    name_type: NameType
}

impl Name {
    /// 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!("testName1", 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)));
    /// ```
    pub fn new(snake_case_name: &str) -> Name {
        let name = snake_case_name;
        let mut parts = Vec::<String>::new();
        for entry in name.split("_") {
            if !entry.is_empty() {
                parts.push(entry.to_ascii_lowercase());
            }
        }
        if parts.len() == 0 {
            parts.push("invalid".into());
            parts.push("name".into());
        }

        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
    }

    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: CodeGenerationInfo) -> CaseType {
        match self.name_type {
            NameType::Default => info.default_name_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_name_case,
        }
    }
}

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

/// The NewLine struct allows the generation info to decide the new line format
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>>,
}

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

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));
                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 change the new line format based on the
    /// context of the generator.
    /// 
    /// ```
    /// # 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
    }
}

/// 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;
    }
}

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
    }
}