Guides · 14
Modules and packages
Every .vyi file is a module. A file's top-level declarations belong to it:
another file can use one only when it's marked export and that file imports
it. A program is its entry file plus every file the entry's imports reach,
directly or through other files' imports. The compiler starts at the entry file
and compiles what it reaches.
This guide covers imports and exports, how methods travel with types from file
to file, the standard-library packages, and the package.vyipac manifest.
Imports and exports
export makes a declaration available to other files. import { ... } from
brings exported names into your file:
// file: greet.vyi
import { println } from "@fmt"
export fn greet(name: [*con]u8) {
println($"hello, ${name}")
}
// file: main.vyi
import { greet } from "./greet"
fn main() !u8 {
greet("ada") // prints hello, ada
return Ok(0)
}The path "./greet" is relative to the importing file's directory, and you
leave off the .vyi. The import binds the name greet itself, so the call is
greet("ada"). There is no prefix such as greet.greet and no namespace object.
You can export any top-level declaration: a function, a method, a struct,
enum, interface, or error, a type binding, and a con or mut
binding. A declaration without export stays in its file, and importing it is
an error:
// file: prices.vyi
fn cents(dollars: i32) i32 { return dollars * 100 }
// file: main.vyi
import { cents } from "./prices" // error: no exported member
fn main() !u8 { return Ok(0) }The full message is "./prices" has no exported member "cents".
Private fields
export decides whether other files can use a name. pub decides whether they
can use a struct's fields. A field without pub is private to the file that
declares the struct:
// file: user.vyi
export struct User {
pub name: [*con]u8,
password: [*con]u8 = "",
}
// file: main.vyi
import { User } from "./user"
fn main() !u8 {
con ada = User{ name: "ada" }
con secret = ada.password // error: is private
return Ok(0)
}Other files can create a User, pass it around, and read its name. They
can't read or set password; they can leave it out of a struct literal only
because it has a default. The full message is
field "password" is private to its defining file. A struct with a private
field that has no default can be created only in its own file.
Renaming an import
{ name: localName } imports a name under a different one. This lets you use
two files that export the same name:
// file: english.vyi
export fn greeting() [*con]u8 { return "hello" }
// file: french.vyi
export fn greeting() [*con]u8 { return "bonjour" }
// file: main.vyi
import { println } from "@fmt"
import { greeting } from "./english"
import { greeting: frenchGreeting } from "./french"
fn main() !u8 {
println(greeting()) // prints hello
println(frenchGreeting()) // prints bonjour
return Ok(0)
}Re-exports
export { names } passes on names a file imported. A package can use this to
offer one file that holds its whole public surface, while the code lives in
smaller files. The standard library's @core package is built this way.
// file: numbers.vyi
export fn isEven(n: i32) bool { return n % 2 == 0 }
// file: lib.vyi
import { isEven } from "./numbers"
export { isEven }
// file: main.vyi
import { println } from "@fmt"
import { isEven } from "./lib"
fn main() !u8 {
println(isEven(4)) // prints true
return Ok(0)
}Loading a file without binding names
An import without a list, such as import "./setup" or import "@libc", loads
the file into the program and binds nothing in your file. import "@fmt"
loads @fmt, but println still isn't defined in your file until you import
it by name. This form is for files that contribute to the program as a whole.
For example, import "@libc" adds the C library's functions to the c
namespace (guide 15).
Same-named functions in different files
A function without export is private to its file, in calls too. Two files can
each declare a function with the same name, and each file's calls run its own:
// file: prices.vyi
fn round(cents: i32) i32 { return cents / 100 * 100 }
export fn wholeDollars(cents: i32) i32 {
return round(cents)
}
// file: main.vyi
import { println } from "@fmt"
import { wholeDollars } from "./prices"
fn round(n: i32) i32 { return n / 10 * 10 }
fn main() !u8 {
println(round(1234)) // prints 1230
println(wholeDollars(1234)) // prints 1200
return Ok(0)
}An imported function joins the functions your file declares under the same name, and together they are one set of overloads (guide 04). When your own function has the same signature as an imported one, yours is the closer declaration and takes your file's calls. The imported file's own calls still run its function:
// file: greet.vyi
export fn greet(name: [*con]u8) [*con]u8 { return "hello" }
export fn welcome() [*con]u8 { return greet("ada") }
// file: main.vyi
import { println } from "@fmt"
import { greet, welcome } from "./greet"
fn greet(name: [*con]u8) [*con]u8 { return "hi" }
fn greet(times: i32) [*con]u8 { return "hi hi" }
fn main() !u8 {
println(greet("ada")) // prints hi
println(greet(2)) // prints hi hi
println(welcome()) // prints hello
return Ok(0)
}When two imports bring functions with the same name and the same signature,
the later import wins:
// file: english.vyi
export fn greeting() [*con]u8 { return "hello" }
// file: french.vyi
export fn greeting() [*con]u8 { return "bonjour" }
// file: main.vyi
import { println } from "@fmt"
import { greeting } from "./english"
import { greeting } from "./french"
fn main() !u8 {
println(greeting()) // prints bonjour
return Ok(0)
}File-level variables
A file owns its file-level variables (guide 02). Another file can import an exported one and read it, and it sees the current value:
// file: visits.vyi
export mut visits = 0
export fn recordVisit() {
visits += 1
}
// file: main.vyi
import { println } from "@fmt"
import { visits, recordVisit } from "./visits"
fn main() !u8 {
recordVisit()
recordVisit()
println(visits) // prints 2
return Ok(0)
}Only the owning file writes to it. To change it from another file, call a
function the owner exports, as main does with recordVisit. Assigning to it
directly is an error:
// file: visits.vyi
export mut visits = 0
// file: main.vyi
import { visits } from "./visits"
fn main() !u8 {
visits += 1 // error: cannot reassign immutable binding
return Ok(0)
}Import paths
An import path has one of three forms:
| Path | What it names |
|---|---|
"./x", "../x" | a file in your own package, relative to the importing file |
"@name" | a standard-library package, such as "@fmt" |
"name" | a third-party package declared in your manifest's deps (planned) |
A relative path can't leave the package root, the directory that holds
package.vyipac (see below). An import such as
"../../shared/util" that climbs above the root is an error:
import "../../shared/util" escapes the package root. Without a manifest, the
entry file's directory is the root. Code from outside the root has to come in
as a package.
Methods travel with types
Guide 04 showed that methods are not members of a type: a call finds the methods in scope where it's written. That is the first place a call looks. The second is the type's pocket: the methods that travel with the type from file to file through imports and re-exports.
A call value.method() looks for method in this order:
- In scope where the call is written: methods declared in the enclosing blocks and the file, and methods the file imports by name.
- In the pocket of the value's type.
Nothing is global. Every method a call can reach comes from a scope or from a pocket, and a pocket holds only what files along the import path exported. The rest of this section builds the pocket up one step at a time.
A method exported beside its type
An exported method declared in the same file as its type goes into the type's pocket. A file that imports the type gets the method with it:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) area() i32 {
return r.width * r.height
}
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./rect"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.area()) // prints 6
return Ok(0)
}main.vyi imports Rect and never imports area. The call finds area in
the pocket Rect carries.
The pocket goes wherever a value of the type goes, even into a file that
doesn't import the type at all. Here main.vyi imports only a function that
returns a Rect:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) area() i32 {
return r.width * r.height
}
export fn square(side: i32) Rect {
return Rect{ width: side, height: side }
}
// file: main.vyi
import { println } from "@fmt"
import { square } from "./rect"
fn main() !u8 {
println(square(3).area()) // prints 9
return Ok(0)
}A method imported on its own
A method declared in another file can be imported by name. The import item is
the receiver type, a dot, and the method's name, as in Rect.perimeter:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
// file: measure.vyi
import { Rect } from "./rect"
export fn (r: Rect) perimeter() i32 {
return 2 * (r.width + r.height)
}
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./rect"
import { Rect.perimeter } from "./measure"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.perimeter()) // prints 10
return Ok(0)
}An imported method is in scope in the importing file, like an imported
function. It doesn't go into the pocket. If main.vyi re-exported Rect, the
files that import Rect from main.vyi would not get perimeter. Here
layout.vyi imports the method and re-exports the type, and the method doesn't
come along:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
// file: measure.vyi
import { Rect } from "./rect"
export fn (r: Rect) perimeter() i32 {
return 2 * (r.width + r.height)
}
// file: layout.vyi
import { Rect } from "./rect"
import { Rect.perimeter } from "./measure"
export { Rect }
// file: main.vyi
import { Rect } from "./layout"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
con edge = r.perimeter() // error: has no method
return Ok(0)
}A few more forms of the method item:
- A method with a pointer receiver is written with the pointer:
*mut Rect.growforfn (r: *mut Rect) grow(by: i32). - A method on a primitive type names that type:
i32.squared. - An item can rename the method: after
import { Rect.perimeter: edge }, the call isr.edge(). - A file can pass on a method it imported with
export { Rect.perimeter }. The next file imports it the same way, asRect.perimeter.
A method is never imported by its bare name. `import { perimeter } from
"./measure" asks for a function, type, or value called perimeter`, and fails
with "./measure" has no exported member "perimeter". A note on the error
names the item to write, Rect.perimeter. The
methods and dispatch reference
lists every receiver form an item can match.
Adding methods along the way
A file can import a type, export new methods beside its import, and re-export the type. Those methods go into the pocket of the type it exports, together with everything the type already carried:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) area() i32 {
return r.width * r.height
}
// file: measure.vyi
import { Rect } from "./rect"
export fn (r: Rect) perimeter() i32 {
return 2 * (r.width + r.height)
}
export { Rect }
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./measure"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.area()) // prints 6
println(r.perimeter()) // prints 10
return Ok(0)
}main.vyi imports Rect from measure.vyi, so its Rect carries both
area from rect.vyi and perimeter from measure.vyi. A file that imports
Rect from rect.vyi gets only area:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) area() i32 {
return r.width * r.height
}
// file: measure.vyi
import { Rect } from "./rect"
export fn (r: Rect) perimeter() i32 {
return 2 * (r.width + r.height)
}
export { Rect }
// file: main.vyi
import { Rect } from "./rect"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
con edge = r.perimeter() // error: has no method
return Ok(0)
}The pocket can grow with each export. A third file could import Rect from
measure.vyi, export an isSquare method beside it, and re-export it; its
importers would get all three methods. Think of each re-export as a subclass of
the pocket it imported: it holds what that file added, on top of everything it
inherited. A file further back along the path sees none of what later files
added, and two files that each import Rect from rect.vyi and add their own
methods hand out two pockets that don't see each other.
A method exported beside a type binding of a type also goes into the pocket
that binding carries. After export type Panel = Rect and
export fn (p: Panel) title(), a file that imports Panel can call
title().
All of these are still one type. Rect has the same fields and layout in every
file, and a Rect from measure.vyi can be passed to a function in rect.vyi
that takes a Rect. Only the methods a call can find differ.
Scope first, then the pocket
A method in scope at the call is found before one in the pocket. When your file declares a method with the same signature as one in the pocket, your file's calls use yours:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) name() [*con]u8 {
return "rectangle"
}
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./rect"
fn (r: Rect) name() [*con]u8 { return "box" }
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.name()) // prints box
return Ok(0)
}Inside the pocket, a re-exporting file can replace a method. When a file exports a method with the same name and signature as one already in the pocket and re-exports the type, its method takes the original's place for every file that imports the type from it:
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }
export fn (r: Rect) name() [*con]u8 {
return "rectangle"
}
// file: ui.vyi
import { Rect } from "./rect"
export fn (r: Rect) name() [*con]u8 { return "panel" }
export { Rect }
// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./ui"
fn main() !u8 {
con r = Rect{ width: 2, height: 3 }
println(r.name()) // prints panel
return Ok(0)
}A replacement changes what callers further along the path find. It doesn't
change code that was written earlier: a function in rect.vyi that calls
r.name() uses the methods it can see where it's written, and gets
"rectangle" whichever pocket the value carries.
Methods without export
Only an exported method goes into the pocket for the next importer. A method
declared without export is usable within the scope it's declared in and
nowhere else, even when it's declared right beside its type. At file level,
that scope is the file. Inside a function body, it's that body (guide
04).
Generic functions and interfaces
A generic function written in another file sees the methods in scope where it's
written, plus the pocket of the type it's called with. A function in a
show.vyi that takes an item: _ and calls item.label() works on any value
whose pocket holds a label.
Converting a value to an interface works like a call: it takes each method from scope at the conversion first, then from the pocket, and the interface value keeps the methods it took. Guide 12 covers this.
The standard packages
The standard library ships as packages whose names start with @. These are
the ones installed with the compiler:
| Package | What it provides |
|---|---|
@fmt | print and println, the IntoString interface, and Template, the type of a $"..." string |
@core | Optional, Result, Array, Range, String, Vec, HashMap, and formatInt, formatUint, formatFloat |
@io | stdin, stdout, stderr, args(), the Reader and Writer interfaces, BufferedReader, BufferedWriter |
@mem | the Allocator interface, systemAllocator, ArenaAllocator, FixedBufferAllocator, and byte operations such as copy and equal |
@errors | Error, an error that carries a message, and capture, which records the call stack as an ErrStack |
@testing | describe, it, and expect, run by vyi test (guide 16) |
@trace | trace and currentPos, for reading the call stack |
@crypto | randomBytes |
@c | the c namespace for calling C, and cstrView and cstrDup (guide 15) |
@libc, @wasi-preview1, @wasm | the platform layers that @io and @mem are built on |
Optional, Result, and Range are what ?T, !T, and a..b stand for.
They and Array are available in every file without an import. Everything
else in @core is imported by name, as in
import { Vec } from "@core". You rarely import @libc, @wasi-preview1, or
@wasm yourself.
The compiler also provides two packages that have no source files. @intrinsics
holds low-level operations that the standard library is built from. @target
describes the target you're building for: targetOS, targetArch, and
targetBuildMode. They are known values, so a file-level if over them
chooses declarations while compiling (guide
11):
import { println } from "@fmt"
import { targetOS } from "@target"
if targetOS == "wasm" {
con platform = "WebAssembly"
} else {
con platform = "Linux"
}
fn main() !u8 {
println(platform)
return Ok(0)
}vyi run builds for WebAssembly unless you pass --target, so this prints
WebAssembly. With --target x86-64-linux, it prints Linux.
Packages and the manifest
A package is a directory with a package.vyipac manifest at its root. The
compiler finds the manifest by walking up from the entry file, and every .vyi
file under that directory belongs to the package. The manifest is YAML:
name: shop
version: 0.1.0
lang: 0.0.1
deps:
json: ^1.0.0
entries:
shop: src/main.vyi
shop-admin: src/admin.vyi
export: src/lib.vyinameandversionidentify the package.versionis a semantic version.langis the Vyi language version the package is written for. It also picks the version of every@package the program imports.entrieslists the package's programs. Each one maps a name to an entry file, which must declaremain.vyi run shopbuilds and runs theshopentry. One package can hold several programs.exportnames the package's library file: the file other packages get when they import this one by name. It needs nomain. It's usually a file that re-exports the package's public names. A package can have bothentriesandexport.depslists third-party packages, each with a version constraint. A declared dependency is imported by its bare name, as inimport { decode } from "json". Importing a bare name thatdepsdoesn't declare is an error:unknown dependency "yaml". Fetching and installing dependencies is (planned): today, an import of a declared dependency fails withcannot resolve import "json".
The manifest has a few more keys, such as source, which narrows which files
belong to the package. The
manifest reference lists them all.
You don't need a manifest to start. A single file that imports only relative
paths and @ packages runs with vyi run main.vyi. Add package.vyipac when
you want named programs, a library file, or dependencies.
See also: the methods and dispatch reference and the manifest reference.