sway_core/semantic_analysis/namespace/
namespace.rs

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
use crate::{
    language::{ty, CallPath, Visibility},
    Engines, Ident, TypeId,
};

use super::{
    module::Module,
    root::{ResolvedDeclaration, Root},
    submodule_namespace::SubmoduleNamespace,
    ModulePath, ModulePathBuf,
};

use sway_error::handler::{ErrorEmitted, Handler};
use sway_types::span::Span;

/// The set of items that represent the namespace context passed throughout type checking.
#[derive(Clone, Debug, Default)]
pub struct Namespace {
    /// An immutable namespace that consists of the names that should always be present, no matter
    /// what module or scope we are currently checking.
    ///
    /// These include external library dependencies and (when it's added) the `std` prelude.
    ///
    /// This is passed through type-checking in order to initialise the namespace of each submodule
    /// within the project.
    init: Module,
    /// The `root` of the project namespace.
    ///
    /// From the root, the entirety of the project's namespace can always be accessed.
    ///
    /// The root is initialised from the `init` namespace before type-checking begins.
    pub(crate) root: Root,
    /// An absolute path from the `root` that represents the current module being checked.
    ///
    /// E.g. when type-checking the root module, this is equal to `[]`. When type-checking a
    /// submodule of the root called "foo", this would be equal to `[foo]`.
    pub(crate) mod_path: ModulePathBuf,
}

impl Namespace {
    pub fn new() -> Self {
        Self {
            init: Module::default(),
            mod_path: vec![],
            root: Root::default(),
        }
    }

    pub fn program_id(&self, engines: &Engines) -> &Module {
        self.root
            .module
            .submodule(engines, &self.mod_path)
            .unwrap_or_else(|| panic!("Could not retrieve submodule for mod_path."))
    }

    /// Initialise the namespace at its root from the given initial namespace.
    /// If the root module contains submodules these are now considered external.
    pub fn init_root(root: &mut Root) -> Self {
        assert!(
            !root.module.is_external,
            "The root module must not be external during compilation"
        );
        let mod_path = vec![];

        // A copy of the root module is used to initialize every new submodule in the program.
        //
        // Every submodule that has been added before calling init_root is now considered
        // external, which we have to enforce at this point.
        fn set_submodules_external(module: &mut Module) {
            for (_, submod) in module.submodules_mut().iter_mut() {
                if !submod.is_external {
                    submod.is_external = true;
                    set_submodules_external(submod);
                }
            }
        }

        set_submodules_external(&mut root.module);
        // The init module itself is not external
        root.module.is_external = false;

        Self {
            init: root.module.clone(),
            root: root.clone(),
            mod_path,
        }
    }

    /// A reference to the path of the module currently being processed.
    pub fn mod_path(&self) -> &ModulePath {
        &self.mod_path
    }

    /// Prepends the module path into the prefixes.
    pub fn prepend_module_path<'a>(
        &'a self,
        prefixes: impl IntoIterator<Item = &'a Ident>,
    ) -> ModulePathBuf {
        self.mod_path.iter().chain(prefixes).cloned().collect()
    }

    /// A reference to the root of the project namespace.
    pub fn root(&self) -> &Root {
        &self.root
    }

    pub fn root_module(&self) -> &Module {
        &self.root.module
    }

    /// Access to the current [Module], i.e. the module at the inner `mod_path`.
    pub fn module(&self, engines: &Engines) -> &Module {
        self.root
            .module
            .lookup_submodule(&Handler::default(), engines, &self.mod_path)
            .unwrap()
    }

    /// Mutable access to the current [Module], i.e. the module at the inner `mod_path`.
    pub fn module_mut(&mut self, engines: &Engines) -> &mut Module {
        self.root
            .module
            .lookup_submodule_mut(&Handler::default(), engines, &self.mod_path)
            .unwrap()
    }

    pub fn lookup_submodule_from_absolute_path(
        &self,
        handler: &Handler,
        engines: &Engines,
        path: &ModulePath,
    ) -> Result<&Module, ErrorEmitted> {
        self.root.module.lookup_submodule(handler, engines, path)
    }

    /// Returns true if the current module being checked is a direct or indirect submodule of
    /// the module given by the `absolute_module_path`.
    ///
    /// The current module being checked is determined by `mod_path`.
    ///
    /// E.g., the `mod_path` `[fist, second, third]` of the root `foo` is a submodule of the module
    /// `[foo, first]`. Note that the `mod_path` does not contain the root name, while the
    /// `absolute_module_path` always contains it.
    ///
    /// If the current module being checked is the same as the module given by the `absolute_module_path`,
    /// the `true_if_same` is returned.
    pub(crate) fn module_is_submodule_of(
        &self,
        _engines: &Engines,
        absolute_module_path: &ModulePath,
        true_if_same: bool,
    ) -> bool {
        // `mod_path` does not contain the root name, so we have to separately check
        // that the root name is equal to the module package name.
        let root_name = self.root.module.name();

        let (package_name, modules) = absolute_module_path.split_first().expect("Absolute module path must have at least one element, because it always contains the package name.");

        if root_name != package_name {
            return false;
        }

        if self.mod_path.len() < modules.len() {
            return false;
        }

        let is_submodule = modules
            .iter()
            .zip(self.mod_path.iter())
            .all(|(left, right)| left == right);

        if is_submodule {
            if self.mod_path.len() == modules.len() {
                true_if_same
            } else {
                true
            }
        } else {
            false
        }
    }

    /// Returns true if the module given by the `absolute_module_path` is external
    /// to the current package. External modules are imported in the `Forc.toml` file.
    pub(crate) fn module_is_external(&self, absolute_module_path: &ModulePath) -> bool {
        let root_name = self.root.module.name();

        assert!(!absolute_module_path.is_empty(), "Absolute module path must have at least one element, because it always contains the package name.");

        root_name != &absolute_module_path[0]
    }
    /// Short-hand for calling [Root::resolve_symbol] on `root` with the `mod_path`.
    pub(crate) fn resolve_symbol(
        &self,
        handler: &Handler,
        engines: &Engines,
        symbol: &Ident,
        self_type: Option<TypeId>,
    ) -> Result<ResolvedDeclaration, ErrorEmitted> {
        self.root
            .resolve_symbol(handler, engines, &self.mod_path, symbol, self_type)
    }

    /// Short-hand for calling [Root::resolve_symbol] on `root` with the `mod_path`.
    pub(crate) fn resolve_symbol_typed(
        &self,
        handler: &Handler,
        engines: &Engines,
        symbol: &Ident,
        self_type: Option<TypeId>,
    ) -> Result<ty::TyDecl, ErrorEmitted> {
        self.resolve_symbol(handler, engines, symbol, self_type)
            .map(|resolved_decl| resolved_decl.expect_typed())
    }

    /// Short-hand for calling [Root::resolve_call_path] on `root` with the `mod_path`.
    pub(crate) fn resolve_call_path_typed(
        &self,
        handler: &Handler,
        engines: &Engines,
        call_path: &CallPath,
        self_type: Option<TypeId>,
    ) -> Result<ty::TyDecl, ErrorEmitted> {
        self.resolve_call_path(handler, engines, call_path, self_type)
            .map(|resolved_decl| resolved_decl.expect_typed())
    }

    /// Short-hand for calling [Root::resolve_call_path] on `root` with the `mod_path`.
    pub(crate) fn resolve_call_path(
        &self,
        handler: &Handler,
        engines: &Engines,
        call_path: &CallPath,
        self_type: Option<TypeId>,
    ) -> Result<ResolvedDeclaration, ErrorEmitted> {
        self.root
            .resolve_call_path(handler, engines, &self.mod_path, call_path, self_type)
    }

    /// "Enter" the submodule at the given path by returning a new [SubmoduleNamespace].
    ///
    /// Here we temporarily change `mod_path` to the given `dep_mod_path` and wrap `self` in a
    /// [SubmoduleNamespace] type. When dropped, the [SubmoduleNamespace] resets the `mod_path`
    /// back to the original path so that we can continue type-checking the current module after
    /// finishing with the dependency.
    pub(crate) fn enter_submodule(
        &mut self,
        engines: &Engines,
        mod_name: Ident,
        visibility: Visibility,
        module_span: Span,
    ) -> SubmoduleNamespace {
        let init = self.init.clone();
        let is_external = self.module(engines).is_external;
        let submod_path: Vec<_> = self
            .mod_path
            .iter()
            .cloned()
            .chain(Some(mod_name.clone()))
            .collect();
        self.module_mut(engines)
            .submodules
            .entry(mod_name.to_string())
            .or_insert(init.new_submodule_from_init(
                mod_name,
                visibility,
                Some(module_span),
                is_external,
                submod_path.clone(),
            ));
        let parent_mod_path = std::mem::replace(&mut self.mod_path, submod_path.clone());
        SubmoduleNamespace {
            namespace: self,
            parent_mod_path,
        }
    }

    /// Pushes a new submodule to the namespace's module hierarchy.
    pub fn push_submodule(
        &mut self,
        engines: &Engines,
        mod_name: Ident,
        visibility: Visibility,
        module_span: Span,
    ) {
        self.module_mut(engines)
            .submodules
            .entry(mod_name.to_string())
            .or_insert(Module::new(mod_name.clone(), visibility, Some(module_span)));
        self.mod_path.push(mod_name);
    }

    /// Pops the current submodule from the namespace's module hierarchy.
    pub fn pop_submodule(&mut self) {
        self.mod_path.pop();
    }
}