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
//! defines `Compiler`.
//!
//! コンパイラーを定義する
use std::path::Path;

use erg_common::codeobj::CodeObj;
use erg_common::color::{GREEN, RESET};
use erg_common::config::{ErgConfig, Input};
use erg_common::error::MultiErrorDisplay;
use erg_common::log;
use erg_common::traits::{Runnable, Stream};
use erg_common::Str;

use erg_parser::ParserRunner;

use crate::codegen::CodeGenerator;
use crate::effectcheck::SideEffectChecker;
use crate::error::{CompileError, CompileErrors, TyCheckErrors};
use crate::lower::ASTLowerer;
use crate::ownercheck::OwnershipChecker;

/// * registered as global -> Global
/// * defined in the toplevel scope (and called in the inner scope) -> Global
/// * defined and called in the toplevel scope -> Local
/// * not defined in the toplevel and called in the inner scope -> Deref
/// * defined and called in the current scope (except the toplevel) -> Fast
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StoreLoadKind {
    Local,
    LocalConst,
    Global,
    GlobalConst,
    Deref,
    DerefConst,
    Fast,
    FastConst,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Name {
    pub kind: StoreLoadKind,
    pub idx: usize,
}

impl Name {
    pub const fn new(kind: StoreLoadKind, idx: usize) -> Self {
        Self { kind, idx }
    }

    pub const fn local(idx: usize) -> Self {
        Self {
            kind: StoreLoadKind::Local,
            idx,
        }
    }
    pub const fn global(idx: usize) -> Self {
        Self {
            kind: StoreLoadKind::Global,
            idx,
        }
    }
    pub const fn deref(idx: usize) -> Self {
        Self {
            kind: StoreLoadKind::Deref,
            idx,
        }
    }
    pub const fn fast(idx: usize) -> Self {
        Self {
            kind: StoreLoadKind::Fast,
            idx,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessKind {
    Name,
    Attr,
    Method,
}

impl AccessKind {
    pub const fn is_local(&self) -> bool {
        matches!(self, Self::Name)
    }
    pub const fn is_attr(&self) -> bool {
        matches!(self, Self::Attr)
    }
    pub const fn is_method(&self) -> bool {
        matches!(self, Self::Method)
    }
}

/// Generates a `CodeObj` from an `AST`.
/// The input AST is not typed, so it's typed by `ASTLowerer` according to the cfg.opt_level.
#[derive(Debug)]
pub struct Compiler {
    cfg: ErgConfig,
    lowerer: ASTLowerer,
    code_generator: CodeGenerator,
}

impl Runnable for Compiler {
    type Err = CompileError;
    type Errs = CompileErrors;
    const NAME: &'static str = "Erg compiler";

    fn new(cfg: ErgConfig) -> Self {
        Self {
            code_generator: CodeGenerator::new(cfg.copy()),
            lowerer: ASTLowerer::new(),
            cfg,
        }
    }

    #[inline]
    fn input(&self) -> &Input {
        &self.cfg.input
    }

    #[inline]
    fn finish(&mut self) {}

    fn clear(&mut self) {
        self.code_generator.clear();
    }

    fn exec(&mut self) -> Result<(), Self::Errs> {
        todo!()
    }

    fn eval(&mut self, src: Str) -> Result<String, CompileErrors> {
        let codeobj = self.compile(src, "eval")?;
        Ok(codeobj.code_info())
    }
}

impl Compiler {
    fn convert(&self, errs: TyCheckErrors) -> CompileErrors {
        errs.into_iter()
            .map(|e| CompileError::new(e.core, self.input().clone(), e.caused_by))
            .collect::<Vec<_>>()
            .into()
    }

    pub fn compile_and_dump_as_pyc<P: AsRef<Path>>(
        &mut self,
        src: Str,
        path: P,
        mode: &str,
    ) -> Result<(), CompileErrors> {
        let code = self.compile(src, mode)?;
        code.dump_as_pyc(path, self.cfg.python_ver)
            .expect("failed to dump a .pyc file");
        Ok(())
    }

    pub fn compile(&mut self, src: Str, mode: &str) -> Result<CodeObj, CompileErrors> {
        log!("{GREEN}[DEBUG] the compiling process has started.{RESET}");
        let mut cfg = self.cfg.copy();
        cfg.input = Input::Str(src);
        let mut parser = ParserRunner::new(cfg);
        let ast = parser.parse()?;
        let (hir, warns) = self
            .lowerer
            .lower(ast, mode)
            .map_err(|errs| self.convert(errs))?;
        if self.cfg.verbose >= 2 {
            let warns = self.convert(warns);
            warns.fmt_all_stderr();
        }
        let effect_checker = SideEffectChecker::new();
        let hir = effect_checker
            .check(hir)
            .map_err(|errs| self.convert(errs))?;
        let ownership_checker = OwnershipChecker::new();
        let hir = ownership_checker
            .check(hir)
            .map_err(|errs| self.convert(errs))?;
        let codeobj = self.code_generator.codegen(hir);
        log!("{GREEN}code object:\n{}", codeobj.code_info());
        log!(
            "[DEBUG] the compiling process has completed, found errors: {}{RESET}",
            self.code_generator.errs.len()
        );
        if self.code_generator.errs.is_empty() {
            Ok(codeobj)
        } else {
            Err(self.code_generator.errs.flush())
        }
    }
}