LEVIATHAN vd52e79c4 · d52e79c486

Declarations

Imports — uses and use

Every library, the standard library included, reaches a file only through an import: use for one name or a namespace, uses for all of a namespace's names.

since 0.1.0-alpha.1linuxwindowswasm

Description

A file can use three kinds of names without importing anything: the core language, the top-level declarations of its own package, and the namespaces its own package declares. Everything else reaches a file only through an import written in that file. That includes every library namespace, the standard library's (io, std, math, json, regex and the rest) as well as other packages'. Two statements import names:

use NS;                       // import the namespace itself; NS::name then works
use NS::name;                 // import ONE name: a value, function, class or namespace
use NS::name as alias;        // import it under another name
use A::B;                     // import a nested namespace itself; B::f() then works

uses NS;                      // import ALL of NS's names into the enclosing scope
uses A::B;                    // a nested path works the same way

use imports a single name, of any kind, and the optional as renames it, which avoids collisions with names you already have. uses imports every name of a namespace at once.

The console is the io library's, so a program that prints imports it:

Hello, imported

use io::console;

console.writeln("hello");
hello

Imports are resolved entirely at compile time. An alias is another name for the same declaration, not a copy, so assigning to an imported variable through its alias assigns the original variable.

Rules

  • Nothing is imported implicitly. A namespace that another package declares, the standard library's included, is visible in a file only when an import in scope brings it in, and that holds for its qualified form too: io::console needs use io; (or use io::console;, which imports console itself). An unknown name that a library declares is an error whose note names the import to add: for console, the note says to add use io::console;.
  • The core language is visible everywhere without an import: the standard library's top-level types, which are the primitive types (int, byte, int8, int16, int32, uint, float, float8, float16, float32, decimal, bool, char and Ptr), string, Array, OrderedArray, Map, Set, Pair, Triple, the iterator interfaces (IIterator, IIterable), Seq, Range, the stream types (InStream, OutStream, IOStream), StringBuilder, Block, RoundingMode, the exception hierarchy (IException, Exception, RuntimeException, LogicException, CancelledException, ContractViolation with its ContractKind and ContractOperand, and their interfaces IRuntimeException, ILogicException and ICancelledException), IDisposable and Promise. (The standard library's internal helper types are not part of it.)
    • A program's top-level type declaration with one of these names (a class, a struct, an interface, an enum or a use ... as alias) is a compile error: 'Range' is part of the core language (the standard library's top-level type); rename this declaration, or declare it inside a namespace of another name. A top-level namespace of one of these names is the same error. Inside a namespace such a type, or such a nested namespace, is an ordinary one (lang.namespaces). A top-level variable or function of one of these names is not a type and stays legal, and so is a type parameter (class Holder<Array>).
    • A primitive type's name names no type declaration in any scope, a namespace's included: no class, struct, interface, enum, type parameter, namespace or use ... as alias (lang.primitives).
  • A package's top-level declarations and namespaces are visible in all of its own files and in no other package's. Another package's namespaces are imported like the standard library's; its top-level declarations are private to it, so a package shares code through namespaces.
  • An import is a declaration in the scope where it is written, and that scope is whatever block, function body or file contains it. An import written at the top of a file is visible in that file only, not in the rest of the program.
  • Imports are hoisted: an import is visible throughout its whole scope, including statements that come before it.
  • A declaration in a scope hides an imported name of the same spelling that arrives from a wider scope or from the same scope. In particular, a nearer use hides a farther use, and a function declared in a scope hides an import of the same name in that scope.
  • The imports written at the top of a file are in the same scope as the program's top-level declarations, and the top levels of all the files of one package are one scope. So a top-level variable, class, struct, enum, interface or namespace, declared in any file of the package, hides a same-named name that a top-of-file uses or use brings in, and a bare read of the name always reaches the declaration, at run time and in comptime code alike. When both the declaration and the imported names are functions, the imported functions stay overloads of the declared one, and the declared one wins a call that both match equally well.
  • That hiding stops at the package boundary. A top-level declaration of one package (the application, or a dependency) never hides a name that a top-of-file uses or use brings into a file of another package: in a dependency's file with uses Util;, a bare scale reads Util::scale even when the application declares its own top-level scale, at run time and in comptime code alike.
  • One name, one declaration per scope, of any kind. Within the top level of a package, the body of one namespace (all of its blocks, in every package that declares one), or one block, a second declaration of a name already declared there is a compile error at the second one that names the first: 'Count' is already declared in this scope as a class at 8:1; rename one. This holds for every pair of kinds: two classes, a class and a variable, two variables, a class and a function, a function and a variable, a class and a namespace, a namespace and a variable. A set of function overloads is not a redeclaration, and neither is another block of the same namespace. A local in a nested block, or in a second loop, is in another scope.
  • A bare name is looked up among the declarations that can stand where it is written; among those, the nearest wins, the program's layer before the standard library's. A declaration hides an import of its name the same way, where both can stand: a top-level variable does not hide an imported namespace of its name.
    • In a value position, a variable, a function or a type can stand; a type there is the "is a type, not a value" error. So a call Box(1) under a local int Box calls the local ('Box' is not callable (it is 'int')), never the class's constructor.
    • On the left of ::, in a base qualifier, in a type position and at the root of use and uses, only a namespace or a type can stand (lang.member-access), so a variable or a function is no candidate there and hides nothing. Under a local int Box, Box b declares a Box and Box::make() calls its static; under a local Holder geo, geo::f() calls the namespace's f. The same holds under a global or a namespace's variable: inside a namespace that declares int geo, geo::k reads the namespace geo's k. Where only a variable of the name exists, x::m is a compile error: 'c' is a variable, not a namespace or type; write the type's name, or c.i for a static through an instance. A static reached through an instance is spelled with . (lang.static-members).
    • So under a top-level variable signal, use signal;, uses signal; and use signal::INT; reach the namespace, and signal::TERM reads it; a bare signal in a value position is still the variable. A single-segment use of a type aliases it: use int as Count;, or use Shape as Quad; for a program class.
    • A class is always reached by its full path as well (Shapes::Box).
  • The standard library is an outer scope of every program, at every path. A program declaration hides a standard-library name and never clashes with it: a top-level variable named like a library namespace (string json, Promise<void> signal), a class named like a built-in type inside a namespace (namespace geo { class Range { ... } }; a top-level one is the core language's, above), or a declaration in a program block of a library namespace (namespace std { class TcpStream { ... } }, namespace regex { int apiCache = 7; }). The program's code reaches its own declaration; the standard library's code keeps its own (lang.standard-library).
    • A program variable at a library variable's path is another variable, with storage of its own, so library code never reads or writes it.
    • A program class that hides a library class is a different class, so passing the program's std::TcpStream where a library function takes its own is a type error. The message says which is which: "the 'TcpStream' given is the class declared at app.lev:8:17, and the one expected is the prelude's 'std::TcpStream'".
    • A literal is always the library's type: a range 1..3 is the library's Range, and an array literal its Array. Where a program class Range is in scope, Range r = 1..3; is a type error; a for over 1..3 still runs. Every built-in feature compares the standard library's own types, never their names: literals, the collection verbs, for-in, throw and catch, using, await and is.
    • The lookup rule above applies inside a program block of a library namespace too. A bare Range there is the program's top-level Range. A bare sum is std::sum, because the enclosing namespace is nearer than the top level.
  • Within one scope, use beats uses: a name imported by use wins over the same name brought in by uses.
  • An alias names the same declaration, so writing through an alias writes the original variable. Writing through the alias of a const variable is the same compile error as writing the const directly.
  • use can import any kind of declaration: a variable, a function, a class, an interface or a nested namespace.
  • use of a class or interface type can also activate a dependency-injection binding that the type's namespace exports; see lang.bind-activation. uses never activates a binding.

Examples

A use in a nearer scope wins over a uses in the same scope, and an import in a function body is visible only inside that function:

Specific beats bulk, and scoping

use io::console;

namespace Shop {
    int price(int base) => base + 1;
}
namespace Other {
    int price(int base) => base * 2;
}
uses Shop;
void bulk() {
    uses Other;
    use Shop::price;
    console.writeln(price(100));
}
void nearer() {
    use Other::price;
    console.writeln(price(100));
}
bulk();
nearer();
console.writeln(price(100));
101
200
101

In bulk, uses Other and use Shop::price both supply price, and the specific use wins. In nearer, the function's own use hides the file-level uses Shop. Outside both functions only uses Shop is in scope.

A top-level declaration hides the import of the same name, so the imported one is reached by its qualified path:

A top-level declaration hides an import

use io::console;

namespace Shop {
    const int tax = 8;
    class Cart {
        int items() => 3;
    }
}
const int tax = 20;
class Cart {
    int items() => 1;
}
uses Shop;
comptime int folded = tax;
console.writeln(tax);
console.writeln(folded);
console.writeln(Cart().items());
console.writeln(Shop::tax);
console.writeln(Shop::Cart().items());
20
20
1
8
3

An alias is the same variable under another name:

Writing through an alias

use io::console;

namespace Cfg {
    int hits = 0;
}
use Cfg::hits as h;
h = 50;
h += 1;
console.writeln(Cfg::hits);
51

An import is visible in its own file only:

File scope of an import

// file a.lev

use io::console;

namespace NS { int v() => 7; }
uses NS;
int fromA() => v();      // fine: the import is in this file

// file b.lev
console.writeln(fromA());
console.writeln(v());    // error: unknown function 'v'; b.lev has no import
not run — needs a project of two source files

Notes

An import is a compile-time rename, so it costs nothing at run time.

See also

  • Namespaces — Group declarations under a name, reopen a namespace to add to it, nest namespaces, and reach members with ::.