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

use erg_common::config::ErgConfig;
use erg_common::error::MultiErrorDisplay;
use erg_common::log;
use erg_common::traits::{Runnable, Stream};

use crate::artifact::{CompleteArtifact, ErrorArtifact};
use crate::context::ContextProvider;
use crate::ty::codeobj::CodeObj;

use crate::build_hir::HIRBuilder;
use crate::codegen::PyCodeGenerator;
use crate::desugar_hir::HIRDesugarer;
use crate::error::{CompileError, CompileErrors, CompileWarnings};
use crate::hir::Expr;
use crate::link::Linker;
use crate::mod_cache::SharedModuleCache;

/// * 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 String or other File inputs.
#[derive(Debug, Default)]
pub struct Compiler {
    pub cfg: ErgConfig,
    builder: HIRBuilder,
    mod_cache: SharedModuleCache,
    code_generator: PyCodeGenerator,
}

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

    fn new(cfg: ErgConfig) -> Self {
        let mod_cache = SharedModuleCache::new(cfg.copy());
        let py_mod_cache = SharedModuleCache::new(cfg.copy());
        Self {
            builder: HIRBuilder::new_with_cache(
                cfg.copy(),
                "<module>",
                mod_cache.clone(),
                py_mod_cache,
            ),
            code_generator: PyCodeGenerator::new(cfg.copy()),
            mod_cache,
            cfg,
        }
    }

    #[inline]
    fn cfg(&self) -> &ErgConfig {
        &self.cfg
    }
    #[inline]
    fn cfg_mut(&mut self) -> &mut ErgConfig {
        &mut self.cfg
    }

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

    fn initialize(&mut self) {
        self.builder.initialize();
        self.code_generator.clear();
        // .mod_cache will be initialized in .builder
    }

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

    fn exec(&mut self) -> Result<i32, Self::Errs> {
        let path = self.cfg.dump_pyc_path();
        let warns = self
            .compile_and_dump_as_pyc(path, self.input().read(), "exec")
            .map_err(|eart| {
                eart.warns.fmt_all_stderr();
                eart.errors
            })?;
        warns.fmt_all_stderr();
        Ok(0)
    }

    fn eval(&mut self, src: String) -> Result<String, CompileErrors> {
        let arti = self.compile(src, "eval").map_err(|eart| {
            eart.warns.fmt_all_stderr();
            eart.errors
        })?;
        arti.warns.fmt_all_stderr();
        Ok(arti.object.code_info(Some(self.code_generator.py_version)))
    }
}

use crate::context::Context;
use crate::varinfo::VarInfo;
use erg_parser::ast::VarName;

impl ContextProvider for Compiler {
    fn dir(&self) -> Vec<(&VarName, &VarInfo)> {
        self.builder.dir()
    }

    fn get_receiver_ctx(&self, receiver_name: &str) -> Option<&Context> {
        self.builder.get_receiver_ctx(receiver_name)
    }

    fn get_var_info(&self, name: &str) -> Option<(&VarName, &VarInfo)> {
        self.builder.get_var_info(name)
    }
}

impl Compiler {
    pub fn compile_and_dump_as_pyc<P: AsRef<Path>>(
        &mut self,
        pyc_path: P,
        src: String,
        mode: &str,
    ) -> Result<CompileWarnings, ErrorArtifact> {
        let arti = self.compile(src, mode)?;
        arti.object
            .dump_as_pyc(pyc_path, self.cfg.py_magic_num)
            .expect("failed to dump a .pyc file (maybe permission denied)");
        Ok(arti.warns)
    }

    pub fn eval_compile_and_dump_as_pyc<P: AsRef<Path>>(
        &mut self,
        pyc_path: P,
        src: String,
        mode: &str,
    ) -> Result<CompleteArtifact<Option<Expr>>, ErrorArtifact> {
        let arti = self.eval_compile(src, mode)?;
        let (code, last) = arti.object;
        code.dump_as_pyc(pyc_path, self.cfg.py_magic_num)
            .expect("failed to dump a .pyc file (maybe permission denied)");
        Ok(CompleteArtifact::new(last, arti.warns))
    }

    pub fn compile(
        &mut self,
        src: String,
        mode: &str,
    ) -> Result<CompleteArtifact<CodeObj>, ErrorArtifact> {
        log!(info "the compiling process has started.");
        let arti = self.build_link_desugar(src, mode)?;
        let codeobj = self.code_generator.emit(arti.object);
        log!(info "code object:\n{}", codeobj.code_info(Some(self.code_generator.py_version)));
        log!(info "the compiling process has completed");
        Ok(CompleteArtifact::new(codeobj, arti.warns))
    }

    pub fn eval_compile(
        &mut self,
        src: String,
        mode: &str,
    ) -> Result<CompleteArtifact<(CodeObj, Option<Expr>)>, ErrorArtifact> {
        log!(info "the compiling process has started.");
        let arti = self.build_link_desugar(src, mode)?;
        let last = arti.object.module.last().cloned();
        let codeobj = self.code_generator.emit(arti.object);
        log!(info "code object:\n{}", codeobj.code_info(Some(self.code_generator.py_version)));
        log!(info "the compiling process has completed");
        Ok(CompleteArtifact::new((codeobj, last), arti.warns))
    }

    fn build_link_desugar(
        &mut self,
        src: String,
        mode: &str,
    ) -> Result<CompleteArtifact, ErrorArtifact> {
        let artifact = self.builder.build(src, mode)?;
        let linker = Linker::new(&self.cfg, &self.mod_cache);
        let hir = linker.link(artifact.object);
        let desugared = HIRDesugarer::desugar(hir);
        Ok(CompleteArtifact::new(desugared, artifact.warns))
    }
}