16. Modules
const shapes = @import("lib/shapes.egg")
imports another file, as a path relative to the importing file ending in
.egg (a missing file is E129). A string without .egg names a
module instead: @import("std/math") is math.egg of the standard
library ("std/a/b" is a/b.egg in it, and "std" alone is std.egg),
which ships with the compiler in lib/std (the EGG_STD
environment variable points elsewhere). The other module names are
packages, given to eggc as --pkg NAME=DIR (the package manager,
clutch, passes one per dependency): @import("json") is DIR/json.egg
and @import("json/util") is DIR/util.egg, as for std. The
packages given hold for the whole program: a package imports the
packages it needs by name from the same list, so every package that any
file imports must be given. Any other name is E129. A file import may
not leave its module’s root, the directory of the root file for a
program, the library’s directory for std and a package’s directory for
it (E129); a file under a package’s directory belongs to that package,
the innermost one when one package’s directory holds another’s. A module is a
self-contained tree, and reaches others only by name. The name, here
shapes, is local to the importing file and reaches the top-level names
of the imported one:
| Written | Means |
|---|---|
shapes.perimeter(r) |
a function |
shapes.Rect, shapes.Box(i64) |
a type, a type function’s type |
shapes.Rect{ .w = 1, .h = 2 } |
a struct literal |
shapes.Kind.rect, shapes.Rect.square(3) |
an enum member, a function of a type |
shapes.biggest(i64, xs[0..]) |
a generic function |
A name not declared by the module is E102 (function), E108 (type) or E122;
an import name used as a value is E129. Imported names are not visible
unqualified, and every top-level name is visible to importers (there is
no pub yet).
Each file is loaded once, however many files import it, so all importers
see the same types. Imports may form cycles. Diagnostics name the file
an error is in, and call imported things by the file’s base name
(shapes.perimeter), whatever the import is called.
// lib/shapes.egg: declares no capabilities
const Rect = struct {
w: i64
h: i64
fn area(self: Rect) i64 {
return self.w * self.h
}
}
// main.egg
uses io
const shapes = @import("lib/shapes.egg")
fn main(io: Io) void {
io.print(shapes.Rect{ .w = 2, .h = 3 }.area()) // 6
}
examples/modules.egg and its examples/lib/ files are the tested
version of this section.