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
//! defines a command-line parser for `ergc`.
//!
//! コマンドオプション(パーサー)を定義する
use std::env;
use std::env::consts::{ARCH, OS};
use std::process;
use std::fs::File;
use std::io::{BufReader, BufRead};

use crate::stdin;
use crate::Str;
use crate::{power_assert, read_file};
use crate::lazy::Lazy;

pub const SEMVER: &str = env!("CARGO_PKG_VERSION");
pub const GIT_HASH_SHORT: &str = env!("GIT_HASH_SHORT");
pub const BUILD_DATE: &str = env!("BUILD_DATE");
/// TODO: タグを含める
pub const BUILD_INFO: Lazy<String> = Lazy::new(|| format!("(tags/?:{GIT_HASH_SHORT}, {BUILD_DATE}) on {ARCH}/{OS}"));

/// 入力はファイルからだけとは限らないので
/// Inputで操作を一本化する
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Input {
    /// filename
    File(Str),
    REPL,
    /// same content as cfg.command
    Pipe(Str),
    /// from command option | eval
    Str(Str),
    Dummy,
}

impl Input {
    pub fn enclosed_name(&self) -> &str {
        match self {
            Self::File(filename) => &filename[..],
            Self::REPL | Self::Pipe(_) =>  "<stdin>",
            Self::Str(_) => "<string>",
            Self::Dummy => "<dummy>",
        }
    }

    /// ファイルに書き出すとき使う
    pub fn filename(&self) -> &str {
        match self {
            Self::File(filename) => &filename[..],
            Self::REPL | Self::Pipe(_) =>  "stdin",
            Self::Str(_) => "string",
            Self::Dummy => "dummy",
        }
    }

    pub fn read(&self) -> Str {
        match self {
            Self::File(filename) => {
                let file = match File::open(&filename[..]) {
                    Ok(f) => f,
                    Err(e) => {
                        let code = e.raw_os_error().unwrap_or(1);
                        println!("cannot open '{filename}': [Errno {code}] {e}");
                        process::exit(code);
                    }
                };
                let src = match read_file(file) {
                    Ok(s) => s,
                    Err(e) => {
                        let code = e.raw_os_error().unwrap_or(1);
                        println!("cannot read '{filename}': [Errno {code}] {e}");
                        process::exit(code);
                    }
                };
                Str::from(src)
            }
            Self::Pipe(s) | Self::Str(s) => s.clone(),
            Self::REPL => stdin::read(),
            Self::Dummy => panic!("cannot read from a dummy file"),
        }
    }

    pub fn reread_lines(&self, ln_begin: usize, ln_end: usize) -> Vec<Str> {
        power_assert!(ln_begin, >=, 1);
        match self {
            Self::File(filename) => {
                match File::open(&filename[..]) {
                    Ok(file) => {
                        let mut codes = vec![];
                        let mut lines = BufReader::new(file).lines().skip(ln_begin - 1);
                        for _ in ln_begin..=ln_end {
                            codes.push(Str::from(lines.next().unwrap().unwrap()));
                        }
                        codes
                    }
                    Err(_) => vec!["<file not found>".into()],
                }
            }
            Self::Pipe(s) | Self::Str(s) => {
                s.split('\n')
                    .collect::<Vec<_>>()[ln_begin-1..=ln_end-1]
                    .into_iter().map(|s| Str::rc(*s)).collect()
            }
            Self::REPL => stdin::reread_lines(ln_begin, ln_end),
            Self::Dummy => panic!("cannot read lines from a dummy file"),
        }
    }

    pub fn reread(&self) -> Str {
        match self {
            Self::File(_filename) => todo!(),
            Self::Pipe(s) | Self::Str(s) => s.clone(),
            Self::REPL => stdin::reread(),
            Self::Dummy => panic!("cannot read from a dummy file"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ErgConfig {
    /// options: lex | parse | compile | exec
    pub mode: &'static str,
    /// optimization level.
    /// * 0: no optimization
    /// * 1 (default): e.g. constant folding, dead code elimination
    /// * 2: e.g. static dispatching, inlining, peephole
    /// * 3: e.g. JIT compiling
    pub opt_level: u8,
    pub dump_as_pyc: bool,
    pub python_ver: Option<u32>,
    pub input: Input,
    pub module: &'static str,
    /// verbosity level for system messages.
    /// * 0: display errors
    /// * 1: display errors and warns
    /// * 2 (default): display errors, warnings and hints
    pub verbose: u8,
}

impl Default for ErgConfig {
    #[inline]
    fn default() -> Self {
        Self::new("exec", 1, false, None, Input::REPL, "<module>", 2)
    }
}

impl ErgConfig {
    pub const fn new(
        mode: &'static str,
        opt_level: u8,
        dump_as_pyc: bool,
        python_ver: Option<u32>,
        input: Input,
        module: &'static str,
        verbose: u8,
    ) -> Self {
        Self {
            mode,
            opt_level,
            dump_as_pyc,
            python_ver,
            input,
            module,
            verbose,
        }
    }

    /// cloneのエイリアス(実際のcloneコストは低いので)
    #[inline]
    pub fn copy(&self) -> Self { self.clone() }

    pub fn parse() -> Self {
        let mut args = env::args();
        args.next(); // "ergc"
        let mut cfg = Self::default();
        // ループ内でnextするのでforにしないこと
        while let Some(arg) = args.next() {
            match &arg[..] {
                "-c" => {
                    cfg.input = Input::Str(Str::from(args.next().unwrap()));
                }
                "--dump-as-pyc" => {
                    cfg.dump_as_pyc = true;
                }
                "-?" | "-h" | "--help" => {
                    println!("erg [option] ... [-c cmd | -m mod | file | -] [arg] ...");
                    // TODO:
                    process::exit(0);
                }
                "-m" => {
                    cfg.module = Box::leak(args.next().unwrap().into_boxed_str());
                }
                "--mode" => {
                    cfg.mode = Box::leak(args.next().unwrap().into_boxed_str());
                }
                "-o" | "--opt-level" | "--optimization-level" => {
                    cfg.opt_level = args.next().unwrap().parse::<u8>().unwrap();
                }
                "-p" | "--py-ver" | "--python-version" => {
                    cfg.python_ver = Some(args.next().unwrap().parse::<u32>().unwrap());
                }
                "--verbose\n" => {
                    cfg.verbose = args.next().unwrap().parse::<u8>().unwrap();
                }
                "-V" | "--version" => {
                    println!("Erg {}", env!("CARGO_PKG_VERSION"));
                    process::exit(0);
                }
                other if other.starts_with('-') => {
                    panic!("invalid option: {other}");
                }
                _ => {
                    cfg.input = Input::File(Str::from(arg));
                    break;
                }
            }
        }
        cfg
    }
}