diff --git a/doc/src/language/modules/import.md b/doc/src/language/modules/import.md index 5e0a377a..b592ff74 100644 --- a/doc/src/language/modules/import.md +++ b/doc/src/language/modules/import.md @@ -7,10 +7,17 @@ Import a Module `import` Statement ----------------- -A module can be _imported_ via the `import` statement, and its members are accessed via '`::`' similar to C++. +A module can be _imported_ via the `import` statement, and be given a name. +Its members can be accessed via '`::`' similar to C++. + +A module that is only `import`-ed but not under any module name is commonly used for initialization purposes, +where the module script contains initialization statements that puts the functions registered with the +[`Engine`] into a particular state. ```rust -import "crypto" as lock; // import the script file 'crypto.rhai' as a module named 'lock' +import "crypto_init"; // run the script file 'crypto_init.rhai' without creating an imported module + +import "crypto" as lock; // run the script file 'crypto.rhai' and import it as a module named 'lock' lock::encrypt(secret); // use functions defined under the module via '::' diff --git a/src/engine.rs b/src/engine.rs index 65228a8f..d485f22b 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1806,7 +1806,7 @@ impl Engine { // Import statement #[cfg(not(feature = "no_module"))] Stmt::Import(x) => { - let (expr, (name, _pos), _) = x.as_ref(); + let (expr, alias, _pos) = x.as_ref(); // Guard against too many modules #[cfg(not(feature = "unchecked"))] @@ -1820,8 +1820,11 @@ impl Engine { { if let Some(resolver) = &self.module_resolver { let mut module = resolver.resolve(self, &path, expr.position())?; - module.index_all_sub_modules(); - mods.push((name.clone().into(), module)); + + if let Some((name, _)) = alias { + module.index_all_sub_modules(); + mods.push((name.clone().into(), module)); + } state.modules += 1; diff --git a/src/parser.rs b/src/parser.rs index c66fa56b..8b3bf3ea 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -568,7 +568,7 @@ pub enum Stmt { ReturnWithVal(Box<((ReturnType, Position), Option, Position)>), /// import expr as module #[cfg(not(feature = "no_module"))] - Import(Box<(Expr, (String, Position), Position)>), + Import(Box<(Expr, Option<(String, Position)>, Position)>), /// expr id as name, ... #[cfg(not(feature = "no_module"))] Export( @@ -2685,14 +2685,8 @@ fn parse_import( let expr = parse_expr(input, state, lib, settings.level_up())?; // import expr as ... - match input.next().unwrap() { - (Token::As, _) => (), - (_, pos) => { - return Err( - PERR::MissingToken(Token::As.into(), "in this import statement".into()) - .into_err(pos), - ) - } + if !match_token(input, Token::As)? { + return Ok(Stmt::Import(Box::new((expr, None, token_pos)))); } // import expr as name ... @@ -2709,7 +2703,7 @@ fn parse_import( Ok(Stmt::Import(Box::new(( expr, - (name, settings.pos), + Some((name, settings.pos)), token_pos, )))) }