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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use super::{
    lexical_scope::GlobImport, module::Module, namespace::Namespace, trait_map::TraitMap, Ident,
};
use crate::{
    decl_engine::DeclRef,
    engine_threading::*,
    language::ty::{self, TyDecl},
    namespace::ModulePath,
};
use sway_error::{
    error::CompileError,
    handler::{ErrorEmitted, Handler},
};
use sway_types::Spanned;
use sway_utils::iter_prefixes;

/// The root module, from which all other modules can be accessed.
///
/// This is equivalent to the "crate root" of a Rust crate.
///
/// We use a custom type for the `Root` in order to ensure that methods that only work with
/// canonical paths, or that use canonical paths internally, are *only* called from the root. This
/// normally includes methods that first lookup some canonical path via `use_synonyms` before using
/// that canonical path to look up the symbol declaration.
#[derive(Clone, Debug)]
pub struct Root {
    pub(crate) module: Module,
}

impl Root {
    /// Given a path to a `src` module, create synonyms to every symbol in that module to the given
    /// `dst` module.
    ///
    /// This is used when an import path contains an asterisk.
    ///
    /// Paths are assumed to be absolute.
    pub(crate) fn star_import(
        &mut self,
        handler: &Handler,
        engines: &Engines,
        src: &ModulePath,
        dst: &ModulePath,
    ) -> Result<(), ErrorEmitted> {
        self.check_module_privacy(handler, src)?;

        let decl_engine = engines.de();

        let src_mod = self.module.lookup_submodule(handler, src)?;

        let implemented_traits = src_mod.current_items().implemented_traits.clone();
        let mut symbols_and_decls = vec![];
        for (symbol, decl) in src_mod.current_items().symbols.iter() {
            if is_ancestor(src, dst) || decl.visibility(decl_engine).is_public() {
                symbols_and_decls.push((symbol.clone(), decl.clone()));
            }
        }

        let dst_mod = &mut self.module[dst];
        dst_mod
            .current_items_mut()
            .implemented_traits
            .extend(implemented_traits, engines); // TODO: No difference made between imported and declared items
        for symbol_and_decl in symbols_and_decls {
            dst_mod.current_items_mut().use_synonyms.insert(
                // TODO: No difference made between imported and declared items
                symbol_and_decl.0,
                (src.to_vec(), GlobImport::Yes, symbol_and_decl.1),
            );
        }

        Ok(())
    }

    /// Pull a single item from a `src` module and import it into the `dst` module.
    ///
    /// The item we want to import is basically the last item in path because this is a `self`
    /// import.
    pub(crate) fn self_import(
        &mut self,
        handler: &Handler,
        engines: &Engines,
        src: &ModulePath,
        dst: &ModulePath,
        alias: Option<Ident>,
    ) -> Result<(), ErrorEmitted> {
        let (last_item, src) = src.split_last().expect("guaranteed by grammar");
        self.item_import(handler, engines, src, last_item, dst, alias)
    }

    /// Pull a single `item` from the given `src` module and import it into the `dst` module.
    ///
    /// Paths are assumed to be absolute.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn item_import(
        &mut self,
        handler: &Handler,
        engines: &Engines,
        src: &ModulePath,
        item: &Ident,
        dst: &ModulePath,
        alias: Option<Ident>,
    ) -> Result<(), ErrorEmitted> {
        self.check_module_privacy(handler, src)?;

        let decl_engine = engines.de();

        let src_mod = self.module.lookup_submodule(handler, src)?;
        let mut impls_to_insert = TraitMap::default();
        match src_mod.current_items().symbols.get(item).cloned() {
            Some(decl) => {
                if !decl.visibility(decl_engine).is_public() && !is_ancestor(src, dst) {
                    handler.emit_err(CompileError::ImportPrivateSymbol {
                        name: item.clone(),
                        span: item.span(),
                    });
                }

                //  if this is an enum or struct or function, import its implementations
                if let Ok(type_id) = decl.return_type(&Handler::default(), engines) {
                    impls_to_insert.extend(
                        src_mod
                            .current_items()
                            .implemented_traits
                            .filter_by_type_item_import(type_id, engines),
                        engines,
                    );
                }
                // if this is a trait, import its implementations
                let decl_span = decl.span();
                if let TyDecl::TraitDecl(_) = &decl {
                    // TODO: we only import local impls from the source namespace
                    // this is okay for now but we'll need to device some mechanism to collect all available trait impls
                    impls_to_insert.extend(
                        src_mod
                            .current_items()
                            .implemented_traits
                            .filter_by_trait_decl_span(decl_span),
                        engines,
                    );
                }
                // no matter what, import it this way though.
                let dst_mod = &mut self.module[dst];
                let add_synonym = |name| {
                    if let Some((_, GlobImport::No, _)) =
                        dst_mod.current_items().use_synonyms.get(name)
                    {
                        handler.emit_err(CompileError::ShadowsOtherSymbol { name: name.into() });
                    }
                    dst_mod.current_items_mut().use_synonyms.insert(
                        // TODO: No difference made between imported and declared items
                        name.clone(),
                        (src.to_vec(), GlobImport::No, decl),
                    );
                };
                match alias {
                    Some(alias) => {
                        add_synonym(&alias);
                        dst_mod
                            .current_items_mut()
                            .use_aliases
                            .insert(alias.as_str().to_string(), item.clone()); // TODO: No difference made between imported and declared items
                    }
                    None => add_synonym(item),
                };
            }
            None => {
                return Err(handler.emit_err(CompileError::SymbolNotFound {
                    name: item.clone(),
                    span: item.span(),
                }));
            }
        };

        let dst_mod = &mut self.module[dst];
        dst_mod
            .current_items_mut()
            .implemented_traits
            .extend(impls_to_insert, engines); // TODO: No difference made between imported and declared items

        Ok(())
    }

    /// Pull a single variant `variant` from the enum `enum_name` from the given `src` module and import it into the `dst` module.
    ///
    /// Paths are assumed to be absolute.
    #[allow(clippy::too_many_arguments)] // TODO: remove lint bypass once private modules are no longer experimental
    pub(crate) fn variant_import(
        &mut self,
        handler: &Handler,
        engines: &Engines,
        src: &ModulePath,
        enum_name: &Ident,
        variant_name: &Ident,
        dst: &ModulePath,
        alias: Option<Ident>,
    ) -> Result<(), ErrorEmitted> {
        self.check_module_privacy(handler, src)?;

        let decl_engine = engines.de();

        let src_mod = self.module.lookup_submodule(handler, src)?;
        match src_mod.current_items().symbols.get(enum_name).cloned() {
            Some(decl) => {
                if !decl.visibility(decl_engine).is_public() && !is_ancestor(src, dst) {
                    handler.emit_err(CompileError::ImportPrivateSymbol {
                        name: enum_name.clone(),
                        span: enum_name.span(),
                    });
                }

                if let TyDecl::EnumDecl(ty::EnumDecl {
                    decl_id,
                    subst_list: _,
                    ..
                }) = decl
                {
                    let enum_decl = decl_engine.get_enum(&decl_id);
                    let enum_ref = DeclRef::new(
                        enum_decl.call_path.suffix.clone(),
                        decl_id,
                        enum_decl.span(),
                    );

                    if let Some(variant_decl) =
                        enum_decl.variants.iter().find(|v| v.name == *variant_name)
                    {
                        // import it this way.
                        let dst_mod = &mut self.module[dst];
                        let mut add_synonym = |name| {
                            if let Some((_, GlobImport::No, _)) =
                                dst_mod.current_items().use_synonyms.get(name)
                            {
                                handler.emit_err(CompileError::ShadowsOtherSymbol {
                                    name: name.into(),
                                });
                            }
                            dst_mod.current_items_mut().use_synonyms.insert(
                                // TODO: No difference made between imported and declared items
                                name.clone(),
                                (
                                    src.to_vec(),
                                    GlobImport::No,
                                    TyDecl::EnumVariantDecl(ty::EnumVariantDecl {
                                        enum_ref: enum_ref.clone(),
                                        variant_name: variant_name.clone(),
                                        variant_decl_span: variant_decl.span.clone(),
                                    }),
                                ),
                            );
                        };
                        match alias {
                            Some(alias) => {
                                add_synonym(&alias);
                                dst_mod
                                    .current_items_mut()
                                    .use_aliases
                                    .insert(alias.as_str().to_string(), variant_name.clone());
                                // TODO: No difference made between imported and declared items
                            }
                            None => add_synonym(variant_name),
                        };
                    } else {
                        return Err(handler.emit_err(CompileError::SymbolNotFound {
                            name: variant_name.clone(),
                            span: variant_name.span(),
                        }));
                    }
                } else {
                    return Err(handler.emit_err(CompileError::Internal(
                        "Attempting to import variants of something that isn't an enum",
                        enum_name.span(),
                    )));
                }
            }
            None => {
                return Err(handler.emit_err(CompileError::SymbolNotFound {
                    name: enum_name.clone(),
                    span: enum_name.span(),
                }));
            }
        };

        Ok(())
    }

    /// Pull all variants from the enum `enum_name` from the given `src` module and import them all into the `dst` module.
    ///
    /// Paths are assumed to be absolute.
    pub(crate) fn variant_star_import(
        &mut self,
        handler: &Handler,
        engines: &Engines,
        src: &ModulePath,
        dst: &ModulePath,
        enum_name: &Ident,
    ) -> Result<(), ErrorEmitted> {
        self.check_module_privacy(handler, src)?;

        let decl_engine = engines.de();

        let src_mod = self.module.lookup_submodule(handler, src)?;
        match src_mod.current_items().symbols.get(enum_name).cloned() {
            Some(decl) => {
                if !decl.visibility(decl_engine).is_public() && !is_ancestor(src, dst) {
                    handler.emit_err(CompileError::ImportPrivateSymbol {
                        name: enum_name.clone(),
                        span: enum_name.span(),
                    });
                }

                if let TyDecl::EnumDecl(ty::EnumDecl {
                    decl_id,
                    subst_list: _,
                    ..
                }) = decl
                {
                    let enum_decl = decl_engine.get_enum(&decl_id);
                    let enum_ref = DeclRef::new(
                        enum_decl.call_path.suffix.clone(),
                        decl_id,
                        enum_decl.span(),
                    );

                    for variant_decl in enum_decl.variants.iter() {
                        let variant_name = &variant_decl.name;

                        // import it this way.
                        let dst_mod = &mut self.module[dst];
                        dst_mod.current_items_mut().use_synonyms.insert(
                            // TODO: No difference made between imported and declared items
                            variant_name.clone(),
                            (
                                src.to_vec(),
                                GlobImport::Yes,
                                TyDecl::EnumVariantDecl(ty::EnumVariantDecl {
                                    enum_ref: enum_ref.clone(),
                                    variant_name: variant_name.clone(),
                                    variant_decl_span: variant_decl.span.clone(),
                                }),
                            ),
                        );
                    }
                } else {
                    return Err(handler.emit_err(CompileError::Internal(
                        "Attempting to import variants of something that isn't an enum",
                        enum_name.span(),
                    )));
                }
            }
            None => {
                return Err(handler.emit_err(CompileError::SymbolNotFound {
                    name: enum_name.clone(),
                    span: enum_name.span(),
                }));
            }
        };

        Ok(())
    }

    /// Given a path to a `src` module, create synonyms to every symbol in that module to the given
    /// `dst` module.
    ///
    /// This is used when an import path contains an asterisk.
    ///
    /// Paths are assumed to be absolute.
    pub fn star_import_with_reexports(
        &mut self,
        handler: &Handler,
        engines: &Engines,
        src: &ModulePath,
        dst: &ModulePath,
    ) -> Result<(), ErrorEmitted> {
        self.check_module_privacy(handler, src)?;

        let decl_engine = engines.de();

        let src_mod = self.module.lookup_submodule(handler, src)?;

        let implemented_traits = src_mod.current_items().implemented_traits.clone();
        let use_synonyms = src_mod.current_items().use_synonyms.clone();
        let mut symbols_and_decls = src_mod
            .current_items()
            .use_synonyms
            .iter()
            .map(|(symbol, (_, _, decl))| (symbol.clone(), decl.clone()))
            .collect::<Vec<_>>();
        for (symbol, decl) in src_mod.current_items().symbols.iter() {
            if is_ancestor(src, dst) || decl.visibility(decl_engine).is_public() {
                symbols_and_decls.push((symbol.clone(), decl.clone()));
            }
        }

        let mut symbols_paths_and_decls = vec![];
        for (symbol, (mod_path, _, decl)) in use_synonyms {
            let mut is_external = false;
            let submodule = src_mod.submodule(&[mod_path[0].clone()]);
            if let Some(submodule) = submodule {
                is_external = submodule.is_external
            };

            let mut path = src[..1].to_vec();
            if is_external {
                path = mod_path;
            } else {
                path.extend(mod_path);
            }

            symbols_paths_and_decls.push((symbol, path, decl));
        }

        let dst_mod = &mut self.module[dst];
        dst_mod
            .current_items_mut()
            .implemented_traits
            .extend(implemented_traits, engines); // TODO: No difference made between imported and declared items

        let mut try_add = |symbol, path, decl: ty::TyDecl| {
            dst_mod
                .current_items_mut()
                .use_synonyms
                .insert(symbol, (path, GlobImport::Yes, decl)); // TODO: No difference made between imported and declared items
        };

        for (symbol, decl) in symbols_and_decls {
            try_add(symbol, src.to_vec(), decl);
        }

        for (symbol, path, decl) in symbols_paths_and_decls {
            try_add(symbol, path, decl);
        }

        Ok(())
    }

    fn check_module_privacy(
        &self,
        handler: &Handler,
        src: &ModulePath,
    ) -> Result<(), ErrorEmitted> {
        let dst = self.module.mod_path();
        // you are always allowed to access your ancestor's symbols
        if !is_ancestor(src, dst) {
            // we don't check the first prefix because direct children are always accessible
            for prefix in iter_prefixes(src).skip(1) {
                let module = self.module.lookup_submodule(handler, prefix)?;
                if module.visibility.is_private() {
                    let prefix_last = prefix[prefix.len() - 1].clone();
                    handler.emit_err(CompileError::ImportPrivateModule {
                        span: prefix_last.span(),
                        name: prefix_last,
                    });
                }
            }
        }
        Ok(())
    }
}

impl From<Module> for Root {
    fn from(module: Module) -> Self {
        Root { module }
    }
}

impl From<Namespace> for Root {
    fn from(namespace: Namespace) -> Self {
        namespace.root
    }
}

fn is_ancestor(src: &ModulePath, dst: &ModulePath) -> bool {
    dst.len() >= src.len() && src.iter().zip(dst).all(|(src, dst)| src == dst)
}