From 26837d4862562064da26a6176316fd537bf440a6 Mon Sep 17 00:00:00 2001 From: Bruno-Vdr Date: Wed, 20 Nov 2024 08:00:23 +0100 Subject: [PATCH] docs: add module hierarchy section (#22919) --- doc/docs.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 30133f781d5376..21be0662968233 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -87,6 +87,7 @@ by using any of the following commands in a terminal: * [Module imports](#module-imports) * [Selective imports](#selective-imports) + * [Module hierarchy](#module-hierarchy) * [Module import aliasing](#module-import-aliasing) * [Statements & expressions](#statements--expressions) * [If](#if) @@ -1577,6 +1578,54 @@ println('Name: ${name}') current_os := user_os() println('Your OS is ${current_os}.') ``` +### Module hierarchy + +> [!NOTE] +> This section is valid when .v files are not in the project's root directory. + +Modules names in .v files, must match the name of their directory. + +A .v file `./abc/source.v` must start with `module abc`. All .v files in this directory +belong to the same module `abc`. They should also start with `module abc`. + +If you have `abc/def/`, and .v files in both folders, you can `import abc`, but you will have +to `import abc.def` too, to get to the symbols in the subfolder. It is independent. + +In `module name` statement, name never repeats directory's hierarchy, but only its directory. +So in `abc/def/source.v` the first line will be `module def`, and not `module abc.def`. + +`import module_name` statements must respect file hierarchy, you cannot `import def`, only +`abc.def` + +Refering to a module symbol such as a function or const, only needs module name as prefix: + +```v ignore +module def + +// func is a dummy example function. +pub fn func() { + println('func') +} +``` + +can be called like this: + +```v ignore +module main + +import def + +fn main() { + def.func() +} +``` + +A function, located in `abc/def/source.v`, is called with `def.func()`, not `abc.def.func()` + +This always implies a *single prefix*, whatever sub-module depth. This behavior flattens +modules/sub-modules hierarchy. Should you have two modules with the same name in different +directories, then you should use Module import aliasing (see below). + ### Module import aliasing