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.
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:
| Class | Examples |
|---|---|
| identifiers | total, Point, @add, $tmp, _hidden, 名前 |
| keywords | con, fn, switch (table below) |
| literals | 42, 0xFF, 3.14, "text", $"n = ${n}", 'a', true |
| labels | #outer, #search |
| operators and punctuation | +, ==, =>, .., {, , |
| trivia | spaces, 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.
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 + bcallsa.@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.
alignof | break | c_enum | c_fn | c_include |
c_ptr | c_struct | c_union | catch | con |
continue | defer | else | enum | error |
export | false | fn | for | from |
if | import | in | interface | known |
match | mut | panic | pub | recover |
return | shapeof | sizeof | struct | switch |
true | try | type | typeof |
Notes:
trueandfalseare the twoboolliterals.errornames the open error type and declares error types (guide 07).- The
c_words belong to C interop (guide 15). defaultis not a keyword. It is the catch-all only when it is the whole head of aswitchormatcharm. Anywhere else it is an ordinary name, so a binding, function, or variant may be calleddefault, 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), nowhileorloop(every loop isfor), nonull, and noand,or, ornot(the boolean operators are&&,||, and!).
Integer literals
| Form | Base | Example | Value |
|---|---|---|---|
| digits | decimal | 1_000_000 | 1000000 |
0x digits | hexadecimal | 0xFF_FF | 65535 |
0b digits | binary | 0b1010_1010 | 170 |
0o digits | octal | 0o17 | 15 |
- The base prefix may be upper or lower case (
0X,0B,0O), and so may hex digits. - A leading
0does not change the base:010is ten. _separates digits. It must sit between two digits, or directly after a base prefix (0x_FF).1_,1__000, and0xFF_are errors. A literal that starts with_is an identifier.- A literal has no sign.
-5is the unary-operator applied to5.
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:
con level: u8 = 300 // error: integer literal 300 overflows u8A 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.
con pi = 3.141_592 // f64
con half: f32 = 0.5 // the annotation makes it f32- A float literal is
f64unless its context asks forf32. - 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.
.5is not a literal, and1.is the integer1followed by.. That keeps1..10a range and1.name()a method call on1.
Char literals
'...' is a char literal: exactly one Unicode code point, or one escape, giving
a 32-bit char value.
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:
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:
| Escape | In a char | In a string or template |
|---|---|---|
\n | newline, code point 10 | the byte 0x0A |
\t | tab, code point 9 | the byte 0x09 |
\r | carriage return, code point 13 | the byte 0x0D |
\0 | code point 0 | the byte 0x00 |
\\ | a backslash | a backslash |
\' | a single quote | not an escape |
\" | a double quote | a double quote |
\xHH | the 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 escape | in 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 é:
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).
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
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:
/* 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:
con width = 4
con height = 3An 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:
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)
}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:
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 >=.
| Group | Tokens |
|---|---|
| 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.