DocsLanguage Guide
Modules and Access Control
Modules and imports, the four visibility levels, and who may subclass and override.
Every chapter so far has written code into a single module. Real programs are split up: into modules that group related declarations, and into packages that are built, versioned and shared as a unit. This chapter covers how Sable code is organised into modules, how one module uses another, and how access control decides which declarations each piece of code can see, subclass and override.
Sable's access model is close to Swift's, with one more level (package, for code shared across a workspace) and a rule about conformances borrowed from Rust.
Modules#
Every Sable source file begins with a module declaration that names the module its declarations belong to:
module Inventory.Storagepublic struct Shelf { public var label: String public var capacity: Int}The module line must be the first item in the file, ignoring comments and blank lines, and there is exactly one per file. A file that declares anything without one is an error (S2007).
Module names are dotted. The first segment is the package's name: every module of the inventory package is Inventory or Inventory.Something, and the standard library's are Sable.Core, Sable.Collections and so on. Because a module belongs to exactly one package, two packages in a build that both declare the same module is an error (S2090) rather than a silent merge.
The dots express organisation, not containment. Inventory.Storage and Inventory.Storage.Cache are two separate modules; importing one doesn't import the other.
A module may span many files#
Any number of files may declare the same module, and they act as one: a declaration in one file can use any non-private declaration in another, with no import. There is no rule tying file names to type names, as Java or C# conventions have; organise files however reads best.
// src/storage/shelf.sbmodule Inventory.Storagepublic struct Shelf { public var label: String var items: Item[>..] = []}// src/storage/item.sbmodule Inventory.Storagestruct Item { var sku: String var quantity: Int}Files within one module may depend on each other in any direction. Modules, though, must form a graph without cycles: if Inventory.Storage imports Inventory.Pricing, then Inventory.Pricing cannot import Inventory.Storage, directly or through others. The module is the unit the compiler builds and caches, and a cycle would leave no order to build them in. When two modules need each other, the shared part usually wants to be a third module that both import.
Importing Modules#
import makes another module's visible declarations available in the file that writes it. Imports go after the module line:
module Inventory.Reportsimport Sable.Collectionsimport Inventory.Storagefn summarise(_ shelf: Shelf) -> String { return "\(shelf.label): \(shelf.capacity) slots"}An import applies to the one file it is written in, not to the whole module. Sable.Core (where Int, String, print and the rest live) is always available without an import.
Sable has several forms of import:
import Sable.Collections // the whole moduleimport Sable.Math as M // the whole module, under a shorter nameimport Sable.IO.{ File, Directory } // only these namesimport Sable.Core.{ Platform, Reflect as Reflection } // only these, one renamedimport Sable.Text.{ * } // every name, explicitly- A plain import brings in the module's visible names.
asafter the module gives the module a short name; you then writeM.Vector3..{ A, B }imports just the names listed, which keeps a file's namespace small and documents where each name came from. A name in the list can be renamed withas, which resolves a clash between two modules that both have, say, aReflect..{ * }is a wildcard. It is discouraged outside a project's prelude-like modules, because it hides where names come from.
An import that a file never uses is reported by the unused_import lint.
Re-exporting with public import#
A public import re-exports a module: consumers of your module see the imported module's declarations as if they had imported it themselves.
module Inventorypublic import Inventory.Storage // users of Inventory see Shelf toopublic import Inventory.PricingThis is how a package offers a single front-door module that gathers its parts. A plain import is private to the file that writes it.
Access Levels#
Each declaration has an access level that decides where it can be seen from. There are four:
| Level | Visible from |
|---|---|
public |
every consumer of the package |
package |
every package in the same workspace |
internal |
the module it is declared in (the default) |
private |
the enclosing declaration, and that type's extensions in the same module; at the top level, the file |
module Inventory.Storagepublic struct Shelf { public var label: String // anyone package var auditTag: String // other packages of this workspace var restockedAt: Int // this module (internal) private var reservations: Int // Shelf and its extensions here public fn freeSlots() -> Int { return reserveSlack() + 1 } private fn reserveSlack() -> Int { return reservations }}internal being the default means a module's helpers stay out of its public API until you say otherwise. A library's surface is exactly what it marks public. Using a declaration where it isn't visible is S3040.
private and extensions#
A private member is visible inside its type's declaration and in extensions of that type in the same module. You can therefore split a type across several extensions, as is common for protocol conformances, without widening its private details:
public struct Account { public var id: Int private var secret: String private fn audit() -> String { return secret }}extension Account { public fn summary() -> String { return "\(id): \(audit())" // allowed: same module, an extension of Account }}fn leak(_ account: Account) -> String { return account.secret // error: 'secret' is private (S3040)}This differs from Swift, where private is scoped to a file and fileprivate exists as a separate level. In Sable, a top-level private declaration is visible in its file, and a private member is visible to its type wherever the type is extended in the module.
package#
package sits between internal and public. It is visible from every package in the same workspace (the packages listed as members of a workspace.sb), but not from consumers outside it. It's for a multi-package project whose packages share helpers they don't want to publish. The standard library's modules use it for internal kernels shared between modules.
package fn arithmeticRun(_ values: F64[:]) -> F64 { // used by several of the workspace's packages, published by none}Note that package is a keyword because of this, which is why a package manifest's top-level value is called manifest, not package.
A declaration is no more visible than what holds it#
A public member of an internal type is effectively internal: no one outside the module can reach the type to reach its member.
The reverse is checked. A public or package declaration may not name a less visible type in its signature: a parameter, a result, an error type or a property's type (S3063). Otherwise code could call the function and receive a value whose type it cannot name:
struct Receipt { var total: Int}public fn checkout() -> Receipt { // error: 'Receipt' is internal (S3063) return Receipt(total: 0)}The fix is to make Receipt public, or checkout internal.
private(set)#
A property can be readable at one level and writable at a more restricted one. private(set) keeps the setter private while the getter has the property's own level:
public class Connection { public private(set) var bytesSent: Int = 0 public private(set) var isResumed = false public fn send(_ data: U8[:]) { bytesSent += data.count // writable here }}let connection = Connection()print(connection.bytesSent) // readable anywhereconnection.bytesSent = 0 // error: the setter is privateSubclassing and Overriding#
For classes (from Structures and Classes), access control also decides who may subclass a class and override its members. Inside the module that declares a class, you may subclass it and override its methods freely (with override, which is always required). Across a module boundary, both need permission:
| Modifier | On a class | On a member |
|---|---|---|
open |
may be subclassed outside its module | may be overridden outside its module |
| (none) | may be subclassed only inside its module | may be overridden only inside its module |
sealed |
may not be subclassed further, anywhere | |
final |
may not be subclassed at all | may not be overridden at all |
abstract |
cannot be instantiated; subclasses fill it in |
public open class Widget { public open fn render() -> String { return "widget" } public fn identifier() -> String { // not open: other modules can't override it return "w" } public final fn version() -> Int { // no one can override it return 1 }}public sealed class Button: Widget { // a Widget, but no one may subclass Button public override fn render() -> String { return "button" }}public abstract class Shape { // cannot be made with Shape(); only subclasses can public init() { }}Subclassing a sealed or final class, or overriding a final member, is S3044. Making an instance of an abstract class is S3045. Overriding without override is S3042, and override on something no base class declares is S3043.
public alone does not mean overridable. A library must opt in, member by member, to being extended by code it can't see.
Why open matters: devirtualisation#
The default is not just a matter of API hygiene. When the compiler knows that no code outside the module can override a method, it can resolve calls to that method directly, and then inline them, instead of going through the class's method table. This is devirtualisation, and it is a large part of why ordinary class code in Sable is fast. Each open you write is a method the compiler must call through the table from other modules, so open is a deliberate promise, not a default. For the same reason, Sable doesn't let a generic base class be inherited across modules without an explicit open.
Conformances Have One Home#
A protocol conformance T: P may be declared only in the module that declares T or the module that declares P (S3046). Written in a third module, it is an error:
module Inventory// error: neither Reflect nor Hashable is Inventory's (S3046)extension Reflect: Hashable { // ...}This is Rust's coherence rule. Without it, two libraries could each declare that Reflect is Hashable, differently, and a program using both would have no single answer. With it, every (type, protocol) pair has at most one conformance in the whole program, so the compiler can look conformances up in a static table, and any P is always sound.
When you need a conformance for a type you don't own to a protocol you don't own, wrap the type in a struct of your own:
struct Token: Hashable { var id: Int operator == (lhs: Token, rhs: Token) -> Bool { return lhs.id == rhs.id } fn hash(into hasher: inout Hasher) { hasher.combine(id) }}Note also that a member an extension adds belongs to the extension's module for access purposes. extension String { fn shouted() -> String } in your app gives String an internal member of your app, not a member of Sable.Core.
Library Evolution and @frozen#
A library changes over time, and some changes would break code that uses it. Sable has a rule for the most common case: adding a case to a union.
A public union matched in another module needs a default arm, unless the union is marked @frozen. That way, a library can add a case to an ordinary public union in a new version without breaking its users' match statements.
// in the Geometry modulepublic union Shape { Circle(radius: F64) Rect(width: F64, height: F64)}@frozenpublic union Axis { Horizontal Vertical}// in another modulefn describe(_ shape: Shape) -> String { return match shape { case .Circle(let r) => "circle \(r)" case .Rect(let w, let h) => "rect \(w)x\(h)" default => "some other shape" // required: Shape may gain cases }}fn flip(_ axis: Axis) -> Axis { return match axis { // no default: Axis is @frozen case .Horizontal => .Vertical case .Vertical => .Horizontal }}@frozen is a promise never to add a case. Make it only when the set of cases is truly fixed. Optional<T> is a @frozen union of Some(T) and None. Inside the declaring module, every match is checked exhaustively as usual, because the module is always compiled with its own cases.
Interface Files#
When the compiler builds a module, it also writes an interface file (.sbi) that describes what other modules need to know about it: its public and package declarations with their full signatures, the bodies of generic functions and other code callers compile themselves, which unions are @frozen, and its conformances.
You don't write .sbi files; the build keeps them in its cache. They matter because they make builds incremental: the file is designed so that a change to a private implementation detail leaves it unchanged, and an unchanged interface means modules that depend on yours don't need recompiling. Editing a function body in one module rebuilds that module, not the program.
Packages and Workspaces#
A package is the unit you build, version and publish: a directory with a manifest, package.sb, beside a src/ directory of .sb files. Getting Started showed sable new, which creates one.
The manifest is written in Sable itself. It declares one top-level let manifest: Package, built with the Sable.Build module:
// package.sbimport Sable.Buildlet manifest = Package { name: "inventory", version: "0.4.2", edition: 2027, license: "MIT", targets: [ .library(path: "src/lib.sb"), .executable("inventory", path: "src/main.sb"), ], dependencies: [ .registry("sable-math", "1.2"), .registry("image", "0.6", features: ["png"], defaultFeatures: false), .path("platform", "../platform"), .git("barcode", "https://example.com/barcode", tag: "v2.1.0"), .registry("metal-sys", "0.9", optional: true, when: .os(.MacOS)), ], devDependencies: [.registry("bench-harness", "0.3")], features: [ "default": ["png"], "png": [], "metal": ["dep:metal-sys"], ], profiles: [ .release(optLevel: 3, lto: .fat), .dev(leakCheck: true), ],}A few points about it:
- Dependencies come from the registry (
.registry(name, version)), a local directory (.path), or a git repository (.git, with atag:,branch:orrev:). Each can enablefeatures, beoptional, or apply onlywhen:a condition on the target holds.sable addandsable removeedit this list for you, keeping your layout and comments. - Features are named, optional parts of the package. Code tests them with
#if feature(png), as Compile-Time Evaluation showed. - The edition is a year. Editions may change syntax but never the ABI, and packages of different editions work together.
- Profiles configure builds:
.dev(...)for ordinary builds and.release(...)for--release, plus profiles of your own that inherit from one of them. They set the optimisation level, debug information, link-time optimisation, and the memory-model checks you may want to toggle, such asarcChecks,exclusivityandleakCheck.debugAssertionsdecides whetherDEBUGorRELEASEis defined.
Because the manifest is code, you can compute parts of it with local lets and functions. But it is evaluated under strict rules so that it means the same on every machine: it may import only Sable.Build and the pure parts of Sable.Core, may not read files or the environment, and may not use #if os() or #if arch(). Platform choices are data, like when: .os(.MacOS), that the build applies per target. A published package carries the manifest's evaluated form, sable.toml, so tools never need to run Sable to read it.
A workspace groups packages that are developed together, like a .NET solution or a Cargo workspace. Its root has a workspace.sb:
// workspace.sbimport Sable.Buildlet workspace = Workspace { members: ["packages/*", "tools/importer"], exclude: ["experiments"],}The workspace is what package access reaches across.
The Standard Library's Tiers#
The standard library is itself a set of modules, in two tiers:
- Core modules, such as
Sable.Core,Sable.Collections,Sable.Text,Sable.IO,Sable.Net,Sable.SerializeandSable.Testing, stand on their own. - Extension modules, such as
Sable.DependencyInjection,Sable.Hosting,Sable.Configuration,Sable.ValidationandSable.CommandLine, are built on top of the core.
A core module never imports an extension module, directly or through others (S3239). That keeps the core self-contained: a program that uses no extension compiles and links only the core. When a conformance would join the two, it lives in the extension, which the coherence rule allows because the extension declares the protocol or imports the type.
Only the standard library's Sable.* modules have tiers. Your own modules may import any module.