LEVIATHAN vd52e79c4 · d52e79c486

Declarations

const declarations

Fix a local, field, global, parameter or loop binding after its initializer, with the exact rules for each kind of slot.

since 0.1.0-alpha.1linuxwindowswasm

Description

const makes a slot read-only after its initialization. It applies to local variables, fields, namespace-level variables, parameters and loop bindings:

const int maxRedirs = 50;                    // local: fixed at declaration
const int limit = 100;                       // const always spells its type
const Array<string> args = std::sysArgs();   // namespace global: fixed at startup

class Session {
    public const string id = "s-1";          // field: a named compile-time constant
    const int SSL = 0x0800;
}

void handle(const Options o) { ... }         // parameter
for (const string a in args) { ... }         // per-iteration binding

const is not part of a type. It never appears where a type is expected and does not change assignability, overload selection or generics. It is also not transitive: const MyClass m = MyClass(); fixes the variable m, but the object it refers to can still change, so m.field = 5; is allowed. For deeply immutable data use a struct, a pure array or map, or a get-only accessor.

const bindings, fields, parameters and loops

use io::console;

const int maxRedirs = 50;
const int limit = 100;
const Array<string> names = ["a", "b"];
class Session {
    public const string id = "s-1";
    const int SSL = 0x0800;
}
class Opts { int level = 1; }
void handle(const Opts o) {
    o.level = 5;
    console.writeln(o.level);
}
console.writeln(maxRedirs);
console.writeln(limit);
console.writeln(Session().id);
console.writeln(Session().SSL);
const Opts shared = Opts();
shared.level = 3;
console.writeln(shared.level);
handle(shared);
for (const string n in names) {
    console.writeln(n);
}
int base = 7;
const int computed = base * 2;
console.writeln(computed);
50
100
s-1
2048
3
5
a
b
14

The objects behind shared and o are still mutable; only the variables are fixed.

Rules

Each slot has a window in which it may be written; after the window closes it is read-only.

  • Locals. The window is the declaration's initializer. const int x; without an initializer is a compile error, because the default value would be frozen forever. The initializer can be any expression.
  • Fields. A const field is a named compile-time constant. It must have an initializer, and the initializer must be a compile-time constant: a literal, None, an array of constants, another const value, or an arithmetic or bitwise operator over constants. No constructor may assign a const field. A field whose value is known only at construction time is readonly (lang.readonly).
  • Namespace and top-level variables. The window is the initializer, which can be any expression.
  • Parameters. The value bound by the call; assigning to a const parameter in the body is an error.
  • for (const T x in ...). Each iteration has its own fresh binding, which cannot be assigned.
  • Compound assignment (x += 1) is a write, like =. a[i] = v on a pure array is a write to the array variable and is rejected for a const array.
  • Calling a mutating method on a const struct variable is a compile error, and so is one through a struct field of it, an interface or optional-of-struct receiver, or a T bound to a struct. Through a const variable of a class type, or of an optional of one, the call writes the shared object (or, for None, does nothing), so it is allowed, as the field store mc.x = 5 always was: const C mc = C(); mc.bump();, const C? om = C(); om?.bump();, and a class field of a const struct (w.c.bump()). This changes behaviour for existing programs: those calls were rejected.
  • A store through a struct's set ([]) indexer is a member write, like a field store: c[0] = 7 or c[1] += 1 on a const struct c with a set ([]) accessor, and cs.bag[0] = 3 through a struct field, are compile errors (cannot assign to const 'c'). This changes behaviour for existing programs: the store compiled and changed the const value.
  • A struct's fields and a struct element of a pure array or map are part of the value the variable holds, so writing through them — p.x = 5 on a const struct p, ps[0].x = 5, ps[0].x += 1, ps[0].q.x = 5 or ps[0].bump() on a const array ps, m["k"].x = 5 on a const map — is a write to the const variable and is a compile error. A field of a struct reached through a class instance is not covered: the object stays mutable.
  • A set accessor cannot be declared over a const field, and a field cannot be both const and readonly.
  • If two bases declare a field with the same name and type, one const and one not, the class that inherits both is a compile error; resolve it with distinct or by restating the field in the derived class.
  • A const: label inside a class body declares a run of fields const, in the way public: and private: set access. The two are independent: public: after const: does not end the const run, and a member written var opts out of it.

Initialization order of globals

Every namespace-level and top-level variable is first created with its type's default value, before any initializer or statement runs, so an initializer always sees a valid variable. The exception is a variable of a class type that has an initializer. Only its initializer creates it, because constructing a default first would run a constructor twice. Reading it before its initializer has run raises a RuntimeException on every engine. An enum's members are constants, never subject to that rule: they are created before anything else, so an initializer that runs before the enum's declaration still reads the right member. The same holds for a variable whose initializer is just an enum member (Dir cur = Dir::South;). An enum-typed variable initialized any other way, such as by a call, follows the class rule. Then:

  1. The standard library's variables initialize.
  2. Namespace-level initializers and static fields (lang.static-members) run, in source order across the program's files, before the program body starts.
  3. Top-level variables' initializers run, in source order across the program's files. Every one of them runs before any top-level statement, whatever file or position either is written in.
  4. Top-level statements run, in source order across the program's files.

So a call such as main(); may be written anywhere, above the variables it reads or in another file, and sees them initialized. What follows from the order:

  • Initializers never reorder among themselves. An initializer that reads a variable whose initializer comes later in that order, directly or through a function it calls, sees that variable's default value. A namespace initializer therefore sees a top-level variable at its default value, not at the value its own initializer will assign later. A class-typed variable with an initializer has no default value. Such a read raises a RuntimeException ("global 'name' was read before its initializer ran") that the reading code can catch. Assigning the variable early does not count as running its initializer.
  • An initializer's side effects, such as output or mutations, happen before the first top-level statement, even one written above it. A throw that escapes a top-level or namespace initializer is reported as an uncaught exception (exit code 1) and no top-level statement runs.
  • Top-level initializers run in the same task as the top-level statements, so an initializer may await just as a top-level statement may.
  • Variables produced by macros, rules or comptime folding are ordinary declarations at the position their expansion occupies, and take that place in the order.
  • A top-level variable that must capture state produced by an earlier top-level statement is written as a declaration plus an assignment statement at that point (Array<int> snapshot; ... snapshot = xs;), not as an initializer.
  • The compiler warns about a top-level variable written below a top-level statement in its file when its initializer may perform a system effect, or reads state that an earlier top-level statement modified. An initializer may perform a system effect when something it calls, directly or through any function, method or lambda argument it passes, calls any system native, e.g. clock, console, files, sockets, random, environment, processes, timers, threads and channels. A statement modifies a top-level variable when it, or a function it calls, assigns the variable, writes a field or element through it, or calls a method on it that changes the object (a method that assigns the object's fields; collection and string methods never do). An assigned variable counts however the initializer reads it; a variable whose contents changed counts when the initializer reads through it (v.n, v[i], v.m()), directly or in a function it calls, or copies it when it holds a value (a number, string, struct or collection), not a class reference. An initializer that is only arithmetic, building collections, or constructing objects without such effects does not warn, and neither does a namespace-level variable:
warning: the initializer of 't1' runs before the top-level statement at line 2 (top-level initializers run first); declare 't1' and assign it after that statement to run it in order

Top-level statements

The top level of a file is the program body and accepts the usual statements: expressions, declarations, if, while, for, do-while, labeled loops, match, try/catch and throw. It does not accept break, continue or return, since there is no enclosing loop or function, nor using, which declares a resource binding for a block.

Examples

Namespace initializers run first and see top-level variables at their defaults:

Initialization order

use io::console;

int seedValue = 5;
namespace Reg {
    int fromTop = seedValue;
    int fixed = 3;
    int fromNs = fixed * 2;
}
console.writeln("start");
console.writeln(Reg::fromTop);
console.writeln(Reg::fromNs);
int later = seedValue + 1;
console.writeln(later);
start
0
6
6

Reg::fromTop is 0, not 5: the namespace initializer ran before the top-level initializer that sets seedValue.

Top-level initializers run before any top-level statement, so a statement may read a variable declared below it:

Initializers run before statements

use io::console;

console.writeln(greeting);
console.writeln(total);
string greeting = "hello";
int total = 2 + 3;
hello
5

A class-typed variable with an initializer cannot be read before that initializer runs:

Reading a class-typed global before its initializer

use io::console;

class Box { string tag = "box"; }
string peek() {
    try { return laterBox.tag; } catch (RuntimeException e) { return e.message; }
}
string early = peek();
Box laterBox = Box();
console.writeln(early);
console.writeln(laterBox.tag);
global 'laterBox' was read before its initializer ran
box

A const: section:

A const: section with a var opt-out

use io::console;

class Config {
const:
    string host = "localhost";
    int port = 8080;
public:
    string name = "svc";
    var int hits = 0;
    void hit() { hits = hits + 1; }
}
Config c = Config();
c.hit();
c.hit();
console.writeln(c.host);
console.writeln(c.port);
console.writeln(c.name);
console.writeln(c.hits);
localhost
8080
svc
2

name is const too, because public: does not end the const: run; only hits, marked var, can change.

Writes that are rejected at compile time:

Writing a const

const int x = 1;
x = 2;                                  // error: cannot assign to const 'x'
const int y;                            // error: needs an initializer
class C {
    const int n = 1;
    new C() { n = 2; }                  // error: cannot assign to const field 'n'
    const readonly int m = 1;           // error: a field cannot be both const and readonly
}
int f() => 3;
class D { const int k = f(); }          // error: needs a compile-time-constant initializer
not run — a compile error on purpose

A const field may be computed from other const fields:

A const field computed from other constants

use io::console;

class Flags {
    const int A = 1;
    const int B = 2;
    const int BOTH = A | B;
}
console.writeln(Flags().BOTH);
3

See also

  • readonly fields — Fix an instance field once, either in its initializer or in every constructor, and keep it read-only afterwards.
  • Fields — Declare the data a class or struct holds, with optional initializers, and how a field without an initializer gets its default value.
  • Value structs — Declare value types that are copied on every assignment, pass and return, with derived equality and explicit mutating methods.
  • Namespaces — Group declarations under a name, reopen a namespace to add to it, nest namespaces, and reach members with ::.