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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783

extern crate clap;
extern crate termcolor;
extern crate atty;

extern crate unicode_segmentation;
extern crate unicode_categories;
extern crate regex;
extern crate lazy_static;
extern crate waterbear_instruction_derive;
extern crate uuid;

pub mod instruction;
pub mod parser;
pub mod ast;
pub mod expression;
pub mod input;
pub mod lexer;
pub mod location;
pub mod files;
mod asm;
mod disasm;
mod env;

use disasm::DisasmError;
use location::{Span};
use unicode_segmentation::UnicodeSegmentation;
use regex::Regex;
use std::fs::File;
use std::io::Write;
use std::fmt::Display;
use std::io::Read;
use ast::ArgType;

use std::path::Path;
use asm::AssemblyError;

use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use atty::Stream;

use expression::{EvaluationError};
use files::{SourceFiles};
use clap::clap_app;
use lazy_static::lazy_static;

pub use asm::{assemble_file,assemble};

const DESCRIPTION: &'static str = env!("CARGO_PKG_DESCRIPTION");
const NAME: &'static str = env!("CARGO_PKG_NAME");
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const RUSTC: &'static str = env!("RUSTC_VERSION");
const CARGO: &'static str = env!("CARGO_VERSION");
const GITSHA: &'static str = env!("GITSHA");

pub fn run_command(args: &[String]) {
    let matches = clap_app!(
        waterbear =>
            (name: NAME)
            (version: VERSION)
            (about: DESCRIPTION)
            (@subcommand assemble =>
              (version: VERSION)
              (about: "Assembler for the Dreamcast VMU")
              (@arg INPUT: +required "Sets the input file to assemble")
              (@arg OUTPUT: -o --output +required +takes_value "Output file")
             )
            (@subcommand expand =>
              (version: VERSION)
              (about: "Expand macros and output to stdout")
              (@arg INPUT: +required "Sets the input file to assemble")
             )
            (@subcommand disassemble =>
              (version: VERSION)
              (about: "Disassembler for the Dreamcast VMU")
              (@arg INPUT: +required "Sets the input file to assemble")
              (@arg OUTPUT: -o --output +required +takes_value "Output file")
              (@arg POSITIONS: -p --positions "Output byte positions")
              (@arg ARRIVED_FROM: -a --arrived_from "Output instruction locations that target each instruction.")
             )
            (@subcommand version =>
              (version: VERSION)
              (about: "Version info about this build")
             )
    ).get_matches_from(args);

    let mut stdout = ColorWriter::new(StandardStream::stdout(if atty::is(Stream::Stdout) { ColorChoice::Auto } else { ColorChoice::Never }));

    if let Some(matches) = matches.subcommand_matches("assemble") {
        let input_file = matches.value_of("INPUT").unwrap();
        let path = Path::new(input_file);
        let dir = path.parent().unwrap_or(Path::new("")).to_str().unwrap();

        let mut files = files::SourceFiles::new(dir.to_owned());
        match assemble_cmd(&mut files, &mut stdout, matches) {
            Ok(_num_bytes) => {},
            Err(ref err) => {
                stdout.write_error().space()
                    .write("Failed to assemble ")
                    .cyan()
                    .write(input_file)
                    .reset()
                    .newline()
                    .newline()
                    .red()
                    .write("✘")
                    .reset()
                    .space();
                print_error(&mut files, err, &mut stdout);
            }
        }
    } else if let Some(matches) = matches.subcommand_matches("disassemble") {
        let input_file = matches.value_of("INPUT").unwrap();
        let output_file = matches.value_of("OUTPUT").unwrap();
        let positions = matches.occurrences_of("POSITIONS") > 0;
        let arrived_from = matches.occurrences_of("ARRIVED_FROM") > 0;
        match disassemble_cmd(positions, arrived_from, input_file, output_file) {
            Ok(_) => {},
            Err(ref err) => {
                println!("ERROR: {:?}", err);
            }
        }
    } else if let Some(matches) = matches.subcommand_matches("expand") {
        let input_file = matches.value_of("INPUT").unwrap();
        let path = Path::new(input_file);
        let dir = path.parent().unwrap_or(Path::new("")).to_str().unwrap();

        let mut files = files::SourceFiles::new(dir.to_owned());
        match expand_cmd(&mut files, matches) {
            Ok(_) => {},
            Err(ref err) => {
                stdout.write_error().space()
                    .write("Failed to expand ")
                    .cyan()
                    .write(input_file)
                    .reset()
                    .newline()
                    .newline()
                    .red()
                    .write("✘")
                    .reset()
                    .space();
                print_error(&mut files, err, &mut stdout);
            }
        }
    } else if let Some(_) = matches.subcommand_matches("version") {
        stdout.magenta()
            .writeln("               _            _")
            .writeln("              | |          | |")
            .writeln("__      ____ _| |_ ___ _ __| |__   ___  __ _ _ __ ")
            .writeln("\\ \\ /\\ / / _` | __/ _ | '__| '_ \\ / _ \\/ _` | '__|")
            .writeln(" \\ V  V | (_| | ||  __| |  | |_) |  __| (_| | |")
            .writeln("  \\_/\\_/ \\__,_|\\__\\___|_|  |_.__/ \\___|\\__,_|_|")
            .reset()
            .newline()
            .yellow()
            .write(NAME)
            .reset()
            .space()
            .bold()
            .write("v")
            .writeln(VERSION)
            .reset()
            .writeln(DESCRIPTION)
            .newline()
            .bold()
            .writeln("Build Info")
            .reset()
            .cyan()
            .write("  Compiler").reset().write(": ")
            .writeln(RUSTC)
            .cyan()
            .write("  Cargo").reset().write(":    ")
            .writeln(CARGO)
            .cyan()
            .write("  git SHA").reset().write(":  ")
            .writeln(GITSHA)
            .reset()
            .newline();
    } else {
        eprintln!("No subcommand specified");
        std::process::exit(1);
    }
}

fn disassemble_cmd(positions: bool, arrived_from: bool, filename: &str, output_file: &str) -> Result<(), DisasmError> {
    let bytes = {
        let mut file = File::open(filename).map_err(|e| DisasmError::NoSuchFile(filename.to_string(), e))?;
        let mut contents: Vec<u8> = vec![];
        file.read_to_end(&mut contents).map_err(|e| DisasmError::NoSuchFile(filename.to_string(), e))?;
        contents
    };
    let entry_points = vec![0, 0x3, 0xb, 0x13, 0x1b, 0x23, 0x2b, 0x33, 0x3b, 0x43, 0x4b, 0x130, 0x1f0];
    let statements = disasm::disassemble(arrived_from, &entry_points, &bytes)?;

    let mut outfile = File::create(output_file).unwrap();
    for dstmt in statements.to_vec() {
        if positions {
            if let Some(pos) = dstmt.pos() {
                write!(outfile, "{:04X}| ", pos).unwrap();
            } else {
                write!(outfile, "    | ").unwrap();
            }
        }
        write!(outfile, "{}", dstmt.statement()).unwrap();
        if let Some(comment) = dstmt.cmt() {
            write!(outfile, " ; {}", comment).unwrap();
        }
        writeln!(outfile, "").unwrap();
    }

    Ok(())
}

fn expand_cmd(mut files: &mut SourceFiles, matches: &clap::ArgMatches) -> Result<(),AssemblyError> {
    let input_file = matches.value_of("INPUT").unwrap();
    asm::expand_file(&mut files, input_file)
}

fn assemble_cmd(mut files: &mut SourceFiles, stdout: &mut ColorWriter, matches: &clap::ArgMatches) -> Result<usize, AssemblyError> {
    let input_file = matches.value_of("INPUT").unwrap();
    let bytes = asm::assemble_file(&mut files, input_file)?;
    let output_file = matches.value_of("OUTPUT").unwrap();
    let mut outfile = File::create(output_file).unwrap();
    outfile.write_all(&bytes).unwrap();

    stdout.write_ok()
        .write(" Assembled ")
        .bold()
        .write(bytes.len())
        .reset()
        .write(" bytes to ")
        .bold()
        .write(output_file)
        .reset()
        .writeln(".");

    Ok(bytes.len())
}

fn print_error(files: &SourceFiles, err: &AssemblyError, stdout: &mut ColorWriter) {
    use asm::AssemblyError::*;
    match err {
        NameNotFound(span,msg) => {
            stdout.writeln(msg);
            stdout.newline();
            highlight_line(&span, "Unknown name", files, stdout);
        },
        DivideByZero(span,msg) => {
            stdout.writeln(msg);
            stdout.newline();
            highlight_line(&span, "", files, stdout);
        },
        MustBeLiteralNumber(span) => {
            stdout.writeln(" Must be a literal number")
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        NameAlreadyExists(current,existing,name) => {
            stdout
                .write("Name already exists: ")
                .bold()
                .writeln(name)
                .newline()
                .reset();

            stdout.bold().writeln("The name found here...").reset();
            highlight_line(&current, "Duplicate", files, stdout);
            stdout.newline().bold().writeln("...was already declared here").reset();
            highlight_line(&existing, "Original", files, stdout);
        },
        InvalidCodeLocation(span,location) => {
            stdout
                .write("Invalid code location: ")
                .bold()
                .writeln(format!("0x{:X}", location))
                .reset()
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        NumOutOfRange {
            span,
            bits,
            value
        } => {
            stdout
                .write("Value out of range: ")
                .bold()
                .write(value)
                .reset()
                .write(". Expected unsigned ")
                .bold()
                .write(bits)
                .reset()
                .writeln(" bit number.")
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        ByteOutOfRange {
            span,
            value
        } => {
            stdout
                .write("Byte out of range: ")
                .bold()
                .writeln(value)
                .reset()
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        WordOutOfRange {
            span,
            value
        } => {
            stdout
                .write("Word out of range: ")
                .bold()
                .writeln(value)
                .reset()
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        SignedNumOutOfRange {
            span,
            bits,
            value
        } => {
            stdout
                .write("Value out of range: ")
                .bold()
                .write(value)
                .reset()
                .write(". Expected signed ")
                .bold()
                .write(bits)
                .reset()
                .writeln(" bit number.")
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        InvalidAddress {
            span,
            value
        } => {
            let hex = format!("0x{:X}", value);
            stdout.write("Invalid address: ")
                .bold()
                .writeln(hex)
                .reset()
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        AddrBitsDontMatch {
            span,
            pos,
            value,
            pos_top,
            value_top
        } => {
            stdout.writeln("Target is a 12 bit absolution position, and the top 4 bits of the")
                .spaces(2)
                .write("target (")
                .yellow()
                .write(format!("0x{:04X}", *value as usize))
                .reset()
                .writeln(") don't match the top 4 bits of the current instruction")
                .write("  position (")
                .yellow()
                .write(format!("0x{:04X}", pos))
                .reset()
                .writeln(")")
                .newline()
                .spaces(2)
                .bold()
                .write("Top 4 bits of target:   ")
                .reset()
                .yellow()
                .writeln(format!("{:04b}", value_top))
                .reset()
                .spaces(2)
                .bold()
                .write("Top 4 bits of position: ")
                .reset()
                .yellow()
                .writeln(format!("{:04b}", pos_top))
                .reset()
                .newline();

            highlight_line(&span, "", files, stdout);
        },
        UnexpectedChar(loc) => {
            stdout.writeln("Unexpected Character").newline();
            highlight_line(&loc.to_span(), "", files, stdout);
        },
        UnexpectedToken(tok) => {
            stdout.writeln("Unexpected Token").newline();
            highlight_line(tok.span(), "", files, stdout);
        },
        InvalidInstruction(tok) => {
            stdout.writeln("Invalid Instruction").newline();
            highlight_line(tok.span(), "", files, stdout);
        },
        ExpectedTokenNotFound(name, tok) => {
            stdout.write("Expected to find ")
                .yellow()
                .writeln(name)
                .reset()
                .newline();
            highlight_line(tok.span(), "", files, stdout);
        },
        InvalidExpression(loc) => {
            stdout.writeln("Invalid Expression")
                .newline();
            highlight_line(&loc.to_span(), "", files, stdout);
        },
        MissingBytes(span) => {
            stdout.writeln("The ")
                .cyan()
                .write(".byte")
                .reset()
                .writeln(" directive requires at least one byte specified.")
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        MissingWords(span) => {
            stdout.writeln("The ")
                .cyan()
                .write(".word")
                .reset()
                .writeln(" directive requires at least one word specified.")
                .newline();
            highlight_line(&span, "", files, stdout);
        },
        UnknownDirective(tok) => {
            stdout.writeln("Unknown Directive")
                .newline();
            highlight_line(tok.span(), "", files, stdout);
        },
        UnknownInstruction(span) => {
            stdout.writeln("Unknown Instruction")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        WrongInstructionArgs(span,name,arg_types) => {
            stdout.write("Wrong arguments for instruction ")
                .cyan()
                .write(name)
                .reset()
                .writeln(".")
                .newline();

            highlight_line(&span, "", files, stdout);

            stdout.newline();

            if arg_types.is_empty() || (arg_types.len() == 1 && arg_types[0].is_empty()) {
                stdout.cyan()
                    .write(name)
                    .reset()
                    .writeln(" expects 0 arguments.")
                    .newline();
            } else {
                stdout.write("Allowed form");
                if arg_types.len() > 1 {
                    stdout.write("s");
                }
                stdout.write(" for instruction ")
                    .cyan()
                    .write(name)
                    .reset()
                    .write(":")
                    .newline();

                for arglist in arg_types {
                    stdout.spaces(2)
                        .cyan()
                        .write(name)
                        .reset()
                        .space();
                    let mut first = true;
                    for arg in arglist {
                        if first {
                            first = false;
                        } else {
                            stdout.write(", ");
                        }
                        match arg {
                            ArgType::Imm => stdout.yellow()
                                .write(arg.to_str())
                                .reset(),
                            ArgType::IM => stdout.magenta()
                                .write(arg.to_str())
                                .reset(),
                            ArgType::B3 |
                            ArgType::A12 |
                            ArgType::A16 |
                            ArgType::R8 |
                            ArgType::R16 |
                            ArgType::Macro |
                            ArgType::D9 => stdout.write(arg.to_str())
                        };
                    }
                    stdout.newline();
                }
            }
            stdout.newline();
        },
        UnexpectedEof => {
            stdout.writeln("Unexpected EOF")
                .newline();
        },
        FileLoadFailure(file, err) => {
            stdout.write("Error loading file ")
                .cyan()
                .write(file)
                .reset()
                .write(": ")
                .writeln(err)
                .newline();
        },
        FileUtf8Error(file, err) => {
            stdout.write("UTF-8 Error loading file ")
                .cyan()
                .write(file)
                .reset()
                .write(": ")
                .writeln(err)
                .newline();
        },
        MacroNameConflictsWithInstruction(span, name) => {
            stdout.write("Cannot name macro ")
                .cyan()
                .write(name)
                .reset()
                .writeln(": it conflicts with the instruction of the same name.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        MacroAlreadyExists(new_span, existing_span, name) => {
            stdout.write("Macro ")
                .cyan()
                .write(name)
                .reset()
                .writeln(" already exists.")
                .newline();
            stdout.writeln("This macro:");
            highlight_line(new_span, "", files, stdout);
            stdout.newline()
                .writeln("Already exists here:");
            highlight_line(existing_span, "Existing definition", files, stdout);
            stdout.newline();
        },
        DuplicateMacroArg(span) => {
            stdout.writeln("Duplicate macro arg.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        InvalidMacroArg(span) => {
            stdout.writeln("No such macro argument name.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        WrongNumberOfMacroArgs(inv_span, def_span, def_args, inv_args) => {
            stdout.write("Wrong number of arguments passed to macro. Expected ")
                .write(def_args)
                .write(", found ")
                .writeln(inv_args)
                .newline();
            highlight_line(inv_span, &format!("Found {} args", inv_args), files, stdout);
            stdout.newline();
            highlight_line(def_span, &format!("Expected {} args", def_args), files, stdout);
            stdout.newline();
        },
        DuplicateLabel(span) => {
            stdout.writeln("Found duplicate label")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        MacroLabelOutsideOfMacro(span) => {
            stdout.writeln("Macro label found outside of macro definition.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        MacroArgOutsideOfMacro(span) => {
            stdout.writeln("Macro arg found outside of macro definition.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        ImmediateValueNotAllowedHere(span) => {
            stdout.writeln("Immediate value not allowed within an expression or another immediate value.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        IndirectionModeNotAllowedHere(span) => {
            stdout.writeln("Indirection mode not allowed within an expression or immediate value.")
                .newline();
            highlight_line(span, "", files, stdout);
        },
        NoSuchMacro(span, name) => {
            stdout.write("No macro definition found for name ")
                .cyan()
                .write(name)
                .reset()
                .writeln(".")
                .newline();
            highlight_line(span, "", files, stdout);
        }
    }
}

fn highlight_line(span: &Span, msg: &str, files: &SourceFiles, stdout: &mut ColorWriter) {
    let file = files.for_id(span.start().file()).unwrap();
    let line = line_for_pos(span.start().pos(), file.contents());

    stdout.yellow().write(file.name()).reset()
        .write(":")
        .bold().write(span.start().line()).reset()
        .write(":")
        .bold().write(span.start().column());

    if span.start().column() != span.end().column() {
        stdout.write("-").write(span.end().column());
    }

    stdout.reset().newline();

    stdout.spaces(2).writeln(line);
    stdout.spaces(2).yellow().writeln(caret(&span, line, msg)).reset();

    match span.parent() {
        Some(parent) => {
            stdout.newline()
                .cyan()
                .write("Derived From")
                .reset()
                .writeln(":")
                .newline();
            highlight_line(&parent, msg, files, stdout);
        },
        None => {}
    }
}

fn caret(span: &Span, line: &str, msg: &str) -> String {
    lazy_static! {
        static ref WS: Regex = Regex::new("^\\s$").unwrap();
    }
    let mut result = String::new();
    let graphemes = UnicodeSegmentation::graphemes(line, true);
    let start = span.start().column();
    let end = span.end().column();
    let mut col = 0;
    for grapheme in graphemes {
        if col < start {
            if WS.is_match(grapheme) {
                result.push_str(grapheme);
            } else {
                result.push_str(" ");
            }
        } else if col == start {
            result.push_str("^");
        } else if col > start && col < end {
            result.push_str("^");
        } else {
            break;
        }
        col += 1
    }
    if !msg.is_empty() {
        result.push_str(" ");
        result.push_str(msg);
    }
    result
}

fn line_for_pos(pos: usize, text: &str) -> &str {
    &text[start_of_line(pos, text)..end_of_line(pos, text)]
}

fn start_of_line(pos: usize, text: &str) -> usize {
    let bytes = text.as_bytes();
    let mut loc = pos;
    while loc > 0 && bytes[loc - 1] != b'\n' {
        loc -= 1;
    }
    loc
}

fn end_of_line(pos: usize, text: &str) -> usize {
    let bytes = text.as_bytes();
    let mut loc = pos;
    while loc < bytes.len()
        && !((loc < bytes.len() - 1 && bytes[loc] == b'\n') ||
             (loc < bytes.len() - 2 && bytes[loc] == b'\r' && bytes[loc + 1] == b'\n')) {
        loc += 1;
    }
    loc
}

struct ColorWriter {
    stream: StandardStream
}

impl ColorWriter {
    pub fn new(stream: StandardStream) -> ColorWriter {
        ColorWriter { stream }
    }

    pub fn newline(&mut self) -> &mut ColorWriter {
        self.writeln("")
    }

    pub fn space(&mut self) -> &mut ColorWriter {
        self.write(" ")
    }

    pub fn spaces(&mut self, count: usize) -> &mut ColorWriter {
        for _idx in 0..count {
            self.write(" ");
        }
        self
    }

    pub fn write_error(&mut self) -> &mut ColorWriter {
        self.write("[")
            .red()
            .write("ERROR")
            .reset()
            .write("]")
    }

    pub fn write_ok(&mut self) -> &mut ColorWriter {
        self.write("[")
            .green()
            .write("OK")
            .reset()
            .write("]")
    }

    pub fn write<T: Display>(&mut self, value: T) -> &mut ColorWriter {
        write!(self.stream, "{}", value).ok();
        self
    }

    pub fn writeln<T: Display>(&mut self, value: T) -> &mut ColorWriter {
        writeln!(self.stream, "{}", value).ok();
        self
    }

    pub fn reset(&mut self) -> &mut ColorWriter {
        self.stream.reset().ok();
        self
    }

    pub fn bold(&mut self) -> &mut ColorWriter {
        self.stream.set_color(ColorSpec::new().set_bold(true)).ok();
        self
    }

    pub fn green(&mut self) -> &mut ColorWriter {
        self.stream.set_color(ColorSpec::new().set_fg(Some(Color::Green))).ok();
        self
    }

    pub fn yellow(&mut self) -> &mut ColorWriter {
        self.stream.set_color(ColorSpec::new().set_fg(Some(Color::Yellow))).ok();
        self
    }

    pub fn magenta(&mut self) -> &mut ColorWriter {
        self.stream.set_color(ColorSpec::new().set_fg(Some(Color::Magenta))).ok();
        self
    }

    pub fn cyan(&mut self) -> &mut ColorWriter {
        self.stream.set_color(ColorSpec::new().set_fg(Some(Color::Cyan))).ok();
        self
    }

    pub fn red(&mut self) -> &mut ColorWriter {
        self.stream.set_color(ColorSpec::new().set_fg(Some(Color::Red))).ok();
        self
    }
}