MoxyMoxy
Docs contents

Diagnostics

Moxy checks your program before any C is generated, and reports problems like this:

error[E0805]: match is not exhaustive; missing Color::Blue
  --> src/main.mxy:4:5
   |
 4 |     match c {
   |     ^^^^^
  = help: add the missing arms or a '_ =>' arm
  • error stops compilation with exit code 1. A syntax error stops at the first one; type errors are all reported, followed by a count.
  • warning is printed and compilation continues.
  • note points at a related location, such as the first definition of a duplicate.
  • help lines suggest a fix.

The path is relative to the current directory, and errors inside included files name that file and its line. Colors are used when stderr is a terminal (set NO_COLOR to disable them).

Codes. Every error and warning has a stable code in brackets: E for errors, W for warnings, then four digits grouped by phase (the table below). A code names one mistake, whatever the exact wording of its message, and is never given to a different one; it is safe to search for, link to and match on in tools. moxy explain E0805 prints the code's entry from this page, and moxy explain --list lists them all. The language server reports the code with each diagnostic.

Codes Phase
E00xx input files and compiler limits
E01xx lexing
E02xx syntax
E03xx declarations and types
E04xx expressions, optionals and slices
E05xx calls and methods
E06xx interfaces, generics, enums and Result
E07xx compile-time reflection
E08xx match, patterns and control flow
E09xx memory, ownership and gates
E10xx threads, channels, actors and parallel loops
W01xx lint warnings (moxy lint)
W02xx other warnings

Internal compiler errors. A crash inside the compiler is reported as error: internal compiler error: ... with the location it was working on, and exits with code 70. That is a bug in Moxy, not in your program; please report it with the code that triggers it.

Errors from the C compiler. Names Moxy doesn't know are assumed to come from C headers. When one of them is wrong (a misspelled C function, a wrong argument to a C API), the C compiler reports it. The generated code carries #line directives, so those messages also point at your .mxy file and line. These have no Moxy code.

Runtime errors. Bounds and key checks happen at run time and stop the program with a panic (exit code 101). A failed assert exits with code 1. See Runtime panics.

In the messages below, <name>, <type> and <n> stand for the actual values. Types are written in Moxy syntax: int[], map[string, int], Result<int>, Result<int, ParseError>, Node?, fn(int) -> int. Each entry shows a program that gets the diagnostic and the same program fixed.

Input files

E0001

cannot find '<file>'

An #include of a .mxy file names a file that doesn't exist. The compiler looks next to the including file, in the include paths and dependencies, and in the standard library. A file never resolves to itself.

#include "helpers.mxy"

void main() {}

Fix the path, or add the directory that holds the file to the include paths. Standard library files are found by their std/ path:

#include "std/cycles.mxy"

void main() {}

E0002

cannot read '<file>'

The file exists but couldn't be read, usually because its permissions deny it. The same error is reported when the file named on the command line can't be opened, including when it doesn't exist. This can't be shown from a single source file:

chmod 000 helpers.mxy
moxy build main.mxy    # main.mxy has #include "helpers.mxy"

Make the file readable, or check the path given to moxy:

chmod 644 helpers.mxy
moxy build main.mxy

E0003

this code is nested too deeply to compile

An expression or block is nested so deeply (parentheses, brackets, braces, or a very long chain of operators) that the compiler ran out of stack while reading or checking it. This happens with machine-generated code, at depths in the tens of thousands; the location is the innermost construct reached.

int x = ((((((((((((((((((((/* ...thousands more... */ 1 /* ... */))))))))))))))))))));

Split the expression or block into smaller pieces, such as local variables or helper functions:

int a = (1 + 2) * 3;
int x = (a + 4) * 5;

If the code isn't deeply nested, the compiler is at fault: report it.

Lexing

E0101

unterminated block comment

A /* comment has no closing */ before the end of the file, so everything after it would be commented out.

void main() {
    int x = 1; /* the count
    print(x);
}

Close the comment with */:

void main() {
    int x = 1; /* the count */
    print(x);
}

E0102

unterminated string literal

A string literal has no closing " before the end of its line. String literals can't span lines.

void main() {
    string s = "hello;
}

Close the string on the same line. For text over several lines, use \n escapes or adjacent literals, which are joined:

void main() {
    string s = "hello";
    string t = "one\n"
               "two\n";
}

E0103

unterminated character literal

A character literal has no closing ' on its line.

void main() {
    char c = 'a;
}

Close the literal with ':

void main() {
    char c = 'a';
}

E0104

unexpected character '<c>'

The source holds a character that isn't part of the language, outside a string, character literal or comment. A stray Unicode character pasted from elsewhere is a common cause.

void main() {
    int x = 1 ` 2;
}

Remove the character or replace it with the operator you meant:

void main() {
    int x = 1 + 2;
}

Syntax

Unsupported C extensions such as __attribute__((...)) on a declaration also show up as syntax errors; see C syntax Moxy doesn't parse for workarounds.

A ; can be left off an expression statement when the next token starts a new line. Declarations always need their ;.

E0201

unterminated actor <name>

The file ends inside an actor's body: its closing } is missing.

actor Counter {
    int n;

Close the actor with }:

actor Counter {
    int n;
}

E0202

an actor's body can't hold preprocessor directives

A directive such as #ifdef appears between an actor's fields and methods. An actor becomes a struct plus its methods, so a directive inside it has no single place to go.

actor Counter {
    int n;
#ifdef DEBUG
    void dump() { print(self.n); }
#endif
}

Move the directive outside the actor, or decide inside the method body at run time:

actor Counter {
    int n;
    void dump() { print(self.n); }
}

E0203

an actor holds fields and methods

A declaration in an actor's body is neither a plain field nor a method. A field can't have an initializer; fields start zeroed when the actor is made.

actor Counter {
    int n;
    int steps[] = {1, 2};
    void bump() { self.n++; }
}

Declare the field without an initializer and set it in a method, or use a local inside the method:

actor Counter {
    int n;
    int step;
    void bump() { self.n += self.step; }
}

E0204

expected a parameter type, expected a type, expected a field declaration

A type was required here, but the next token doesn't start one. Every parameter and field is declared as a type followed by a name.

int add(int a, 5) { return a; }

Give the parameter a type and a name:

int add(int a, int b) { return a + b; }

E0205

expected a function call after '|>'

The right side of a pipe must be a call, a function name or a member. x |> f() calls f(x).

int twice(int x) { return x * 2; }

void main() {
    int y = 3 |> 4;
}

Pipe into a function:

int twice(int x) { return x * 2; }

void main() {
    int y = 3 |> twice();
}

E0206

lambda parameters need names

A lambda's parameter list has a type without a name. The body can't refer to an unnamed parameter.

void main() {
    auto f = (int) => 1;
}

Name each parameter:

void main() {
    auto f = (int x) => x + 1;
}

E0208

unexpected <token> in interpolation

The part inside \( ... ) is more than one expression. Each interpolation holds exactly one.

void main() {
    int a = 1;
    int b = 2;
    string s = "\(a b)";
}

Interpolate each value on its own:

void main() {
    int a = 1;
    int b = 2;
    string s = "\(a) \(b)";
}

E0209

unexpected end of file in expression

The file ends in the middle of an expression.

void main() {
    int x = 1 +

Finish the expression and the rest of the function:

void main() {
    int x = 1 + 2;
}

E0210

unexpected '<token>' in expression

An expression was expected, but the next token can't start one.

void main() {
    int x = ;
}

Give the expression, or leave the declaration without an initializer:

void main() {
    int x = 0;
}

E0211

expected a field or method name after '?.', expected a field or method name after '<operator>'

A member access operator (., -> or ?.) isn't followed by a name.

struct Point { int x; int y; }

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    int n = p.;
}

Name the field or method:

struct Point { int x; int y; }

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    int n = p.x;
}

E0212

a type-argument list needs at least one type

A generic type is used with an empty <>. A generic type needs a type for each of its parameters.

struct Box<T> { T value; }

void main() {
    Box<> b;
}

Give the type argument:

struct Box<T> { T value; }

void main() {
    Box<int> b;
}

E0213

type parameter '<name>' is declared twice

The same name appears twice in one type-parameter list, so uses of it would be ambiguous.

struct Pair<T, T> { T a; T b; }

Give each type parameter its own name:

struct Pair<A, B> { A a; B b; }

E0214

methods can't have their own type parameters yet

A method in an impl block, interface or actor declares type parameters of its own. Only the type itself can be generic for now.

struct P { int x; }

impl P {
    T pick<T>(T a) { return a; }
}

Make it a free generic function, or make the type generic:

struct P { int x; }

T pick<T>(P p, T a) { return a; }

E0215

method '<name>' needs a body

A method in an impl block or actor is declared without a body. Only an interface lists methods without bodies.

struct Point { int x; int y; }

impl Point {
    int sum();
}

Give the method a body:

struct Point { int x; int y; }

impl Point {
    int sum() { return self.x + self.y; }
}

E0216

unterminated <kind> block

The file ends inside an impl block or an interface: its closing } is missing.

struct Point { int x; int y; }

impl Point {
    int sum() { return self.x + self.y; }

Close the block with }:

struct Point { int x; int y; }

impl Point {
    int sum() { return self.x + self.y; }
}

E0217

an interface holds method declarations only

An interface declares something other than a method. Interfaces describe behavior; data belongs in the types that implement them.

interface Named {
    string name();
    int id;
}

Declare an accessor method instead of the field:

interface Named {
    string name();
    int id();
}

E0218

an impl block holds methods only; fields belong in the type

An impl block declares a field. Fields are part of the type's definition.

struct Point { int x; int y; }

impl Point {
    int z;
    int sum() { return self.x + self.y; }
}

Move the field into the struct:

struct Point { int x; int y; int z; }

impl Point {
    int sum() { return self.x + self.y; }
}

E0219

expected 'in' in static for

A static for loop is written static for name in list { ... }, and the word after the loop variable isn't in.

struct Point { int x; int y; }

void show<T>(T v) {
    static for f of T.fields {
        print(f.name);
    }
}

Use in:

struct Point { int x; int y; }

void show<T>(T v) {
    static for f in T.fields {
        print(f.name);
    }
}

E0220

a select arm is c.recv(), v = c.recv(), c.send(value), timeout(ms) or default

An arm of a select isn't one of the forms select waits on. Each arm is a channel receive, a send, a timeout or default.

void main() {
    chan<int> c = chan<int>(1);
    select {
        print("x") => print("y"),
    }
}

Wait on a channel operation, and do the work in the arm's body:

void main() {
    chan<int> c = chan<int>(1);
    select {
        c.send(1) => print("y"),
    }
}

E0221

only a receive binds a value: v = c.recv()

A select arm binds a name to a send. A send produces no value; only v = c.recv() binds one.

void main() {
    chan<int> c = chan<int>(1);
    select {
        v = c.send(1) => print("sent"),
    }
}

Drop the binding:

void main() {
    chan<int> c = chan<int>(1);
    select {
        c.send(1) => print("sent"),
    }
}

E0222

unclosed select

The file ends inside a select block: its closing } is missing.

void main() {
    chan<int> c = chan<int>(1);
    select {
        c.send(1) => print("sent"),

Close the select and the function:

void main() {
    chan<int> c = chan<int>(1);
    select {
        c.send(1) => print("sent"),
    }
}

E0223

'..=' needs an end: a[i..=j]

An inclusive slice a[i..=j] has no end index. ..= includes its end, so the end can't be left out.

void main() {
    int[] xs = [1, 2, 3];
    int[..] s = xs[1..=];
}

Give the end, or use .. to slice to the end of the list:

void main() {
    int[] xs = [1, 2, 3];
    int[..] s = xs[1..=2];
}

E0224

expected <thing>, found <token>

The general parse error: the parser needed a specific token here and found another. The most common case is a missing ;, which is reported just after the previous token.

void main() {
    int x = 1
    print(x);
}

Add the missing token:

void main() {
    int x = 1;
    print(x);
}

E0225

unclosed '{' — reached end of file

The file ends inside a block: a { has no matching }. The error points at the { left open.

void main() {
    int x = 1;

Close the block:

void main() {
    int x = 1;
}

E0226

expected 'in' in for-in loop

A for-in loop is written for x in xs { ... }, and the word after the loop variable isn't in.

void main() {
    int[] xs = [1, 2, 3];
    for x of xs {
        print(x);
    }
}

Use in:

void main() {
    int[] xs = [1, 2, 3];
    for x in xs {
        print(x);
    }
}

E0227

unclosed match

The file ends inside a match block: its closing } is missing.

enum Shape { Circle(double r), Square(double s) }

void main() {
    Shape s = Shape::Circle(1.0);
    match s {
        Circle(r) => print(r),

Close the match and the function:

enum Shape { Circle(double r), Square(double s) }

void main() {
    Shape s = Shape::Circle(1.0);
    match s {
        Circle(r) => print(r),
        Square(x) => print(x),
    }
}

E0228

parallel for needs a range: parallel for i in 0..n { ... }

parallel for splits a range across threads, so it takes the for-in form over a range. A C-style loop has no range to split.

void main() {
    parallel for (int i = 0; i < 10; i++) {
        print(i);
    }
}

Loop over a range:

void main() {
    parallel for i in 0..10 {
        print(i);
    }
}

E0229

a test name is a plain string, without interpolation

A test block's name contains \( ... ). Test names are fixed when the program is compiled, so they can't depend on values.

int n = 1;

test "case \(n)" {
    assert(n == 1);
}

Write the name out:

int n = 1;

test "case 1" {
    assert(n == 1);
}

E0230

expected a declaration

Something at file level isn't a declaration, function or directive. Statements belong inside functions.

int x = 1;
return x;

Move the statement into a function:

int x = 1;

int get() {
    return x;
}

E0231

expected a name in declaration, found '<token>'

A declaration has a type but no name. A reserved word used as a name causes this too.

int = 5;

Name the variable:

int count = 5;

E0232

'async' marks a function: async T name(...) { ... }, 'async' marks a function, not a parameter, 'async' marks a function, not a field

async appears before a variable, typedef, parameter or field. It only marks functions, which then return a Future.

async int count = 0;

void main() {}

Remove async, or put it on the function that should run asynchronously:

int count = 0;

void main() {}

E0233

functions cannot be defined inside other functions

A function is defined inside another function's body. Moxy, like C, has no nested functions.

void main() {
    int twice(int x) { return x * 2; }
    print(twice(2));
}

Use a lambda, or move the function to file level:

void main() {
    auto twice = (int x) => x * 2;
    print(twice(2));
}

E0234

'auto' declarations need an initializer

An auto variable takes its type from its initializer, so it can't be declared without one.

void main() {
    auto x;
}

Give it an initializer, or write the type:

void main() {
    auto x = 0;
}

E0235

#<directive> without #if, #endif without #if

An #else, #elif or #endif has no open #if, #ifdef or #ifndef before it.

int x = 1;
#endif

Remove the stray directive, or add the #if it should close:

#ifdef DEBUG
int x = 1;
#endif

E0236

unterminated #if block

An #if, #ifdef or #ifndef has no matching #endif before the end of the file.

#if 1
int x = 1;

Close the block with #endif:

#if 1
int x = 1;
#endif

E0237

expected a name or '{' after '<keyword>'

A struct, union or enum keyword is followed by neither a tag name nor a body.

struct;

Give the type a name and a body:

struct Point { int x; int y; };

E0238

'<type>' is not generic; it takes no type arguments

Type arguments are given to a type that has no type parameters.

struct Point { int x; int y; }

void main() {
    Point<int> p;
}

Drop the type arguments, or make the type generic:

struct Point { int x; int y; }

void main() {
    Point p;
}

Declarations and types

E0301

'atomic' is only allowed on struct fields, '<qualifier>' is only allowed on struct fields

The qualifiers atomic, weak, unowned and strong describe how a struct field is stored and shared. On a global, a local or a parameter they have no meaning.

atomic int hits = 0;

void main() {
    print(hits);
}

Put the value in a field. An atomic field belongs in a shared ref struct, which threads can share:

shared ref struct Stats {
    atomic int hits;
}

void main() {
    Stats s = Stats{ .hits = 0 };
    print(s.hits);
}

E0302

<type> does not implement <interface>

A generic was given a type argument that doesn't meet one of its bounds. Here area_of needs T: Shape, and Square has no impl Shape.

interface Shape { double area(); }

struct Square { double side; }

double area_of<T: Shape>(T x) { return x.area(); }

void main() {
    print(area_of(Square{ 2 }));
}

Implement the interface for the type, or drop the bound if the generic doesn't need it:

interface Shape { double area(); }

struct Square { double side; }

impl Shape for Square {
    double area() { return self.side * self.side; }
}

double area_of<T: Shape>(T x) { return x.area(); }

void main() {
    print(area_of(Square{ 2 }));
}

E0303

'<name>' is already declared

Two different kinds of declaration, such as a global and a function, or a type and a function, share one name in the same namespace. Moxy has one namespace for these, as C does.

int count = 0;

int count() { return 1; }

void main() {
    print(count);
}

Rename one of them:

int count = 0;

int next_count() { return count + 1; }

void main() {
    print(next_count());
}

E0304

function '<name>': names starting with mxy_ are reserved, global '<name>': names starting with mxy_ are reserved

The runtime owns the mxy_ prefix, so a program can't define or declare a function or global with it, or put one in a namespace whose name starts with it. extern declarations of runtime functions and globals are allowed.

int mxy_twice(int x) { return x * 2; }

void main() {
    print(mxy_twice(2));
}

Pick a name without the prefix:

int twice(int x) { return x * 2; }

void main() {
    print(twice(2));
}

E0305

function '<name>' is defined twice

Two bodies are given for the same function. A note points at the first one. Definitions in different #if branches are allowed, since only one is compiled.

int twice(int x) { return x * 2; }

int twice(int x) { return x + x; }

void main() {
    print(twice(2));
}

Keep one definition. Prototypes without a body can repeat freely:

int twice(int x) { return x * 2; }

void main() {
    print(twice(2));
}

E0306

global '<name>' is defined twice

The same global has two initialized definitions, so it is unclear which value it starts with.

int limit = 10;
int limit = 20;

void main() {
    print(limit);
}

Initialize it once. Other declarations of it can be extern and carry no initializer:

extern int limit;
int limit = 20;

void main() {
    print(limit);
}

E0307

unknown namespace '<name>'

using names something that isn't a namespace, often a misspelling.

namespace geo {
    double area(double w, double h) { return w * h; }
}

using geom;

void main() {
    print(area(2, 3));
}

Name a namespace the program declares:

namespace geo {
    double area(double w, double h) { return w * h; }
}

using geo;

void main() {
    print(area(2, 3));
}

E0308

<qualifier> fields must hold a ref struct

weak, unowned and strong qualify references to heap objects, and only a ref struct is one. A plain struct is stored by value, so there is no reference to qualify.

struct Point { int x; int y; }

ref struct Marker {
    weak Point? at;
}

void main() {}

Make the held type a ref struct, or drop the qualifier and store the value:

ref struct Point { int x; int y; }

ref struct Marker {
    weak Point? at;
}

void main() {}

E0309

unowned fields are only allowed in ref structs

unowned is a field qualifier for ref struct holders only. A plain struct, which is copied by value, can hold the object with a weak or an ordinary strong field.

ref struct Account { string name; }

struct Card {
    unowned Account owner;
}

void main() {}

Make the holder a ref struct, or use a weak field if it must stay a plain struct:

ref struct Account { string name; }

ref struct Card {
    unowned Account owner;
}

void main() {}

E0310

struct '<name>' cannot contain itself

A struct has a field of its own type by value, which would make its size infinite.

struct Node {
    int value;
    Node next;
}

void main() {}

Hold the next value through a reference: a ref struct with an optional field, or a pointer:

ref struct Node {
    int value;
    Node? next;
}

void main() {}

E0311

unions cannot hold managed values like strings, lists or maps

Managed values are reference counted, and a union can't know which member is live, so it can't release the right one.

union Value {
    int i;
    string s;
};

void main() {}

Use a Moxy enum with payloads, which records the active case:

enum Value {
    Int(int i),
    Str(string s)
}

void main() {}

E0312

ref unions are not supported

A union was declared over a type first declared as a ref struct, as with a forward ref struct declaration followed by a union body. A union can't be a reference-counted heap object.

ref struct Value;

union Value {
    int i;
    double d;
};

void main() {}

Declare it as a plain union throughout, or make it a ref struct:

union Value;

union Value {
    int i;
    double d;
};

void main() {}

E0313

main must return void or int

main's return value becomes the process exit status, so it must be void (exit 0) or int.

string main() {
    return "done";
}

Return int or void, and print anything else:

int main() {
    return 0;
}

E0314

main takes no parameters, (string[] args), or (int argc, char **argv)

main is called by the runtime with the command line, so it can only take one of these shapes.

void main(int verbose) {
    print(verbose);
}

Take the arguments as a string[] and parse what you need from them:

void main(string[] args) {
    print(args.len);
}

E0315

cannot infer a type for '<name>', cannot infer a type from null

auto takes its type from the initializer, and null (or a void call, for a global) has no type of its own to give.

void main() {
    auto name = null;
}

Write the type, as an optional if it can be null:

void main() {
    string? name = null;
}

E0316

variables cannot have type void, cannot store a void value

A variable was declared void, or initialized from a call that returns nothing. There is no value to store.

void greet() { print("hi"); }

void main() {
    auto r = greet();
}

Call the function as a statement, or make it return a value:

void greet() { print("hi"); }

void main() {
    greet();
}

E0317

unknown type '<name>'

A namespaced type name doesn't resolve, usually because the namespace is misspelled. Plain unknown names are left to C, but a :: name must be a Moxy type.

namespace geo {
    struct Point { int x; int y; }
}

void main() {
    geom::Point p;
}

Use the namespace that declares the type:

namespace geo {
    struct Point { int x; int y; }
}

void main() {
    geo::Point p;
}

E0318

<method>() takes 1 argument, got <n>

The integer methods wrapping_*, saturating_* and checked_* combine the receiver with one other operand.

void main() {
    int x = 5;
    print(x.wrapping_add(1, 2));
}

Pass one argument, and chain calls for more:

void main() {
    int x = 5;
    print(x.wrapping_add(1));
}

E0319

typedef '<name>' refers to itself

Typedefs form a cycle, directly or through other typedefs, so none of them reaches a real type.

typedef Celsius Temp;
typedef Temp Celsius;

void main() {
    Temp t = 0;
}

End the chain at a real type:

typedef double Celsius;
typedef Celsius Temp;

void main() {
    Temp t = 0;
}

E0320

'<name>' is generic; give its type arguments, as in <name><<params>>

A generic struct or enum was named as a type without type arguments. Each instance is a separate type, so the arguments are required.

struct Pair<A, B> { A first; B second; }

void main() {
    Pair p;
}

Give the type arguments:

struct Pair<A, B> { A first; B second; }

void main() {
    Pair<int, string> p;
}

E0321

generic structs are declared on their own at the top level

A struct with type parameters was declared inside a function body or another declaration. Generic structs are instantiated program-wide, so they must be top-level declarations.

void main() {
    struct Box<T> { T value; };
}

Move the declaration to the top level:

struct Box<T> { T value; }

void main() {
    Box<int> b;
}

E0322

redefinition of <struct or union> '<name>'

Two bodies are given for the same struct or union tag. Definitions in different #if branches are allowed.

struct Point { int x; int y; };
struct Point { double x; double y; };

void main() {}

Keep one definition, or rename the second type:

struct Point { int x; int y; };
struct PointF { double x; double y; };

void main() {}

E0323

array size must be a constant expression

A C array's size is fixed when it is compiled, and the size given is computed at run time.

int size() { return 4; }

void main() {
    int buf[size()];
}

Use a constant size, or a list (T[]), which grows as needed:

int size() { return 4; }

void main() {
    int buf[4];
    int[] items = [];
}

E0324

a Result's error type can't be void

A Result<T, E> carries an E when it fails, and void carries nothing.

Result<int, void> parse(string s) {
    return Ok(1);
}

void main() {}

Give an error type, or write Result<T>, whose error is a string. A function that can fail with no detail can return T? instead:

Result<int, string> parse(string s) {
    return Ok(1);
}

void main() {}

E0325

void can't be optional, a C array can't be optional; use a list (T[]) instead

An optional holds a value or null. void has no value, and a C array can't be stored or assigned as one.

void? log(string s) {
    print(s);
}

void main() {}

Drop the ? from void. For an optional sequence, use a list, as in int[]?:

void log(string s) {
    print(s);
}

void main() {}

E0326

a channel carries values; chan<void> has none

A channel moves values between tasks, and void has none to send.

void main() {
    chan<void> done = chan<void>();
}

To signal without data, send a small value such as a bool:

void main() {
    chan<bool> done = chan<bool>();
}

E0327

field '<name>' is declared twice

Two fields of one struct have the same name, so a read of that name could mean either.

struct Shape {
    int kind;
    double size;
    int kind;
}
void main() {}

Rename or remove one of them:

struct Shape {
    int kind;
    double size;
}
void main() {}

E0328

this field needs a name

A field with a type but no name is only allowed for a struct or union defined in place, whose fields are then read as if they were the outer struct's (an anonymous member). A named type there declares nothing C can use.

struct Point {
    int x;
}
struct Labeled {
    Point;
    int label;
}
void main() {}

Name the field, or define the struct in place:

struct Point {
    int x;
}
struct Labeled {
    Point at;
    int label;
}
void main() {}

E0329

a function cannot return a function, a function cannot return a C array

C has no values of function or array type to return. The declarator int count()() declares a function that returns a function.

int count()() { return 0; }
void main() {}

Return a function pointer, a closure or a list instead:

int[] firsts() { return [1, 2, 3]; }
void main() {}

E0330

'<name>' takes <n> parameters here but <m> in another #if branch

A function can be defined once in each branch of an #if, for different platforms. The branches share one declaration, so the parameter types may differ but their number can't.

#ifdef _WIN32
bool aborted(int e) { return e == 1; }
#else
bool aborted() { return false; }
#endif
void main() {}

Give every branch the same parameters, and ignore the ones a branch doesn't need:

#ifdef _WIN32
bool aborted(int e) { return e == 1; }
#else
bool aborted(int e) { return false; }
#endif
void main() {}

E0331

'<name>' is ambiguous: it could be <candidates>

using ns; makes the namespace's names visible as if they were declared where the using is. When one of them has the same name as a name declared there, or as one another using brings in, code after the using can't tell which is meant, so naming it is an error rather than a silent pick. Code before the using, such as a library included ahead of it, keeps its own names, and so does the standard library wherever it is included; a static function or global in another file is never a candidate. Each candidate is listed with where it's declared.

enum Align { Left, Right, Center }

namespace ui {
    enum Align { Start, Center, End }
}

using ui;

void main() {
    ui::Align a = Align::Center;
    print((int)a);
}

Name the one you mean with its namespace:

enum Align { Left, Right, Center }

namespace ui {
    enum Align { Start, Center, End }
}

using ui;

void main() {
    ui::Align a = ui::Align::Center;
    print((int)a);
}

Expressions, optionals and slices

E0401

<context>: this lambda captures '<name>' and cannot become a plain C function pointer

A lambda passed where a C function pointer is expected uses a local variable from the enclosing function. A C function pointer is a bare address with nowhere to keep the captured value.

int apply(int x, int f(int)) { return f(x); }

void main() {
    int k = 3;
    print(apply(1, (int x) => x + k));
}

Declare the parameter as a closure type, which carries its captures:

int apply(int x, fn(int) -> int f) { return f(x); }

void main() {
    int k = 3;
    print(apply(1, (int x) => x + k));
}

E0402

<context>: cannot use a C value of unknown type as <type>

The value comes from a C function Moxy has no declaration for, so its type is unknown. A plain C value can pass through unchecked, but it can't become a list, map or other managed value.

void main() {
    int[] xs = c_values();
    print(xs);
}

Declare the function with a prototype so Moxy knows what it returns:

extern int[] c_values(void);

void main() {
    int[] xs = c_values();
    print(xs);
}

E0403

<context>: expected <type>, found <type>

A value of the wrong type is used in an initializer, assignment, argument, return or element. The context at the start of the message says which.

void main() {
    int n = "five";
    print(n);
}

Use a value of the declared type, or convert it explicitly:

void main() {
    int n = 5;
    print(n);
}

E0404

cannot modify '<name>' inside a lambda; captured values are copies

A lambda receives a copy of each variable it captures, so assigning to one would change nothing outside the lambda.

void main() {
    int count = 0;
    fn(int) -> int add = (int x) => {
        count = count + x;
        return count;
    };
    print(add(2));
}

Copy the value into a local inside the lambda, or pass it in as a parameter:

void main() {
    int count = 0;
    fn(int, int) -> int add = (int total, int x) => total + x;
    count = add(count, 2);
    print(count);
}

E0405

a void value cannot be used as a condition, a <kind> cannot be used as a condition, a struct value cannot be used as a condition, a Result cannot be used as a condition, an optional <type> cannot be used as a condition, a value of type parameter <T> cannot be used as a condition, a <interface> value cannot be used as a condition

A condition needs a number, pointer, string, closure or optional reference. A list, map, slice, struct value, Result, optional value type, unbounded type parameter or dyn value has no single truth value.

void main() {
    int[] xs = [1, 2, 3];
    if (xs) print("has items");
}

Ask the question you mean: .is_empty() or .len for collections, .is_ok() for a Result, != null for an optional.

void main() {
    int[] xs = [1, 2, 3];
    if (!xs.is_empty()) print("has items");
}

E0406

'<name>' is a type, not a value

A type name is used where an expression is expected. Types can't be stored or passed as values.

struct Point { int x; int y; }

void main() {
    auto p = Point;
}

Construct a value of the type with a struct literal:

struct Point { int x; int y; }

void main() {
    auto p = Point{ .x = 1, .y = 2 };
    print(p.x);
}

E0407

'<name>' is a namespace, not a value

A namespace name is used on its own as an expression. A namespace only groups names; reach a member with ::.

namespace geo {
    int origin() { return 0; }
}

void main() {
    auto g = geo;
}

Name the member you want:

namespace geo {
    int origin() { return 0; }
}

void main() {
    int g = geo::origin();
    print(g);
}

E0408

'<name>' is a static for variable, known only at compile time

The variable of a static for stands for a field or variant while the program is compiled. It has no run-time value of its own.

struct Point { int x; int y; }

void show<T>(T v) {
    static for f in T.fields {
        print(f);
    }
}

void main() {
    show(Point{ .x = 1, .y = 2 });
}

Use one of its properties, such as f.name, f.index or f.type, or v.[f] for the field of a value:

struct Point { int x; int y; }

void show<T>(T v) {
    static for f in T.fields {
        print(v.[f]);
    }
}

void main() {
    show(Point{ .x = 1, .y = 2 });
}

E0409

'string' is a type; did you mean string(value)?

string is used on its own where a value is expected. It names a type; to format a value as text, call it like a function.

void main() {
    int n = 5;
    print(string);
}

Call string(value), or use interpolation:

void main() {
    int n = 5;
    print(string(n));
}

E0410

a static method has no self

A static method is called on the type, not on a value, so there is no self inside it.

struct Counter { int n; }

impl Counter {
    static int start() { return self.n; }
}

void main() {
    print(Counter::start());
}

Drop static so the method takes self, or pass the value in as a parameter:

struct Counter { int n; }

impl Counter {
    int start() { return self.n; }
}

void main() {
    Counter c = Counter{ .n = 1 };
    print(c.start());
}

E0411

unknown name '<name>'

A :: path names something that doesn't exist: the namespace or type has no member by that name.

namespace geo {
    int origin() { return 0; }
}

void main() {
    int n = geo::nothing;
}

Check the spelling and that the member is declared in that namespace:

namespace geo {
    int origin() { return 0; }
}

void main() {
    int n = geo::origin();
    print(n);
}

E0412

'<op>' is not defined on <type>

An operator is applied to an optional value. An optional may be null, so it can't be used as the value it holds until it is checked.

int? digit(char c) { return c >= '0' && c <= '9' ? c - '0' : null; }

void main() {
    int? d = digit('4');
    print(d + 1);
}

Check it for null first, or give a fallback with ??:

int? digit(char c) { return c >= '0' && c <= '9' ? c - '0' : null; }

void main() {
    int? d = digit('4');
    print((d ?? 0) + 1);
}

E0413

'<op>' needs a number, found <type>

Unary - and + apply only to numbers.

void main() {
    string s = "five";
    print(-s);
}

Convert the value to a number first, or apply the operator to a number:

void main() {
    int n = 5;
    print(-n);
}

E0414

'~' needs an integer

Bitwise complement works on integer types only, not on floating-point or other values.

void main() {
    double d = 1.5;
    print(~d);
}

Use an integer, casting first if needed:

void main() {
    double d = 1.5;
    print(~(int)d);
}

E0415

cannot dereference a value of type <type>

Unary * needs a pointer or C array. The value here is neither.

void main() {
    int n = 5;
    print(*n);
}

Dereference a pointer, or use the value directly:

void main() {
    int n = 5;
    int *p = &n;
    print(*p);
}

E0416

'<op>' needs a variable

++ and -- change what they are applied to, so it must be a variable, field or element, not the result of an expression.

void main() {
    int n = 5;
    print((n + 1)++);
}

Apply the operator to a variable, or write the arithmetic out:

void main() {
    int n = 5;
    n++;
    print(n + 1);
}

E0417

'<op>' is not defined between <type> and <type>

The operator doesn't apply to this pair of types: for example arithmetic on a list or struct, == on a struct without Eq, or an operator on a type parameter whose bounds don't provide it.

void main() {
    int[] xs = [1, 2, 3];
    print(xs + 4);
}

Use a method for what you mean. On a struct, implement the operator's interface; on a type parameter, add Eq, Ord or Num to its bounds.

void main() {
    int[] xs = [1, 2, 3];
    xs.push(4);
    print(xs);
}

E0418

cannot add a number to a string

+ on a string joins two strings. A number isn't converted to text by itself.

void main() {
    int n = 5;
    string s = "n=" + n;
    print(s);
}

Use interpolation or string(value):

void main() {
    int n = 5;
    string s = "n=\(n)";
    print(s);
}

E0419

'<op>' between string and <type>

A string operator has a value on the other side that isn't a string, and the operator has no meaning for that pair.

void main() {
    string s = "a";
    bool[] xs = [true];
    print(s == xs);
}

Compare or combine strings with strings, converting the other value first:

void main() {
    string s = "a";
    bool[] xs = [true];
    print(s == string(xs[0]));
}

E0420

'<op>' is not defined for strings

Strings support + to join and the comparison operators, nothing else.

void main() {
    string s = "ab";
    print(s * "b");
}

Use a string method instead, such as s.repeat(n):

void main() {
    string s = "ab";
    print(s.repeat(2));
}

E0421

strings are immutable; build a new string instead

A string's characters can be read by index but not assigned. Strings are shared values and never change in place.

void main() {
    string s = "cat";
    s[0] = 'b';
}

Build a new string from pieces and assign it to the variable:

void main() {
    string s = "cat";
    s = "b" + s[1..];
    print(s);
}

E0422

'<name>' is read-only

The member is a built-in property, such as a list's len, computed from the value. It can be read but not assigned.

void main() {
    int[] xs = [1, 2, 3];
    xs.len = 2;
}

Change the value with one of its methods instead:

void main() {
    int[] xs = [1, 2, 3];
    xs.pop();
    print(xs.len);
}

E0423

cannot assign to a slice; assign to its elements, as in s[i] = x

A slice is a view of elements in a list or array. Assigning a whole slice has no single meaning, so it is rejected.

void main() {
    int[] xs = [1, 2, 3];
    int[] ys = [8, 9];
    xs[0..2] = ys;
}

Assign to the elements one by one:

void main() {
    int[] xs = [1, 2, 3];
    int[] ys = [8, 9];
    for (int i = 0; i < 2; i++) xs[i] = ys[i];
    print(xs);
}

E0424

the left side of an assignment must be a variable, field or element

The target of = or a compound assignment is an expression that doesn't name storage.

void main() {
    int n = 5;
    n + 1 = 7;
}

Assign to a variable, field or element:

void main() {
    int n = 5;
    n = 7 - 1;
    print(n);
}

E0425

cannot assign to 'self'

Inside a method, self refers to the receiver. Replacing it as a whole is not allowed.

struct P { int x; }

impl P {
    void reset() { self = P{ .x = 0 }; }
}

void main() {
    P p = P{ .x = 1 };
    p.reset();
}

Change its fields instead:

struct P { int x; }

impl P {
    void reset() { self.x = 0; }
}

void main() {
    P p = P{ .x = 1 };
    p.reset();
    print(p.x);
}

E0426

only '+=' works on strings

Of the compound assignments, strings support only +=, which appends.

void main() {
    string s = "hello";
    s -= "o";
}

Build the new string with a method or a slice:

void main() {
    string s = "hello";
    s = s[0..4];
    print(s);
}

E0427

the branches of '?:' have different types: <type> and <type>

Both branches of a conditional expression must have one type, so the result has one type. These two can't be unified.

void main() {
    bool ok = true;
    auto v = ok ? 1 : "one";
}

Make both branches the same type:

void main() {
    bool ok = true;
    auto v = ok ? "1" : "one";
    print(v);
}

E0428

index must be an integer

Lists, slices and strings are indexed by position, which must be an integer.

void main() {
    int[] xs = [1, 2, 3];
    print(xs["1"]);
}

Use an integer index. For lookup by key, use a map:

void main() {
    int[] xs = [1, 2, 3];
    print(xs[1]);
}

E0429

cannot index a value of type <type>

[] applies to lists, slices, strings, maps, pointers and C arrays. This value is none of them, or is an optional that must be checked first.

void main() {
    int n = 5;
    print(n[0]);
}

Index a value that holds elements:

void main() {
    int[] ns = [5];
    print(ns[0]);
}

E0430

cannot cast <type> to <type>

The cast has no meaning between these types: managed values (lists, maps, strings, optionals, structs) don't convert by cast, and a type parameter has no conversions. (void)x is the exception: it discards a value of any type.

void main() {
    int[] xs = [1, 2, 3];
    long n = (long)xs;
}

Use a method or property that gives the value you want:

void main() {
    int[] xs = [1, 2, 3];
    long n = xs.len;
    print(n);
}

E0431

cannot cast to string; use string(value) to format a value

A cast to string is only for C strings (char *). Formatting a number or other value as text is a call, not a cast.

void main() {
    int n = 42;
    string s = (string)n;
}

Call string(value) or use interpolation:

void main() {
    int n = 42;
    string s = string(n);
    print(s);
}

E0432

cannot infer the element type of an empty list, cannot infer the element type of a list from <null|a C value of unknown type>

[] has no elements to take a type from, and nothing around it says what the list holds. The first element can't give the type either when it is null or a C name Moxy knows no type for, such as a macro.

void main() {
    auto xs = [];
}

Give the variable a type:

void main() {
    int[] xs = [];
    print(xs.len);
}

E0433

<Ok|Err>(...) needs a Result<T> context

Ok(...) and Err(...) build a Result<T>, but nothing around them says which T.

void main() {
    auto r = Ok(5);
}

Return it from a function that returns Result<T>, or assign it to a typed variable:

void main() {
    Result<int> r = Ok(5);
    print(r.is_ok());
}

E0434

Ok() of Result<void> takes no value, Ok(...) needs a value, Err(...) needs a message, Err(...) needs an error value

The argument of Ok or Err doesn't match the Result it builds. Ok takes a value unless the result is Result<void>, and Err always takes a message or error value.

Result<int> parse(string s) {
    if (s == "") return Err();
    return Ok((int)s.len);
}

void main() {
    print(parse("12").is_ok());
}

Pass what the Result holds:

Result<int> parse(string s) {
    if (s == "") return Err("empty input");
    return Ok((int)s.len);
}

void main() {
    print(parse("12").is_ok());
}

E0435

'<name>' is not a struct defined in Moxy

A Name{ ... } literal needs a struct declared in Moxy. This name is a C type, a typedef of a non-struct, or a struct Moxy can't see the fields of.

typedef int Num;

void main() {
    auto n = Num{ 1 };
}

Use a C-style initializer for C types, or declare the struct in Moxy:

typedef int Num;

void main() {
    Num n = 1;
    print(n);
}

E0436

cannot infer the type of this initializer

A brace initializer { ... } has no type of its own, and nothing around it gives one.

void main() {
    auto p = { 1, 2 };
}

Use a typed declaration or a struct literal:

struct Point { int x; int y; }

void main() {
    Point p = { 1, 2 };
    print(p.x);
}

E0437

await needs a Future, found <type>

await waits for a Future<T>, the result of calling an async function, a Future<T> function, a spawn block or an actor. A plain value has nothing to wait for.

int compute() { return 42; }

void main() {
    int n = await compute();
    print(n);
}

Make the function async so its call returns a Future, or drop the await:

async int compute() { return 42; }

void main() {
    int n = await compute();
    print(n);
}

E0439

unexpected expression

A brace initializer for a plain value holds a designator (.x = 1) or a key: value entry, which only struct, array and map initializers accept.

void main() {
    int n = { .x = 1 };
}

Initialize the value directly, or give it a struct type that has the field:

struct Box { int x; }

void main() {
    Box n = { .x = 1 };
    print(n.x);
}

E0440

unexpected initializer for a struct, unexpected initializer for an array, unexpected initializer for a list

The brace initializer holds an entry of the wrong kind for its type: a key: value entry or [i] = designator in a struct, a .field = or key: value entry in an array, or any designator in a list.

void main() {
    int[] xs = { [0] = 1, [1] = 2 };
}

Give a list its elements in order:

void main() {
    int[] xs = { 1, 2 };
    print(xs);
}

E0441

too many values for <struct>, too many values in initializer for <type>

A brace initializer has more values than the struct has fields, or more than one value for a plain type.

struct Point { int x; int y; }

void main() {
    Point p = { 1, 2, 3 };
}

Give one value per field:

struct Point { int x; int y; }

void main() {
    Point p = { 1, 2 };
    print(p.y);
}

E0442

map literals need 'key: value' entries

Each entry of a map initializer must pair a key with a value.

void main() {
    map[string, int] ages = { "ann", 31 };
}

Write each entry as key: value:

void main() {
    map[string, int] ages = { "ann": 31 };
    print(ages["ann"]);
}

E0443

'{}' cannot initialize <type>

An empty initializer has no value to give this type. Lists, maps and structs can start empty; a Result, dyn value or other managed value can't.

void main() {
    Result<int> r = {};
}

Initialize it with a real value:

void main() {
    Result<int> r = Ok(0);
    print(r.is_ok());
}

E0444

this lambda takes <n> parameter(s) but <n> is/are expected

The lambda is passed or assigned where a closure or function pointer of another arity is expected.

int apply(fn(int) -> int f, int x) { return f(x); }

void main() {
    print(apply((int a, int b) => a + b, 2));
}

Give the lambda the parameters the expected type has:

int apply(fn(int) -> int f, int x) { return f(x); }

void main() {
    print(apply((int a) => a + 1, 2));
}

E0445

lambda parameter is <type> but <type> is expected

A lambda parameter's declared type differs from the matching parameter of the expected closure or function pointer. Parameter types must match exactly.

int apply(fn(int) -> int f, int x) { return f(x); }

void main() {
    print(apply((double a) => (int)a * 2, 2));
}

Declare the parameter with the expected type:

int apply(fn(int) -> int f, int x) { return f(x); }

void main() {
    print(apply((int a) => a * 2, 2));
}

E0446

'<method>' returns a Future, so its receiver must be a ref struct

An async or Future method on a value type takes self as a pointer to the caller's variable, which may be gone before the call finishes.

struct Point { int x; }

impl Point {
    async int later() { return self.x; }
}

void main() {
    Point p = Point{ .x = 1 };
    print(await p.later());
}

Use a ref struct, or a static method that takes the value:

struct Point { int x; }

impl Point {
    static async int later(Point p) { return p.x; }
}

void main() {
    Point p = Point{ .x = 1 };
    print(await Point::later(p));
}

E0447

<context>: expected <type>, found <type>?, which may be null

An optional value is used where a non-optional one is required. It may be null, so it has to be checked or given a fallback first.

int? digit(char c) { return c >= '0' && c <= '9' ? c - '0' : null; }

void main() {
    int? d = digit('4');
    int x = d;
    print(x);
}

Give a fallback with ??, check it with if (d != null), or unwrap it with !:

int? digit(char c) { return c >= '0' && c <= '9' ? c - '0' : null; }

void main() {
    int? d = digit('4');
    int x = d ?? 0;
    print(x);
}

E0448

'!' needs an optional value; this is <type>, which is never null

x! unwraps an optional. The value here isn't optional, so there is nothing to unwrap.

void main() {
    int n = 3;
    print(n!);
}

Remove the !:

void main() {
    int n = 3;
    print(n);
}

E0449

'??' needs an optional on its left; <type> is never null

a ?? b gives b when a is null. Here a is never null, so the fallback would never be used.

void main() {
    int n = 3;
    print(n ?? 4);
}

Remove the fallback, or make the left side optional:

void main() {
    int? n = 3;
    print(n ?? 4);
}

E0450

'?.' needs an optional on its left; <type> is never null

a?.b reads b only when a isn't null. Here a is never null.

struct Point { int x; }

void main() {
    Point p = Point{ .x = 1 };
    print(p?.x);
}

Use .:

struct Point { int x; }

void main() {
    Point p = Point{ .x = 1 };
    print(p.x);
}

E0451

slice bounds must be integers

The start and end of a[i..j] are positions, so both must be integers.

void main() {
    int[] xs = [1, 2, 3];
    int[..] b = xs["a"..2];
}

Use integer bounds:

void main() {
    int[] xs = [1, 2, 3];
    int[..] b = xs[0..2];
    print(b.len());
}

E0452

the length of this array is unknown, so its slice needs an end

The C array is declared without a length, so a[i..] has no end to stop at.

extern int table[];

void main() {
    int[..] rest = table[1..];
}

Give the end explicitly:

extern int table[];

void main() {
    int[..] rest = table[1..4];
}

E0453

cannot slice a pointer (<type>): its length is unknown

A pointer doesn't record how many elements it points at, so a slice of it can't be checked.

void main() {
    int nums[4] = { 1, 2, 3, 4 };
    int *p = nums;
    int[..] a = p[0..2];
}

Slice the C array the pointer points into, or copy the elements into a list:

void main() {
    int nums[4] = { 1, 2, 3, 4 };
    int[..] a = nums[0..2];
    print(a.len());
}

E0454

cannot slice a value of type <type>

Only lists, strings, slices and C arrays can be sliced. This includes a C value whose type Moxy can't see.

void main() {
    int k = 3;
    int[..] q = k[1..];
}

Slice a value that holds elements:

void main() {
    int[] ks = [3, 4, 5];
    int[..] q = ks[1..];
    print(q.len());
}

E0455

an array of unknown length cannot be a slice

A C array declared without a length is passed where a slice T[..] is expected. A slice needs a length, and this array has none.

extern int table[];

long total(int[..] xs) { return xs.len(); }

void main() {
    print(total(table));
}

Slice it with an explicit end:

extern int table[];

long total(int[..] xs) { return xs.len(); }

void main() {
    print(total(table[0..4]));
}

E0456

<method>() needs elements that implement <interface>; <type> does not

sort() needs Ord on the element type, and contains() and index_of() need Eq. This element type doesn't implement it.

struct Point { int x; }

void main() {
    Point[] ps = [Point{ .x = 2 }, Point{ .x = 1 }];
    Point[..] view = ps;
    view.sort();
}

Implement the interface for the element type:

struct Point { int x; }

impl Ord for Point {
    int cmp(Point o) { return self.x - o.x; }
}

void main() {
    Point[] ps = [Point{ .x = 2 }, Point{ .x = 1 }];
    Point[..] view = ps;
    view.sort();
    print(ps[0].x);
}

E0457

cannot infer the return type of this lambda from a C value of unknown type

A lambda becomes a C function, which needs a return type. With nothing around it saying what the lambda returns, the type comes from its result, and a C name Moxy knows no type for, such as a macro, doesn't give one.

#define BASE 10
void main() {
    auto add = (int x) => x + BASE;
}

Give the lambda a function type:

#define BASE 10
void main() {
    fn(int) -> int add = (int x) => x + BASE;
    print(add(1));
}

Calls and methods

E0501

<Enum>::<Variant> carries <n> value(s); pass them in parentheses

The variant is written without parentheses, but it carries data. A variant with values is built like a call, with one argument per value.

enum Shape { Circle(double r), None }

void main() {
    Shape s = Shape::Circle;
}

Pass the variant's values in parentheses:

enum Shape { Circle(double r), None }

void main() {
    Shape s = Shape::Circle(1.0);
}

E0502

<Enum>::<Variant> takes <n> value(s), got <n>

The variant is built with a different number of values than its declaration lists. Each value the variant carries needs exactly one argument.

enum Shape { Circle(double r), None }

void main() {
    Shape s = Shape::Circle(1.0, 2.0);
}

Pass one argument per declared value:

enum Shape { Circle(double r), None }

void main() {
    Shape s = Shape::Circle(1.0);
}

E0503

<function> takes <n> argument(s), got <n>

The call passes a different number of arguments than the function declares. Only C variadic functions accept extra arguments; nothing is ever filled in for a missing one.

int add(int a, int b) { return a + b; }

void main() {
    int n = add(1);
}

Pass every parameter the function declares:

int add(int a, int b) { return a + b; }

void main() {
    int n = add(1, 2);
}

E0504

cannot print a void value, cannot convert a void value to a string, cannot interpolate a void value

A call that returns void is used where a value is needed: an argument to print, the value in string(...), or a \(...) part of a string. There is nothing to show.

void hello() {}

void main() {
    print(hello());
}

Call the function on its own, or make it return the value you want shown:

string hello() { return "hello"; }

void main() {
    print(hello());
}

E0505

assert takes a condition and an optional message

assert is given no arguments or more than two. It takes a condition, and optionally a string to report when the condition is false.

void main() {
    int n = 3;
    assert(n > 0, "positive", 1);
}

Pass the condition and at most one message; build the message with interpolation if it needs values:

void main() {
    int n = 3;
    assert(n > 0, "positive, got \(n)");
}

E0506

cancelled() takes no arguments

cancelled() reports whether the current async call has been cancelled. It always asks about the call it runs in, so it takes no arguments.

async int work() {
    if (cancelled(1)) return 0;
    return 1;
}

void main() { print(await work()); }

Call it with empty parentheses:

async int work() {
    if (cancelled()) return 0;
    return 1;
}

void main() { print(await work()); }

E0507

panic takes one message

panic is given no arguments or more than one. It takes exactly one string, the message to report.

void main() {
    panic("bad", 1);
}

Pass a single message, with interpolation for any values:

void main() {
    panic("bad: \(1)");
}

E0508

string(...) takes one value

string(...) converts one value to a string. It doesn't join several values.

void main() {
    string s = string(1, 2);
}

Convert one value, or use interpolation to combine several:

void main() {
    string s = "\(1)\(2)";
}

E0509

<name> is not callable (type <type>), field '<name>' is not a function

Something that isn't a function, a function pointer or a closure is called. For a struct field, the field's type has to be a function type for p.f() to work.

void main() {
    int n = 3;
    n(1);
}

Call only functions and function values; to use a plain value, read it:

void main() {
    int n = 3;
    print(n);
}

E0510

construct <Struct> with <Struct>{ ... } instead of calling it

A struct type is called like a function. Structs have no constructor functions; build them with a brace initializer.

struct Point { int x; int y; }

void main() {
    Point p = Point(1, 2);
}

Use the initializer form, positional or with field names:

struct Point { int x; int y; }

void main() {
    Point p = Point{ 1, 2 };
    Point q = Point{ .x = 1, .y = 2 };
}

E0511

'<name>' is a type, not a function

A type other than a struct, such as an enum or a typedef, is called like a function. Types can't be called.

enum Color { Red, Green }

void main() {
    Color c = Color(1);
}

Name the value you want through the type:

enum Color { Red, Green }

void main() {
    Color c = Color::Green;
}

E0512

unknown function '<name>'

A call through a :: path names a function that doesn't exist: the prefix is not a type with that static method, an enum with that variant, or a namespace holding that function.

namespace geo {
    int area(int w, int h) { return w * h; }
}

void main() {
    int a = geo::volume(2, 3);
}

Check the spelling and the namespace the function lives in:

namespace geo {
    int area(int w, int h) { return w * h; }
}

void main() {
    int a = geo::area(2, 3);
}

E0513

<type> has no method '<name>', <type> has no field or method '<name>'

The method isn't defined for the receiver's type: no impl gives it, and the type has no built-in method of that name. On a type parameter, only the methods its bounds declare are available.

struct P { int x; }

void main() {
    P p = P{ 1 };
    p.grow();
}

Define the method in an impl block, or call one that exists:

struct P { int x; }

impl P {
    void grow() { self.x += 1; }
}

void main() {
    P p = P{ 1 };
    p.grow();
}

E0514

<method>() takes <n> argument(s), got <n>

A method is called with a different number of arguments than it takes. The receiver before the . is not counted.

void main() {
    string s = "hello";
    string t = s.upper(1);
}

Pass the arguments the method declares:

void main() {
    string s = "hello";
    string t = s.upper();
}

E0515

result() takes no arguments, got <n>

f.result() turns a Future<T> into a Future<Result<T>>, catching a panic as an Err. It takes no arguments.

async int work() { return 1; }

void main() {
    Future<int> f = work();
    Result<int> r = await f.result(1);
}

Call it with empty parentheses:

async int work() { return 1; }

void main() {
    Future<int> f = work();
    Result<int> r = await f.result();
}

E0516

timeout() takes 1 argument, got <n>

f.timeout(ms) needs exactly one argument: the number of milliseconds to wait before giving up and cancelling the call.

async int work() { return 1; }

void main() {
    int? n = await work().timeout();
}

Pass the limit in milliseconds:

async int work() { return 1; }

void main() {
    int? n = await work().timeout(100);
}

E0517

<x>.<method>() is ambiguous: <type> has <n> methods of that name

Several impls give the type a method of this name, such as Into<string> and Into<int>, and nothing tells the compiler which one you mean. The expected type of the result picks one when there is one.

struct Version { int major; int minor; }

impl Into<string> for Version {
    string into() { return "\(self.major).\(self.minor)"; }
}

impl Into<int> for Version {
    int into() { return self.major * 100 + self.minor; }
}

void main() {
    Version v = Version{ 1, 2 };
    print(v.into());
}

Give the result a type:

struct Version { int major; int minor; }

impl Into<string> for Version {
    string into() { return "\(self.major).\(self.minor)"; }
}

impl Into<int> for Version {
    int into() { return self.major * 100 + self.minor; }
}

void main() {
    Version v = Version{ 1, 2 };
    string s = v.into();
    print(s);
}

E0518

'<name>' is a static method; call it as <Type>::<name>()

A static method is called on a value. Static methods have no self, so they belong to the type, not to an instance.

struct P { int x; }

impl P {
    static P origin() { return P{ 0 }; }
}

void main() {
    P p = P{ 1 };
    P o = p.origin();
}

Call it through the type:

struct P { int x; }

impl P {
    static P origin() { return P{ 0 }; }
}

void main() {
    P o = P::origin();
}

E0519

drop() runs by itself when the last reference goes; it can't be called

drop() from impl Drop is called by hand. The runtime calls it once, when the last reference to the value goes away; calling it yourself would release the resource twice.

ref struct File { int fd; }

impl Drop for File {
    void drop() { print("closed"); }
}

void main() {
    File f = File{ 3 };
    f.drop();
}

Let the value go out of scope. For an early release, put the work in a separate method such as close():

ref struct File { int fd; }

impl Drop for File {
    void drop() { print("closed"); }
}

void main() {
    File f = File{ 3 };
}

E0520

<Type> is generic; give its type arguments, as in <Type><int>::<method>()

A static method of a generic type is called without the type's arguments. The method's types depend on them, so the call has to name them.

struct Box<T> { T value; }

impl<T> Box<T> {
    static Box<T> of(T v) { return Box<T>{ v }; }
}

void main() {
    Box<int> b = Box::of(1);
}

Write the type arguments before :::

struct Box<T> { T value; }

impl<T> Box<T> {
    static Box<T> of(T v) { return Box<T>{ v }; }
}

void main() {
    Box<int> b = Box<int>::of(1);
}

E0521

<Actor>::<method> is a message of actor <Actor>; it can't be used as a function

An actor's method is taken as a function value. Calling an actor's method sends it a message that runs on the actor, so it has no plain function to point at.

actor Counter {
    long n;
    long get() { return self.n; }
}

void main() {
    fn(Counter) -> long g = Counter::get;
}

Wrap the call in a lambda that sends the message:

actor Counter {
    long n;
    long get() { return self.n; }
}

void main() {
    fn(Counter) -> Future<long> g = (Counter a) => a.get();
}

E0522

'<name>' takes self; call it on a value, as in x.<name>()

A method that uses self is called through the type, as if it were static. It needs an instance to work on.

struct P { int x; }

impl P {
    int get() { return self.x; }
}

void main() {
    int n = P::get();
}

Call it on a value:

struct P { int x; }

impl P {
    int get() { return self.x; }
}

void main() {
    P p = P{ 1 };
    int n = p.get();
}

E0523

<type> has no field '<name>'

The struct has no field of this name. This covers reads with . and ->, field names in an initializer, and fields in a struct pattern.

struct P { int x; }

void main() {
    P p = P{ 1 };
    print(p.y);
}

Use a field the struct declares, or add the field to it:

struct P { int x; }

void main() {
    P p = P{ 1 };
    print(p.x);
}

E0524

<method> expects a function like (x) => ...

A list method that takes a function, such as map, filter, each or par_map, is given something that isn't a function or closure.

void main() {
    int[] xs = [1, 2, 3];
    print(xs.map(5));
}

Pass a lambda that takes one element:

void main() {
    int[] xs = [1, 2, 3];
    print(xs.map((int x) => x * 5));
}

E0525

<method> expects a function taking <type>

The function passed to a list method takes the wrong parameters. It must take exactly one value of the list's element type.

void main() {
    fn(string) -> int size = (string s) => s.len;
    int[] xs = [1, 2, 3];
    int[] ys = xs.map(size);
}

Pass a function whose one parameter is the element type:

void main() {
    fn(int) -> int twice = (int x) => x * 2;
    int[] xs = [1, 2, 3];
    int[] ys = xs.map(twice);
}

E0526

cannot sort a list of <type>

sort() needs an element type with an order: numbers, strings, or a type with impl Ord. The element type has none.

struct P { int x; }

void main() {
    P[] ps = [P{ 2 }, P{ 1 }];
    ps.sort();
}

Give the type a cmp() with impl Ord:

struct P { int x; }

impl Ord for P {
    int cmp(P o) { return self.x - o.x; }
}

void main() {
    P[] ps = [P{ 2 }, P{ 1 }];
    ps.sort();
}

E0527

map needs a function that returns a value

The function passed to map returns void, so there is nothing to put in the new list. map builds a list from what the function returns.

void show(int x) { print(x); }

void main() {
    int[] xs = [1, 2, 3];
    xs.map((int x) => show(x));
}

To run a function for each element without collecting results, use each:

void show(int x) { print(x); }

void main() {
    int[] xs = [1, 2, 3];
    xs.each((int x) => show(x));
}

E0528

par_map needs a function that returns a value

The function passed to par_map returns void. par_map collects what the function returns into a new list, so it needs a value.

void show(int x) { print(x); }

void main() {
    int[] xs = [1, 2, 3];
    xs.par_map((int x) => show(x));
}

Return the value to collect from the function:

int square(int x) { return x * x; }

void main() {
    int[] xs = [1, 2, 3];
    int[] ys = xs.par_map((int x) => square(x));
}

E0529

filter needs a function that returns bool

The function passed to filter returns something that can't be a condition, such as a struct. filter keeps the elements for which the function returns true.

struct P { int x; }

void main() {
    fn(int) -> P wrap = (int x) => P{ x };
    int[] xs = [1, 2, 3];
    int[] ys = xs.filter(wrap);
}

Pass a predicate that returns bool:

void main() {
    fn(int) -> bool big = (int x) => x > 1;
    int[] xs = [1, 2, 3];
    int[] ys = xs.filter(big);
}

E0530

<type>? may be null; it has no '<name>'

A field or method is reached through an optional value. The value may be null, which has no fields, so the compiler makes you check first. (Through a field declared weak T, without ?, this is warning W0207 in 0.4.)

struct P { int x; }

P? find() { return null; }

void main() {
    P? p = find();
    print(p.x);
}

Test it for null first; inside the check it is narrowed to the plain type. p! also works when you know it is set:

struct P { int x; }

P? find() { return null; }

void main() {
    P? p = find();
    if (p != null) print(p.x);
}

E0531

'<name>' is a method; call it as <name>()

A method of a built-in type is named without parentheses. Only .len is a property; every other method has to be called.

void main() {
    int[] xs = [1, 2, 3];
    xs.push;
}

Add the parentheses and the arguments:

void main() {
    int[] xs = [1, 2, 3];
    xs.push(4);
}

E0532

'->' needs a pointer; use '.' on struct values, '.' on a pointer; use '->'

The member operator doesn't match the receiver: -> is for pointers to structs and . for struct values, as in C. ref struct values accept either.

struct P { int x; }

void main() {
    P p = P{ 1 };
    int n = p->x;
}

Use . on the value, or -> on a pointer to it:

struct P { int x; }

void main() {
    P p = P{ 1 };
    P *q = &p;
    int n = p.x + q->x;
}

E0533

'<field>' takes <n> argument(s), got <n>

A function stored in a struct field is called with a different number of arguments than its type declares.

struct Op { fn(int) -> int run; }

int twice(int x) { return x * 2; }

void main() {
    Op op = Op{ twice };
    int n = op.run(1, 2);
}

Pass the arguments the field's function type lists:

struct Op { fn(int) -> int run; }

int twice(int x) { return x * 2; }

void main() {
    Op op = Op{ twice };
    int n = op.run(1);
}

E0534

Buf has no method '<name>'; write to it with put(value)

Inside a format() method, the Buf has one method, put, which appends any value's text. Other names are rejected.

struct P { int x; }

impl Format for P {
    void format(Buf *b) { b.write(self.x); }
}

void main() {}

Write to the buffer with put:

struct P { int x; }

impl Format for P {
    void format(Buf *b) { b.put(self.x); }
}

void main() {}

E0535

put() takes 1 argument, got <n>

b.put(value) appends one value to the buffer per call.

struct P { int x; }

impl Format for P {
    void format(Buf *b) { b.put("x", self.x); }
}

void main() {}

Call put once per value, or combine them with interpolation:

struct P { int x; }

impl Format for P {
    void format(Buf *b) { b.put("x \(self.x)"); }
}

void main() {}

E0536

cannot put a void value

The value passed to b.put(...) is a call that returns void, so there is no text to append.

struct P { int x; }

void nothing() {}

impl Format for P {
    void format(Buf *b) { b.put(nothing()); }
}

void main() {}

Pass a value that has text, such as a field or a function that returns one:

struct P { int x; }

int value() { return 1; }

impl Format for P {
    void format(Buf *b) { b.put(value()); }
}

void main() {}

E0537

cannot call <method>() on a temporary value

A method that changes its receiver, such as push, is called on a value that lives nowhere, like a function's result. The change would be lost at once, so a variable, field or element is required.

int[] make() { return [1, 2]; }

void main() {
    make().push(3);
}

Store the value in a variable first:

int[] make() { return [1, 2]; }

void main() {
    int[] xs = make();
    xs.push(3);
}

Interfaces, generics, enums and Result

E0601

method '<name>' doesn't match interface <interface>: expected <signature>, found <signature>

An impl's method has a different return type or parameters than the interface declares. Every impl of an interface must use the declared signature, so callers through the interface get what they expect.

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    int area() { return 1; }
}
void main() {}

Write the method with the interface's signature:

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
void main() {}

E0602

<impl> is missing method '<name>'

An impl of an interface leaves out a method the interface requires. Only methods with a default body in the interface may be left out.

interface Shape {
    double area();
    string name();
}
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
void main() {}

Add the missing method, or give it a default body in the interface:

interface Shape {
    double area();
    string name();
}
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
    string name() { return "square"; }
}
void main() {}

E0603

'<name>' must take self, as interface <interface> declares it

The interface declares the method on a value, but the impl writes it as static. Interface methods always take self.

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    static double area() { return 1.0; }
}
void main() {}

Remove static so the method takes self:

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
void main() {}

E0604

'<name>' is not a method of interface <interface>

An impl of an interface defines a method the interface doesn't declare. An interface impl holds only the interface's methods.

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
    string name() { return "square"; }
}
void main() {}

Move extra methods to a plain impl of the type:

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
impl Square {
    string name() { return "square"; }
}
void main() {}

E0605

<context>: a <type> always holds a value; it can't be null

A dyn value always points at a value of some type that implements the interface, so it has no null state.

interface Shape { double area(); }
void main() {
    dyn Shape s = null;
}

Give it a value of a type that implements the interface:

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
void main() {
    dyn Shape s = Square{ 2 };
}

E0606

<context>: cannot make a <type> from a C value of unknown type

A dyn value needs a type that implements the interface, and a value whose type comes from a C header can't implement one.

#include <stdio.h>
interface Stream { int fd(); }
void main() {
    dyn Stream s = stdin;
}

Wrap the C value in a Moxy struct and implement the interface for it:

#include <stdio.h>
interface Stream { int fd(); }
struct File { FILE *f; }
impl Stream for File {
    int fd() { return fileno(self.f); }
}
void main() {
    dyn Stream s = File{ stdin };
}

E0607

<context>: <type> does not implement <interface>

A value converted to dyn must have a type with an impl of that interface.

interface Shape { double area(); }
struct Square { double side; }
void main() {
    dyn Shape s = Square{ 2 };
}

Add an impl of the interface for the type:

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
void main() {
    dyn Shape s = Square{ 2 };
}

E0608

'<name>' is declared again under another #if condition; generic declarations can't vary by #if yet

A generic struct, enum or function is declared twice under different #if branches. Each generic has one declaration for the whole program.

#ifdef WIDE
struct Box<T> { T value; long pad; }
#else
struct Box<T> { T value; }
#endif
void main() {}

Declare the generic once, outside the conditional:

struct Box<T> { T value; }
void main() {}

E0609

generic unions are not supported

A union can't take type parameters.

union Cell<T> { T value; int raw; }
void main() {}

Use a generic enum with payloads, which also records which case it holds:

enum Cell<T> { Value(T value), Raw(int raw) }
void main() {}

E0610

instantiating <name> never ends: each instance needs a larger one

A generic function calls itself with a type built from its own parameter, such as T[]. Each instance asks for a new one, so the compiler stops.

int grow<T>(T x, int n) {
    if (n == 0) return 0;
    return grow([x], n - 1);
}
void main() { print(grow(1, 3)); }

Keep the recursive call on the same type arguments:

int grow<T>(T x, int n) {
    if (n == 0) return 0;
    return grow(x, n - 1);
}
void main() { print(grow(1, 3)); }

E0611

generic function '<function>' has no body

A generic function is declared without a definition. Its instances are generated from the body, so a prototype alone can't be used.

T first<T>(T[] xs);
void main() {}

Give the function its body:

T first<T>(T[] xs) { return xs[0]; }
void main() {}

E0612

<name> takes <n> type argument<s>, got <n>

A generic type or function is given more or fewer type arguments than it declares.

struct Pair<A, B> { A first; B second; }
void main() {
    Pair<int> p;
}

Give one type argument per parameter:

struct Pair<A, B> { A first; B second; }
void main() {
    Pair<int, string> p;
}

E0613

void cannot be a type argument

A type parameter stands for a type of values, and void has none.

struct Box<T> { T value; }
void main() {
    Box<void> b;
}

Use a type that has values:

struct Box<T> { T value; }
void main() {
    Box<int> b;
}

E0614

unknown generic type '<name>'

Type arguments follow a name that isn't a generic type in this scope, for example a generic declared inside a namespace and named without it.

namespace geo {
    struct Box<T> { T value; }
}
void main() {
    Box<int> b;
}

Name the type with its namespace:

namespace geo {
    struct Box<T> { T value; }
}
void main() {
    geo::Box<int> b;
}

E0615

unknown type parameter '<name>'

A generic declaration uses a type parameter name it doesn't declare.

struct Box<T> { U value; }
void main() {}

Use a declared parameter, or add the name to the <...> list:

struct Box<T> { T value; }
void main() {}

E0616

'<name>' is a standard interface; pick another name

The program declares an interface with the name of a standard one, such as Eq, Ord, Hash, Format, Into, Drop or Num.

interface Eq { bool eq(int x); }
void main() {}

Rename the interface:

interface Matches { bool eq(int x); }
void main() {}

E0617

interface '<name>' is declared twice

Two interfaces have the same name in the same namespace.

interface Shape { double area(); }
interface Shape { double perimeter(); }
void main() {}

Merge them into one interface, or rename one:

interface Shape {
    double area();
    double perimeter();
}
void main() {}

E0618

interface <interface> declares '<name>' twice

An interface lists two methods with the same name. A method name means one thing per interface, so overloads aren't allowed.

interface Twice {
    int f();
    int f();
}
void main() {}

Remove the duplicate, or give it another name:

interface Twice {
    int f();
    int g();
}
void main() {}

E0619

interface methods can't be static

Interface methods are called on a value, so each one takes self.

interface Shape {
    static double unit();
    double area();
}
void main() {}

Remove the static method from the interface, or make it an instance method:

interface Shape {
    double unit();
    double area();
}
void main() {}

E0620

'self' is implicit in methods; remove this parameter

A method or interface method lists self as a parameter. Methods get self on their own.

struct P { int x; }
impl P {
    int get(P self) { return self.x; }
}
void main() {}

Remove the parameter:

struct P { int x; }
impl P {
    int get() { return self.x; }
}
void main() {}

E0621

'<name>' is a type, not an interface

A bound, an impl or a static if (T: ...) condition names a type where an interface belongs.

struct P { int x; }
double area<T: P>(T x) { return 0; }
void main() {}

Name an interface there:

interface Shape { double area(); }
struct P { int x; }
double area<T: Shape>(T x) { return 0; }
void main() {}

E0622

unknown interface '<name>'

A bound, an impl, a dyn type or a static if (T: ...) condition names an interface that doesn't exist.

double area<T: Shape>(T x) { return 0; }
void main() {}

Declare the interface, or fix its name:

interface Shape { double area(); }
double area<T: Shape>(T x) { return 0; }
void main() {}

E0623

interface <interface> takes <n> type argument<s>, as in <interface><string>, interface <interface> takes no type arguments

An interface is named with the wrong number of type arguments. A generic interface such as Into needs its arguments, and a plain one takes none.

string text<T: Into>(T x) { return x.into(); }
void main() {}

Give the interface its type arguments:

string text<T: Into<string>>(T x) { return x.into(); }
void main() {}

E0624

dyn <interface>: generic interfaces can't be used with dyn yet

A dyn type names an interface that has type parameters. dyn works only with non-generic interfaces for now.

interface Conv<U> { U conv(); }
void main() {
    dyn Conv<int> c;
}

Use an interface without type parameters:

interface ToInt { int conv(); }
struct N { int v; }
impl ToInt for N {
    int conv() { return self.v; }
}
void main() {
    dyn ToInt c = N{ 1 };
}

E0625

dyn Drop has no methods to call; every dyn value already drops what it holds

Drop has no method a program can call, so dyn Drop would be a value with nothing to do. Every dyn value already runs the drop of what it holds.

void main() {
    dyn Drop d;
}

Use dyn with an interface whose methods you call:

interface Shape { double area(); }
struct Square { double side; }
impl Shape for Square {
    double area() { return self.side * self.side; }
}
void main() {
    dyn Shape d = Square{ 2 };
}

E0626

dyn Num has no methods to call; Num only allows arithmetic in generic code

Num is a bound that permits arithmetic on a type parameter. It has no methods, so a dyn Num value could do nothing.

void total(dyn Num n) {}

Use a type parameter bounded by Num instead:

T twice<T: Num>(T n) { return n + n; }

E0627

interface <interface> can't be used with dyn: method '<name>' takes Self, interface <interface> can't be used with dyn: method '<name>' returns Self

A method of the interface takes or returns Self. A dyn value doesn't know which type it holds, so it can't accept or produce another value of that type.

interface Same { bool same(Self other); }
void main() {
    dyn Same s;
}

Use the interface as a bound on a type parameter instead, where Self is known:

interface Same { bool same(Self other); }
bool check<T: Same>(T a, T b) { return a.same(b); }
void main() {}

E0628

methods can't be added to <type>

An impl targets a type that can't hold methods: void, a dyn type, a function type, null or a type parameter.

interface Shape { double area(); }
impl dyn Shape {
    int sides() { return 0; }
}
void main() {}

Add the method to the interface, or to the concrete types:

interface Shape {
    double area();
    int sides();
}
void main() {}

E0629

a generic impl must be for a generic struct or enum, as in impl<T> Box<T>

An impl<T> targets a type that has no type parameters to bind.

struct P { int x; }
impl<T> P {
    int get() { return self.x; }
}
void main() {}

Drop the type parameters from a plain impl:

struct P { int x; }
impl P {
    int get() { return self.x; }
}
void main() {}

E0630

every type parameter of this impl must appear in its target

An impl<T, U> names a parameter its target doesn't use, so nothing could decide its type.

struct Box<T> { T value; }
impl<T, U> Box<T> {
    T get() { return self.value; }
}
void main() {}

Remove the unused parameter:

struct Box<T> { T value; }
impl<T> Box<T> {
    T get() { return self.value; }
}
void main() {}

E0631

Drop is only for ref struct: value types are copied, so drop() would run once per copy; use a ref struct for resources that must be released once

impl Drop targets a value type. Values are copied freely, so drop() would run once per copy.

struct Handle { int fd; }
impl Drop for Handle {
    void drop() { print("close", self.fd); }
}
void main() {}

Make the type a ref struct, which is released once:

ref struct Handle { int fd; }
impl Drop for Handle {
    void drop() { print("close", self.fd); }
}
void main() {}

E0632

Num is built in: only the integer and floating-point types implement it

A program writes impl Num. Num marks the number types, which have arithmetic built in.

struct Point { int x; }
impl Num for Point { }
void main() {}

Remove the impl, and add methods for the operations you need:

struct Point { int x; }
impl Point {
    Point add(Point o) { return Point{ .x = self.x + o.x }; }
}
void main() {}

E0633

<type> already implements <interface>; built-in types can't replace it

A program implements a standard interface such as Eq for a built-in type, which already has it. Standard interfaces can be implemented only for Moxy structs and enums.

impl Eq for int {
    bool eq(int o) { return true; }
}
void main() {}

Wrap the value in a struct and implement the interface for that:

struct Id { int v; }
impl Eq for Id {
    bool eq(Id o) { return self.v == o.v; }
}
void main() {}

E0634

a static method has no self; remove 'static' to take one

A static method lists self as a parameter. Static methods aren't called on a value.

struct P { int x; }
impl P {
    static int get(P self) { return self.x; }
}
void main() {}

Remove static and the parameter, so the method takes self:

struct P { int x; }
impl P {
    int get() { return self.x; }
}
void main() {}

E0635

method '<name>' is defined twice

One impl defines two methods with the same name. Moxy has no overloading.

struct P { int x; }
impl P {
    int get() { return self.x; }
    int get() { return 0; }
}
void main() {}

Remove one, or rename it:

struct P { int x; }
impl P {
    int get() { return self.x; }
    int zero() { return 0; }
}
void main() {}

E0636

<type> already implements <interface>

Two impls of the same interface, with the same type arguments, target one type.

interface Named { string name(); }
struct P { int x; }
impl Named for P {
    string name() { return "p"; }
}
impl Named for P {
    string name() { return "again"; }
}
void main() {}

Keep one impl:

interface Named { string name(); }
struct P { int x; }
impl Named for P {
    string name() { return "p"; }
}
void main() {}

E0637

<type> already has a method '<name>'

Two impls of one type define a method with the same name. A method name means one thing per type, across all its impls.

struct P { int x; }
impl P {
    int twice() { return self.x * 2; }
}
impl P {
    long twice() { return 0; }
}
void main() {}

Remove or rename one of them:

struct P { int x; }
impl P {
    int twice() { return self.x * 2; }
}
impl P {
    long zero() { return 0; }
}
void main() {}

E0638

conflicting types for <parameter> in <function>: <type> and <type>

The arguments of a generic call give one type parameter two different types.

T both<T>(T a, T b) { return a; }
void main() {
    auto d = both(1, "two");
}

Pass arguments of one type, or name the type argument and convert:

T both<T>(T a, T b) { return a; }
void main() {
    auto d = both(1, 2);
}

E0639

cannot infer type parameter <parameter> of <name>

Nothing in the call or literal decides a type parameter: no argument uses it and there is no declared type to take it from.

T make<T>() {
    T x = {};
    return x;
}
void main() {
    auto a = make();
}

Name the type argument, or declare the variable's type:

T make<T>() {
    T x = {};
    return x;
}
void main() {
    auto a = make<int>();
}

E0640

'<function>' is generic; call it, or name one instance as <function><<parameters>>

A generic function is used as a value without type arguments, so there is no single function to point at.

T id<T>(T x) { return x; }
void main() {
    auto f = id;
}

Name one instance:

T id<T>(T x) { return x; }
void main() {
    auto f = id<int>;
}

E0641

<name> is an enum; build it with <name>::Variant(...)

A generic enum is built with struct literal syntax. Enum values are built from a variant.

enum Option<T> { Some(T value), None }
void main() {
    auto o = Option{ 1 };
}

Name the variant:

enum Option<T> { Some(T value), None }
void main() {
    auto o = Option::Some(1);
}

E0642

'?' can't convert the error type <type> to <type>, which <function> returns (<type>)

? returns the error to the caller, but the caller's error type differs and there is no conversion. ? converts through Into<F>, or through Format when F is string.

struct Raw { int code; }
struct Wrapped { int code; }
Result<int, Raw> get() { return Err(Raw{ .code = 1 }); }
Result<int, Wrapped> wrap() {
    int n = get()?;
    return Ok(n);
}
void main() {}

Implement Into from the inner error type to the outer one:

struct Raw { int code; }
struct Wrapped { int code; }
impl Into<Wrapped> for Raw {
    Wrapped into() { return Wrapped{ .code = self.code }; }
}
Result<int, Raw> get() { return Err(Raw{ .code = 1 }); }
Result<int, Wrapped> wrap() {
    int n = get()?;
    return Ok(n);
}
void main() {}

E0643

'?' needs a Result or an optional; this is <type>

? unwraps a value that may be missing or failed. A plain value has nothing to unwrap.

Result<int> twice(int x) {
    int y = x?;
    return Ok(y * 2);
}
void main() {}

Remove the ?:

Result<int> twice(int x) {
    int y = x;
    return Ok(y * 2);
}
void main() {}

E0644

'?' returns from a function; it can only be used inside one

? returns early from the enclosing function, so it can't appear in a global initializer.

int? find() { return 1; }
int g = find()?;

Give a fallback with ??, or compute the value inside a function:

int? find() { return 1; }
int g = find() ?? 0;

E0645

'?' can't return from inside defer

A defer block runs while the function is already returning, so ? can't return from it.

Result<int> parse(string s) { return s == "" ? Err("empty") : Ok(1); }
Result<int> run() {
    defer { int z = parse("2")?; }
    return Ok(1);
}
void main() {}

Handle the result inside the block:

Result<int> parse(string s) { return s == "" ? Err("empty") : Ok(1); }
Result<int> run() {
    defer { int z = parse("2").unwrap_or(0); }
    return Ok(1);
}
void main() {}

E0646

'?' in a lambda needs its return type known

? returns from the lambda, so the lambda's return type must be known before its body is checked. A lambda assigned to auto infers its return type from the body.

Result<int> parse(string s) { return s == "" ? Err("empty") : Ok(1); }
void main() {
    auto f = (string s) => { int n = parse(s)?; return Ok(n + 1); };
}

Declare the lambda's type where it is stored or passed:

Result<int> parse(string s) { return s == "" ? Err("empty") : Ok(1); }
void main() {
    fn(string) -> Result<int> f = (string s) => { int n = parse(s)?; return Ok(n + 1); };
}

E0647

'?' on a Result needs the function to return a Result; <function> returns <type>

? on a failed Result returns the error from the enclosing function, so that function must return a Result too.

Result<int> parse(string s) { return s == "" ? Err("empty") : Ok(1); }
int total(string s) {
    int n = parse(s)?;
    return n;
}
void main() {}

Handle the error in place, or make the function return a Result:

Result<int> parse(string s) { return s == "" ? Err("empty") : Ok(1); }
int total(string s) {
    int n = parse(s).unwrap_or(0);
    return n;
}
void main() {}

E0648

'?' on an optional needs the function to return an optional; <function> returns <type>

? on a null optional returns null from the enclosing function, so that function must return an optional too.

int? find(int x) { return x > 0 ? x : null; }
Result<int> mixed(int x) {
    int y = find(x)?;
    return Ok(y);
}
void main() {}

Give a fallback with ??, or check it with if (x != null):

int? find(int x) { return x > 0 ? x : null; }
Result<int> mixed(int x) {
    int y = find(x) ?? 0;
    return Ok(y);
}
void main() {}

E0649

variant '<name>' is declared twice

Two variants of one enum have the same name, so Enum::Name could mean either.

enum Entry {
    File(string name),
    Dir(string name),
    File(string path),
}
void main() {}

Rename or remove one of them:

enum Entry {
    File(string name),
    Dir(string name),
}
void main() {}

Compile-time reflection

E0701

'<name>' is not a type reflection can read

The name before the dot is a type whose own definition failed, so reflection has nothing to read. It shows up after an earlier error in that type, most often a typedef of a generic struct written without its type arguments.

struct Pair<A, B> { A a; B b; }
typedef Pair Both;

void main() {
    print(Both.name);
}

Fix the earlier error first. Here the typedef needs the generic's arguments:

struct Pair<A, B> { A a; B b; }
typedef Pair<int, string> Both;

void main() {
    print(Both.name);
}

E0702

<type> is an enum; walk <type>.variants instead, <type> is a struct; walk <type>.fields instead, <type> has no fields; .fields needs a struct or ref struct

.fields was asked of an enum or a builtin type, or .variants of a struct. Only structs and ref structs have fields, and only Moxy enums have variants.

enum Color { Red, Green }

void main() {
    static for f in Color.fields { print(f.name); }
}

Walk the list the type has. In a generic body, ask T.is_struct or T.is_enum first:

enum Color { Red, Green }

void main() {
    static for c in Color.variants { print(c.name); }
}

E0703

<type> is a union; .fields covers structs and ref structs

.fields was asked of a union. Its members overlap in memory, so walking them as separate fields would read garbage; reflection only lists struct fields.

union Number { int i; float f; }

void main() {
    static for f in Number.fields { print(f.name); }
}

Use a struct, or a Moxy enum with payloads when only one member is live at a time:

struct Number { int i; float f; }

void main() {
    static for f in Number.fields { print(f.name); }
}

E0704

<type> has no definition Moxy can see

.fields was asked of a struct that is only declared, not defined. Without the body there are no fields to list.

struct Opaque;

void main() {
    static for f in Opaque.fields { print(f.name); }
}

Define the struct in this file or in a Moxy file it includes:

struct Opaque { int id; };

void main() {
    static for f in Opaque.fields { print(f.name); }
}

E0705

<type> is not a Moxy enum; .variants needs one

.variants was asked of a type that is not a Moxy enum, here a builtin type reached through a type parameter. The error is reported for the instance that supplied it.

void names<T>() {
    static for c in T.variants { print(c.name); }
}

void main() {
    names<int>();
}

Guard the walk with T.is_enum, or only instantiate the generic with enums:

void names<T>() {
    static if (T.is_enum) {
        static for c in T.variants { print(c.name); }
    }
}

void main() {
    names<int>();
}

E0706

<type> has no .<part>

T.elem was used on a type that is not a list, slice or optional, or T.key or T.value on a type that is not a map. The error is reported for the instance that supplied the type.

void first<T>(T v) {
    T.elem e;
}

void main() {
    first(5);
}

Ask what kind of type T is before naming its parts:

void first<T>(T v) {
    static if (T.is_list) {
        T.elem e;
    }
}

void main() {
    first(5);
}

E0707

a type has no compile-time property '<name>'

The property after a type is not one reflection knows. Types have name, fields, variants, elem, key, value and the is_ tests; the help line lists them.

struct Point { int x; int y; }

void main() {
    print(Point.size);
}

Use one of the listed properties, or sizeof for the size:

struct Point { int x; int y; }

void main() {
    print(Point.name, sizeof(Point));
}

E0708

a compile-time list has no property '<name>'

T.fields, T.variants and a variant's .fields are compile-time lists. The only property they have is .len.

struct Point { int x; int y; }

void main() {
    print(Point.fields.count);
}

Take .len, or walk the list with static for:

struct Point { int x; int y; }

void main() {
    print(Point.fields.len);
}

E0709

a variant has no compile-time property '<name>'

The loop variable of a static for over T.variants stands for a variant, which has name, index and fields only.

enum Color { Red, Green }

void main() {
    static for c in Color.variants { print(c.offset); }
}

Use one of those properties:

enum Color { Red, Green }

void main() {
    static for c in Color.variants { print(c.index); }
}

E0710

a field has no compile-time property '<name>'

The loop variable of a static for over fields stands for a field, which has name, index and type only. The field's value is read with v.[f].

struct Point { int x; int y; }

void main() {
    static for f in Point.fields { print(f.offset); }
}

Use one of those properties:

struct Point { int x; int y; }

void main() {
    static for f in Point.fields { print(f.index); }
}

E0711

expected a compile-time value such as T.fields or f.name

One side of a type comparison in static if is neither a type nor a reflection expression. A comparison with a type such as int needs a type on the other side too.

void main() {
    static if (1 == int) { print(1); }
}

Compare a type with a type:

void main() {
    static if (long == int) { print(1); }
}

E0712

a compile-time constant has no property '<name>'

f.name, T.name, f.index and .len fold to plain constants, which have no further compile-time properties.

struct Point { int x; int y; }

void main() {
    print(Point.name.len);
}

Store the constant in a variable and use its run-time properties there:

struct Point { int x; int y; }

void main() {
    string n = Point.name;
    print(n.len);
}

E0713

'.<name>' is a type, not a value, '.<name>' is a compile-time list, not a value

A type such as f.type or T.elem, or a list such as T.fields, was used where a value goes. Neither exists at run time.

struct Point { int x; int y; }

void main() {
    print(Point.fields);
}

Take a value from it, such as .len, or walk it with static for. Use f.type only where a type goes:

struct Point { int x; int y; }

void main() {
    print(Point.fields.len);
}

E0714

'<name>' is not the variable of an enclosing static for

v.[f] reads the field that f names, so f must be the variable of a static for over fields that encloses it. An ordinary variable can't select a field.

struct Point { int x; int y; }

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    int f = 0;
    print(p.[f]);
}

Walk the fields and select with the loop variable:

struct Point { int x; int y; }

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    static for f in Point.fields { print(p.[f]); }
}

E0715

'<name>' is <kind>; v.[f] needs a struct field

v.[f] was given the variable of a static for over an enum's variants or a variant's fields. A variant's payload has no lvalue form, so v.[f] only takes struct fields.

struct Point { int x; int y; }
enum Color { Red, Green }

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    static for c in Color.variants { print(p.[c]); }
}

Select with the variable of a loop over the struct's fields. Read a variant's payload with match:

struct Point { int x; int y; }

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    static for f in Point.fields { print(p.[f]); }
}

E0716

'<name>.type' needs '<name>' to be the variable of an enclosing static for

f.type names the type of the field f stands for. Here a local declared inside the loop hides the loop variable, so f is no longer a field.

struct Point { int x; int y; }

void main() {
    static for f in Point.fields {
        int f = 0;
        f.type copy = 1;
    }
}

Give the local another name:

struct Point { int x; int y; }

void main() {
    static for f in Point.fields {
        int n = 0;
        f.type copy = 1;
    }
}

E0717

'<name>' is a variant; variants have no type

c.type was used with the variable of a static for over variants. A variant is not a value of one type; its payload is a list of fields, each with its own type.

enum Shape { Circle(float r), Rect(int w, int h) }

void main() {
    static for c in Shape.variants { c.type x; }
}

Walk the variant's payload and take each field's type:

enum Shape { Circle(float r), Rect(int w, int h) }

void main() {
    static for c in Shape.variants {
        static for f in c.fields { f.type x; }
    }
}

E0718

static for runs over T.fields, T.variants or a variant's .fields

The source of a static for must be a list known at compile time. A run-time value such as a list variable is walked with a plain for.

void main() {
    int[] xs = [1, 2, 3];
    static for x in xs { print(x); }
}

Use a plain for:

void main() {
    int[] xs = [1, 2, 3];
    for x in xs { print(x); }
}

E0719

expected a type to compare with

One side of a type comparison in static if is a compile-time constant, not a type. == and != with a type on one side compare types, so both sides must be types.

struct Point { int x; int y; }

void main() {
    static if (Point == Point.fields.len) { print(1); }
}

Compare types with types, and numbers with numbers:

struct Point { int x; int y; }

void main() {
    static if (Point.fields.len == 2) { print(1); }
}

E0720

division by zero in a static if condition

A / or % in a static if condition has a right side that folds to zero, so the condition has no value.

struct Point { int x; int y; }

void main() {
    static if (4 / (Point.fields.len - 2)) { print(1); }
}

Rewrite the condition so it never divides by zero:

struct Point { int x; int y; }

void main() {
    static if (Point.fields.len > 2) { print(1); }
}

E0721

'<op>' is not allowed in a static if condition

A static if condition is folded at compile time from integer arithmetic, comparisons, &&, ||, ! and type comparisons. Operators that need a place in memory, such as &, * and ++, have nothing to work on there.

struct Point { int x; int y; }

void main() {
    static if (++Point.fields.len > 2) { print(1); }
}

Use plain arithmetic:

struct Point { int x; int y; }

void main() {
    static if (Point.fields.len + 1 > 2) { print(1); }
}

E0722

a type is not a condition; compare it, as in f.type == int

A type on its own was used as a static if condition. A type has no truth value; compare it with another type, or ask one of its is_ properties.

struct Point { int x; int y; }

void main() {
    static if (Point) { print(1); }
}

Ask a question about the type:

struct Point { int x; int y; }

void main() {
    static if (Point.is_struct) { print(1); }
}

E0723

a static if condition needs an integer here

A reflection expression in a static if condition folds to a string or a list, not an integer. Names such as f.name and lists such as T.fields can't be tested for truth.

struct Point { int x; int y; }

void main() {
    static if (Point.fields) { print(1); }
}

Use an integer property such as .len or .index:

struct Point { int x; int y; }

void main() {
    static if (Point.fields.len) { print(1); }
}

E0724

static if needs a condition known at compile time

The condition uses something only known at run time, such as a variable, a call or sizeof. static if decides at compile time which branch exists.

void main() {
    int x = 1;
    static if (x) { print(1); }
}

Use a plain if for a run-time condition:

void main() {
    int x = 1;
    if (x) { print(1); }
}

Match, patterns and control flow

E0801

<Enum> has no variant '<name>'

A pattern or a constructor names a variant the enum doesn't declare. In a pattern, a capitalized bare name that is neither a variant nor a known constant also lands here.

enum Light { Red, Amber, Green }

void main() {
    Light l = Light::Red;
    match l {
        Light::Blue => print("blue"),
        _ => print("other"),
    }
}

Use one of the enum's variants, or add the variant to the enum:

enum Light { Red, Amber, Green }

void main() {
    Light l = Light::Red;
    match l {
        Light::Green => print("green"),
        _ => print("other"),
    }
}

E0803

this alternative never matches: earlier patterns cover it

One alternative of an a | b pattern is already matched by an earlier arm or an earlier alternative, so it can never be the one that matches.

void main() {
    int n = 2;
    match n {
        1 | 2 => print("small"),
        3 | 2 => print("again"),
        _ => print("other"),
    }
}

Drop the covered alternative:

void main() {
    int n = 2;
    match n {
        1 | 2 => print("small"),
        3 => print("three"),
        _ => print("other"),
    }
}

E0804

match on <type> needs a '_ =>' arm

The match is over values that arms can't list out, such as numbers, strings, or a struct whose fields hold them. Only a _ arm, or a binding arm without a guard, covers the rest.

void main() {
    string s = "b";
    match s {
        "a" => print("a"),
        "b" => print("b"),
    }
}

Add a _ => arm for every other value:

void main() {
    string s = "b";
    match s {
        "a" => print("a"),
        "b" => print("b"),
        _ => print("other"),
    }
}

E0805

match is not exhaustive; missing <patterns>

A match on an enum, an optional, a Result or a bool must handle every case. The message lists the cases no arm covers. A guarded arm never counts as covering its pattern.

enum Color { Red, Green, Blue }

void main() {
    Color c = Color::Red;
    match c {
        Color::Red => print("r"),
        Color::Green => print("g"),
    }
}

Add the missing arms, or a _ => arm:

enum Color { Red, Green, Blue }

void main() {
    Color c = Color::Red;
    match c {
        Color::Red => print("r"),
        Color::Green => print("g"),
        Color::Blue => print("b"),
    }
}

E0806

cannot match on a value of type <type>

match works on enums, optionals, Results, numbers, chars, bools, strings and structs. Lists, maps, unions and pointers have no patterns.

void main() {
    int[] xs = [1, 2, 3];
    match xs {
        _ => print("list"),
    }
}

Match on something derived from the value, such as its length:

void main() {
    int[] xs = [1, 2, 3];
    match xs.len() {
        0 => print("empty"),
        _ => print("list"),
    }
}

E0807

a range loop has one variable

A loop over a range such as 0..n binds only the current number. There is no separate index, so a second variable is an error. This applies to parallel for too.

void main() {
    for i, v in 0..3 {
        print(i);
    }
}

Use one variable; it already is the index:

void main() {
    for i in 0..3 {
        print(i);
    }
}

E0808

'<name>' is bound twice in this pattern

A pattern binds the same name in two places. A pattern can't compare its parts with each other; each name binds once.

enum Shape { Rect(int w, int h), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Rect(w, w) => print("square"),
        _ => print("other"),
    }
}

Bind two names and compare them in a guard:

enum Shape { Rect(int w, int h), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Rect(w, h) if w == h => print("square"),
        _ => print("other"),
    }
}

E0809

'<name>' is not bound by the first alternative, this alternative does not bind '<name>'

Every alternative of p1 | p2 must bind the same names, since the arm's body uses them whichever alternative matched.

enum Shape { Circle(double r), Square(double side), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Circle(x) | Shape::Square(y) => print("shape"),
        _ => print("other"),
    }
}

Use the same name in each alternative, or _ where the value isn't needed:

enum Shape { Circle(double r), Square(double side), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Circle(x) | Shape::Square(x) => print(x),
        _ => print("other"),
    }
}

E0810

'<name>' is <type> here but <type> in the first alternative

A name bound in several alternatives of p1 | p2 must have the same type in each, so the arm's body sees one variable of one type.

enum Shape { Circle(double r), Label(string text), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Circle(x) | Shape::Label(x) => print(x),
        _ => print("other"),
    }
}

Split the alternatives into separate arms:

enum Shape { Circle(double r), Label(string text), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Circle(x) => print(x),
        Shape::Label(x) => print(x),
        _ => print("other"),
    }
}

E0811

'<name>' would bind a void value

The pattern binds a name to a payload that has no value, such as the Ok of a Result<void>. There is nothing for the variable to hold.

Result<void> save() {
    return Ok();
}

void main() {
    match save() {
        Ok(v) => print("saved"),
        Err(e) => print(e),
    }
}

Match the constructor without binding its payload:

Result<void> save() {
    return Ok();
}

void main() {
    match save() {
        Ok(_) => print("saved"),
        Err(e) => print(e),
    }
}

E0812

pattern '<path>' does not belong to <Enum>

A pattern names a variant through an enum other than the type of the value being matched.

enum Color { Red, Green }
enum Shape { Circle, Square }

void main() {
    Shape s = Shape::Circle;
    match s {
        Color::Red => print("red"),
        _ => print("other"),
    }
}

Use the variants of the matched value's own enum:

enum Color { Red, Green }
enum Shape { Circle, Square }

void main() {
    Shape s = Shape::Circle;
    match s {
        Shape::Circle => print("circle"),
        _ => print("other"),
    }
}

E0813

Some binds one value, None binds nothing, patterns for an optional are Some(value), None and _

A pattern on an optional is Some(p) with exactly one subpattern, a bare None, a binding or _. Any other constructor, or the wrong number of subpatterns, is an error.

void main() {
    int? n = 3;
    match n {
        Some(a, b) => print(a),
        None => print("none"),
    }
}

Give Some one subpattern:

void main() {
    int? n = 3;
    match n {
        Some(a) => print(a),
        None => print("none"),
    }
}

E0814

Ok binds one value, Err binds one error, patterns for a Result are Ok(value), Err(error) and _

A pattern on a Result is Ok(p), Err(p), a binding or _, and each constructor takes at most one subpattern.

Result<int> parse() {
    return Ok(1);
}

void main() {
    match parse() {
        Ok(a, b) => print(a),
        Err(e) => print(e),
    }
}

Give Ok and Err one subpattern each:

Result<int> parse() {
    return Ok(1);
}

void main() {
    match parse() {
        Ok(a) => print(a),
        Err(e) => print(e),
    }
}

E0815

<Enum>::<Variant> carries <n> value<s>, the pattern binds <n>

A variant pattern has more subpatterns than the variant has payload values.

enum Shape { Rect(int w, int h), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Rect(w, h, d) => print(w),
        _ => print("other"),
    }
}

Write one subpattern per payload value:

enum Shape { Rect(int w, int h), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Rect(w, h) => print(w),
        _ => print("other"),
    }
}

E0816

pattern '<name>' does not fit a value of type <type>

A constructor pattern such as Some(x) or Circle(r) is used on a value that has no such constructor, for example a plain int.

void main() {
    int n = 4;
    match n {
        Some(v) => print(v),
        _ => print("other"),
    }
}

Match the value with patterns of its own type, or make the value optional:

void main() {
    int? n = 4;
    match n {
        Some(v) => print(v),
        _ => print("other"),
    }
}

E0817

a struct pattern cannot match a value of type <type>

A struct pattern Point{ ... } is used on a value that isn't a struct.

struct Point {
    int x;
    int y;
}

void main() {
    int n = 0;
    match n {
        Point{ .x = 0 } => print("origin"),
        _ => print("other"),
    }
}

Match a struct value with a struct pattern:

struct Point {
    int x;
    int y;
}

void main() {
    Point p = Point{ .x = 0, .y = 1 };
    match p {
        Point{ .x = 0 } => print("on the axis"),
        _ => print("other"),
    }
}

E0818

pattern '<Name>' cannot match a value of type <type>

A struct pattern names a different struct than the type of the matched value.

struct Point {
    int x;
    int y;
}

struct Size {
    int w;
    int h;
}

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    match p {
        Size{ .w = 0 } => print("size"),
        _ => print("other"),
    }
}

Name the matched value's own struct:

struct Point {
    int x;
    int y;
}

struct Size {
    int w;
    int h;
}

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    match p {
        Point{ .x = 0 } => print("left"),
        _ => print("other"),
    }
}

E0819

a pattern cannot read the fields of actor <A>

An actor's fields belong to its own thread, so a struct pattern can't read them from outside.

actor Counter {
    int n;
}

void main() {
    Counter c = Counter{};
    match c {
        Counter{ .n = 0 } => print("zero"),
        _ => print("more"),
    }
}

Add a method that returns what to match on, and match on its awaited result:

actor Counter {
    int n;
    int count() { return n; }
}

void main() {
    Counter c = Counter{};
    match await c.count() {
        0 => print("zero"),
        _ => print("more"),
    }
}

E0820

a pattern cannot read the fields of a shared ref struct

Fields of a shared ref struct may be written by other threads, so they are read under lock. A pattern would read them without it.

shared ref struct Counter {
    int n;
}

void main() {
    Counter c = Counter{ .n = 0 };
    match c {
        Counter{ .n = 0 } => print("zero"),
        _ => print("more"),
    }
}

Read the fields inside lock and match on the values:

shared ref struct Counter {
    int n;
}

void main() {
    Counter c = Counter{ .n = 0 };
    lock (c) {
        match c.n {
            0 => print("zero"),
            _ => print("more"),
        }
    }
}

E0821

'<name>' is a field of an anonymous member; a pattern cannot name it

A struct pattern names a field that lives in an anonymous union or struct member. Patterns only reach the struct's direct fields.

struct Value {
    int tag;
    union {
        int i;
        double d;
    };
}

void main() {
    Value v = Value{ .tag = 0 };
    match v {
        Value{ .i = 0 } => print("zero"),
        _ => print("other"),
    }
}

Match on the field's value directly:

struct Value {
    int tag;
    union {
        int i;
        double d;
    };
}

void main() {
    Value v = Value{ .tag = 0 };
    match v.i {
        0 => print("zero"),
        _ => print("other"),
    }
}

E0822

a pattern cannot read the <weak|atomic> field '<name>'

A weak field can be cleared and an atomic field changed by another thread at any moment, so a pattern can't test them as plain values.

ref struct Box {
    int id;
    weak Box? parent;
}

void main() {
    Box b = Box{ .id = 1 };
    match b {
        Box{ .parent = None } => print("orphan"),
        _ => print("child"),
    }
}

Read the field into a local first, then match on that:

ref struct Box {
    int id;
    weak Box? parent;
}

void main() {
    Box b = Box{ .id = 1 };
    Box? p = b.parent;
    match p {
        None => print("orphan"),
        _ => print("child"),
    }
}

E0823

field '<name>' is named twice in this pattern

A struct pattern names the same field more than once. One field holds one value.

struct Point {
    int x;
    int y;
}

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    match p {
        Point{ .x = 0, .x = 1 } => print("twice"),
        _ => print("other"),
    }
}

Name each field once, and use | for several values:

struct Point {
    int x;
    int y;
}

void main() {
    Point p = Point{ .x = 1, .y = 2 };
    match p {
        Point{ .x = 0 } | Point{ .x = 1 } => print("near"),
        _ => print("other"),
    }
}

E0824

this pattern does not fit a value of type <type>

A literal or constant is used where the matched value is an enum, optional or Result, which are matched by their variants.

enum Shape { Circle(double r), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        3 => print("three"),
        _ => print("other"),
    }
}

Match with the type's variants:

enum Shape { Circle(double r), Empty }

void main() {
    Shape s = Shape::Empty;
    match s {
        Shape::Empty => print("empty"),
        _ => print("other"),
    }
}

E0825

pattern of type <type> cannot match <type>

A literal pattern has a different type from the matched value, such as a string against an int.

void main() {
    int n = 4;
    match n {
        "four" => print("four"),
        _ => print("other"),
    }
}

Use a literal of the value's type:

void main() {
    int n = 4;
    match n {
        4 => print("four"),
        _ => print("other"),
    }
}

E0826

static locals of managed types need a literal or null initializer

A static local is initialized once, before the program runs any code, so a managed type (a string, list, map or ref struct) can only start as a literal or null.

string make() {
    return "hi";
}

void main() {
    static string s = make();
    print(s);
}

Start it as a literal and fill it in on first use:

string make() {
    return "hi";
}

void main() {
    static string s = "";
    if (s == "") s = make();
    print(s);
}

E0827

function declarations inside functions are not supported

A function prototype is written inside a function body. Moxy declares functions only at the top level.

void main() {
    int twice(int x);
    print(twice(2));
}

int twice(int x) {
    return x * 2;
}

Move the declaration to the top level, or drop it, since functions can be used before their definition:

void main() {
    print(twice(2));
}

int twice(int x) {
    return x * 2;
}

E0828

range bounds must be integers

Both ends of a range a..b must be integers. A range counts up one at a time, which has no meaning for floating-point bounds.

void main() {
    for i in 0.0..3.0 {
        print(i);
    }
}

Use integer bounds, and compute any fractional value inside the loop:

void main() {
    for i in 0..3 {
        print(i * 0.5);
    }
}

E0829

a channel loop has one variable

A loop over a channel receives one value per iteration and has no index, so it binds one variable.

void main() {
    chan<int> c = chan<int>(1);
    c.send(1);
    c.close();
    for i, v in c {
        print(v);
    }
}

Bind one variable, and count separately if you need an index:

void main() {
    chan<int> c = chan<int>(1);
    c.send(1);
    c.close();
    for v in c {
        print(v);
    }
}

E0830

cannot iterate over an array of unknown length

A for ... in loop over a C array needs the array's length, and an array declared as T name[] without an initializer has none.

extern int table[];

void main() {
    for x in table {
        print(x);
    }
}

Give the array a length or an initializer, or loop with an index up to a known count:

int table[] = {1, 2, 3};

void main() {
    for x in table {
        print(x);
    }
}

E0831

cannot iterate over a value of type <type>

for ... in works on lists, maps, strings, C arrays, channels and ranges. Other values, including numbers and pointers, have nothing to iterate.

void main() {
    int n = 5;
    for i in n {
        print(i);
    }
}

To count to a number, loop over a range:

void main() {
    int n = 5;
    for i in 0..n {
        print(i);
    }
}

E0832

return is not allowed inside defer, break is not allowed inside defer, continue is not allowed inside defer

Deferred code runs while the scope is being left, during cleanup, so it can't jump elsewhere.

int run() {
    defer {
        return 1;
    }
    return 0;
}

void main() {
    print(run());
}

Keep the jump in the function body, and use defer only for cleanup:

int run() {
    defer {
        print("done");
    }
    return 1;
}

void main() {
    print(run());
}

E0833

return can't leave a parallel for: its iterations run at once, on several threads, break can't stop a parallel for: its iterations run at once, on several threads

The iterations of a parallel for run at the same time on several threads, so no one iteration can end the loop or return from the function.

void main() {
    parallel for i in 0..4 {
        if (i == 2) { break; }
        print(i);
    }
}

Use continue to end the current iteration, or a plain for when the loop must stop early:

void main() {
    parallel for i in 0..4 {
        if (i == 2) { continue; }
        print(i);
    }
}

E0834

this function must return a value

A bare return; appears in a function that returns a value. Only void functions, and main, may return without one.

int pick(bool b) {
    if (b) return;
    return 1;
}

void main() {
    print(pick(true));
}

Return a value of the function's type:

int pick(bool b) {
    if (b) return 0;
    return 1;
}

void main() {
    print(pick(true));
}

E0835

a void function cannot return a value

A void function has return with a value. Its callers have nothing to receive.

void log(string s) {
    print(s);
    return 1;
}

void main() {
    log("hi");
}

Drop the value, or give the function a return type:

void log(string s) {
    print(s);
    return;
}

void main() {
    log("hi");
}

E0836

break outside of a loop or switch, continue outside of a loop

break only leaves a loop or a switch, and continue only moves to the next iteration of a loop.

void main() {
    int n = 1;
    if (n > 0) {
        break;
    }
    print(n);
}

To leave a function early, use return:

void main() {
    int n = 1;
    if (n > 0) {
        return;
    }
    print(n);
}

E0837

switch needs an integer, found <type>

A C switch branches on integers, chars and C enums. Other values, such as strings, are matched with match.

void main() {
    string s = "a";
    switch (s) {
        case 1: print("one"); break;
    }
}

Use match to branch on a string:

void main() {
    string s = "a";
    match s {
        "a" => print("a"),
        _ => print("other"),
    }
}

E0838

'<name>' needs its own block inside a switch

A managed variable is declared directly in a switch body. A case label can jump past its initialization, and cleanup would then release garbage.

void main() {
    int k = 1;
    switch (k) {
        case 1:
        string s = "one";
        print(s);
        break;
    }
}

Wrap the case body in braces:

void main() {
    int k = 1;
    switch (k) {
        case 1: {
            string s = "one";
            print(s);
            break;
        }
    }
}

Memory, ownership and gates

These protect the automatic memory management (see memory.md).

E0901

gates are nested more than <n> deep

Gates can be nested at most 64 deep. This is reported when code is generated, so moxy check doesn't show it; moxy emit and builds do.

void main() {
    gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{gate{ print(1); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
}

Nest fewer gates; one gate around the work is usually enough:

void main() {
    gate { print(1); }
}

E0902

'<function>' is `in gate`: its result is made in its caller's gate, so it can't be returned from inside a gate of its own, which would copy it out

An in gate function allocates its result in its caller's gate. Returning from inside a gate of its own would hand back something made in that inner gate, which is freed when the block ends.

string[] words(string s) in gate {
    gate {
        return s.split(" ");
    }
}

void main() {
    print("\(words("a b"))");
}

Declare the result before the inner gate {, and return it after the block:

string[] words(string s) in gate {
    string[] out = s.split(" ");
    gate {
        print(out.len);
    }
    return out;
}

void main() {
    print("\(words("a b"))");
}

E0903

a case label of a switch outside a gate can't be inside the gate

A case or default label inside a gate that belongs to a switch outside it would jump into the middle of the gate, past its start.

void main() {
    int x = 1;
    switch (x) {
        case 1:
        gate {
            case 2:
            x++;
        }
        break;
    }
}

Put the whole switch inside the gate, or the gate inside the case:

void main() {
    int x = 1;
    switch (x) {
        case 1:
        case 2:
        gate {
            x++;
        }
        break;
    }
}

E0904

<goto or a label> can't be used inside a gate: it would jump past the gate's start or end

A goto or a label inside a gate could jump into it past its start or out of it past its end, skipping the code that opens or frees the gate.

void main() {
    int x = 1;
    gate {
        if (x) goto out;
        x++;
    }
    out:
    return;
}

Use structured control flow inside the gate instead:

void main() {
    int x = 1;
    gate {
        if (!x) {
            x++;
        }
    }
    return;
}

E0905

'<function>' can't be `in gate`: <an async function's or a Future function's> body never runs in its caller's gate

An in gate function allocates in its caller's gate. An async or Future<T> function's body runs later or on another thread, outside that gate.

async int count(string s) in gate { return s.len(); }

void main() {
    print(await count("abc"));
}

Drop in gate:

async int count(string s) { return s.len(); }

void main() {
    print(await count("abc"));
}

E0906

gate (...) needs an Arena, found <type>

gate (x) { ... } allocates from the Arena x, the one from std/arena.mxy. Any other type is rejected.

void main() {
    int n = 3;
    gate (n) { print(n); }
}

Make an Arena with Arena::new() and pass it, or use a plain gate { ... }:

#include "std/arena.mxy"

void main() {
    int n = 3;
    Arena a = Arena::new();
    gate (a) { print(n); }
}

E0907

<a ref struct T> made inside a gate can't be passed to async '<function>': the call may outlive the gate, and ref structs can't be copied out

An async call may still be running after the gate ends and frees what was made inside it. A ref struct has identity, so it can't be copied out to survive.

ref struct Box { int v; }

async int read(Box b) { return b.v; }

void main() {
    gate {
        Box inside = Box{ .v = 2 };
        print(await read(inside));
    }
}

Make the object before the gate:

ref struct Box { int v; }

async int read(Box b) { return b.v; }

void main() {
    Box outside = Box{ .v = 2 };
    gate {
        print(await read(outside));
    }
}

E0908

a ref struct <T> made inside a gate can't leave it: ref structs have identity and can't be copied out

A ref struct made inside a gate is freed with it. Returning it, or storing it somewhere declared outside the gate, would keep a reference to freed memory, and it can't be copied out because it has identity.

ref struct Node { int v; }

Node made() {
    gate {
        Node n = Node{ .v = 1 };
        return n;
    }
}

void main() {
    print(made().v);
}

Create it before gate { and fill it inside:

ref struct Node { int v; }

Node made() {
    Node n = Node{ .v = 0 };
    gate {
        n.v = 1;
    }
    return n;
}

void main() {
    print(made().v);
}

E0909

<type> holds ref structs that may be made inside the gate; they can't be copied out

The same rule as E0908, for a value that holds ref structs: a list of them, or a struct with one as a field. Copying the value out of the gate would keep references to objects freed with it.

ref struct Node { int v; }

struct Wrap { Node n; }

void main() {
    Wrap w = Wrap{ .n = Node{ .v = 1 } };
    gate {
        w = Wrap{ .n = Node{ .v = 2 } };
    }
    print(w.n.v);
}

Create the objects before gate { and fill them inside:

ref struct Node { int v; }

struct Wrap { Node n; }

void main() {
    Wrap w = Wrap{ .n = Node{ .v = 1 } };
    gate {
        w.n.v = 2;
    }
    print(w.n.v);
}

Threads, channels, actors and parallel loops

Values that cross into a task, out of one or through a channel must be safe to share (see Sharing between threads).

E1001

field '<field>' of actor <A> is reached only by its own methods

An actor's fields are touched only by its own methods, one message at a time. Reading or writing one from outside, through another actor, or in a lambda inside a method (which may run elsewhere, later) would race with those messages.

actor Counter {
    long n;
    void bump() { self.n += 1; }
}

void main() {
    Counter c = Counter{};
    c.bump();
    print(c.n);
}

Add a method that returns the field, and await it:

actor Counter {
    long n;
    void bump() { self.n += 1; }
    long get() { return self.n; }
}

void main() {
    Counter c = Counter{};
    c.bump();
    print(await c.get());
}

E1002

a method of actor <A> can't be async: called from outside, it is a message already

Calling an actor's method from outside sends a message and returns a Future already, so async adds nothing.

actor Svc {
    int n;
    async int slow() { return 1; }
}

void main() {
    Svc s = Svc{};
    print(await s.slow());
}

Drop async; callers still get a Future<int>:

actor Svc {
    int n;
    int slow() { return 1; }
}

void main() {
    Svc s = Svc{};
    print(await s.slow());
}

E1003

a method of actor <A> can't return a Future: called from outside, it returns one already

A call to an actor's method from outside already returns a Future of its result. Declaring the method to return one would make it a Future of a Future.

actor Svc {
    int n;
    Future<int> pooled() { return 2; }
}

void main() {
    Svc s = Svc{};
    print(await s.pooled());
}

Return the value itself:

actor Svc {
    int n;
    int pooled() { return 2; }
}

void main() {
    Svc s = Svc{};
    print(await s.pooled());
}

E1004

actor <A> can't implement <interface>: its methods would be called directly, from any thread

An interface's methods are called directly, not as messages, so they would run on any thread at the same time as the actor's messages. Only Drop is allowed.

actor Svc {
    int n;
}

impl Format for Svc {
    void format(Buf *b) { b.put("svc"); }
}

void main() {
    Svc s = Svc{};
}

Add a method to the actor and call it as a message instead:

actor Svc {
    int n;
    string name() { return "svc"; }
}

void main() {
    Svc s = Svc{};
    print(await s.name());
}

E1005

atomic fields are only allowed in shared ref structs

atomic matters only when several threads use one object. A plain struct or ref struct can't be shared between threads, so atomic is rejected there.

ref struct Solo {
    atomic int a;
}

void main() {
    Solo s = Solo{};
}

Make it a shared ref struct, or drop atomic:

shared ref struct Solo {
    atomic int a;
}

void main() {
    Solo s = Solo{};
}

E1006

an atomic field can't have a bit width

A bit field shares its storage word with other fields, so it can't be read or written as one atomic operation.

shared ref struct Flags {
    atomic int bits: 3;
}

void main() {
    Flags f = Flags{};
}

Drop the bit width:

shared ref struct Flags {
    atomic int bits;
}

void main() {
    Flags f = Flags{};
}

E1007

atomic fields hold an integer, bool or C pointer, found <type>

Only integers, bool and C pointers have atomic operations. A string, double or other managed value can't be updated atomically.

shared ref struct Stats {
    atomic double ratio;
}

void main() {
    Stats s = Stats{};
}

Make it a plain field and use it inside lock (x) { ... }:

shared ref struct Stats {
    double ratio;
}

void main() {
    Stats s = Stats{};
    lock (s) { s.ratio = 0.5; }
}

E1008

'<op>' on atomic field '<field>' is not one atomic operation

Only some updates are one atomic operation: =, +=, -=, &=, |=, ^=, ++ and -- on an integer, and = on a bool or pointer. Others, such as *= or <<=, would read and write in two steps another thread could slip between.

shared ref struct Counter {
    atomic long n;
}

void main() {
    Counter c = Counter{};
    c.n *= 2;
}

Make it a plain field and update it inside lock, or use an operation that is atomic:

shared ref struct Counter {
    long n;
}

void main() {
    Counter c = Counter{};
    lock (c) { c.n *= 2; }
}

E1009

a channel's capacity is an integer, found <type>

chan<T>(n) makes a channel that buffers up to n values, so n has to be an integer.

void main() {
    chan<int> c = chan<int>("big");
}

Pass an integer, or nothing for an unbuffered channel:

void main() {
    chan<int> c = chan<int>(16);
}

E1010

<a select receive or a select send> needs a channel, found <type>

A select arm's recv() or send(...) has to be called on a channel.

void main() {
    int n = 3;
    select {
        n.send(1) => print("no"),
    }
}

Use a channel:

void main() {
    chan<int> c = chan<int>(1);
    select {
        c.send(1) => print("sent"),
    }
}

E1011

timeout takes milliseconds as an integer, found <type>

A select arm's timeout(ms), and a Future's .timeout(ms), take a number of milliseconds as an integer.

void main() {
    chan<int> c = chan<int>(1);
    select {
        x = c.recv() => print(x),
        timeout("soon") => print("slow"),
    }
}

Pass an integer:

void main() {
    chan<int> c = chan<int>(1);
    select {
        x = c.recv() => print(x),
        timeout(100) => print("slow"),
    }
}

E1012

select has more than one timeout arm, select has more than one default arm

A select has at most one timeout arm and at most one default arm; a second one could never run.

void main() {
    chan<int> c = chan<int>(1);
    select {
        x = c.recv() => print(x),
        default => print("a"),
        default => print("b"),
    }
}

Keep one, and merge their bodies:

void main() {
    chan<int> c = chan<int>(1);
    select {
        x = c.recv() => print(x),
        default => print("a"),
    }
}

E1013

select has both a default and a timeout arm

default runs at once when no other arm is ready, so a timeout arm in the same select could never fire.

void main() {
    chan<int> c = chan<int>(1);
    select {
        x = c.recv() => print(x),
        default => print("idle"),
        timeout(5) => print("slow"),
    }
}

Keep one of them: default not to wait at all, timeout to wait at most that long:

void main() {
    chan<int> c = chan<int>(1);
    select {
        x = c.recv() => print(x),
        timeout(5) => print("slow"),
    }
}

E1014

select needs at least one arm

A select with no arms has nothing to wait for and could never finish.

void main() {
    select {
    }
}

Give it an arm. To sleep, use a timeout arm alone:

void main() {
    select {
        timeout(10) => print("done"),
    }
}

E1015

<type> can't be <how>: it <is or holds> an async call's Future, which stays on the thread that called it

An async call runs on the thread that made it, and its Future belongs to that thread. A spawn block, a parallel for, or a lambda passed to a pool task runs elsewhere, so it can't take the Future along.

async int later() { return 1; }

void main() {
    Future<int> a = later();
    Future<int> h = spawn { return await a; };
    print(await h);
}

Await it on this thread and use the result:

async int later() { return 1; }

void main() {
    int a = await later();
    Future<int> h = spawn { return a; };
    print(await h);
}

E1016

'<name>' is written by index in this parallel for, so its body can't otherwise use it

A parallel for may write a list from outside by its loop variable (out[i] = ...). Other iterations write its elements at the same time, so the body can't read it or use it any other way.

void main() {
    int[] out = [0, 0, 0, 0, 0];
    parallel for i in 0..4 {
        out[i] = out[i + 1];
    }
}

Read from another list, or read it after the loop:

void main() {
    int[] src = [1, 2, 3, 4, 5];
    int[] out = [0, 0, 0, 0];
    parallel for i in 0..4 {
        out[i] = src[i + 1];
    }
    print(out[0]);
}

E1017

parallel for runs over a range of integers: parallel for i in 0..n { ... }

A parallel for splits a range of integers among threads. It doesn't loop over a list's elements.

void main() {
    int[] xs = [1, 2, 3];
    parallel for x in xs { print(x); }
}

Loop over the indices, or use xs.par_map(f):

void main() {
    int[] xs = [1, 2, 3];
    parallel for i in 0..xs.len { print(xs[i]); }
}

E1018

cannot modify '<name>' inside a spawn block; it runs on another thread, with a copy

A spawn block runs on another thread with a copy of what it captures. Assigning a captured variable would change only the copy.

void main() {
    long sum = 0;
    Future<void> f = spawn { sum = 1; };
    await f;
}

Return what the block computes and await it:

void main() {
    Future<long> f = spawn { return 1; };
    long sum = await f;
    print(sum);
}

E1019

cannot modify '<name>' inside a parallel for; its body runs on several threads at once

The body runs on several threads at once, so assigning a variable from outside, a global, or a list other than by the loop variable would race.

void main() {
    long sum = 0;
    parallel for i in 0..4 {
        sum += i;
    }
}

Write results into a list by the loop variable, out[i] = ..., and combine them after the loop:

void main() {
    long[] parts = [0, 0, 0, 0];
    parallel for i in 0..4 {
        parts[i] = i;
    }
    long sum = 0;
    for p in parts { sum += p; }
    print(sum);
}

E1020

<type> can't be <how>: <it is or it holds T,> a slice, a view of storage this thread keeps using

A slice is a view into storage this thread owns and may change or free. It can't cross to another thread: passed to a Future function, sent on a channel, captured by a spawn block, and so on.

Future<int> viewed(int[..] xs) {
    return xs.len;
}

void main() {
    int[] xs = [1, 2, 3];
    print(await viewed(xs[0..2]));
}

Copy it into a list first with .to_list(), and pass the list:

Future<int> viewed(int[] xs) {
    return xs.len;
}

void main() {
    int[] xs = [1, 2, 3];
    print(await viewed(xs[0..2].to_list()));
}

E1021

<type> can't be <how>: <it is or it holds T,> a plain ref struct, which can't cross threads

A plain ref struct is used by one thread at a time with no locking, so it can't cross to another: passed to or returned from a Future function, sent on a channel, captured by a spawn block or parallel for, or held by a shared ref struct.

ref struct Node { int v; }

Future<int> count(Node n) {
    return n.v;
}

void main() {
    print(await count(Node{ .v = 1 }));
}

Declare it shared ref struct, whose fields are then written inside lock (x) { ... }, or pass the plain values it holds:

shared ref struct Node { int v; }

Future<int> count(Node n) {
    return n.v;
}

void main() {
    print(await count(Node{ .v = 1 }));
}

E1022

field '<field>' of shared ref struct <S> is read outside a lock

A field holding a counted value (a string, list, map, closure, object, or a value holding one) may be replaced by another thread, which frees the old value while it is being read. Read it inside lock on the variable it is reached through. Scalars and atomic fields need no lock.

shared ref struct Note {
    string text;
}

void main() {
    Note n = Note{ .text = "hi" };
    print(n.text);
}

Read it inside lock (n) { ... }:

shared ref struct Note {
    string text;
}

void main() {
    Note n = Note{ .text = "hi" };
    lock (n) {
        print(n.text);
    }
}

E1023

field '<field>' of shared ref struct <S> is <written or lent by address to a method> outside a lock

Writing a field of a shared ref struct, or calling a method that changes it in place, races with other threads using the same object. Do it inside lock on the variable it is reached through. atomic fields need no lock.

shared ref struct Account {
    long balance;
}

void main() {
    Account a = Account{ .balance = 0 };
    a.balance = 5;
}

Write it inside lock (a) { ... }:

shared ref struct Account {
    long balance;
}

void main() {
    Account a = Account{ .balance = 0 };
    lock (a) {
        a.balance = 5;
    }
}

E1024

'<name>' can't be assigned inside lock (<name>) { ... }

The block unlocks the object its variable holds when it ends. Assigning the variable inside the block would unlock a different object than it locked.

shared ref struct Account { long balance; }

void main() {
    Account a = Account{ .balance = 1 };
    lock (a) {
        a = Account{ .balance = 0 };
    }
}

Change the object's fields, or assign the variable after the block:

shared ref struct Account { long balance; }

void main() {
    Account a = Account{ .balance = 1 };
    lock (a) {
        a.balance = 0;
    }
}

E1025

lock needs an object, found an optional; check it for null first

lock (x) locks the object x holds. When x is an optional that hasn't been checked, there may be no object to lock.

shared ref struct Account { long balance; }

void show(Account? a) {
    lock (a) {
        print(1);
    }
}

void main() {
    show(Account{ .balance = 1 });
}

Check it for null first; inside the check, x is the object:

shared ref struct Account { long balance; }

void show(Account? a) {
    if (a != null) {
        lock (a) {
            print(a.balance);
        }
    }
}

void main() {
    show(Account{ .balance = 1 });
}

E1026

lock needs a shared ref struct, found <type>

Only a shared ref struct carries a lock. A plain ref struct can't cross threads, so it needs none, and an actor runs its methods one message at a time.

ref struct Node { int v; }

void main() {
    Node n = Node{ .v = 2 };
    lock (n) {
        n.v = 3;
    }
}

Declare it shared ref struct, or drop the lock:

shared ref struct Node { int v; }

void main() {
    Node n = Node{ .v = 2 };
    lock (n) {
        n.v = 3;
    }
}

E1027

lock needs a variable

The fields lock protects are known by the variable they are reached through, so lock takes a variable, not an expression such as a call or a literal.

shared ref struct Account { long balance; }

Account make() { return Account{ .balance = 1 }; }

void main() {
    lock (make()) {
        print(1);
    }
}

Store the object in a local first:

shared ref struct Account { long balance; }

Account make() { return Account{ .balance = 1 }; }

void main() {
    Account a = make();
    lock (a) {
        print(a.balance);
    }
}

Lint warnings

moxy lint adds these, each switched by a setting under lint: in moxyfmt.yaml:

Warning Setting
W0101 unused variable '<name>' (names starting with _ are exempt) unused_vars
W0102 empty if body, empty while body, empty for body empty_blocks
W0103 '<name>' shadows a variable declared at line <n> shadow_vars

W0101

unused variable '<name>'

moxy lint reports a local variable that is declared but never read. Names starting with _ are exempt. Turn it off with unused_vars: false under lint: in moxyfmt.yaml.

void main() {
    int total = 2;
    int count = 3;
    print(total);
}

Remove the variable, use it, or start its name with _:

void main() {
    int total = 2;
    print(total);
}

W0102

empty <if, while or for> body

moxy lint reports an if, while or for whose body is an empty block, which is often a mistake. Turn it off with empty_blocks: false under lint: in moxyfmt.yaml.

void main() {
    int x = 1;
    if (x > 0) { }
    print(x);
}

Give the body something to do, or remove the statement:

void main() {
    int x = 1;
    if (x > 0) { print("positive"); }
    print(x);
}

W0103

'<name>' shadows a variable declared at line <n>

moxy lint reports a local that hides a variable of the same name from an enclosing block in the same function. Turn it off with shadow_vars: false under lint: in moxyfmt.yaml.

void main() {
    int x = 1;
    {
        int x = 3;
        print(x);
    }
    print(x);
}

Give the inner variable another name:

void main() {
    int x = 1;
    {
        int y = 3;
        print(y);
    }
    print(x);
}

Warnings

W0201

this Future is dropped at once, which cancels the call

A call that returns a Future, used as a statement, drops the Future at once. Dropping a Future cancels the call it started, so the work may never run.

Future<int> compute(int x) {
    return x * 2;
}

void main() {
    compute(1);
}

Keep the Future and await it, or call a plain function instead:

Future<int> compute(int x) {
    return x * 2;
}

void main() {
    Future<int> kept = compute(1);
    print(await kept);
}

W0202

strong reference cycle: <path>

These ref struct types can point at each other in a loop of strong references, as a child that holds its parent. Objects in such a loop keep each other alive and are never freed.

ref struct Dir {
    string name;
    Dir[] subdirs;
    Dir? up;
}

void main() {
    Dir root = Dir{ .name = "/" };
    print(root.name);
}

Make the back-pointer weak (it holds null once its object is gone), or unowned:

ref struct Dir {
    string name;
    Dir[] subdirs;
    weak Dir? up;
}

void main() {
    Dir root = Dir{ .name = "/" };
    print(root.name);
}

W0203

'<function>' uses goto together with managed values or defer; goto skips automatic cleanup

Moxy frees managed values (strings, lists, objects) and runs defer when a scope ends. A goto can jump past that code, leaking values or skipping deferred work.

void main() {
    string s = "x";
    if (s.len() > 0) goto done;
    print(s);
    done:
    return;
}

Use structured control flow, such as return, break or an if:

void main() {
    string s = "x";
    if (s.len() == 0) {
        print(s);
    }
    return;
}

W0204

'<name>' may be null, but <T> is not optional

A non-optional ref struct variable, field, parameter or return value receives null, or a value that may be null. This is a warning for now and will become an error; the declaration should say T?.

ref struct Node { string name; }

void main() {
    Node b = null;
    print(b == null);
}

Make it optional:

ref struct Node { string name; }

void main() {
    Node? b = null;
    print(b == null);
}

W0205

a value that may be null is used as a non-optional <T>

A T? value, which may be null, is stored where a non-optional ref struct is expected, with no declaration to blame: a list element, a pushed value, a lambda's result.

ref struct Node { int v; }

Node? find(Node[] xs) { return null; }

void main() {
    Node[] nodes = [Node{ .v = 1 }];
    nodes.push(find(nodes));
    print(nodes.len);
}

Check it for null first, or unwrap it with !:

ref struct Node { int v; }

Node? find(Node[] xs) { return null; }

void main() {
    Node[] nodes = [Node{ .v = 1 }];
    Node? found = find(nodes);
    if (found != null) nodes.push(found);
    print(nodes.len);
}

W0206

'<name>' is not declared in Moxy code; assuming it comes from C

A name Moxy can't see is left to C, which may declare it in a header or macro. When it is close to a Moxy name, it is likely a typo, so Moxy warns and suggests that name.

int length = 1;

void main() {
    print(lenght);
}

Fix the spelling:

int length = 1;

void main() {
    print(length);
}

W0207

weak field '<name>' may be null; reading '<member>' through it panics if its object is gone (an error from 0.5)

A field or method is reached through a weak T field, which reads as T?: null once its object is gone. Up to 0.3 the read gave a T and such code compiled, so in 0.4 it is a warning, and the access is checked as ! would check it: it panics with the location (unwrapped a null T?) when the object is gone. It becomes error E0530 in 0.5.

A null check on the field doesn't remove the warning: w.app != null && w.app.stopping reads the field twice, and only locals are narrowed.

ref struct App { bool stopping; }
ref struct Window { weak App app; }

void main() {
    App app = App{ .stopping = false };
    Window w = Window{ .app = app };
    if (w.app != null && !w.app.stopping) print("running");
}

Check a local copy, which also keeps the object alive while it's used. w.app!.stopping keeps the panic without the warning, and w.app?.stopping gives null instead:

ref struct App { bool stopping; }
ref struct Window { weak App app; }

void main() {
    App app = App{ .stopping = false };
    Window w = Window{ .app = app };
    App? a = w.app;
    if (a != null && !a.stopping) print("running");
}

W0208

unreachable match arm: the arms above already match every value it does

An arm can never run because earlier arms already match everything it would. Typical causes are an arm after _, a repeated variant, or a specific case after a broader unguarded one. The arm is left out of the program. (Before 0.4 shipped this was briefly error E0802.)

void main() {
    int n = 2;
    match n {
        1 => print("one"),
        _ => print("other"),
        2 => print("two"),
    }
}

Remove the arm, or move it above the arm that covers it:

void main() {
    int n = 2;
    match n {
        1 => print("one"),
        2 => print("two"),
        _ => print("other"),
    }
}

W0209

'<name>' is a variant of <enum>; name it <enum>::<name> (an error from 0.5)

A variant of an enum without payloads is named bare. Up to 0.3 those variants were global C constants, so this compiled; in 0.4 a variant is reached through its enum. The bare name still means the variant when exactly one such enum has it, with this warning, and becomes an error in 0.5. (When two enums have a variant of that name, the name is left to C, as any unknown name is.)

enum Power { Low, High }

void main() {
    Power p = Low;
    print(p == Power::Low);
}

Name it through its enum:

enum Power { Low, High }

void main() {
    Power p = Power::Low;
    print(p == Power::Low);
}

Or, when the constants are meant to be global, as for a C API, declare a C enum: a trailing ; or an = value makes one (enum Power { Low, High };).

Runtime panics

A panic prints its message and the source location, then exits with code 101:

panic: index 10 out of range for list of length 3
  at src/main.mxy:5:13
Message Cause
index <i> out of range for list of length <n> xs[i], insert, remove, first, last
slice [<a>, <b>) out of range for list of length <n> xs.slice(a, b)
slice <a>..<b> out of range for <list, string, array or slice> of length <n> (also <a>..=<b>, <a>..) xs[a..b] and the other range forms, when the range leaves the value or ends before it starts
index <i> out of range for slice of length <n> s[i] on a T[..]
pop from an empty list
key <key> not found in map m[k] or m.get(k) with a missing key; use get_or or has
string index <i> out of range (length <n>), string slice [<a>, <b>) out of range (length <n>)
unwrap of Err: <message> r.unwrap() on an error; a typed error is formatted as print would
unwrapped a null <type>? x! when x is null, including a weak field whose object is gone, and w.f.x through a weak field (warning W0207)
call of a null closure calling an unset fn(...) variable
read through a dead unowned reference reading an unowned field after its object was freed (debug builds only)
call through an empty dyn value calling a method on a dyn variable that was never given a value
await on a null future
an async call's Future crossed into another thread (<how>); it stays on the thread that called it an async call's Future the compiler couldn't see (in a list declared Future<T>[], a struct field, a closure) was passed to a Future function, returned from one, sent on a channel or stored in a shared ref struct
await on an async call's Future on a thread other than the one that called it; ..., waiting on an async call's Future on a thread other than ... an async call's Future reached another thread through a global (globals aren't checked) and was awaited, or given to all, race or timeout, there
await on an unfinished async call while holding a lock; ... inside lock (x) { ... } (or with a std/sync lock held) code can't switch away, so nothing else on the thread could finish the async call. Await it after the block
race of no futures: nothing could finish first race([])
a null future in all or race, a null future in timeout, timeout on a null future
send on a null channel, receive from a null channel, close of a null channel a chan<T> variable that was declared but never given a channel
channel capacity <n> is negative chan<int>(-1)
select has no channel to wait on every channel in a select without default or timeout is null, so it would wait forever
select waits only on closed channels, in arms that need a value every arm of a select without default or timeout is v = c.recv() on a closed, empty channel (or a null one), so no arm can ever fire
values of type <type> cannot be sorted
a plain ref struct <T> crossed into another thread (<how>); declare it `shared ref struct <T>` a closure or dyn value holding a plain ref struct was passed to a task, returned from one, sent on a channel or stored in a shared ref struct (the compiler can't see inside those)
out of memory allocation failed
out of memory for a task stack, cannot create a fiber for a task a worker couldn't get another stack to run on while a task waits (address space or, on Windows, fiber creation exhausted)
cannot start the timer thread the first timed wait inside a task (select with timeout, a socket timeout) couldn't start the thread that keeps deadlines
a ref struct <T> made inside the gate at <file:line:col> would outlive it here; it can't be copied out. Make it before the gate opens a function called inside a gate stored an object the gate made (or a weak or unowned reference to one) somewhere older: an object from outside, a global, a list or map held there. The compiler rejects the cases it sees in the gate's own body; this is the check on everything else. The same message names a closure or a dyn value when one of those can't be copied
a value from the gate at <file:line:col> was used after the gate closed; it escaped without being copied out debug builds only: a pointer into a closed gate's memory was read (or stored, or freed). The compiler copies every escape it knows about, so this is a C pointer kept past the gate, or a bug in the compiler
gates closed out of order a gate's closing found another gate still open inside it; the compiler never generates that, so something jumped out of a gate without closing it
entered an arena after its free(), reset an arena after its free(), freed an arena after its free() an Arena was used after free()
entered an arena that a `gate (...)` block already has open a second gate (a) block of the same arena opened while one was open (nested, in another task, or on another thread); one block of an arena at a time
reset an arena inside a `gate (...)` block of it, freed an arena inside ... reset() or free() would give back the memory of the block that is running; call it after the block
<message> panic("message")
deadlock: actor <A> awaits actor <B> at <loc>, and actor <B> awaits actor <A> at <loc> actors whose running messages await each other (any cycle; every await is named). Caught like any panic in an actor message: the awaiting message fails
deadlock: actor <A> awaits a message to itself, which can't start until this one ends; call the method on self instead an actor's message awaited a call to the same actor through a reference other than self
message to a null actor a method call on an actor reference that is null (an unset A? unwrapped by C code)
<message> (+ in actor <A>'s <m>(), awaited, at <loc>) the panic of an actor's call or a spawn block, raised again where its Future was awaited; the first at is where it happened
<message> (+ in a parallel for or in par_map, at <loc>) a panic in a parallel loop's body, raised in its caller after the loop

Inside an actor's message, a spawn block, or a chunk of a parallel loop, a panic is caught at that boundary instead of ending the program; see Crash isolation. When a cast's message panics, or a call's whose Future nobody awaits, it is printed and the program goes on:

panic: unknown word 'cat'
  at src/main.mxy:44:30
  in actor WordStore's strict() sent at src/main.mxy:70:11; the actor goes on with its next message

A panic while holding a lock is still fatal there, and adds the line note: this panic happened while holding a lock, so it ends the program even inside an actor message, a spawn block or a parallel loop.

In debug builds a program whose main returns with ref struct objects still alive lists them on stderr, grouped by where they were made, and moxy test fails the test:

leak: 3 Node objects still alive, allocated at src/main.mxy:12
  = help: objects that hold each other strongly are never freed; make the back-pointer weak or unowned (MOXY_LEAKS=0 turns this report off)

When panics were caught (in actor messages, spawn blocks or parallel loops), the report adds = note: <n> panics were caught ...; what their unwound frames held was never released and may be listed here.

A failed assertion prints the condition (or your message) and exits with code 1:

assertion failed: assert(total == 6)
  at tests/sum.mxy:9:5

Edit this page on GitHub