Docs · Language

Lexical structure

This page defines how Vyi source text becomes tokens: the encoding, identifiers and keywords, every literal form and escape, comments, and how statements are separated. Guide 02, Values and bindings introduces literals and bindings by example.

Source encoding

Vyi source is UTF-8: identifiers, string and char literals, and comments may all hold any Unicode text.

Vyi
con héllo = 1
con 名前 = 2
// comments may contain 任意の文字

A byte sequence that is not valid UTF-8, or a character that cannot start a token, is reported as unexpected character and skipped. The rest of the file still lexes, so one stray character gives one diagnostic.

Tokens

The lexer splits source into these classes:

ClassExamples
identifierstotal, Point, @add, $tmp, _hidden, 名前
keywordscon, fn, switch (table below)
literals42, 0xFF, 3.14, "text", $"n = ${n}", 'a', true
labels#outer, #search
operators and punctuation+, ==, =>, .., {, ,
triviaspaces, tabs, newlines, comments

The parser skips trivia, but newlines still end statements (below), and /// doc comments attach to declarations (below).

Identifiers

An identifier is one start character followed by any number of continue characters:

  • Start: an ASCII letter, _, $, @, or a Unicode letter (including letter numbers such as Roman numerals).
  • Continue: any start character, an ASCII or Unicode digit, a combining mark, connector punctuation, or a zero-width joiner or non-joiner.

An identifier never starts with a digit. _, $, and @ are ordinary identifier characters and may appear anywhere in a name. Keywords are the ASCII spellings in the table below; no Unicode spelling is a keyword.

Vyi
import { println } from "@fmt"

con _hidden = 10
con my_value2 = 20
con $count = 30
con 名前 = 40

fn main() !u8 {
    println(_hidden)    // prints 10
    println(my_value2)  // prints 20
    println($count)     // prints 30
    println(名前)       // prints 40
    return Ok(0)
}

A lone _ is not an identifier. It is the inference and discard placeholder (types, patterns). A $ directly followed by " opens a string template, not a name.

The names of the primitive types and of the standard enums and variants (i32, bool, any, Optional, Some, Ok) are not keywords. They are ordinary names that every file sees without an import, and a binding of the same name in an inner scope shadows them like any other name.

The @ sigil

A leading @ is part of an identifier. It marks two things:

  • Operator method names, such as @add, @eq, and @index. An operator is a call of one of these methods: a + b calls a.@add(b). The operators reference has the full list; guide 13 introduces them. An import names one with its receiver type, like any method: Money.@add.
  • Standard-library package paths. In import { println } from "@fmt" the @ is part of the import string and marks a standard-library package (@core, @fmt, @io, @mem). See guide 14.

There is no standalone @ token: @add lexes as one identifier.

Keywords

These 39 words are reserved. None of them can be used as an identifier.

alignofbreakc_enumc_fnc_include
c_ptrc_structc_unioncatchcon
continuedeferelseenumerror
exportfalsefnforfrom
ifimportininterfaceknown
matchmutpanicpubrecover
returnshapeofsizeofstructswitch
truetrytypetypeof

Notes:

  • true and false are the two bool literals.
  • error names the open error type and declares error types (guide 07).
  • The c_ words belong to C interop (guide 15).
  • default is not a keyword. It is the catch-all only when it is the whole head of a switch or match arm. Anywhere else it is an ordinary name, so a binding, function, or variant may be called default, and an arm that refers to one is written (default): (statements).
  • Vyi has no void (a function with no return type returns (), the empty tuple), no while or loop (every loop is for), no null, and no and, or, or not (the boolean operators are &&, ||, and !).

Integer literals

FormBaseExampleValue
digitsdecimal1_000_0001000000
0x digitshexadecimal0xFF_FF65535
0b digitsbinary0b1010_1010170
0o digitsoctal0o1715
  • The base prefix may be upper or lower case (0X, 0B, 0O), and so may hex digits.
  • A leading 0 does not change the base: 010 is ten.
  • _ separates digits. It must sit between two digits, or directly after a base prefix (0x_FF). 1_, 1__000, and 0xFF_ are errors. A literal that starts with _ is an identifier.
  • A literal has no sign. -5 is the unary - operator applied to 5.
Vyi
import { println } from "@fmt"

fn main() !u8 {
    println(1_000_000)     // prints 1000000
    println(0xFF)          // prints 255
    println(0b1010_1010)   // prints 170
    println(0o17)          // prints 15
    return Ok(0)
}

An integer literal has no type of its own. It takes the integer type its context asks for (an annotation, a parameter, a conversion), and i32 when nothing asks. A literal whose value does not fit that type is a compile error, never a wrapped value:

Vyi · does not compile
con level: u8 = 300    // error: integer literal 300 overflows u8

A literal written directly after unary - may reach one past the type's positive limit, so con low: i8 = -128 is valid.

Float literals

A float literal is digits, a ., and digits. Both sides are required. _ may separate digits on either side, between two digits.

Vyi
con pi = 3.141_592     // f64
con half: f32 = 0.5    // the annotation makes it f32
  • A float literal is f64 unless its context asks for f32.
  • There is no exponent form and no type suffix. A number followed directly by letters (1e5, 1.5e3, 2E3) is an error; write the digits out (100000.0).
  • There is no leading or trailing dot form. .5 is not a literal, and 1. is the integer 1 followed by .. That keeps 1..10 a range and 1.name() a method call on 1.

Char literals

'...' is a char literal: exactly one Unicode code point, or one escape, giving a 32-bit char value.

Vyi
import { println } from "@fmt"

fn main() !u8 {
    println('A')               // prints A
    println('\x41')            // prints A
    println(u32('\u{1F600}'))  // prints 128512
    return Ok(0)
}

A char literal holds one code point even when that code point takes several bytes in UTF-8 ('😀' is four bytes). More than one code point between the quotes is an error; text goes in a string, in double quotes:

Vyi · does not compile
con initials = 'ab'    // error: char literal holds exactly one codepoint

' also opens a lifetime annotation, '(x) or 'src(text), written after a type (guide 09). A ' followed by ( or a name is a lifetime mark, unless a ' closes it right after that one ( or name and is not itself followed by ( or a name. So '(' and 'a' are chars, while in '(x), 'src(text), and '('all) every ' is a lifetime mark.

String literals

"..." is a string literal: UTF-8 bytes stored in the compiled program, with type [*con]u8, a read-only view of the bytes with a length. A string literal opens and closes on one line. A raw newline inside one is the error unterminated string literal; write \n for a line break.

Strings have no length limit and no multi-line or raw form. Guide 10 covers working with text.

Escapes

Chars, strings, and string templates share these escapes:

EscapeIn a charIn a string or template
\nnewline, code point 10the byte 0x0A
\ttab, code point 9the byte 0x09
\rcarriage return, code point 13the byte 0x0D
\0code point 0the byte 0x00
\\a backslasha backslash
\'a single quotenot an escape
\"a double quotea double quote
\xHHthe code point HH (two hex digits, 0 to 255)the single byte HH
\u{H}the code point H (1 to 6 hex digits)the UTF-8 bytes of code point H
\$not an escapein a template, a $; in a string, not an escape

\u{H} takes a code point up to 10FFFF, outside the surrogate range D800 to DFFF.

So \xHH means different things in the two literals: in a char it is a code point, in a string a raw byte. '\xE9' is é, while "\xE9" is the one byte 0xE9, which is not valid UTF-8 on its own; "\u{E9}" is the two bytes of é:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    println(u32('\xE9'))    // prints 233
    println("\xE9".len)     // prints 1
    println("\u{E9}".len)   // prints 2
    println("caf\xC3\xA9")  // prints café
    return Ok(0)
}

In a string or template, a backslash before anything that is not an escape for that literal, including a malformed \x or \u escape, is kept as written: "\q" is the two bytes \ and q.

String templates

$"..." is a string template. Each ${expr} in it is a hole that the value of expr fills when the template is printed. A template has type Template, from @fmt (guide 10).

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con price = 15
    println($"total: ${price}")     // prints total: 15
    println($"total: \$${price}")   // prints total: $15
    return Ok(0)
}
  • \$ is a literal $, so \${ does not open a hole. A $ not followed by { is a literal $ too.
  • A hole holds any expression, braces included; the hole ends at the } that balances its ${.
  • Like a string, a template stays on one line, and its text takes the string escapes.

Comments

Vyi
import { println } from "@fmt"

// A line comment runs to the end of the line.

/* A block comment runs to the closing marker,
   across as many lines as it needs. */

/// A doc comment. Consecutive /// lines form one block
/// that attaches to the declaration below them.
fn answer() i32 {
    return 42
}

fn main() !u8 {
    println(answer())   // prints 42
    return Ok(0)
}

Block comments do not nest. The first */ closes the comment, so commenting out code that itself contains */ leaves the rest as code:

Vyi · does not compile
/* outer /* inner */ still a comment? */   // error: expected declaration at top level
fn main() !u8 { return Ok(0) }

A /// block attaches to the declaration that follows it, with only blank space between them, and the language server shows its text on hover. A /// block with no declaration after it is an ordinary comment.

Newlines and statement separation

A newline ends a statement whenever what comes before it is complete. There is no required terminator:

Vyi
con width = 4
con height = 3

An expression continues onto the next line only when the line's last token can't end one: a binary operator, =, ., ,, or an unclosed (, [, or {. So a long expression breaks after the operator, never before it:

Vyi
import { println } from "@fmt"

fn total(a: i32, b: i32, c: i32) i32 { return a + b + c }

fn main() !u8 {
    con sum = 100 +
        20
    con all = total(
        1,
        2,
        3,
    )
    println(sum)   // prints 120
    println(all)   // prints 6
    return Ok(0)
}
Vyi · does not compile
fn main() !u8 {
    con sum = 100
        + 20       // error: unexpected Plus at statement start
    return Ok(0)
}

For the same reason, a line that starts with (, [, or . never continues the line before it. ( and [ begin a new statement, and a leading . is an error.

A semicolon separates statements on one line and means the same as a newline:

Vyi
import { println } from "@fmt"

fn main() !u8 { con a = 1; con b = 2; println(a + b); return Ok(0) }

Commas in argument lists, aggregate literals, and switch and match arms belong to those constructs, not to statement separation. The arm comma rule is in statements.

Labels

#name, a # directly followed by an identifier, is one label token. A # with no name after it is an error. A label goes in front of a for loop or a block, and break #name and continue #name target it. The rules are in statements and expressions; guide 05 introduces them.

Operators and punctuation

Multi-character operators lex greedily: >>= is one token, not > and >=.

GroupTokens
arithmetic+ - * / %
wrapping arithmetic+% -% *%
comparison== != < > <= >=
boolean&& || !
bitwise& | ^ << >>
assignment=
compound assignment+= -= *= /= %= &= |= ^= <<= >>= +%= -%= *%=
range.. ...
type sugar? ! in a type
type pattern~ (patterns)
arrow=>
decorator:<, written at the start of a statement (statements)
lifetime mark' before ( or a name, after a type (above)
punctuation( ) { } [ ] , . : ;

Several tokens mean different things by position. Prefix & takes an address and infix & is bitwise and; prefix * dereferences and infix * multiplies; ! is boolean not in an expression and marks an error union in a type. What each operator does, and how tightly it binds, is in the operators reference.