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
use std::mem;
use std::path::{Path, PathBuf};

use erg_common::config::{ErgConfig, Input};
use erg_common::python_util::BUILTIN_PYTHON_MODS;
use erg_common::traits::{Locational, Stream};
use erg_common::Str;
use erg_common::{enum_unwrap, log};

use erg_parser::ast::{DefId, OperationKind};
use erg_parser::token::{Token, TokenKind};

use crate::ty::free::fresh_varname;
use crate::ty::typaram::TyParam;
use crate::ty::value::ValueObj;
use crate::ty::HasType;

use crate::hir::*;
use crate::mod_cache::SharedModuleCache;

pub struct Linker<'a> {
    cfg: &'a ErgConfig,
    mod_cache: &'a SharedModuleCache,
}

impl<'a> Linker<'a> {
    pub fn new(cfg: &'a ErgConfig, mod_cache: &'a SharedModuleCache) -> Self {
        Self { cfg, mod_cache }
    }

    pub fn link(&self, mut main: HIR) -> HIR {
        log!(info "the linking process has started.");
        for chunk in main.module.iter_mut() {
            self.replace_import(chunk);
        }
        for chunk in main.module.iter_mut() {
            self.resolve_pymod_path(chunk);
        }
        log!(info "linked: {main}");
        main
    }

    /// ```erg
    /// urllib = pyimport "urllib"
    /// urllib.request.urlopen! "https://example.com"
    /// ```
    /// ↓
    /// ```python
    /// urllib = __import__("urllib.request")
    /// import urllib.request
    /// urllib.request.urlopen("https://example.com")
    /// ```
    fn resolve_pymod_path(&self, expr: &mut Expr) {
        match expr {
            Expr::Lit(_) => {}
            Expr::Accessor(acc) => {
                if matches!(acc, Accessor::Attr(_)) && acc.ref_t().is_py_module() {
                    let import = Expr::Import(acc.clone());
                    *expr = Expr::Compound(Block::new(vec![import, mem::take(expr)]));
                }
            }
            Expr::Array(array) => match array {
                Array::Normal(arr) => {
                    for elem in arr.elems.pos_args.iter_mut() {
                        self.resolve_pymod_path(&mut elem.expr);
                    }
                }
                Array::WithLength(arr) => {
                    self.resolve_pymod_path(&mut arr.elem);
                    self.resolve_pymod_path(&mut arr.len);
                }
                _ => todo!(),
            },
            Expr::Tuple(tuple) => match tuple {
                Tuple::Normal(tup) => {
                    for elem in tup.elems.pos_args.iter_mut() {
                        self.resolve_pymod_path(&mut elem.expr);
                    }
                }
            },
            Expr::Set(set) => match set {
                Set::Normal(st) => {
                    for elem in st.elems.pos_args.iter_mut() {
                        self.resolve_pymod_path(&mut elem.expr);
                    }
                }
                Set::WithLength(st) => {
                    self.resolve_pymod_path(&mut st.elem);
                    self.resolve_pymod_path(&mut st.len);
                }
            },
            Expr::Dict(dict) => match dict {
                Dict::Normal(dic) => {
                    for elem in dic.kvs.iter_mut() {
                        self.resolve_pymod_path(&mut elem.key);
                        self.resolve_pymod_path(&mut elem.value);
                    }
                }
                other => todo!("{other}"),
            },
            Expr::Record(record) => {
                for attr in record.attrs.iter_mut() {
                    for chunk in attr.body.block.iter_mut() {
                        self.resolve_pymod_path(chunk);
                    }
                }
            }
            Expr::BinOp(binop) => {
                self.resolve_pymod_path(&mut binop.lhs);
                self.resolve_pymod_path(&mut binop.rhs);
            }
            Expr::UnaryOp(unaryop) => {
                self.resolve_pymod_path(&mut unaryop.expr);
            }
            Expr::Call(call) => {
                self.resolve_pymod_path(&mut call.obj);
                for arg in call.args.pos_args.iter_mut() {
                    self.resolve_pymod_path(&mut arg.expr);
                }
                for arg in call.args.kw_args.iter_mut() {
                    self.resolve_pymod_path(&mut arg.expr);
                }
            }
            Expr::Def(def) => {
                for chunk in def.body.block.iter_mut() {
                    self.resolve_pymod_path(chunk);
                }
            }
            Expr::Lambda(lambda) => {
                for chunk in lambda.body.iter_mut() {
                    self.resolve_pymod_path(chunk);
                }
            }
            Expr::ClassDef(class_def) => {
                for def in class_def.methods.iter_mut() {
                    self.resolve_pymod_path(def);
                }
            }
            Expr::AttrDef(attr_def) => {
                // REVIEW:
                for chunk in attr_def.block.iter_mut() {
                    self.resolve_pymod_path(chunk);
                }
            }
            Expr::TypeAsc(tasc) => self.resolve_pymod_path(&mut tasc.expr),
            Expr::Code(chunks) | Expr::Compound(chunks) => {
                for chunk in chunks.iter_mut() {
                    self.resolve_pymod_path(chunk);
                }
            }
            Expr::Import(_) => unreachable!(),
        }
    }

    fn replace_import(&self, expr: &mut Expr) {
        match expr {
            Expr::Lit(_) => {}
            Expr::Accessor(acc) => {
                /*if acc.ref_t().is_py_module() {
                    let import = Expr::Import(acc.clone());
                    *expr = Expr::Compound(Block::new(vec![import, mem::take(expr)]));
                }*/
                match acc {
                    Accessor::Attr(attr) => {
                        self.replace_import(&mut attr.obj);
                    }
                    Accessor::Ident(_) => {}
                }
            }
            Expr::Array(array) => match array {
                Array::Normal(arr) => {
                    for elem in arr.elems.pos_args.iter_mut() {
                        self.replace_import(&mut elem.expr);
                    }
                }
                Array::WithLength(arr) => {
                    self.replace_import(&mut arr.elem);
                    self.replace_import(&mut arr.len);
                }
                _ => todo!(),
            },
            Expr::Tuple(tuple) => match tuple {
                Tuple::Normal(tup) => {
                    for elem in tup.elems.pos_args.iter_mut() {
                        self.replace_import(&mut elem.expr);
                    }
                }
            },
            Expr::Set(set) => match set {
                Set::Normal(st) => {
                    for elem in st.elems.pos_args.iter_mut() {
                        self.replace_import(&mut elem.expr);
                    }
                }
                Set::WithLength(st) => {
                    self.replace_import(&mut st.elem);
                    self.replace_import(&mut st.len);
                }
            },
            Expr::Dict(dict) => match dict {
                Dict::Normal(dic) => {
                    for elem in dic.kvs.iter_mut() {
                        self.replace_import(&mut elem.key);
                        self.replace_import(&mut elem.value);
                    }
                }
                other => todo!("{other}"),
            },
            Expr::Record(record) => {
                for attr in record.attrs.iter_mut() {
                    for chunk in attr.body.block.iter_mut() {
                        self.replace_import(chunk);
                    }
                }
            }
            Expr::BinOp(binop) => {
                self.replace_import(&mut binop.lhs);
                self.replace_import(&mut binop.rhs);
            }
            Expr::UnaryOp(unaryop) => {
                self.replace_import(&mut unaryop.expr);
            }
            Expr::Call(call) => match call.additional_operation() {
                Some(OperationKind::Import) => {
                    self.replace_erg_import(expr);
                }
                Some(OperationKind::PyImport) => {
                    self.replace_py_import(expr);
                }
                _ => {
                    self.replace_import(&mut call.obj);
                    for arg in call.args.pos_args.iter_mut() {
                        self.replace_import(&mut arg.expr);
                    }
                    for arg in call.args.kw_args.iter_mut() {
                        self.replace_import(&mut arg.expr);
                    }
                }
            },
            Expr::Def(def) => {
                for chunk in def.body.block.iter_mut() {
                    self.replace_import(chunk);
                }
            }
            Expr::Lambda(lambda) => {
                for chunk in lambda.body.iter_mut() {
                    self.replace_import(chunk);
                }
            }
            Expr::ClassDef(class_def) => {
                for def in class_def.methods.iter_mut() {
                    self.replace_import(def);
                }
            }
            Expr::AttrDef(attr_def) => {
                // REVIEW:
                for chunk in attr_def.block.iter_mut() {
                    self.replace_import(chunk);
                }
            }
            Expr::TypeAsc(tasc) => self.replace_import(&mut tasc.expr),
            Expr::Code(chunks) | Expr::Compound(chunks) => {
                for chunk in chunks.iter_mut() {
                    self.replace_import(chunk);
                }
            }
            Expr::Import(_) => unreachable!(),
        }
    }

    /// ```erg
    /// x = import "mod"
    /// ```
    /// ↓
    /// ```python
    /// x =
    ///     _x = ModuleType("mod")
    ///     _x.__dict__.update(locals()) # `Nat`, etc. are in locals but treated as globals, so they cannot be put in the third argument of exec.
    ///     exec(code, _x.__dict__)  # `code` is the mod's content
    ///     _x
    /// ```
    fn replace_erg_import(&self, expr: &mut Expr) {
        let line = expr.ln_begin().unwrap_or(0);
        let path =
            enum_unwrap!(expr.ref_t().typarams().remove(0), TyParam::Value:(ValueObj::Str:(_)));
        let path = Path::new(&path[..]);
        let path = self.cfg.input.local_resolve(path).unwrap();
        // In the case of REPL, entries cannot be used up
        let hir = if self.cfg.input.is_repl() {
            self.mod_cache
                .get(path.as_path())
                .and_then(|entry| entry.hir.clone())
        } else {
            self.mod_cache
                .remove(path.as_path())
                .and_then(|entry| entry.hir)
        };
        let mod_name = enum_unwrap!(expr, Expr::Call)
            .args
            .get_left_or_key("Path")
            .unwrap();
        // let sig = option_enum_unwrap!(&def.sig, Signature::Var)
        //    .unwrap_or_else(|| todo!("module subroutines are not allowed"));
        if let Some(hir) = hir {
            let code = Expr::Code(Block::new(Vec::from(hir.module)));
            let module_type =
                Expr::Accessor(Accessor::private_with_line(Str::ever("#ModuleType"), line));
            let args = Args::new(vec![PosArg::new(mod_name.clone())], None, vec![], None);
            let block = Block::new(vec![module_type.call_expr(args)]);
            let tmp =
                Identifier::private_with_line(Str::from(fresh_varname()), expr.ln_begin().unwrap());
            let mod_def = Expr::Def(Def::new(
                Signature::Var(VarSignature::new(tmp.clone())),
                DefBody::new(Token::dummy(), block, DefId(0)),
            ));
            let module = Expr::Accessor(Accessor::Ident(tmp));
            let __dict__ = Identifier::public("__dict__");
            let m_dict = module.clone().attr_expr(__dict__);
            let locals = Expr::Accessor(Accessor::public_with_line(Str::ever("locals"), line));
            let locals_call = locals.call_expr(Args::empty());
            let args = Args::new(vec![PosArg::new(locals_call)], None, vec![], None);
            let mod_update = Expr::Call(Call::new(
                m_dict.clone(),
                Some(Identifier::public("update")),
                args,
            ));
            let exec = Expr::Accessor(Accessor::public_with_line(Str::ever("exec"), line));
            let args = Args::new(
                vec![PosArg::new(code), PosArg::new(m_dict)],
                None,
                vec![],
                None,
            );
            let exec_code = exec.call_expr(args);
            let compound = Block::new(vec![mod_def, mod_update, exec_code, module]);
            *expr = Expr::Compound(compound);
        }
    }

    /// ```erg
    /// x = pyimport "x" # called from dir "a"
    /// ```
    /// ↓
    /// ```python
    /// x = __import__("a.x").x
    /// ```
    fn replace_py_import(&self, expr: &mut Expr) {
        let mut dir = if let Input::File(mut path) = self.cfg.input.clone() {
            path.pop();
            path
        } else {
            PathBuf::new()
        };
        let args = &mut enum_unwrap!(expr, Expr::Call).args;
        let mod_name_lit = enum_unwrap!(args.remove_left_or_key("Path").unwrap(), Expr::Lit);
        let mod_name_str = enum_unwrap!(mod_name_lit.value.clone(), ValueObj::Str);
        if BUILTIN_PYTHON_MODS.contains(&&mod_name_str[..]) {
            args.push_pos(PosArg::new(Expr::Lit(mod_name_lit)));
            return;
        }
        let mod_name_str = if let Some(stripped) = mod_name_str.strip_prefix("./") {
            stripped
        } else {
            &mod_name_str
        };
        dir.push(mod_name_str);
        let mut comps = dir.components();
        let _first = comps.next().unwrap();
        let path = dir.to_string_lossy().replace('/', ".").replace('\\', ".");
        let token = Token::new(
            TokenKind::StrLit,
            path,
            mod_name_lit.ln_begin().unwrap(),
            mod_name_lit.col_begin().unwrap(),
        );
        let mod_name = Expr::Lit(Literal::try_from(token).unwrap());
        args.insert_pos(0, PosArg::new(mod_name));
        let line = expr.ln_begin().unwrap_or(0);
        for attr in comps {
            *expr = mem::replace(expr, Expr::Code(Block::empty())).attr_expr(
                Identifier::public_with_line(
                    Token::dummy(),
                    Str::rc(attr.as_os_str().to_str().unwrap()),
                    line,
                ),
            );
        }
    }
}