Modules
silt’s module system maps directly to the filesystem. There is no module or
package keyword inside source files — the name comes from the path.
File = module
Each .silt file is a module named after the file:
-- File: src/geometry.silt
pub fn add(a, b) {
a + b
}
fn helper(x) {
x * 2
} -- private
A module’s name is lowercase letters, digits and _, not starting
with a digit (src/geo_util.silt, imported as geo_util). A file such as
src/Util.silt, src/geo-util.silt, src/2d.silt or src/match.silt
(a keyword) is an error, and so is import Util. A file named on the
command line is a module too:
silt check Demo.silt and silt check my-script.silt are the same error,
and a file named like a builtin module (string.silt) is refused there as
in src/ (silt fmt checks no names and formats it).
A module path is one name: there is no import net.http, and a file in a
subdirectory of src/ is not a module.
src/
main.silt
geometry.silt -- imported as `geometry`
Visibility
Items are private by default. Only pub items are exported:
pub fn add(a, b) {
a + b
}
fn helper(x) {
x * 2
} -- not exported
pub let limit = 10 -- exported
pub let (low, high) = (1, 99) -- exports `low` and `high`
pub type Point {
x: Int,
y: Int,
} -- exports the type and its constructor
pub type Shape { -- exports the type and all variants
Circle(Int),
Square(Int),
}
When a pub type declares enum variants, all constructors are exported with
it. A trait is exported with pub trait:
pub trait Describe {
fn describe(self) -> String
}
The methods of a trait declared without pub can be called only inside
its module, even on a value of an exported type.
A public declaration cannot name a private record, enum or trait of its
module: a pub fn whose parameter, return type or where bound, or a
pub type whose field or variant, names one is an error, since an
importer could use the declaration but never name what it uses. A
private type alias may appear there: an alias is only another name for
its type. A pub opaque type may hold a private type: nothing outside
its module sees what it holds (see below).
An impl is never exported or imported: trait Describe for Point { ... }
applies wherever the trait and the type are used.
Naming a private item from another module is an error at the name:
import geometry.{ helper } reports that helper is private to
geometry, and import geometry.{ nope } that geometry has no member
nope.
Opaque types
pub opaque type exports a record or an enum without what is in it:
other modules can name the type (in annotations, List(mail.Email),
where bounds) and nothing more. Inside its module it is an ordinary
type.
import string
pub opaque type Email {
Email(String),
}
pub fn parse(text: String) -> Option(Email) {
match string.contains(text, "@") {
true -> Some(Email(string.to_lower(text)))
false -> None
}
}
In another module, a value of mail.Email cannot be built, taken
apart in a pattern, updated or read: each is an error that says to use
the functions of module mail. The module of the code is what counts.
An impl sees what its module sees, and a test file is a module like any
other.
Decoding (json.parse, toml.parse, a postgres row) builds a value as
a constructor does, and json encoding reads what is in it. Outside its
module an opaque type, at the top or in a part at any depth, is decoded
only by the module’s trait json.Decode impl, which can check the data,
and json-encoded only by its trait json.Encode impl; without one each
is an error. A function of the type’s own module may decode and encode
it wherever it is called from.
Equality, order and hashing still compare what is inside, and
printing a value shows it, as for any type; a module that wants to
hide it writes its own Display. opaque needs pub, and an alias
cannot be opaque.
What an opaque type holds may be private to its module, since no other module builds, matches or reads it; its printed form shows the private names all the same:
type Secret {
Secret(Int),
}
pub opaque type Vault {
Vault(Secret),
}
Imports
Three forms:
import geometry -- qualified: geometry.add(1, 2)
import geometry as g -- aliased: g.add(1, 2)
import geometry.{ add, Point } -- direct: add(1, 2)
An alias is the module’s name in the file, and starts with a lower-case
letter as a module’s name does: a capital starts a type, a trait or a
variant. import math as Float is an error, “module alias ‘Float’ starts
with a capital”, with the help import math as float_ (float is the
name of a builtin module).
import geometry binds one name, geometry, and every member of the
module is reached through it, in every position:
- functions and values:
geometry.add(1, 2); - constructors and record literals:
geometry.Circle(2.0),geometry.Shape.Circle(2.0),geometry.Point { x: 1, y: 2 }; - patterns:
geometry.Circle(r) ->,geometry.Shape.Circle(r) ->,geometry.Point { x, .. } ->; - types:
fn area(s: geometry.Shape),List(geometry.Point),Fn(geometry.Point) -> Int,type Shapes = List(geometry.Shape); - traits:
trait geometry.Describe for Local,trait Display for geometry.Point,where a: geometry.Describe,trait Loud: geometry.Describe.
geometry.Circle works when Circle is the only variant of that name
among the module’s exports; geometry.Shape.Circle always works.
import geometry.{ add, Shape } binds exactly add and Shape, and not
geometry. An enum imported this way does not bring its variants: write
Shape.Circle(2.0), or list Circle as well. To also use other items as
geometry.sub, add a separate import geometry.
A member used without its module is an error that says how to reach it:
error[type]: undefined variable 'add'
= help: did you mean `geometry.add`? or import the name: `import geometry.{ add }`
Variants of one name
Two enums may have variants of one name. Shape.Red and Color.Red say
which; a bare Red where both enums are in scope is an error, with a
label at each declaration:
type Shape {
Red,
Square,
}
type Color {
Red,
Blue,
}
fn main() {
let s = Shape.Red
let c = Color.Red
println("{s} {c}") -- Red Red
}open in playgroundFrom another module, geometry.Red works when Red is the only variant of
that name among the module’s exports, and geometry.Shape.Red always
works. import geometry.{ Red } of a name two of its enums share is an
error: import the enum and write Shape.Red.
Two types of one name
Two modules may each declare a type of one name. They are different
types, kept apart by their qualifiers: a.Pt and b.Pt, or a module’s
own Pt and an imported b.Pt. A value of one is not a value of the
other, and each has its own trait impls.
A record of such a type prints qualified, as the program names the
module: a.Pt { x: 1 } for a module a of the program, db.Pt { x: 1 }
for the library of a dependency db, and db.util.Pt { x: 1 } for its
module util. A record type whose name no other type of the program has
prints bare: Pt { x: 1 }. A variant prints by its own name, whichever
enum it is of: a.V("s") prints V("s").
Two modules may also each declare a trait of one name, say Show with
a method show, and implement it for one type. A call names the trait
it means, as it names any item: a.Show.show(5) and b.Show.show(5)
are two calls of two methods. A trait of the program with a method named
display implemented for Int is no Display: Pretty.display(5) calls
it, and interpolation still shows 5 structurally. The structural traits of a type (Equal, Hash, Compare,
Display without a written impl) go by the builtin traits of its
fields, whatever trait of the program has a method of the same name.
Names in messages and in the editor
The messages of the check (what a file is refused or warned for before
it runs), their help lines, hover, signature help, completion and the
REPL’s :type write a name of another module (a type, a trait, a
function, a variant) as the file at hand writes it: bare where the file
imports the name (import da.{ Sq }: Sq, also beside import da),
with the file’s name for the module where it has one (import da as d:
d.Sq, d.load; import json as j: j.Value), and else with the
module’s own name (da.Sq for a type the file reaches only through
another module). Two different names are never written alike: where the
module’s own name is one the file gives to something else (import da as other beside a module other), its names are described, T of module other. A runtime error is raised in the builtin, not in a file, and
names a builtin by its own name: list.chunks: n must be positive, also
under import list as l.
Module names and shadowing
Module names follow the ordinary lexical-scoping rules: a value binding
inside a function (function parameter, lambda parameter, let, pattern
binder) with the same name shadows an imported module within its scope.
At the top level there is no shadowing: an import and a top-level fn,
type, let or trait may not bind the same name, and neither may two
imports (import a.{ x } and import b.{ x }, or two import m as n with
the same alias). Such a program is rejected with an error naming both
declarations. An import alias cannot be the name of a builtin module:
import a as list is an error, since list. always means the builtin
list.
import other -- other.silt: pub fn double(x) { x * 2 }
type P {
year: Int,
}
fn f(other: P) -> Int {
other.year -- field access on the parameter, not a module lookup
}
fn caller() -> Int {
other.double(21) -- no `other` binding in scope here: module call
}
A builtin module follows the same rule: after import list, a binding named
list hides the module inside its scope: list.map there is a field of
the binding, which a List value does not have. The binding gets a warning
that it hides the module; rename the binding, or import the module under
another name (import list as l), to reach both.
Type names are not value bindings, so Shape.Circle keeps resolving through
the enum even though Shape is in scope. Qualified type paths
(geometry.Point { .. } literals, geometry.Circle(r) patterns) are an
exception in the other direction: because a local can never carry that
syntax, using a module qualifier whose name is shadowed by a value binding
is a compile error rather than a silent module pick — rename the binding or
the import.
Multi-file projects
silt init creates a package with a silt.toml manifest and a src/ tree
with a first test (see Testing).
The entry point is src/main.silt, and every .silt file directly in
src/ is a module of the package, imported by its file name. A file in a
sub-directory of src/ is no module: it cannot be imported. silt check
of the package checks it all the same, as a program of its own whose
imports are the package’s modules, as silt check src and a check of the
file itself do, so a script kept there (run by its path) is checked too.
Test files (*_test.silt) are found
anywhere under the package, in src/, its sub-directories or a tests/
directory beside it, and import the package’s modules by name. Any other
.silt file under tests/ is no module either (an import looks only in
src/), and silt check of the package checks it the same way, as a
program of its own.
External dependencies are declared in silt.toml via silt add <name> --path <path> or silt add <name> --git <url> --tag <tag> (or
--branch <branch>, --rev <commit>: a git dependency names one of
them). The git URL is an https://, http://, ssh://, git:// or
file:// URL, host:path or user@host:path, or a local path. An
https://, http://, ssh:// or git:// URL is read as url.parse
reads one, so a port that is no port, a host that is none or is not ASCII,
or an escape that is none is an error of silt.toml (and of silt add),
not of git later; the URL is kept as written in silt.lock. A value that
starts with https:, http:, ssh:, git: or file: (in any case)
without // is refused as a URL with its // left out, so a host named
ssh, git or file is written as an ssh:// URL
(ssh://git/~/team/pkg.git for git:team/pkg.git). The form
user@host:path holds no password, as git would take the user for the
host: a value of that form whose first : stands before its first @,
whatever stands between them (user:word@host:path, user:word@host/path,
host:dir/a@b), is refused. A path with an @ in it is written with the
user in front (git@host:team/pkg@v2.git) or as an ssh:// URL
(ssh://host/~/dir/a@b). On Windows a value that starts with one character
and : and holds no other : is a drive, not this form. Elsewhere a
Windows path, a letter, : and then \ or / with no other : (C:\repo),
or one that starts with \\, is refused: git there would read C:\repo as
the host C and a path. A host of one letter is written as an ssh:// URL
(ssh://C/repo). A message shows no user or password of a git URL
(https://***@host/repo.git, ***@host:path). After adding,
imports from the dependency package work exactly like local modules. silt remove <name> takes one out of silt.toml
and silt.lock again.
import x in a module of a package means one of three things: the
builtin module x; the dependency whose key under [dependencies] in
this package’s silt.toml is x (its src/lib.silt); or this
package’s own src/x.silt. A name never means two of them: a module
file named like a builtin module (src/list.silt), a dependency key
named like a builtin module (silt add list ... is refused, and so is
the key in silt.toml), and a dependency key named like a module of the
package (src/x.silt beside the dependency x, E0605) are errors. A
dependency’s own dependencies are its own: to import one, declare it in
your silt.toml too.
A package is known by where it comes from (its directory, or its
repository and commit), not by its name: two packages of one name from
different places, such as two libraries that each depend on a utils of
their own, are two packages, and their types are two types (a message
tells them apart: Thing of package utils (dependency `helpers` of `lb`)).
One repository at two commits is an error (E0604, “utils is required at
two commits”), and so is one commit reached by URLs written in different
ways (../utils and a file:// URL of it, with a host such as
localhost or a user in it or not, which git does not read, or with an
escape in its path such as %61 for a, which git reads; ../utils for
the repository ../utils.git, and a working repository and its .git,
which git opens as one; an https:// URL with a user in it and without): a
program holds one copy of a repository.
A package consumed as a dependency exposes src/lib.silt instead of
src/main.silt (silt init --lib creates one). Such a library-only package has nothing to execute — silt run refuses it — but a bare silt check works, falling back to
src/lib.silt when no src/main.silt exists.
Built-in modules
Standard-library modules are registered in the global environment — there is
no .silt file for them. You still import them explicitly:
import channel
import io
import list
Each built-in module has a page of its own, listed in the
Language Guide, and the editor
shows the same text when you hover a qualified built-in name
(list.map, math.cos, Result, …). The
language card lists every
module with its types and the signature of each function.
The types and enums of a built-in module are its members like any
other: time.Weekday and time.Monday, channel.Message(v) and
channel.Closed, http.Request and http.GET, io.IoError and
io.NotFound(path), tcp.TcpStream,
task.RuntimeError, postgres.PgPool (and PgTx, PgCursor(a)). Two
modules may have a variant of one name (tcp.Timeout,
http.Timeout): the module says which. A selective import works for
them too: import channel.{ Message }.
The prelude needs no import: the primitive and container types (Int,
Float, Bool, String, (), Bytes, List, Map, Set, Channel, Fn),
Never (the type of what never returns),
TypeOf(a) (the type of a type used as a value, like Int or a
type a parameter), Option, Result, Step, Some, None, Ok, Err, Stop,
Continue, print, println and panic. The primitive and container types, Never and TypeOf cannot be declared
again: type List { ... } is an error, “type ‘List’ shadows builtin type
‘List’”, and so is type Never { ... }. No trait may take the name of a type
of the prelude, Option and Result included: trait Int { ... } is an error,
“trait ‘Int’ shadows builtin type ‘Int’”; nor of a variant of the prelude:
trait Some { ... } is “trait ‘Some’ shadows builtin variant ‘Some’”. A type of a built-in module reserves no name: a module may declare
its own type Regex or type Weekday, a type apart from regex.Regex and
time.Weekday, and use both; with import regex.{ Regex } as well, the name is
bound twice. The other names of the prelude can be declared again: a module’s
own declaration or import of Option, Result, Step, one of their variants,
print, println or panic shadows the prelude. After type Maybe(a) { Some(a), None }, a
bare None is Maybe.None, and the prelude’s is still Option.None; after
type Msg { Add(Int), Stop }, the prelude’s Stop is Step.Stop.
When modules are initialised
A module’s top-level lets are evaluated once, before the first module that
imports it uses them. The modules a file imports are initialised in the order
silt fmt writes the file’s imports: by the name of the module (digits, then
_, then letters), each after the modules it
imports itself. A file’s own top-level lets run after its imports.
Modules are read and checked in that order too. So the order in which the import lines are written carries no meaning: formatting a file changes neither what a program does nor what is reported for one that has errors. The errors of several modules come in that order, whichever import line stands first.
Circular imports
silt rejects circular imports at compile time. If a.silt imports b
which imports a, the compiler emits the full chain:
error[compile]: circular import detected: a -> b -> a (...)
Cycles inside a single package render with bare module names; cycles that
cross package boundaries use the qualified package::module form so the
boundary is visible. The chain starts at the module of the cycle that is
reached first, in the order modules are initialised in, so it is the same
chain in whatever order the import lines are written. Break the cycle by
moving the shared code into a third module that both sides import.