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
use std::{
    error::Error,
    fs,
    io::{self, Read},
    path::PathBuf,
};

use lazy_static::lazy_static;
use structopt::StructOpt;

use corewars_parser as parser;

lazy_static! {
    static ref IO_SENTINEL: PathBuf = PathBuf::from("-");
}

#[derive(Debug, StructOpt)]
#[structopt(rename_all = "kebab")]
/// Parse, assemble, and save Redcode files
struct CliOptions {
    /// Input file; use "-" to read from stdin
    #[structopt(parse(from_os_str))]
    input_file: PathBuf,

    #[structopt(subcommand)]
    command: Command,
}

#[derive(Debug, StructOpt)]
enum Command {
    /// Save/print a program in "load file" format
    #[structopt(name = "dump")]
    Dump {
        /// Output file; defaults to stdout ("-")
        #[structopt(long, short, parse(from_os_str), default_value = IO_SENTINEL.to_str().unwrap())]
        output_file: PathBuf,

        /// Whether labels, expressions, macros, etc. should be resolved and
        /// expanded in the output
        #[structopt(long, short = "E")]
        no_expand: bool,
    },
}

pub fn run() -> Result<(), Box<dyn Error>> {
    let cli_options = CliOptions::from_args();

    let mut input = String::new();

    if cli_options.input_file == *IO_SENTINEL {
        io::stdin().read_to_string(&mut input)?;
    } else {
        input = fs::read_to_string(cli_options.input_file)?;
    }

    let parsed_core = match parser::parse(input.as_str()) {
        parser::Result::Ok(warrior, warnings) => {
            print_warnings(&warnings);
            Ok(warrior)
        }
        parser::Result::Err(err, warnings) => {
            print_warnings(&warnings);
            Err(err)
        }
    }?;

    match cli_options.command {
        Command::Dump {
            output_file,
            no_expand,
        } => {
            if no_expand {
                unimplemented!()
            }

            if output_file == *IO_SENTINEL {
                println!("{}", parsed_core);
            } else {
                fs::write(output_file, format!("{}\n", parsed_core))?;
            };
        }
    };

    Ok(())
}

fn print_warnings(warnings: &[parser::Warning]) {
    for warning in warnings.iter() {
        eprintln!("Warning: {}", warning)
    }
}