Rx Compiler Specification
Welcome to the Rx Compiler course! In this course, you are required to write a compiler for a subset of Rust we call Rx. The compiler will target the RV32IM instruction set architecture. To simplify frontend development, we provide an ANTLR v4 grammar for Rx that automates parsing, allowing you to begin directly with an Abstract Syntax Tree (AST).
The compiler must use LLVM IR as its intermediate representation and support emitting it as text. This lets you validate the frontend using Clang before implementing your own RISC-V backend, as described in Backend.
For Rust compatibility, the parser also accepts top-level use declarations and lifetime syntax. You may discard both after parsing; import resolution and lifetime checking are not part of the assignment.
This book rigorously defines the syntax and semantics of Rx and, alongside the official Rust compiler (rustc), serves as the source of truth for this course. If you find any ambiguities or disagreements between the two, do not hesitate to reach out to your TA for clarification.
How to read the specification
Start by reading Language scope and test guarantees, which distinguishes valid programs, compile errors, and excluded cases (i.e., undefined behavior) to understand which features are required and which are out of scope.
Next, proceed to lexical structure, followed by items, types, and expressions. These sections define the complete grammar of the Rx language. There is a quick lookup table in the grammar summary section.
While reading, we recommend experimenting with the Rust compiler (rustc). You can also use online environments such as the Rust Playground or Compiler Explorer to see what compiles and what does not. Note that we do not treat compiler warnings as compile errors.
How to get started
Before beginning, we recommend reviewing an introductory Rust tutorial. You do not need an exhaustive understanding because Rx implements only a subset, but familiarity with basic Rust syntax is essential.
Many excellent online resources explain the various phases of compiler construction. Some blogs from your TAs (or their TAs) include:
- Compiler for Mx* 编译器随笔 by legendary TA @darksharpness: A classic blog post that focuses heavily on various optimization techniques in Mx (the course language used prior to Rx).
- Writing a Compiler for Rust by RayZh (co-designer of this specification): Focuses primarily on the end-to-end compiler pipeline. Note that certain techniques discussed are no longer needed or applicable due to updates in this year’s specification.
Additional information:
- Compiler 101: A collection of projects and notes by ACM Class students over the years. Note that many of the techniques described are specific to Mx and may not apply to Rx.
- The Rust Reference: The official, comprehensive reference for the Rust language. While this Rx specification is intended to be self-contained, the Rust Reference is an authoritative supplementary guide to standard Rust semantics.
- Rust Compiler Development Guide: An advanced, in-depth guide to
rustcinternals and architecture, recommended as a background reference for compiler engineering patterns.
Language scope and test guarantees
Definition
We distinguish among valid programs, compile errors, and undefined behavior:
| Category | Compiler requirement | Test policy |
|---|---|---|
| Valid program | Compile and produce the specified behavior | May appear in any applicable test |
| Compile error | Reject normally; diagnostic wording is unspecified | May appear in negative tests |
| Undefined behavior | No required diagnostic or behavior | Excluded as stated by its defining rule |
Unsupported syntax may be rejected at the language-subset boundary even if the supplied parser recognizes it. Unless a source form is explicitly classified as undefined behavior, ordinary name, type, and place-mutability errors remain compile errors, including in unreachable code. The compiler need not prove termination, borrow validity, or ownership validity. Runtime checks, panic handling, and stack unwinding are not required for excluded executions.
Language subset
Rx is a subset of Rust 2021. Every Rx source program uses valid Rust syntax, but this specification defines its own built-in environment and required runtime behavior.
Rx includes:
- Functions, named-field structs, constants, and inherent implementations.
- Top-level use declarations for Rust compatibility, ignored after parsing.
- Identifier bindings and local type inference.
- Integers, booleans, fixed arrays, references, and builtin
BoxandVeccontainers. if,while,loop,return,break, andcontinuecontrol flow.- Struct derives for
Copy,Clone,PartialEq, andEq.
The Rx subset excludes:
- User traits, trait bounds, and trait objects.
- Enums, non-unit tuples, tuple structs, tuple variants, and unit variants.
- Pattern matching, destructuring, and guards.
- Type parameters and general generics. Lifetime syntax is supported, but its validity is guaranteed rather than checked.
- Module declarations and import resolution, visibility, privacy, macros, and arbitrary attributes. Use declarations are accepted only as described by the use compatibility guarantee.
- Unsafe Rust and the standard library beyond the builtins defined here.
- Const generics and general constant evaluation beyond the restricted constant contexts. Constant propagation remains an optional optimization.
- Integer overflow checks.
Types, expressions, and the grammar summary define the complete subset. Forms outside that grammar are unsupported.
Test guarantees
The following source forms trigger undefined behavior and will never appear in test suites, including within unreachable code or constant contexts where applicable:
| Undefined behavior | Defining rules |
|---|---|
| Integer literal outside its determined type | Integer literal range |
| Integer inference requiring expected-type propagation through binary operations, unary operations, or shared/mutable borrows | Expected-type propagation |
Omitting the explicit concrete type argument in a Box::new(...) or Vec::new() constructor call | Builtin constructors |
| Using a function as a value | Function values |
Declaring a struct named u32, isize, usize, bool, Box, Vec, Copy, Clone, PartialEq, or Eq | Protected builtin names |
Local binding named get_i32, print_i32, or println_i32 | Protected builtin names |
| Place-mutability violation in unreachable code, including assignment, mutable borrowing, or mutable receiver adjustment | Unreachable code |
Array or Vec index operand with the never type ! | Index operand types |
Documentation comment (///, //!, /**, /*!) | Documentation comments |
| Let or parameter name colliding with a visible unqualified constant | Constant-name collisions |
| Equality between different source types | Cross-type equality |
| LUB coercion for which neither type can become the common target | Least upper bound coercions |
| Multiple distinct matching methods in a dot call | Method lookup |
| Use declaration violating the Rust compatibility guarantees | Use compatibility |
| Invalid lifetime declaration, use, bound, or elision | Lifetime validity |
| Observable zero-sized data use outside the unit-result exception | Zero-sized data |
These guarantees constrain valid source programs. Any invalid memory access, incorrect termination, or incorrect program output introduced during compilation remains a compiler defect.
Integer literal range
An integer literal’s type is selected by its suffix, its expected integer type, or the i32 fallback, in that order. An unsuffixed integer literal whose value falls outside the i32 range when evaluated without an expected type constitutes undefined behavior.
Integer literal overflow exhibits undefined behavior. The literal rules still permit signed minima such as -2147483648i32 and -(2147483648i32).
Constant-name collisions
A let binding or function parameter whose name matches a visible unqualified constant triggers undefined behavior, regardless of mutability or declaration order. No diagnostic or constant-pattern interpretation is required. An associated constant reachable only as Type::NAME does not exclude a local NAME. Collisions with builtin names follow the protected builtin rules.
Cross-type equality
Applying == or != to operands of differing source types triggers undefined behavior. No diagnostic, coercion, or cross-type PartialEq implementation is required. This includes shared versus mutable references, different array types, different container element types, and Vec versus array comparisons.
The equality rules define operand types, capability requirements, and same-type comparison. Lifetime arguments alone do not distinguish source types under type identity.
Use compatibility
Tests may contain use declarations, such as
use rx::core::*;, to compile the same source with Rust and the course support
crate. Their import paths and combinations are valid in that Rust environment.
Any imported name used by the program denotes an Rx builtin under its existing
spelling; unused imports and aliases are allowed. Tests never rely on a use
declaration to introduce another type, value, module, or usable alias into Rx.
Violations of these guarantees constitute undefined behavior and will not appear in any positive, negative, or performance test. The compiler need not resolve imports or diagnose missing imported items, conflicting imports, or other import validity errors. Malformed use syntax must still be rejected by the parser with a standard syntax error. After discarding use declarations, ordinary name, type, and place-mutability errors elsewhere in the program remain compile errors.
Lifetime validity
Lifetime declarations, annotations, arguments, bounds, and elision follow the supported Rust 2021 rules described in References. Tests guarantee their validity throughout the program. Invalid lifetime use is undefined behavior and appears in no positive, negative, or performance test.
The compiler may discard this lifetime syntax after parsing and need not carry it through semantic analysis or LLVM IR generation. The parser conventions explain which information remains necessary.
Excluded lifetime errors
Tests exclude undeclared or duplicate lifetimes, invalid shadowing, incorrect argument counts or placement, forbidden explicit late-bound arguments, ambiguous missing annotations, unsatisfied outlives bounds, invalid 'static claims, rejected unused parameters, and bodies or uses that fail to uphold their annotations.
Malformed tokens and syntax retain their ordinary lexer and parser behavior. Other type and place-mutability errors remain compile errors. No lifetime or ownership checker is required; actual references must still obey the borrowing rules.
Zero-sized data
Unit () is valid as a function or control-flow result.
Excluded zero-sized uses
All other uses requiring observable zero-sized storage are undefined behavior, including:
- Zero-sized parameters, bindings, constants, statics, or assignment destinations.
- Empty structs or zero-sized fields.
- Zero-length arrays or zero-sized array elements.
- References to zero-sized values and dereferences of zero-sized data.
An empty Vec<T> with nonzero-sized T is valid and is not itself zero-sized. Its representation is implementation-defined.
Resource limits, stack size, allocation policy, and output constraints are part of the backend contract.
Notation
Grammar
The following notations are used by the Lexer and Syntax grammar snippets:
| Notation | Examples | Meaning |
|---|---|---|
| CAPITAL | IDENTIFIER, INTEGER_LITERAL | A token produced by the lexer |
| ItalicCamelCase | LetStatement, Item | A syntactical production |
string | x, while, * | The exact character(s) |
| x? | mut? | An optional item |
| x* | OuterAttribute* | 0 or more of x |
| x+ | Statement+ | 1 or more of x |
| xa..b | HEX_DIGIT1..6 | a to b repetitions of x |
| Rule1 Rule2 | fn Name Parameters | Sequence of rules in order |
| | | i32 | u32, Block | Item | Alternation (matches one of the alternatives) |
[ ] | [b B] | Any of the characters listed |
[ - ] | [a-z] | Any of the characters in the range |
~[ ] | ~[b B] | Any characters, except those listed |
~string | ~\n, ~*/ | Any characters, except this sequence |
| ( ) | (, Parameter)? | Groups items |
| U+xxxx | U+0060 | A single Unicode character |
| <text> | <any ASCII char except CR> | An English description of what should be matched |
| Rule suffix | IDENTIFIER_OR_KEYWORD except crate | A modification to the previous rule |
Sequencing has higher precedence than | alternation.
String-table productions
String-table productions
Certain rules, including unary operators, binary operators, and keywords, are defined as tables of literal strings. In syntax productions, literal string references implicitly match the corresponding token produced by lexical analysis. See Tokens.
Grammar visualizations
Grammar productions appear in the chapters that define them. Lexer rules use uppercase names; syntax rules use mixed-case names. The button below each grammar block shows its syntax diagram, where rectangles represent nonterminals and rounded rectangles represent terminals.
Common productions
The following are common definitions used in the grammar.
Lexical structure
The lexical chapters define source input, keywords, identifiers, comments, whitespace, and tokens. Each chapter contains its lexer productions and linked syntax diagrams; Notation explains the grammar notation.
The Literal expressions chapter defines boolean literal values and integer literal range rules. The Parser conventions chapter specifies how combined punctuation is consumed in reference and generic contexts.
Input format
A source compilation unit is a single file containing 7-bit ASCII source text. LF and CRLF line endings are supported. Unicode identifiers, byte-order marks, and interpreter directives are excluded from the Rx language subset.
Whitespace and comments separate tokens. The parser consumes the resulting sequence of tokens according to the Crate production.
Keywords
The strict and reserved keywords listed below cannot be used as identifiers anywhere in Rx. The lists are string-table productions as described in Notation.
Strict keywords
as, break, const, continue, crate, else, enum, extern, false, fn, for, if, impl, in, let, loop, match, mod, move, mut, pub, ref, return, self, Self, static, struct, super, trait, true, type, unsafe, use, where, while, async, await, dyn.
Reserved keywords
abstract, become, box, do, final, macro, override, priv, typeof, unsized, virtual, yield, try.
Contextual names
Contextual keywords in Rust (such as union, macro_rules, and gen) may be used as ordinary identifiers in Rx. Built-in type and trait names and standard I/O function names are governed by the protected namespace rules.
Identifiers
Lexer
IDENTIFIER_OR_KEYWORD → ( ASCII_ALPHA | _ ) ASCII_CONTINUE*
ASCII_ALPHA → [a-z A-Z]
ASCII_CONTINUE → ASCII_ALPHA | DEC_DIGIT | _
NON_KEYWORD_IDENTIFIER → IDENTIFIER_OR_KEYWORDexcept _ and a strict or reserved keyword
Identifiers use ASCII letters, digits, and underscores as specified above. They are case-sensitive and have no fixed length limit. _value, _1, and __ are identifiers; _ alone is punctuation and cannot be a binding or assignment destination.
self and Self are keywords with the semantics specified in Names. In contrast, built-in names such as i32, Vec, and Clone are lexically standard identifiers; their restrictions are enforced by namespace scoping rules rather than dedicated lexer keyword rules.
Comments
Lexer
COMMENT → LINE_COMMENT | BLOCK_COMMENT
LINE_COMMENT → // ~LF*
BLOCK_COMMENT → /* ( BLOCK_COMMENT | BLOCK_CHAR )* */
BLOCK_CHAR → CHARnot at the start of /* or */
Comments support both line (//) and nestable block (/* ... */) forms, and act as whitespace. A line comment ends before an LF character or at the end of the file; a CR in a CRLF sequence is treated as part of the ignored comment text. An empty line comment at the end of the file is valid.
At each position in a block comment, /* opens a nested comment and */ closes the current one. Otherwise, one character is consumed as BLOCK_CHAR. Delimiters take priority over ordinary content, and each opening delimiter requires a matching closing delimiter. Unterminated comments are invalid.
// A line comment.
/* outer /* inner */ outer again */
/***/
/* a trailing slash / */
fn main() {}
Documentation comments
Documentation comments, including outer (///, /** ... */) and inner (//!, /*! ... */) forms, exhibit undefined behavior under the test guarantees.
Whitespace
Whitespace separators are space, horizontal tab, LF, and CRLF.
Whitespace separates tokens and otherwise has no semantic significance. Replacing a whitespace separator with another supported separator preserves the token sequence. Comments also act as separators. Whitespace cannot be inserted inside an identifier, inside an integer token, or between the two characters of a comment delimiter (such as // or /*).
Tokens
Lexer
Token →
IDENTIFIER_OR_KEYWORD
| INTEGER_LITERAL
| LIFETIME_TOKEN
| PUNCTUATION
Tokens are identifiers or keywords, integer literals, lifetime tokens, and punctuation. Keywords, including boolean literals (true and false), share the lexical character patterns of identifiers, but their syntactic roles are determined by keyword rules and the LiteralExpression production.
Tokenization selects the longest token subject to the numeric and lifetime boundaries below. The parser may consume prefixes of combined punctuation according to contextual punctuation.
Integer literals
Lexer
INTEGER_LITERAL →
( DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL ) INTEGER_SUFFIX?
DEC_LITERAL → DEC_DIGIT ( DEC_DIGIT | _ )*
BIN_LITERAL → 0b ( BIN_DIGIT | _ )* BIN_DIGIT ( BIN_DIGIT | _ )*
OCT_LITERAL → 0o ( OCT_DIGIT | _ )* OCT_DIGIT ( OCT_DIGIT | _ )*
HEX_LITERAL → 0x ( HEX_DIGIT | _ )* HEX_DIGIT ( HEX_DIGIT | _ )*
BIN_DIGIT → [0-1]
OCT_DIGIT → [0-7]
DEC_DIGIT → [0-9]
HEX_DIGIT → [0-9 a-f A-F]
Lexer
INTEGER_SUFFIX → i32 | u32 | isize | usize
Integer literals use decimal digits or a binary, octal, or hexadecimal prefix, with optional underscore separators. A non-decimal literal must contain at least one digit after the prefix. The four integer suffixes specify the corresponding integer type.
| Form | Examples |
|---|---|
| Decimal | 123, 1_234, 123_i32 |
| Binary | 0b1010, 0b____1, 0b10_u32 |
| Octal | 0o77, 0o7_usize |
| Hexadecimal | 0xff, 0xAB_CD, 0xff_isize |
The lexer consumes the complete numeric token using maximal munch. The lexer must not recover from an invalid suffix or invalid radix digit by splitting the input into a valid integer token followed by trailing tokens; spellings such as 123i32foo, 123bad, 0b102, and 0x must be rejected as invalid tokens. A supplied Rust lexer may retain a general suffix and reject unsupported suffixes at the language-subset boundary.
There is no token-length or numeric-magnitude limit. Compilers must preserve the raw digits and suffix without requiring the literal’s magnitude to fit into a host-platform integer type. Type determination and range validity follow literal expressions.
A literal outside its determined type’s range is undefined behavior; see the integer literal range guarantee.
A leading minus sign (-) is tokenized as a separate operator, not as part of an integer literal. Because f, 3, and 2 are valid hexadecimal digits, 0x01_f32 is parsed as a single hexadecimal integer literal whose value is 0x01f32 with no suffix, rather than as a floating-point literal.
Lifetimes
A lifetime token consists of an apostrophe immediately followed by its name, with no intervening whitespace or comment. The lexer consumes the complete name. Examples include 'a, 'data, 'static, and '_. A lifetime token must not be followed by a closing apostrophe; spellings such as 'a' represent character literals, which are not supported in Rx.
LIFETIME_OR_LABEL supplies ordinary named lifetimes to Lifetime. The special spellings 'static and '_ have their own alternatives there. Lifetime tokens occur in reference types, parameter declarations, path arguments, and bounds. Although the lexer production LIFETIME_OR_LABEL matches loop label tokens, Rx control-flow productions (Loops) do not support labeled loops or jumps.
Punctuation
Lexer
PUNCTUATION →
= | < | <= | == | != | >= | >
| && | || | !
| + | - | * | / | % | ^ | & | | | << | >>
| += | -= | *= | /= | %= | ^= | &= | |= | <<= | >>=
| . | , | ; | : | :: | -> | # | _
| { | } | [ | ] | ( | )
Comments take priority over / punctuation. Combined operators follow the longest-token rule; their contextual splits are specified in Parser conventions.
Floating-point numbers are not supported in Rx; numeric tokens containing fractional or exponent parts (such as 1.0 or 1e5) must be rejected as lexical errors rather than split into integer and punctuation tokens. Delimiters (parentheses, brackets, and braces) must always occur in matched pairs. The # character is used exclusively to introduce outer derive attributes.
Parser conventions
The language grammar is defined by the Lexer and Syntax blocks in each chapter. The grammar summary collects those same productions in one place. This guide indexes the rules for precedence and expression boundaries and specifies contextual token interpretation.
Grammar coverage by source form
Each occurrence of Type or Expression admits all alternatives defined in its
respective production. This composition applies recursively: a struct field
may hold a nested container type such as Vec<Box<T>>, a constructor argument may contain a block, and a
constructor result may be chained with indexing or a method call.
| Source form | Defining productions | Examples |
|---|---|---|
| Identifiers and integers | IDENTIFIER, INTEGER_LITERAL | _value, 123_i32, 0b1010 |
| Lifetime tokens and forms | LIFETIME_TOKEN, Lifetime | 'a, 'static, '_ |
| Lifetime parameters and bounds | GenericParams, LifetimeParam, WhereClause | fn f<'a>(x: &'a i32), where 'a: 'b |
| Source compilation unit | Crate, Item | Top-level use declarations, functions, structs, constants, impls |
| Use declarations | UseDeclaration, UseTree, UsePath | use rx::core::*;, use rx::core::{get_i32, println_i32}; |
| Functions and receivers | Function, FunctionParameters, ShorthandSelf | fn f(v: Vec<i32>) -> Box<i32> { ... }, &mut self |
| Struct declarations and construction | StructStruct, StructExpression | struct S { x: i32 }, S { x: 1 }, Self { x: 1 } |
| Associated items | InherentImpl, AssociatedItem | impl S { fn new() -> Self { ... } } |
| Derive attributes | OuterAttribute, DeriveAttribute | #[derive(Clone, PartialEq, Eq)] |
| Bindings and statements | LetStatement, ExpressionStatement | let mut v = Vec::<i32>::new();, v.push(1); |
| Type names, arrays, references, and unit | TypePath, ArrayType, ReferenceType, UnitType | Self, [Vec<i32>; 2], &mut Box<i32>, () |
| Container types | TypePath, TypePathSegment, GenericArgs | Box<[i32; 4]>, Vec<Box<Node>>, Vec<Vec<i32,>,> |
| Container construction | CallExpression, PathInExpression | Box::<i32>::new(7), Vec::<Box<i32>>::new() |
| Paths, calls, fields, and indexing | PathExpression, CallExpression, MethodCallExpression, FieldExpression, IndexExpression | S::new(), value.clone(), value.field, values[0] |
| Arrays, grouping, and unit values | ArrayExpression, GroupedExpression, UnitExpression | [1, 2, 3], [0; 4], (value), () |
| Operators | OperatorExpression | *p, &mut values[0], a + b, x += &y |
| Blocks and branching | BlockExpression, IfExpression | { make() }.field, if flag { a } else { b } |
| Loops and jumps | LoopExpression, BreakExpression, ContinueExpression, ReturnExpression | loop { break 3; }, while condition { ... }, return value |
| Constant contexts | ConstValue, Magnitude | 123, COUNT, (-1), -(2147483648i32), ((true)) |
The grammar describes the shape of a construct. Name resolution, typing, place mutability, and the test domain determine which parsed programs are valid. For example, the identifier in a struct construction expression must name a declared struct, a called method must be defined in an inherent impl for the receiver’s type, and an assignment destination must denote a mutable place.
Rule locations
| Topic | Defining chapter |
|---|---|
| Use declarations | Use declarations |
| Type and expression arguments | Paths |
| Lifetime declarations and bounds | Lifetime parameters |
| Derive attributes | Attribute grammar |
| Operator precedence | Expressions |
| Casts followed by comparison or shift | Cast parsing |
| Struct construction in a condition | If expressions |
| Expression-statement boundaries | Statements |
| Block tails | Block expressions |
| Break/continue targets and loop results | Loops |
| Never and unreachable code | Never type |
| Assignment places | Assignment destinations |
Syntax that may be discarded after parsing
Two forms of Rust compatibility syntax must be parsed, but need no subsequent semantic processing or LLVM IR representation:
- Use declarations: discard the entire declaration. No import resolution, module loading, alias insertion, or import-conflict checking is required.
- Lifetime syntax: discard lifetime parameter declarations, reference lifetime annotations, explicit lifetime arguments, outlives bounds, and lifetime where clauses. No lifetime name resolution, inference, elision checking, or lifetime/borrow checker is required.
The use compatibility and lifetime validity guarantees exclude tests that would require these checks. Discarding lifetime syntax is an internal AST transformation; the compiler is not required to ensure that source text stripped of lifetime annotations forms valid Rust.
Parsing must still enforce the grammar of these constructs. The compiler must preserve
reference types, mutability qualifiers, concrete type arguments (such as i32 in Vec::<&'a i32>),
and all other AST structures. Ordinary name, type, and place-mutability
checks and correct reference behavior remain required.
Contextual punctuation
The parser interprets combined punctuation according to its current grammar context. The lexer may emit a combined token; the parser consumes the needed prefix and leaves the remaining punctuation for the enclosing construct.
| Combined token | Context | Interpretation |
|---|---|---|
&& | Reference type or prefix borrow | Two & tokens, as in &&i32 or &&x |
>> | Closing nested type arguments | Two closing > tokens |
>= | Closing type arguments before assignment | A closing > followed by = |
>>= | Closing nested type arguments before assignment | Two closing > tokens followed by = |
In ordinary infix expression contexts, these tokens denote their corresponding
operators. Thus, the following variable initializations do not require whitespace between the closing > and the = token:
let values: Vec<i32>=Vec::<i32>::new();
let nested: Vec<Vec<i32>>=Vec::<Vec<i32>>::new();
Crates and source files
An Rx program consists of a single source compilation unit containing a sequence of top-level items. Its functions, structs, constants, and inherent impls share the namespaces described in Names.
The top-level Item alternatives are use declarations, functions, named-field structs, constants, and inherent impl blocks. Use declarations exist solely for Rust compatibility and may be discarded after parsing; they do not introduce any names into Rx namespaces. Items cannot be declared in expression blocks. Program entry follows the main contract.
Names and scopes
Scope rules
Top-level functions, structs, constants, and inherent associated items introduce names. Parameters and let statements introduce local bindings. Fields belong to their enclosing struct’s namespace and are resolved through the receiver’s type.
Use declarations do not introduce names in Rx and participate in neither name resolution nor collision checks. Imported paths and aliases may be discarded after parsing; the builtin environment is independent of these declarations.
Top-level and associated-item lookup is independent of declaration order. A local binding is visible only after its initializer and until the end of its block, subject to shadowing. Constant initializers, array lengths, and array-repeat lengths may use constant-item paths under the constant-context rules, which also require acyclic constant dependencies.
self denotes a method receiver. Self denotes the struct being declared or the target type of the current inherent implementation, including within its associated items. Neither is an ordinary user-defined identifier, and Self cannot be used in top-level functions declared outside of an impl block.
Lifetime names occupy a separate namespace governed by lifetime parameters and the lifetime validity guarantee.
Type and value namespaces
Types and values use separate namespaces:
| Context | Namespace |
|---|---|
Struct name, primitive type, Box, Vec, or Self in a type position | Type |
Function, constant, local binding, or self in an expression | Value |
Prefix of Type::member | Type |
| Struct field | That struct’s field namespace |
A named-field struct is not a callable value constructor; therefore, a struct and a function may share the same name without collision.
Name collisions
Top-level names must be unique within their namespace. Fields within a struct and parameters within a function must also be unique. All inherent implementations of a struct share a single associated-value namespace; defining duplicate methods, associated functions, or associated constants is a compile-time error, regardless of their signatures or whether they are declared across different impl blocks. A struct field and an inherent method may share the same name because they reside in separate namespaces.
Successive let bindings may shadow earlier locals, parameters, and non-protected global functions. Lookup resolves to the nearest enclosing binding; if that binding is not callable, an invocation is a compile-time error rather than falling back to an outer shadowed function. The initializer expression of a let binding is evaluated in the scope preceding the newly introduced binding.
A let or ordinary parameter that collides with a visible unqualified constant is undefined behavior under the centralized constant-name collision guarantee.
Protected builtin names
The following names are protected in their respective namespaces:
| Namespace | Protected names |
|---|---|
| Type | i32, u32, isize, usize, bool, Box, Vec, Copy, Clone, PartialEq, Eq |
| Value | get_i32, print_i32, println_i32 |
| Derive entry | Copy, Clone, PartialEq, Eq |
These protected names remain valid lexical identifiers. They may be used in other namespaces or as field and associated-item names (for example, a field named Vec is valid). Because inherent implementations can only be declared for user-defined structs, inherent methods cannot be added to protected builtin types.
The following collisions are undefined behavior under the test guarantees, with no required diagnostic or behavior:
- Declaring a struct named
u32,isize,usize,bool,Box,Vec,Copy,Clone,PartialEq, orEq. - Declaring a local binding (
letor ordinary parameter) namedget_i32,print_i32, orprintln_i32.
Other redeclarations of protected builtins within their respective namespaces are compile-time errors, including defining a struct named i32 or declaring a top-level function or constant with a protected I/O name.
Paths
A path names a value, type, or associated item through ::-separated segments. Both type and expression paths share the same generic argument syntax (GenericArgs).
Use declarations have a separate UsePath syntax for Rust compatibility. Their paths are not resolved by the Rx compiler and do not extend the type or expression paths defined here.
Paths in expressions
Syntax
PathInExpression → PathExprSegment ( :: PathExprSegment )*
PathExprSegment → PathIdentSegment ( :: GenericArgs )?
PathIdentSegment → IDENTIFIER | self | Self
Expression paths use :: before generic arguments (the ‘turbofish’ syntax), as in Box::<i32>::new. Their final segment may name a value or an associated item. Calls on these paths are governed by CallExpression and MethodCallExpression.
Paths in types
Syntax
TypePath → TypePathSegment ( :: TypePathSegment )*
TypePathSegment → PathIdentSegment ( ::? GenericArgs )?
Type arguments may follow a segment directly or after ::, so Box<i32> and Box::<i32> name the same type. Type paths referencing user-defined structs may supply lifetime arguments, such as View<'a>, or rely on permitted lifetime elision.
Generic arguments
Syntax
GenericArgs → < GenericArgList? >
GenericArgList → ( GenericArg , )* GenericArg ,?
GenericArg → Lifetime | Type
Generic arguments are comma-separated with an optional trailing comma, and any lifetime arguments must precede type arguments. In valid programs, Box and Vec have exactly one explicit concrete type argument. Omitting it in a Box::new(...) or Vec::new() constructor call is undefined behavior. User-defined functions and structs accept only their declared lifetime arguments, whereas primitive types accept no generic arguments. Any other mismatch in generic argument arity or kind is a compile-time error; lifetime correctness is governed by the lifetime validity guarantee.
A type argument may recursively contain any supported concrete type. For example:
let values: Vec<Box<[i32; 4]>> = Vec::<Box<[i32; 4]>>::new();
let borrowed = Vec::<&'a i32>::new();
Path resolution
| Path role | Resolved form |
|---|---|
| Value | Binding, constant, function, or self |
| Type | Primitive, declared struct, Self, Box<T>, or Vec<T> |
| Associated item | Struct path or Self, followed by a declared member or derived builtin method |
| Builtin associated operation | Box::<T>::new, Vec::<T>::new, or a supported builtin method on a type path, such as Box::<i32>::clone |
Functions and methods may use explicit lifetime arguments where Rust permits them. Omitted lifetimes use the supported Rust 2021 inference and elision rules. Tests guarantee that explicit lifetime arguments, including early-bound and late-bound uses, are valid.
Unresolved names are compile-time errors. After name resolution, call expressions are checked against argument and receiver rules. Supplying incorrect lifetime arguments or invalid lifetime elisions results in undefined behavior under the lifetime validity guarantee.
Items
Syntax
Item → UseDeclaration | Function | Struct | ConstantItem | Implementation
Items form a source compilation unit. The following chapters define use declarations, functions, structs, constants, and inherent implementations. Implementation block members are described in associated items, and lifetime parameter lists are specified in lifetime parameters and bounds.
Use declarations
Syntax
UseDeclaration → use UseTree ;
UseTree →
( UsePath? :: )? ( * | { ( UseTree ( , UseTree )* ,? )? } )
| UsePath ( as ( IDENTIFIER | _ ) )?
UsePath → ::? UsePathSegment ( :: UsePathSegment )*
UsePathSegment → IDENTIFIER | self | super | crate
Use declarations are accepted as top-level items so that the same test source can be compiled with Rust and the course support crate. For example:
use rx::core::*;
fn main() {
println_i32(42);
}
The syntax accepts individual paths, * globs, nested brace groups with optional
trailing commas, and as aliases. For example, use rx::core::println_i32; and
use rx::core::{get_i32, println_i32}; are also accepted. Use declarations cannot
appear in expression blocks or impl blocks, and they do not accept visibility modifiers or
attributes.
After parsing, the compiler may discard the entire declaration. The compiler does not
resolve import paths, load crates or modules, introduce names or aliases into any scope,
check for import conflicts, or emit LLVM IR for the declaration. Builtins such as
println_i32 are already available in Rx, with or without a use declaration.
The use compatibility guarantee
ensures that tests do not depend on additional import semantics. The extended path syntax
accepted in use declarations (including multi-segment paths, leading ::, crate, and super)
does not apply to type and expression paths. See also
syntax that may be discarded after parsing.
Functions
Syntax
Function →
fn IDENTIFIER GenericParams?
( FunctionParameters? )
FunctionReturnType? WhereClause?
BlockExpression
FunctionParameters →
SelfParam ,?
| ( SelfParam , )? FunctionParam ( , FunctionParam )* ,?
ShorthandSelf → ( & Lifetime? )? mut? self
FunctionParam → IdentifierBinding : Type
FunctionReturnType → -> Type
A function definition consists of a name, optional lifetime parameters, a parameter list, an optional return type, optional lifetime bounds, and a required body. Top-level functions accept only ordinary parameters, whereas functions within inherent impl blocks may also include a receiver parameter, as described below.
GenericParams declares lifetime parameters after the function name. WhereClause states lifetime bounds after the result type, or after the parameter list when the result annotation is omitted. See lifetime parameters.
Ordinary parameters use IdentifierBinding followed by an explicit type. Function signatures determine parameter and return types independently of their callers. An optional trailing comma is permitted after a receiver or the last ordinary parameter. If the return type is omitted, it defaults to the unit type ().
An ordinary parameter binding that collides with a visible unqualified const name is undefined behavior; see the constant-name collision guarantee.
The name lookup rules permit forward calls and mutual recursion. Function names may only serve as call targets; treating a function as a first-class value results in undefined behavior. Call expressions specify argument evaluation and parameter passing; return expressions specify function return values. The program entry point is defined in Program entry.
fn add(left: i32, mut right: i32) -> i32 {
right += left;
right
}
Receivers
Within an inherent impl, the first parameter may be SelfParam. Its forms are:
| Form | Receiver |
|---|---|
self | By-value receiver |
mut self | Mutable by-value receiver |
&self or &'a self | Shared reference |
&mut self or &'a mut self | Mutable reference |
A function with a receiver is a method; a function without a receiver is an associated function. Any subsequent parameters must follow the FunctionParam syntax. Receiver lifetimes follow the lifetime validity rules, and by-value receivers follow copy/move semantics.
Structs
Syntax
Struct → OuterAttribute* StructStruct
StructStruct → struct IDENTIFIER GenericParams? WhereClause? { StructFields? }
StructFields → StructField ( , StructField )* ,?
A struct declaration defines a name, optional lifetime parameters and where-clause bounds, and a brace-delimited list of named fields. The field list may include an optional trailing comma after the final field. A struct may have derive attributes.
Lifetime parameters describe references stored in the struct, as in struct View<'a> { value: &'a i32 }. A type path supplies the corresponding arguments with View<'a> or uses Rust’s permitted lifetime elision. See lifetime parameters and lifetime validity.
A struct is a nominal type with explicitly typed, named fields. Its fields are accessible throughout the source compilation unit. Name rules define field uniqueness and the meaning of Self in its declaration. For example, in struct Node { children: Vec<Self> }, the type Self refers to the Node struct being defined.
Struct definitions must have finite layouts. Struct declarations with empty braces (zero-sized structs) are syntactically permitted, and operations on zero-sized data follow the zero-sized-data rules. The backend contract governs implementation layout. Values are created with struct expressions and accessed with field expressions.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Point {
x: i32,
y: i32,
}
Constant items
Syntax
ConstantItem → const IDENTIFIER : Type = ConstValue ;
A constant declaration specifies a name, an explicit type, and an initializer. The initializer expression must evaluate to a ConstValue conforming to the constant-context rules. A constant initializer may reference other constant items, subject to the same rules and an acyclic-dependency requirement. Referencing a constant in an ordinary expression evaluates to its defined value.
Constants are declared at the top level or as associated items in an inherent impl. The name lookup rules permit forward references, allowing a constant to be used before its textual declaration.
const LIMIT: i32 = 100;
const NEGATIVE: i32 = (-1);
Implementations
Syntax
Implementation → InherentImpl
InherentImpl → impl GenericParams? Type WhereClause? { AssociatedItem* }
An inherent impl defines associated items for a user-defined named-field struct. The implementing Type must resolve to that struct; specifying any other kind of target type is a compile-time error. Parentheses enclosing the type retain their standard grouping semantics; thus, impl S { ... } and impl (S) { ... } target the same struct.
An impl block may declare lifetime parameters immediately after the impl keyword, as in impl<'a> View<'a> { ... }. These parameters remain in scope throughout all associated items in the block. Methods and associated functions may declare additional lifetime parameters. A WhereClause before the opening brace specifies lifetime bounds.
Multiple impl blocks for the same struct are supported. Their member namespaces and duplicate-name restrictions are governed by Names. Permitted items within an implementation block are defined in Associated items, and method receivers are described in Function receivers.
impl Point {
const ZERO: i32 = 0;
fn total(&self) -> i32 {
self.x + self.y
}
fn translate(&mut self, amount: i32) {
self.x += amount;
self.y += amount;
}
}
Associated items
Syntax
AssociatedItem → ConstantItem | Function
An inherent impl block may contain associated constants, associated functions, and methods.
Associated functions and methods are governed by the function and receiver rules. Associated items are referenced via a PathInExpression, such as Point::new or Self::LIMIT. Method calls use MethodCallExpression and the receiver lookup rules.
Lifetime parameters and bounds
Parameter declarations
Syntax
GenericParams → < ( GenericParam ( , GenericParam )* ,? )? >
LifetimeParam → Lifetime ( : LifetimeBounds )?
Functions, named-field structs, and inherent impls may declare lifetime
parameters. A function or struct places GenericParams after its name; an impl
places the list after impl. The parameter list may end with an optional trailing comma.
Each parameter declares a lifetime, optionally accompanied by outlives bounds.
struct View<'a> {
value: &'a i32,
}
impl<'a> View<'a> {
fn new(value: &'a i32) -> Self {
Self { value: value }
}
fn get(&self) -> &'a i32 {
self.value
}
}
fn choose<'a>(left: &'a i32, right: &'a i32, first: bool) -> &'a i32 {
if first { left } else { right }
}
Lifetime parameters remain in scope throughout the item in which they are declared.
Lifetimes declared on an impl block also apply within its associated items, though
a method or associated function may declare additional lifetime parameters. Lifetime names
occupy their own namespace. Incorrect lifetime declarations, uses, or bounds are
undefined behavior; see the lifetime validity guarantee.
Lifetime forms and bounds
Syntax
Lifetime → LIFETIME_OR_LABEL | 'static | '_
LifetimeBounds → ( Lifetime + )* Lifetime?
TypeParamBounds → TypeParamBound ( + TypeParamBound )* +?
A named lifetime such as 'a refers to an in-scope parameter. 'static denotes
the lifetime covering the entire program. '_ represents an anonymous lifetime
inferred according to Rust’s elision rules at that occurrence. Generic parameter declarations
only accept ordinary named lifetimes; 'static and '_ are only valid at use sites.
The bound 'a: 'b means that 'a outlives 'b. A list such as
'a: 'b + 'c states both bounds. A type bound such as View<'a>: 'b means that
references contained in the type remain valid for 'b. The types in these
bounds are the concrete types described by Type.
fn shorten<'long: 'short, 'short>(value: &'long i32) -> &'short i32 {
value
}
Where clauses
Syntax
WhereClause → where ( WhereClauseItem , )* WhereClauseItem?
WhereClauseItem → LifetimeWhereClauseItem | TypeBoundWhereClauseItem
A where clause specifies lifetime bounds following a function’s return type
(or parameter list if omitted), a struct’s lifetime parameters, or an impl block’s
target type. Bounds are comma-separated with an optional trailing comma. A lifetime
bound may be written here or directly on its parameter declaration.
fn shorten_where<'long, 'short>(value: &'long i32) -> &'short i32
where
'long: 'short,
{
value
}
These productions use Rust’s parameter-list and bound syntax. GenericParam defines lifetime parameters; GenericArg defines the lifetime and concrete type arguments used in paths. The supported named types and callable signatures are specified in Paths.
Traits and attributes
Rx supports derive attributes for four builtin traits: Copy, Clone, PartialEq, and Eq. User-defined traits, trait bounds, and explicit trait implementations are unsupported.
Attribute grammar
Syntax
OuterAttribute → # [ DeriveAttribute ]
DeriveAttribute → derive ( ( DeriveName ( , DeriveName )* ,? )? )
DeriveName → Copy | Clone | PartialEq | Eq
This is the complete attribute grammar. Zero or more outer attributes (OuterAttribute) may precede a top-level named-field Struct. Attributes on other constructs, inner attributes (#![...]), and other attribute names or derive names are unsupported.
Derive lists may be empty or have a trailing comma. All derive attributes on a struct contribute to the same set of requested traits; specifying duplicate traits within the same attribute or across multiple attributes on the same struct is a compile-time error. Each requested trait must satisfy its requirements.
#[derive(Clone)]
#[derive(Copy, PartialEq, Eq,)]
struct Point { x: i32, y: i32 }
Builtin traits
The compiler recognizes Copy, Clone, PartialEq, and Eq. Structs implement them by specifying derive attributes. The only builtin trait operations are .clone(), ==, and !=; ordering and arithmetic operations are governed by Operators.
Copy
Functionality. Reading a place copies a Copy value and moves any other value. This applies to initialization, assignment, by-value arguments and receivers, returns, and field reads. A move makes its source unavailable until reinitialized; it never creates an implicit alias. Copy is a marker trait and introduces no methods.
Copies are semantically independent. Copying a shared reference copies the reference, not its target. A machine-level address-passing convention must preserve by-value semantics. Moves may reuse storage when no observable behavior changes.
Tests exclude reading uninitialized values, use after move, double move, invalid partial move, and moving non-Copy values from borrowed contents or array indices. The compiler is not required to diagnose these ownership violations, but valid moves across branches, through fields, and during early returns must be correctly supported.
Requirements. Deriving Copy requires every field of the struct to implement Copy, and Clone must also be explicitly derived on the struct. Deriving Copy must be explicitly requested even when a bitwise copy could implement Clone.
Example. Copy a small value while keeping the original usable.
#[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }
fn main() {
let original = Point { x: 1, y: 2 };
let mut copied = original;
copied.x = 9;
print_i32(original.x); // 1
}
Clone
Functionality. Clone provides fn clone(&self) -> Self. A derived Clone implementation recursively clones all fields and array elements to produce an independent value. Scalars and shared references are copied; the target of a shared reference is not cloned. Cloning semantics for owned heap containers are defined in Container cloning.
An explicit .clone() uses method lookup. If multiple candidate methods match the same candidate receiver type (such as an inherent method competing with a derived clone method), the method call results in undefined behavior.
Requirements. Deriving Clone requires every field to be Clone. Mutable references are not Clone.
Example. Duplicate owned heap data so that each value can change independently.
#[derive(Clone)]
struct Buffer { value: Box<i32> }
fn main() {
let original = Buffer { value: Box::<i32>::new(7) };
let mut cloned = original.clone();
*cloned.value = 9;
print_i32(*original.value); // 7
}
PartialEq
Functionality. PartialEq enables == and !=, which borrow their operands. Scalar values are compared by value; arrays are compared element-wise; derived structs compare each corresponding field; and references compare their referents rather than their pointer addresses. Padding bytes are ignored, so a whole-object memcmp is generally invalid. Box and Vec follow container equality.
Requirements. Deriving PartialEq requires every field to be PartialEq. Both operands must share the exact same source type implementing PartialEq; the equality operators do not perform implicit type coercion and do not infer an unsuffixed integer literal’s type from the opposing operand. Thus 1 == 1i32 is valid, while 1 == 1u32 is undefined behavior under the cross-type equality guarantee.
Example. Compare records without consuming them.
#[derive(PartialEq)]
struct Reading { value: i32 }
fn main() {
let first = Reading { value: 7 };
let second = Reading { value: 7 };
let same = first == second; // true
let different = first != second; // false; both remain usable
}
Eq
Functionality. Eq marks equality as an equivalence relation: reflexive, symmetric, and transitive. It introduces no new operations; equality comparisons continue to use PartialEq.
Requirements. Deriving Eq requires every field to be Eq and PartialEq to be explicitly requested for the struct.
Example. Declare that record identifiers have equivalence-based equality.
#[derive(PartialEq, Eq)]
struct Key { id: i32 }
fn same_key(left: &Key, right: &Key) -> bool {
left == right // compares id fields
}
Trait capability summary
| Type | Copy | Clone | PartialEq / Eq with the same source type |
|---|---|---|---|
Integers, bool | Yes | Yes | Both |
&T | Yes | Yes | Requires the corresponding capability of T |
&mut T | No | No | Requires the corresponding capability of T |
[T; N] | If T is Copy | If T is Clone | Requires the corresponding capability of T |
| Struct | Valid explicit derive | Valid explicit derive | Valid explicit derive |
Box<T>, Vec<T> | No | If T is Clone | Requires the corresponding capability of T |
Zero-sized data follows the zero-sized-data guarantee. Trait capability verification must terminate even when evaluating recursive type definitions, while still enforcing each field’s trait requirements. For example, struct Node { children: Vec<Node> } may derive Clone, PartialEq, and Eq, provided all other fields satisfy the corresponding trait requirements.
Statements and bindings
Syntax
Statement → ; | LetStatement | ExpressionStatement
Identifier bindings
Syntax
LetStatement → let IdentifierBinding ( : Type )? = Expression ;
IdentifierBinding → mut? IDENTIFIER
A let statement binds a single identifier to the evaluated result of an initializer expression. Specifying mut makes the binding mutable. The initializer may produce any supported value, including a reference formed by a borrow expression.
Binding visibility and shadowing follow Names. A let binding that collides with a visible unqualified constant name results in undefined behavior; see the constant-name collision guarantee.
The optional type annotation and initializer expression are governed by local type inference and coercion rules. Subsequent assignments to the binding are governed by assignment destinations.
Expression statements
Syntax
ExpressionStatement →
ExpressionWithoutBlock ;
| ExpressionWithBlock ;?
An expression statement evaluates an expression and discards its result while
preserving its effects. An empty ; statement has no effect.
ExpressionWithoutBlock requires a semicolon. ExpressionWithBlock
({ ... }, if, while, or loop) may omit it.
When an ExpressionWithBlock is used as a statement (where its result is discarded),
omitting the semicolon requires its evaluated type to be compatible with the unit
type ().
In contrast, when an ExpressionWithBlock without a semicolon appears as the final expression of a block, it serves as the block’s tail expression rather than an expression statement; it is governed by the tail-expression rules and may evaluate to any type.
fn show(flag: bool) {
if flag { print_i32(1); } // unit result: semicolon optional
if flag { 1 } else { 2 }; // integer result: semicolon discards it
}
Statement boundary
When parsing an expression statement, an expression with an outer block form terminates the statement immediately rather than greedily consuming any subsequent infix operator. In an initializer or other value-expression context, the expression continues normally. Parentheses can force an ordinary expression context.
An attached else or else if clause remains part of its if expression, and postfix field accesses or method calls may continue directly after a completed block expression. Other expression statements extend until their terminating semicolon; alternatively, an enclosing block may conclude with a tail expression immediately preceding the closing }. For example, { make() }.value; is a valid field-access expression statement provided make() returns a struct with a value field.
let value = if true { 10 } else { 20 } - 1; // initializer is the whole subtraction
if true {} else {} -1; // if statement, then -1 expression statement
(if true { 10 } else { 20 }) - 1; // one expression statement
A conforming compiler must implement these statement boundaries and adhere to the grammar defined above.
Types and inference
Syntax
Type → TypeNoBounds
TypeNoBounds →
ParenthesizedType
| TypePath
| UnitType
| ReferenceType
| ArrayType
ParenthesizedType → ( Type )
Supported types
| Type | Meaning |
|---|---|
i32, isize | Distinct signed 32-bit integers |
u32, usize | Distinct unsigned 32-bit integers |
bool | Boolean |
Named struct; Self in its declaration or impl | Nominal named-field product |
[T; N] | Fixed array with a restricted usize constant length |
&T, &mut T, &'a T, &'a mut T | Shared or mutable reference |
() | Function or control-flow result |
Box<T>, Vec<T> | Owned heap object or dynamic sequence |
The never type ! is used internally. Expressions of type ! diverge, but a diverging expression can have another type.
Struct types are nominal. References, arrays, Box, and Vec are structural. The four integer types remain distinct. Array lengths are compared by value, so [i32; 4] and [i32; (4usize)] are identical. Two reference types are identical if and only if their referent types and mutabilities match; lifetime arguments do not distinguish reference types and must satisfy the lifetime validity guarantee.
Inference
Type inference fills in omitted local binding types from their initializers. Function and item signatures are explicit. Each binding has one fixed type; later uses do not change it. Omitting explicit concrete type arguments in Box and Vec constructor calls is undefined behavior. A receiver’s type must be known before field or method lookup.
Integer literals
Integer literals use this limited inference rule, in order:
- A suffix fixes the type.
- Without a suffix, use the expected type if it is one of
i32,u32,isize, orusize. - Otherwise, use
i32.
Expected types come from the contexts and propagation rules below. Without such an expectation, another operand, a neighboring array element or branch, and later uses of a binding do not select the literal’s type. Once chosen, an integer type does not change implicitly.
let n = 1; // i32: no expected type
let count: u32 = 1; // u32: from the annotation
let sum: u32 = 1 + 2; // undefined behavior: needs propagation through +
let neg: isize = -1; // undefined behavior: needs propagation through unary -
let r: &u32 = &1; // undefined behavior: needs propagation through &
let values: [u32; 2] = [1, 2]; // u32 elements; usize length
let bad: u32 = 1i32; // compile error: a suffix fixes the type
let later: u32 = n; // compile error: n is already i32
let mixed = 1 + 2u32; // compile error: no expected type for 1
Array lengths and indices have expected type usize, so [i32; 4], [0; 4], and data[0] are valid without suffixes. Range checking follows type selection: an integer literal whose value falls outside the selected type’s representable range exhibits undefined behavior. The magnitude of the literal never causes a different integer type to be selected.
Conversions and coercions
An explicit conversion uses as. A coercion is an automatic adjustment at one of the expression positions listed below. The organization follows the Rust Reference, with only the types and operations supported by Rx.
Explicit conversions
Integer-to-integer and bool-to-integer conversions require as. Integer casts preserve the 32-bit pattern; false becomes 0 and true becomes 1. These are the only supported casts. Conditions require expressions of type bool; integer values cannot be used as conditions and are not implicitly converted.
Coercion sites and expected types
A one-to-one coercion checks one expression against a known target, called its expected type. A least upper bound (LUB) coercion finds a common target for several expressions. This distinction follows the Rust Compiler Development Guide. An expected integer type can select an unsuffixed literal’s type before coercion; coercion itself does not convert integers.
These sites have a known expected type and use one-to-one coercion:
| Expression position | Expected type |
|---|---|
Annotated let initializer | Annotation |
| Constant initializer | Declared constant type, subject to the restricted constant forms |
| Assignment right operand | Destination |
| Function, method, or container constructor argument | Declared parameter; method receivers follow receiver adjustments |
Function tail or return operand | Declared result |
| Struct field initializer | Declared field |
The expected type propagates through parentheses, into block tail expressions, to both result branches of an if expression, and to all break value expressions targeting a loop. An expected array type [T; N] supplies T to each listed or repeated element and requires length N. Each of these result expressions is checked against that target; failure is a compile error except for the propagation exclusion below.
Propagation repeats only through the forms listed above. It does not pass through binary operations, unary operations, or borrow expressions (&e and &mut e), and does not revisit earlier binding initializers. If a program requires type propagation through an operator or borrow expression to determine an integer literal’s type, its behavior is undefined behavior, rather than triggering a required compile error.
This excludes reliance on propagation, not the operators or borrows themselves. For example, let n: i32 = 1 + 2; works by defaulting, and let r: &u32 = &1u32; works because the suffix fixes the type. Incompatible types fixed by suffixes or existing bindings remain compile errors. Call arguments still get their declared expected types, even inside an operator or borrow.
// Expected type u32 propagates into block tails, if branches, and loop breaks:
let x: u32 = { 1 }; // valid: 1 receives expected type u32
let y: u32 = if true { 1 } else { 2 }; // valid: 1 and 2 receive expected type u32
let z: u32 = loop { break 42; }; // valid: 42 receives expected type u32
// But expected type does NOT penetrate operators or borrows:
let a: u32 = 1 + 2; // undefined behavior (requires propagation through +)
let b: &u32 = &1; // undefined behavior (requires propagation through &)
let c: &u32 = &1u32; // valid: suffix fixes the literal type
Conditions require bool, array lengths and indices have expected type usize, and loop bodies and an if without else require unit results. Operators follow their operand rules. These requirements do not enable additional conversions.
Coercion types
Only the following adjustments are supported:
| Source | Target | Adjustment |
|---|---|---|
T | T | Keep the type; ordinary copy/move rules apply, except for mutable-reference reborrowing below |
&mut T | &T | Borrow the same value through a shared reference |
&S or &mut S | &T | Follow builtin dereferences from S to a T place, then borrow it |
&mut S | &mut T | Follow builtin dereferences from S to a mutable T place, then borrow it mutably |
| Never | Any target | No value is produced on that path |
The builtin dereference steps are &U to U, &mut U to U, and Box<U> to U. They may be repeated until the target’s referent type matches exactly. A mutable target requires an outer &mut and no shared reference along the path. The adjustment borrows the reached value without moving its contents. Vec has no builtin dereference.
let mut boxed = Box::<i32>::new(1);
let r: &i32 = &boxed; // &Box<i32> to &i32
let m: &mut i32 = &mut boxed; // &mut Box<i32> to &mut i32
Coercion does not borrow an owned value implicitly: Box<T> cannot coerce to T or &T; write &boxed for the latter. It does not convert stored array or container elements, change inner reference mutability, or produce slices. For example, &mut &mut i32 cannot coerce to &mut &i32. Array literal elements may each coerce because they are separate expression sites.
Mutable-reference reborrowing
Note: Since we guarantee that lifetimes are valid, you do not need to know about reborrowing for this project. It is retained here solely for the completeness of the specification.
At a coercion site, an &mut T may be borrowed again as &mut T. This is a reborrow: after the new borrow ends, the original reference is usable again. An unannotated let binding instead moves the reference:
let mut x = 1;
let p = &mut x;
{
let q: &mut i32 = p; // reborrow
*q = 2;
}
*p = 3;
let moved = p; // move
*moved = 4;
After the move, p cannot be used without reinitialization. Passing p as an argument to an &mut i32 parameter reborrows it in the same way. Later uses do not turn a move into a reborrow.
Least upper bound coercions
When no expected type fixes the target, LUB coercion finds a common type for:
- The result branches of an
ifwithelse. - The elements of an array literal.
- The values of all
breakexpressions targeting the sameloop.
With an expected type, these same expressions use one-to-one coercions to that fixed target. Function returns and the function tail also share a fixed target: the declared result type. They never infer a different function signature.
For an unknown target, first determine each result’s type independently, using i32 for unsuffixed integers that have no expected integer type. The current LUB target is not an expected type for another result. Consider results in source order and ignore never results, which can fit any target. Start with the first remaining result’s type as the current target T. For each next result of type U:
- If
Ucan coerce toT, keepT. - Otherwise, if
Tcan coerce toUand every earlier result can be adjusted toU, useUas the new target and adjust those results too. - If not, the behavior is undefined (undefined behavior). No search for a third common type is required.
If all results are never, the result type is never. Empty arrays follow the zero-sized-data exclusion. A bare break; supplies (); breaks targeting nested loops do not participate.
Each row below is a separate example:
| Expression | Result |
|---|---|
let a = [&mut 1, &123]; | [&i32; 2]; the first element becomes shared |
let a = [&123, &mut 1]; | The same type; the second element becomes shared |
let a = [&mut 1u32, &123u32]; | [&u32; 2] |
let a = [&mut 1u32, &123]; | Undefined behavior: no expected type for 123, so it is i32 |
let a: [&u32; 2] = [&mut 1, &123]; | Undefined behavior: inferring u32 would require propagation through both borrows |
let a: [&u32; 2] = [&mut 1u32, &123u32]; | Valid: the literals are already u32; the first reference coerces to shared |
let a = [&mut &1, &mut &mut 2]; | Undefined behavior: inner reference mutability differs |
let a: [&mut &i32; 2] = [&mut &1, &mut &mut 2]; | Compile error: the second element cannot meet the fixed expected type |
These rules determine the types of expressions; they do not change evaluation order or the separate method and operator adjustment rules.
Recursive types
A by-value struct or array containment cycle has no finite size and is a compile error. References, Box, and Vec provide indirection, so recursive and mutually recursive structs through those types are supported.
struct Node {
value: i32,
children: Vec<Node>,
}
Recursive layout details
struct Infinite { child: Infinite } is invalid because the child is inline; an inline array also fails to break the cycle. Referencing an invalid cyclical type inside a container (such as Box or Vec) within another declaration does not make the cyclic type definition valid.
// Invalid: infinite size due to inline containment cycle
// struct BadNode { child: BadNode }
// struct BadArray { items: [BadArray; 1] }
// Valid: indirection breaks the layout cycle
struct GoodNode {
child: Box<GoodNode>,
}
Finite layout does not imply constructibility. struct Chain { next: Box<Chain> } has finite layout but no terminating value because Box is non-nullable. This does not make its declaration invalid.
An implementation may check cycles only through inline struct and array dependencies. Container APIs, trait capabilities, and reclamation are defined separately in Box and Vec.
Array types
Syntax
ArrayType → [ Type ; ConstValue ]
An array type specifies an element type and a ConstValue length. The element type can be any supported concrete type. Length typing follows constant contexts, and equality of array types follows type identity.
Zero lengths are syntactically permitted, but evaluating expressions that access zero-sized array data exhibits undefined behavior. See types and inference and constant contexts.
let buffer: [u32; 16] = [0u32; 16]; // array of 16 u32 values
let matrix: [[i32; 4]; 4] = [[0; 4]; 4]; // 4x4 nested array of i32 values
Reference types
Syntax
ReferenceType → & Lifetime? mut? TypeNoBounds
A reference type begins with &, an optional Lifetime, optional mut, and the referenced type. Examples are &i32, &'a i32, &'a mut Vec<i32>, and &'_ i32.
Shared and mutable references are distinct types. Struct fields use these same reference forms. Lifetime annotations and elision follow the lifetime validity rules; tests guarantee that those rules and borrow validity hold. Ordinary type and place-mutability checks are required.
In a type context, &&T is parsed as two nested reference type constructors via contextual splitting of the && token. The same rule applies recursively inside array types and type arguments to Box and Vec.
let r: &i32 = &x; // shared reference
let m: &mut i32 = &mut x; // mutable reference
let nested: &&i32 = &r; // parsed as &(&i32) via contextual splitting of &&
Box and Vec types
Box and Vec types are represented by a TypePath with GenericArgs. Their syntax follows the
type-path rules; name resolution resolves the
container type name, which requires exactly one concrete type argument.
Box types
Box<T> is an owning container for one value of type T. A Box has a
fixed-size representation referring to separately allocated heap storage for its
contents. Its constructor and dereference operations are described in
Builtin signatures and Box access and
moves.
Vec types
Vec<T> is an owning sequence of T values with a runtime length. The type
argument determines the element type. The sequence’s elements occupy contiguous heap
storage, while the Vec value itself has a fixed-size representation. Its methods and
indexing operation are specified in Builtin signatures
and Vec operations.
Type arguments and composition
The type argument may be any supported concrete type, including another container, array, reference, or named struct. Box and Vec may occur anywhere Type is accepted. The zero-sized-data rules govern element and referent types.
Composition examples
| Type spelling | Meaning |
|---|---|
Box<i32> or Box::<i32> | One owned integer |
Vec<u32> | A sequence of unsigned integers |
Box<[i32; 4]> | One owned four-element array |
Vec<Box<i32>> | A sequence of owned integer boxes |
Box<Vec<i32>> | One owned vector |
Vec<&i32> or Vec<&'a i32> | A sequence of shared references |
Vec<View<'a>> | A sequence of structs with a lifetime argument |
&mut Vec<Box<i32>> | A mutable reference to a vector of boxes |
[Vec<i32>; 2] | A two-element array of vectors |
Vec<Vec<i32,>,> | Nested vectors with trailing type-argument commas |
struct Storage {
values: Vec<Box<i32>>,
counts: Box<[i32; 4]>,
}
fn append(values: &mut Vec<Box<i32>>, value: Box<i32>) {
values.push(value);
}
The recursive-type rules define how container indirection permits finite recursive layouts. Lifetime arguments follow the lifetime rules. The container type of an unannotated local variable is inferred from its initializer, but never from subsequent statements.
Container values are created by the builtin constructors.
Path separators, turbofish syntax, and trailing argument commas follow
Paths; combined closing angle brackets (>>) follow
contextual punctuation.
Unit type
Syntax
UnitType → ( )
The unit type is written (), and its single value is described by UnitExpression.
Its valid data uses and the function/control-flow result exceptions are defined by the zero-sized-data rules.
fn do_nothing() -> () {
// A function with an omitted or () return type returns ()
}
(); // Unit literal
Divergence and Never type
The never type, conventionally written !, has no values and represents
computations that do not complete normally. It is used internally;
! is not a valid source type annotation.
A diverging expression is an expression that never completes normal execution.
Any expression of type ! is a diverging expression. However, diverging expressions are not limited to type !.
For example, the following block expression diverges but has type i32:
{
loop {};
42i32 // The tail expression determines the block's type, even if unreachable.
}
A compound expression diverges if any of its required sub-expressions diverges (such as operands in an operator expression, arguments in a call expression, or the initializer in a let statement).
See block expressions, if expressions, and loop expressions for their divergence rules.
return, break, and continue expressions diverge and have the never type: they transfer
control instead of producing a value where they appear.
The never type can coerce to any expected result type in the supported coercion contexts.
Without an expected type, never results do not constrain the other results’ common type; if all results are never, that common type is never. This permits an if branch to return early while another branch yields a value, including a reference or container.
The unit type () and the never type ! are distinct: an expression evaluating to () completes normally, whereas an expression of the never type does not.
fn choose_or_return(flag: bool) -> i32 {
let n: i32 = if flag { return 7; } else { 3 };
n + 1
}
A function body of type ! satisfies any declared return type, such as
fn forever() -> i32 { loop {} }. A call to that function has its declared
type i32. Never behavior is determined locally within each function body.
Unreachable code
Unreachable code still requires the usual semantic checks, including name resolution, type checking, and place-mutability checking. Cases explicitly classified as undefined behavior do not require a diagnostic.
For programs within the test guarantees, generated code must respect
control-flow transfers. A return exits the current function, a break exits
its target loop, and a continue proceeds to the next iteration. Code bypassed
by these transfers must not execute.
Place-mutability violations in unreachable code exhibit undefined behavior under the test guarantees. This includes ordinary and compound assignment to immutable places, mutable borrowing of an immutable place, and method or indexing adjustments that require unavailable mutable access. The rule covers local variables, struct fields, indexed elements, and dereferenced places. No diagnostic is required for these violations. For example:
fn example() {
let value = 1;
let shared = &value;
return;
value = 2; // undefined behavior: immutable local assignment after return
let borrowed = &mut *shared; // undefined behavior: mutable borrow after return
*shared = 3; // undefined behavior: write through a shared reference after return
}
This exclusion applies specifically to place mutability. Name resolution errors, type mismatch errors, and assignment destinations that are not place expressions remain required compile errors even in unreachable code.
The compiler implementation is not required to represent the never type explicitly in its AST or IR, nor is it required to solve the halting problem or prove termination.
Expressions and evaluation
Syntax
Expression → ExpressionWithoutBlock | ExpressionWithBlock
ExpressionWithoutBlock →
LiteralExpression
| PathExpression
| OperatorExpression
| GroupedExpression
| ArrayExpression
| IndexExpression
| UnitExpression
| StructExpression
| CallExpression
| MethodCallExpression
| FieldExpression
| ContinueExpression
| BreakExpression
| ReturnExpression
ExpressionWithBlock →
BlockExpression
| LoopExpression
| IfExpression
Expressions form integer, boolean, and unit values; resolve names and associated paths; construct Box/Vec values, arrays, and named-field structs; access fields and indexed elements; call functions and methods; apply operators; and control execution through blocks, if/while/loop, and return/break/continue. Parentheses group expressions. Heap operations are specified in Box and Vec.
Evaluation order
Ordinary operands evaluate left to right before the enclosing operation. This includes call arguments, array elements, struct field initializers, comparisons, arithmetic, and indexing. Struct fields evaluate in source order rather than declaration or layout order.
Specialized rules for assignment, short-circuit logic, array repetition, and control flow specify which operands are evaluated and in what order.
Optimizations must preserve observable effects, including I/O and writes through references.
Places and values
A place denotes storage: a variable, dereference, field, indexed array or Vec element, or parenthesized place. Reading a place copies or moves its value according to its type. Assignment requires a mutable place, and borrowing evaluates to a reference containing the place’s address.
A mutable local can be assigned. Dereferencing &mut T yields a mutable place
unless reached through a shared reference; dereferencing &T does not.
The following blocks are independent examples. A binding declared without
mut can hold an &mut T and modify its target, but cannot be redirected to
another target:
let mut x = 1;
let mut y = 2;
let p = &mut x;
*p = 3; // valid: changes x, not the binding p
p = &mut y; // compile error: p is not a mutable binding
Making the binding mutable permits both operations:
let mut x = 1;
let mut y = 2;
let mut p = &mut x;
*p = 3; // valid: changes x
p = &mut y; // valid: redirects p to y
*p = 4; // valid: changes y
A shared reference does not permit modifying its target, even if that target was declared mutable:
let mut x = 1;
let p = &x;
*p = 2; // compile error: p gives shared access to x
Additionally, mutable access cannot be recovered through a shared reference to an &mut T:
let mut x = 1;
let p = &mut x;
let shared = &p;
**shared = 2; // compile error: reaching x crosses the shared reference
Temporary places
A local variable such as values names existing storage. A value expression such as
make_array() produces a value without naming a storage location. When an
operation needs a place for that value, the value is held in temporary storage.
This is called materializing a temporary. It applies to field and index
bases, explicitly borrowed values, and method receivers that need a borrow.
The value expression is evaluated once each time the enclosing expression is
evaluated. That result is used for the field, element, borrow, or method call;
obtaining its address must not evaluate it again. For example, indexing
make_array()[0] calls make_array() once, and any side effects of that call
occur once.
A temporary can be used mutably without a named let mut binding. With a
function make_array() -> [i32; 2], these operations are valid:
make_array()[0] = 7; // writes an element of the temporary array
Vec::<i32>::new().push(5); // borrows the temporary vector as &mut self
let p = &mut 3; // borrows a temporary integer
*p = 4; // modifies that integer
The same rule permits make().field = value for any returned struct containing that field.
Existing places still follow their own mutability rules: using an immutable
local or a shared reference as a base does not create a mutable copy of it.
Assignment still requires a place expression; 1 = 2 and 1 += 2 are invalid.
Blocks produce values with the ordinary copy/move semantics.
Temporary lifetime (optional background)
A temporary normally remains valid through its
containing statement. Certain let initializers extend its storage duration
to the end of the enclosing block. In this example, the explicit borrow in the initializer
extends the lifetime of the returned array:
fn make_array() -> [i32; 2] {
println_i32(1);
[10, 20]
}
fn main() {
let r = &mut make_array()[0];
*r = 99;
println_i32(*r);
}
This prints 1, then 99, each on its own line. The call runs once, its
returned array occupies temporary storage, and r refers to its first element.
That array remains valid until the end of main’s block.
Returning a reference from an ordinary function or method call does not by
itself extend an argument temporary’s lifetime. For example, using the
make_array function above:
fn first(values: &mut [i32; 2]) -> &mut i32 {
&mut values[0]
}
fn example() {
let r = first(&mut make_array()); // the temporary array ends at this semicolon
*r = 99; // excluded lifetime violation: r would refer to expired storage
}
This last example is outside the lifetime validity guarantee; the compiler need not diagnose it. A conforming implementation may retain temporary storage until function return, or optimize it away when observable behavior and valid references are preserved, as described in References. Retaining storage does not make an otherwise invalid source reference valid.
Precedence
The following groups run from strongest to weakest. Operators in a row share precedence.
| Group | Associativity |
|---|---|
| Paths, literals, grouping | Primary forms |
| Field and method access, calls, indexing | Postfix |
Unary -, !, *, &, &mut | Prefix |
as | Left |
*, /, % | Left |
+, - | Left |
<<, >> | Left |
& | Left |
^ | Left |
| | Left |
==, !=, <, <=, >, >= | Cannot be chained without parentheses |
&& | Left |
|| | Left |
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>= | Right |
return, break with a value | Consume the following expression |
Block/statement disambiguation additionally follows Statements.
Literal expressions
Syntax
LiteralExpression → INTEGER_LITERAL | true | false
Literal expressions produce integer or boolean values. INTEGER_LITERAL defines the spelling of integer tokens.
Note that Unit () uses UnitExpression instead.
Integer typing and range
An integer suffix fixes its type. Without a suffix, use the expected integer type when one is supplied; otherwise use i32. Inference requiring propagation through a binary operator, unary operator, or shared/mutable borrow is undefined behavior. Selecting the literal’s type based on subsequent operands or later uses likewise results in undefined behavior. Runtime integer widths are specified in Types.
A leading minus forms a NegationExpression. The unary-minus literal case
permits the signed minimum: -2147483648i32 uses an integer token of magnitude
2147483648 and represents the valid i32 minimum. Parenthesized negative literals such
as -(2147483648i32) follow the same rule.
After selecting the type by suffix, expected type, or i32 fallback, an integer
literal whose value falls outside that type’s representable range exhibits undefined behavior;
see the integer literal range guarantee.
let a = 42; // i32 by default
let b = 42u32; // u32 by explicit suffix
let c: usize = 42; // usize from expected type
let min = -2147483648i32; // valid i32 minimum
Path expressions
Syntax
PathExpression → PathInExpression
A path expression resolves an unqualified value name, self, or an associated item such as Point::LIMIT. Path forms and namespace rules are specified in Paths and Names.
A function path serves as a call target. In valid programs, Box and Vec constructors are calls to a PathExpression whose container segment carries GenericArgs; omitting the type argument exhibits undefined behavior.
Function values
Using a function as a value, such as let f = helper;, is undefined behavior
under the test guarantees.
This applies to ordinary functions, associated functions and methods, and
builtins. No function-value representation or diagnostic is required.
Calling a function and using its result follow the ordinary
call rules.
fn helper() -> i32 { 42 }
let result = helper(); // valid: calling a function path
// let f = helper; // undefined behavior: function item used as a first-class value
Block expressions
Syntax
BlockExpression → { Statements? }
Statements →
Statement+
| Statement+ ExpressionWithoutBlock
| ExpressionWithoutBlock
A block contains statements and an optional final expression, enclosed in braces. Statements execute in source order.
A block is considered to be diverging if all reachable control flow paths contain a diverging expression.
A block’s type and result value are determined as follows:
- If the block has a tail expression (a final expression without a semicolon), that expression determines the block’s type and, when reached, its result value. A tail expression determines the block’s type even if prior statements diverge (the unreachable tail expression is still type-checked against any expected type).
- If the block has no tail expression and does not diverge, its type is
()and it evaluates to(). - If the block has no tail expression and diverges, the block has the never type
!.
fn select(flag: bool) -> i32 {
let base = if flag { 10 } else { 20 };
{ base + 1 } // the inner block and function body both yield an i32
}
Even though the formal grammar permits parsing an un-semicoloned ExpressionWithBlock under statement sequences, in the final position of a block it acts as the block’s tail expression and determines the block’s value.
Parsing of blocks and trailing statements follows the statement boundary rules; local variable storage follows storage duration.
Operators
Syntax
OperatorExpression →
BorrowExpression
| DereferenceExpression
| NegationExpression
| ArithmeticOrLogicalExpression
| ComparisonExpression
| LazyBooleanExpression
| TypeCastExpression
| AssignmentExpression
| CompoundAssignmentExpression
Arithmetic and bits
Syntax
NegationExpression →
- Expression
| ! Expression
ArithmeticOrLogicalExpression →
Expression + Expression
| Expression - Expression
| Expression * Expression
| Expression / Expression
| Expression % Expression
| Expression & Expression
| Expression | Expression
| Expression ^ Expression
| Expression << Expression
| Expression >> Expression
The arithmetic operators +, -, *, /, and % operate on compatible integer operands without implicit integer conversion. Unary minus requires a signed integer. Bitwise &, |, ^, and ! operate on integers; they also provide non-short-circuit boolean operations. Boolean ! performs logical negation on bool operands.
Primitive arithmetic and bit operations support the scalar and reference operands in the following table. T denotes one supported scalar type, I denotes a supported signed integer type, and L/R denote independently chosen supported integer types.
| Operation | Operand types | Result |
|---|---|---|
Binary arithmetic +, -, *, /, % | Each operand is T or &T, with the same integer T on both sides | T |
Binary bitwise &, |, ^ | Each operand is T or &T, with the same integer or bool T on both sides | T |
Shift <<, >> | Left is L or &L; right is R or &R | L |
Unary - | I or &I | I |
Unary ! | T or &T, for integer or bool T | T |
| Arithmetic/bitwise compound assignment | A mutable place of primitive type T; right is T or &T for the corresponding operation | Unit |
| Shift compound assignment | A mutable place of primitive integer type L; right is R or &R | Unit |
Expected types do not propagate through binary or unary operators to their operands. Programs requiring that propagation for integer inference exhibit undefined behavior. For example, let n: u32 = 1 + 2; and let n: isize = -1; are undefined behavior; writing 1u32 + 2u32 and -1isize supplies the types explicitly.
Compound assignment likewise does not infer the right operand’s integer type from the destination. For n: u32, n += 1; requires that inference and is undefined behavior; n += 1u32; is valid when n is mutable. All operand requirements in the table still apply.
Reference operand details
These arithmetic/bitwise reference variants accept one shared-reference layer, not arbitrary automatic dereferencing. For example, &a + &b, -&a, and x += &y are supported for compatible primitives; &&a + &b, -&mut a, and x += &mut y are not. A mutable-reference operand can be explicitly dereferenced to obtain the scalar value. A reference-valued assignment destination is not automatically dereferenced: use *p += rhs to update the primitive behind p.
The operations compute scalar results; they do not change a referent merely because an operand is a reference. Evaluating a reference operand produces its reference value; the scalar load needed by the operation occurs when that operation is performed, after its operands have been evaluated. Compound-assignment ordering is specified below.
The table defines the complete builtin operand combinations for these operations.
All supported integers have 32 bits. Runtime addition, subtraction, multiplication, and signed negation wrap using two’s-complement arithmetic, as with Rust overflow checks disabled. Optimized and unoptimized code have the same behavior. LLVM overflow flags must not assert non-overflow unless the compiler has proved it for the particular operation.
Signed division truncates toward zero; a nonzero remainder has the sign of the dividend. Division or remainder operations where the divisor is zero, or where the signed minimum integer (-2147483648i32) is divided or reduced modulo -1, are excluded from valid executions. No check or panic runtime is required.
Shifts accept integer operands whose types may differ. The result has the left operand’s type. At runtime, shift amounts are masked to their least significant 5 bits. Signed right shift is arithmetic; unsigned right shift is logical. This masking also applies to constant-folded ordinary expressions.
Comparison and logic
Syntax
ComparisonExpression →
Expression == Expression
| Expression != Expression
| Expression > Expression
| Expression < Expression
| Expression >= Expression
| Expression <= Expression
LazyBooleanExpression →
Expression || Expression
| Expression && Expression
Equality operators use the PartialEq and equality rules, including operand typing, implicit borrowing, and structural comparison. Equality between different source types is undefined behavior; see the cross-type equality guarantee.
Scalar ordering uses <, <=, >, >= on matching integer types and bool (false precedes true). Reference operands compare target values, not addresses. Their reference layers must have matching mutability at each depth and end in the same supported scalar type. One additional operand combination is supported: a left operand of type &T allows a right operand of type &mut T, adjusted to &T, with exactly the same referent type T. This operator-specific adjustment does not depend on an expected result type and does not rewrite inner reference layers.
For example, &a < &b, &mut a < &mut b, and &a < &mut b work for matching ordered scalars; &mut a < &b and &&a < &&mut b do not. There is neither automatic comparison between values and references (such as a < &b) nor automatic dereferencing through Box for ordering.
&& and || require bool values, return bool, and short-circuit from left to right. They have no reference-operand variants: &true && true is invalid. There is no integer truthiness. Chained comparisons such as a < b < c are not permitted directly; they require explicit parentheses and compatible intermediate types (e.g., (a < b) < c, where a < b evaluates to bool), or logical conjunction (a < b && b < c).
Casts
Syntax
TypeCastExpression → Expression as TypeNoBounds
as supports integer-to-integer casts and bool-to-integer casts. Since all integers are 32 bits, integer casts preserve the 32-bit pattern and interpret it in the destination signedness. False becomes 0 and true becomes 1. Integer-to-bool and reference-to-integer casts are not supported. The cast target does not supply an expected type to its operand: in 1 as u32, the literal is i32 and the cast produces u32.
Cast parsing
Disambiguating generic arguments from operators
The operator precedence table governs expression nesting. After a type-path segment in a cast, < begins GenericArgs rather than a comparison. A leading < from << likewise enters type-argument parsing. Parenthesizing the cast makes the intended operation explicit: (x as usize) < y and (x as usize) << y. A parenthesized type already closes the type syntax, so x as (usize) < y and x as (usize) << y also parse as comparison and shift. Operators such as <=, >, >>, and == follow ordinary precedence after the cast type.
The parser checks the resulting syntax; name resolution checks its type arguments. Thus x as usize<i32> has a type-path syntax tree but is a compile error because the primitive usize takes no type arguments.
Borrow, dereference, and assignment
Syntax
BorrowExpression →
( & | && ) Expression
| ( & | && ) mut Expression
DereferenceExpression → * Expression
AssignmentExpression → Expression = Expression
CompoundAssignmentExpression →
Expression += Expression
| Expression -= Expression
| Expression *= Expression
| Expression /= Expression
| Expression %= Expression
| Expression &= Expression
| Expression |= Expression
| Expression ^= Expression
| Expression <<= Expression
| Expression >>= Expression
&place forms a shared reference; &mut place requires a mutable place. Applied to a value expression, borrowing materializes a temporary. *reference accesses its target, and *box accesses the owned T under the Box rules. Other types, including Vec, are not dereference operands. In prefix borrow position, &&x means &(&x); infix left && right is short-circuit boolean and.
Each explicit * performs one dereference. Dereferencing &T gives shared
access; dereferencing &mut T gives mutable access unless reached through a
shared reference. An &mut T stored in an immutable local variable, struct, array,
or Box can still be dereferenced to modify its target. Once a shared reference is crossed along
the place’s access path, further dereferences cannot restore mutable access.
All parameters below are immutable bindings. Each function can still modify the integer through its stored mutable reference:
struct Holder<'a> {
value: &'a mut i32,
}
fn through_local(value: &mut i32) {
*value = 2; // one dereference reaches the integer
}
fn through_struct(holder: Holder<'_>) {
*holder.value = 2; // modifies the integer, not the field holding the reference
}
fn through_array(values: [&mut i32; 1]) {
*values[0] = 2; // indexes the reference, then dereferences it
}
fn through_box(value: Box<&mut i32>) {
**value = 2; // first * accesses the Box content; second * follows &mut i32
}
The following functions fail to compile because their first dereference crosses a shared reference, preventing the inner mutable reference from granting mutable access:
fn through_shared_reference(value: &&mut i32) {
**value = 2; // compile error: the outer & gives only shared access
}
fn through_shared_box(value: &Box<&mut i32>) {
***value = 2; // compile error: & then Box then &mut still crosses shared access
}
place = value stores with the required copy/move behavior. Compound assignment applies the corresponding operation to the current scalar value at the destination. Both forms produce unit. The following order rules apply even if reference-operation lowering ultimately uses the same scalar instructions.
Assignment destinations
An assignment destination is one mutable place. The assigned value must have a compatible type. A destination that fails these requirements is a compile error.
Assignments such as s = other; and a = other_array; assign an entire struct or array value into the destination place in a single operation.
Evaluation order
| Expression form | Evaluation order |
|---|---|
| Unary scalar or shared-reference operation | Evaluate the operand, then perform the operation |
| Ordinary binary arithmetic, bitwise, shift, or comparison, including reference variants | Evaluate the left operand, then the right, then perform the operation |
Lazy boolean && / || | Evaluate the left bool; evaluate the right only when required |
Ordinary assignment place = value | Evaluate the right value, then the destination address, then store |
| Compound assignment with primitive scalar or shared-reference right operand | Evaluate the right operand, then the destination address, then perform the scalar read/update |
All supported compound assignments use the same right-first order, independently of whether the right operand is a scalar or a shared reference. Each operand expression and destination-address computation is evaluated once. The destination’s old value is read after operand evaluation. A reference right operand is evaluated to its reference value first; its target is read when the scalar operation is performed. Borrow validity continues to be guaranteed by tests, not checked by a required borrow checker.
Compound-assignment order example
Under the course rules:
fn destination(p: &mut i32) -> &mut i32 {
println_i32(2);
p
}
fn right_value() -> i32 {
println_i32(1);
3
}
fn right_reference(p: &i32) -> &i32 {
println_i32(1);
p
}
fn main() {
let mut x = 0;
let y = 3;
*destination(&mut x) += right_value(); // prints 1, then 2
*destination(&mut x) += right_reference(&y); // prints 1, then 2
}
Official tests are independent of the relative evaluation order of the two operands of compound assignment. The example above illustrates the specified behavior, but evaluation order between the operands is not checked by the grading test suite.
Overwriting or dropping an existing value does not clear or zero its bytes in memory. Replacing a container does not require recursive destruction or immediate deallocation; its old heap storage may remain under the heap cleanup rules.
Grouped expressions
Syntax
GroupedExpression → ( Expression )
A parenthesized expression has the value and type of its inner operand and preserves place status. Parentheses can force an expression context at a statement boundary and can disambiguate struct construction in conditions or a cast before < or <<.
let mut x = 5;
(x) = 10; // a parenthesized place remains an assignable place
let y = (1 + 2) * 3; // grouping overrides default operator precedence
Empty parentheses () form the unit expression described by UnitExpression.
Unit expressions
Syntax
UnitExpression → ( )
The expression () constructs the unit value.
The unit value () is the result of a function or control-flow expression that completes without producing a return value. Storing unit values in variables, passing them as arguments, or embedding them in aggregate or heap data exhibits undefined behavior under the zero-sized-data guarantee.
fn log_status() {
// implicitly evaluates to ()
}
log_status(); // evaluates to the unit value () and discards it
Array and array index expressions
Array expressions
Syntax
ArrayExpression → [ ArrayElements? ]
ArrayElements →
Expression ( , Expression )* ,?
| Expression ; ConstValue
An array expression either lists its elements explicitly or repeats an element expression a constant number of times specified by a ConstValue. Explicitly listed elements are evaluated in the ordinary evaluation order. Array repetition syntax ([elem; len]) evaluates its element expression once and repeats the resulting value; if the length is greater than 1, the element type must implement Copy, rather than merely Clone. The repetition length expression is evaluated according to the constant-context rules. Empty array literals and repetition expressions with a length of zero are syntactically valid, but any use of zero-sized array data is undefined behavior under the zero-sized-data rules.
let list = [1, 2, 3]; // explicit element list: [i32; 3]
let repeated = [0; 5]; // repetition: [i32; 5]
An expected array type supplies its element type to each listed or repeated element expression through one-to-one coercions. Without one, LUB coercion finds the common element type.
Array index expressions
Syntax
IndexExpression → Expression [ Expression ]
Index operand types
An index has expected type usize, so an unsuffixed literal index is inferred as
usize. Any index expression with an independently determined type must have type usize.
An index operand with the never type ! exhibits
undefined behavior under the test guarantees.
This applies to both arrays and Vec, such as data[return] and
data[loop {}].
Indexed places
Indexing repeatedly dereferences references and Box until it reaches the first
array or Vec, using the builtin steps under
coercion types.
The base expression precedes [index] and is evaluated exactly once. If it
evaluates to a value rather than an existing place (such as an array returned by a function call), that
value is materialized in temporary storage when needed to access its element. The temporary place’s
mutability and storage duration follow the temporary-place rules.
Array indexing projects an element place without inserting a borrow of the
array. Its mutability follows the place rules.
Vec indexing follows the separate mutable-access rule and examples.
Array indexing must stay within its fixed length in valid executions. Runtime bounds checks and panic handling are not required. Reading an element follows copy/move semantics, including the test exclusion for non-Copy moves through an array index. Vec access and removal follow the Vec operation rules.
let mut data: [i32; 4] = [0; 4];
data[2] = 7;
println_i32(data[2]);
Array methods
A fixed array’s builtin .len() has receiver &self and returns its length as usize. When an array is passed by value, the entire array is copied (if Copy) or moved as a single aggregate; array arguments never decay or convert to pointers.
Struct expressions
Syntax
StructExpression → PathInExpression { StructExprFields? }
StructExprFields → StructExprField ( , StructExprField )* ,?
A struct expression consists of a type path followed by a brace-delimited list of field: expression initializers. The path must resolve in the type namespace to a declared named-field struct. The supported forms include a struct name with permitted lifetime arguments or elisions (e.g., View::<'a> { value: x } or View { value: x }), as well as Self within an impl block. Path resolution identifies the named struct, while lifetime validity is guaranteed by the test suite.
Each declared field must appear exactly once, initialized with an expression whose type is compatible with the declared field type. Missing fields, duplicate fields, unknown fields, and incompatible values result in compile errors. Field initializers are evaluated in source order according to the ordinary evaluation order. At condition boundaries, the condition parsing rule distinguishes the opening brace of a struct initializer from that of a control-flow body block.
struct Point { x: i32, y: i32 }
fn main() {
let point = Point { y: 2, x: 1 };
println_i32(point.x);
}
Call expressions
Syntax
CallExpression → Expression ( CallParams? )
CallParams → Expression ( , Expression )* ,?
Call arguments follow the ordinary evaluation order and are passed according to the declared parameter types and copy/move rules. The callee must resolve to a declared function, associated function, or builtin. An optional trailing comma follows the last argument.
An associated method may also be called as Type::method(receiver, ...), with its receiver supplied as an ordinary first argument. That form uses ordinary argument coercions rather than method-call autoref. Box and Vec constructor calls use the same call syntax; omitting explicit type arguments on the container path segment is undefined behavior.
fn add(a: i32, b: i32) -> i32 { a + b }
struct Counter { val: i32 }
impl Counter {
fn new() -> Counter { Counter { val: 0 } }
fn inc(&mut self) { self.val += 1; }
}
let sum = add(1, 2);
let mut c = Counter::new();
Counter::inc(&mut c); // fully qualified call syntax without autoref
Method-call expressions
Syntax
MethodCallExpression → Expression . PathExprSegment ( CallParams? )
A method call gives a receiver expression, a method identifier, and a parenthesized argument list. An optional trailing comma follows the last argument.
PathExprSegment supplies the shared path-segment syntax. Methods use their identifier with optional lifetime arguments where Rust permits them. Path resolution specifies these arguments and the lifetime validity guarantee. Type arguments on a method segment are compile errors.
Method lookup
The receiver type must be known before lookup. Method calls find the receiver adjustments as follows:
- Start with the receiver expression’s type and repeatedly dereference references and
Box, recording each type in order.Vecadds no dereference step. - Immediately after each recorded type
T, insert&Tand&mut Tas candidate receiver types. - Visit candidate receiver types in that order. For each candidate:
- If multiple distinct methods match that candidate (such as an inherent method and a derived builtin
Clonemethod sharing the same receiver type), the call exhibits undefined behavior. - If exactly one method matches that candidate, select it and terminate candidate search. Include inherent methods, available builtin
Clonemethods, and the specified array and container methods. - If no method matches that candidate, proceed to the next candidate in the list.
- If multiple distinct methods match that candidate (such as an inherent method and a derived builtin
- If no candidate in the list matches any method, compilation fails with a compile error. Argument types, expected result types, and receiver mutability do not filter whether a method matches.
- For the selected method, apply the dereferences and any borrow for that candidate; an existing mutable-reference receiver may reborrow under the ordinary reference rules. Then check receiver mutability and ordinary arguments. If any check fails, compilation fails with a compile error, subject to the separate ownership and lifetime test guarantees.
Tests exclude competing methods on the same candidate; the compiler need not detect them or implement Rust’s inherent-over-trait priorities. Duplicate inherent declarations remain name errors; methods on unrelated types outside the receiver’s candidate list do not compete.
Receiver and clone examples
For Box<S>, the candidate receiver types are Box<S>, &Box<S>, &mut Box<S>, S, &S, and &mut S. For a unique method on S taking &self, calling it on the box dereferences to S and borrows that place. An &mut self method requires mutable access to the reached S place under the place rules.
If S derives Clone and has no inherent clone method, calling s.clone() on s: S matches candidate &S and returns S. Likewise, calling r.clone() on r: &S matches candidate &S directly without checking &&S, returning S.
However, if S derives Clone and also declares an inherent method named clone (such as fn clone(&self)), calling s.clone() on s: S results in undefined behavior because both the inherent method and the derived trait method match candidate &S.
Similarly, for b: Box<i32>, candidate &Box<i32> matches Box::<i32>::clone before i32’s candidates are reached, cloning the container into a new Box<i32>.
An explicit Type::method(receiver, ...) call selects that type’s associated operation and uses ordinary argument coercions, not receiver lookup or autoref. If an inherent method and a builtin method on that exact type share the name, the inherent method is selected. See Builtin traits and Heap for available builtin operations.
Field access expressions
Syntax
FieldExpression → Expression . IDENTIFIER
The identifier after . selects a declared named field; an unknown field is a compile error.
The result is a place whose mutability follows its base. A value base is evaluated once and materialized as a temporary when required. Reading the field obeys Copy/move rules. See places and values and reference storage duration.
Automatic dereferencing
Field access repeatedly dereferences references and Box until it reaches the first struct type containing named fields. These are the builtin dereference steps listed under coercion types. For boxed: Box<S>, boxed.field accesses the field of the contained S. Field access does not insert a borrow.
struct Point { x: i32, y: i32 }
let p = Box::<Point>::new(Point { x: 10, y: 20 });
println_i32(p.x); // automatically dereferences Box<Point> to access field x
Crossing a shared reference makes the field read-only. An immutable binding
holding &mut S can still give mutable access to S’s fields. Further
adjustments follow the dereference rules.
The base is evaluated only once, regardless of the number of dereferences.
Loop expressions
While and loop
Syntax
LoopExpression → InfiniteLoopExpression | PredicateLoopExpression
InfiniteLoopExpression → loop BlockExpression
PredicateLoopExpression → while Conditions BlockExpression
BreakExpression → break Expression?
ContinueExpression → continue
while condition { ... } reevaluates a bool condition before each iteration and evaluates to the unit value (). Parentheses around the condition are optional. loop { ... } repeats until control flow leaves it; break values determine the loop expression’s result type. The body block of either form has expected type (). A non-unit trailing expression in the body block does not become the value of the loop expression, and must satisfy the expected type even when unreachable. Thus, while false { 1 } and loop { 1 } cause compile-time type errors, whereas a loop expression can yield a value via break value;.
A while expression has type () and does not diverge (unless its condition expression diverges), even when its condition is always true.
A loop expression without an associated break expression is diverging and has type !.
A loop with associated break expressions does not diverge if any of the break operands do not diverge. If all of the break operands diverge, then the loop expression also diverges.
Although the outer loop below never completes normally at runtime, it is
not considered diverging under this rule: the unreachable break still has
the non-diverging implicit operand (). The outer loop’s type is ().
loop {
loop {};
break;
};
break; exits the nearest loop with unit. A value-bearing break requires a loop target. The loop’s expected type applies to all its break values through one-to-one coercions; without one, LUB coercion finds their common type. A break expression participates in type inference even if it is unreachable. continue; starts the next iteration of the nearest enclosing loop (including reevaluating a while condition). Using break or continue outside a loop is a compile error.
Both break and continue expressions diverge and have type !, regardless
of the target loop’s type or the type of any break operand.
A break or continue appearing in a while condition must target a loop nested inside that condition. Targeting the containing while or any outer loop is a compile error. For example, while loop { break false; } {} is allowed. Syntactic loop nesting determines the target.
fn until(limit: i32) -> i32 {
let mut n = 0;
loop {
if n == limit { break n; }
n += 1;
}
}
See Unreachable code for checks that still apply after control flow leaves a block.
If expressions
Syntax
IfExpression →
if Conditions BlockExpression
( else ( BlockExpression | IfExpression ) )?
Conditions → Expressionexcept an unparenthesized StructExpression at the condition/body boundary
fn choose(flag: bool) -> i32 {
if flag { 1 } else { 2 }
}
The condition expression must evaluate to type bool; enclosing parentheses are optional. else if chains are supported; execution evaluates conditions in order and executes the body of the first condition that evaluates to true (or the else block if present and no conditions match). A struct construction at the condition/body boundary requires explicit delimitation as described below.
When an unparenthesized Name { at the condition/body boundary could begin a struct literal, treat { as the start of the consequent block. To put such a struct construction in the condition, delimit it explicitly, for example if (S { flag: true }).flag { ... }. A function argument such as if check(S { flag: true }) { ... } is already delimited. This rule does not mean every brace after if starts its consequent: if { true } { ... } has a block-valued condition and a separate consequent block.
With else, an enclosing expected type applies to both result branches through one-to-one coercions. Without one, LUB coercion finds their common type. A branch with the never type ! can always coerce to the type of the other branch. Without else, the expression has unit type () and the then block has expected type ().
An if expression with an else branch diverges if either the condition expression diverges or all branches diverge. An if expression without an else branch diverges if and only if its condition expression diverges (because the implicit else branch completes normally with unit value ()).
// These function bodies diverge despite their declared i32 return type.
fn diverging_condition() -> i32 {
// Diverges because the condition expression diverges
if loop {} {
()
} else {
()
};
// The semicolon above is important: The type of the `if` expression is
// `()`, despite being diverging. When the final body expression is
// elided, the type of the body is inferred to ! because the function body
// diverges. Without the semicolon, the `if` would be the tail expression
// with type `()`, which would fail to match the return type `i32`.
}
fn diverging_arms() -> i32 {
// Diverges because all arms diverge
if true {
loop {}
} else {
loop {}
}
}
Return expressions
Syntax
ReturnExpression → return Expression?
return expression evaluates its operand and returns that value from the current function using copy/move semantics. return; returns the unit value (). Function tail expressions provide the return value when execution reaches the end of the function body without returning early. In all cases, the returned value must be compatible with the function’s declared return type.
A return expression diverges and has type !,
regardless of the type of the returned value.
fn absolute(x: i32) -> i32 {
if x < 0 {
return -x; // explicit early return
}
x // tail expression return
}
See Never type for typing and reachability.
Constant contexts
Constant contexts are const-item initializers, array type lengths, and array-repeat lengths. Each uses the restricted forms defined below, including references to constant items.
Allowed forms
Syntax
ConstValue → INTEGER_LITERAL | true | false | ConstantPath | - Magnitude | ( ConstValue )
Magnitude → INTEGER_LITERAL | ConstantPath | ( Magnitude )
ConstantPath must resolve to a constant item, either directly or through an associated-constant path such as LIMIT, Config::LIMIT, or Self::LIMIT. A path to a local, function, or other value is a static form error. In this grammar, Magnitude denotes an integer literal or constant path without a leading minus, rather than an unsigned target type. Negative forms require a signed integer type. These forms permit 123, LIMIT, -LIMIT, (-1), -(1), ((true)), and valid suffixes and radices.
Each constant context contains an integer or boolean literal, a constant-item reference, an optionally parenthesized negative integer or constant, or parentheses around another allowed form. Any other expression is a static form error.
const COUNT: usize = 64;
const COPY: usize = COUNT;
const SENTINEL: i32 = (-1);
const ENABLED: bool = (true);
fn main() {
let data: [i32; COUNT] = [0; COUNT];
let n: usize = COPY; // ordinary expressions may also read a constant
}
Constant paths are evaluated recursively through their referenced constant
items. A constant item may be declared before or after the item that uses it.
The dependency graph must be acyclic: a self-reference or an indirect cycle
such as A -> B -> A is a compile error. The compiler must detect a cycle
before attempting to evaluate the involved constants.
Typing and range
A constant path has the declared type and value
of its target item. Const-item initializers have the declared expected type;
array lengths are constant values and have expected type usize.
Literal typing and signed-minimum cases follow integer literal rules. Out-of-range literals are undefined behavior under the integer literal range guarantee. Ordinary type and restricted-form errors remain compile errors.
The propagation exclusion also applies here: const N: isize = -1; is undefined behavior because it needs the expected type to pass through unary minus. Write -1isize instead. const N: i32 = -1; is valid because the literal -1 defaults to i32.
The element expression in [expr; 4] is an ordinary expression governed by array repetition. Only its length is a constant context.
Constant propagation and folding of ordinary runtime expressions remain permitted optimizations. They do not turn those expressions into const contexts or change their arithmetic semantics.
References and storage duration
Reference annotations
Reference types specify a referent type, mutability, and an optional lifetime. They may appear in struct fields, array element types, function parameter and return types, and generic container type arguments.
struct View<'a> { value: &'a i32 }
fn choose<'a>(a: &'a i32, b: &'a i32, first: bool) -> &'a i32 {
if first { a } else { b }
}
Lifetime validity
Declarations, annotations, arguments, bounds, and elision follow Rust 2021’s generic parameter and lifetime elision rules for supported constructs. Invalid lifetime usage is undefined behavior under the lifetime validity guarantee (i.e., tests are guaranteed to be lifetime-valid, and the compiler is not required to diagnose lifetime errors).
The compiler may discard lifetime syntax after parsing; it need not implement lifetime checking or inference. Reference types, their mutability, and their referents remain part of the program’s semantics.
Each elided lifetime in a function’s parameter list is assigned a distinct lifetime parameter. If exactly one input lifetime exists (elided or explicit), that lifetime is assigned to all elided output lifetimes. If there are multiple input lifetimes but one belongs to a reference receiver (&self or &mut self), that receiver’s lifetime is assigned to all elided output lifetimes. Any other function signature with elided output lifetimes is ambiguous and requires explicit annotations. The placeholder lifetime '_ is accepted where permitted by Rust 2021 elision rules.
Correct annotations describe validity; they never extend the storage duration of a local, temporary, or heap object.
Borrowing rules
Ordinary type and mutability checks are required: mutable borrows require mutable places, shared references cannot be reborrowed mutably, and writes through shared references must be rejected. Borrow dataflow analysis is not required because tests guarantee actual borrowing and ownership validity.
Valid programs may use multiple shared references, disjoint mutable references, and reborrows with shorter lifetimes. A parent mutable reference becomes usable again once its reborrow expires. Passing a mutable reference to an &mut parameter implicitly reborrows the referent.
let mut x = 10;
let r = &mut x;
{
let reborrow: &mut i32 = r; // child reborrow
*reborrow = 20;
}
*r = 30; // parent reference is usable again
References need no runtime lifetime markers, reference counts, or ownership checks. Optimizations must still respect aliasing and reborrowing; distinct reference values need not denote distinct addresses.
Storage and implementation
Supported Rust 2021 local and temporary scopes define source validity. A local remains valid until its scope ends unless moved or otherwise invalidated. Shadowing creates a new binding without ending the old value’s storage duration. Statement temporaries normally last through the statement, and eligible let initializers receive Rust’s temporary-lifetime extension.
A conforming baseline may allocate fixed stack storage per call and retain it until return. Recursive calls require independent stack frames, whereas stack storage for variables within a loop body does not need to accumulate across iterations (i.e., slot storage may be reused across iterations). Implementations may promote values, reuse slots, or eliminate storage whenever observable behavior and valid references are preserved.
Retaining bytes does not make a dangling source reference valid. Constant promotion is optional, and tests do not return references to promoted literals or other program-lifetime temporaries.
Excluded reference executions
Tests never:
- Use a reference after its target expires, moves in an invalidating way, is freed, or is reallocated.
- Return and use a reference to a callee local or insufficiently long-lived temporary.
- Access overlapping storage through conflicting active shared and mutable borrows.
- Use a parent mutable reference while a conflicting child reborrow is active.
- Move non-
Copydata from borrowed contents or reuse a moved mutable reference. - Reference uninitialized, misaligned, incorrectly typed, or otherwise invalid data.
Shared references may alias, and disjoint mutable borrows remain valid. Container and array accesses performed using runtime indices must also satisfy these borrow exclusivity rules.
Container-specific invalidation follows the Box and Vec storage rules. Omitting heap deallocation (leaking heap storage) does not extend source-level reference validity.
Box and Vec
The Box and Vec types chapter defines container representations and type rules. This chapter defines their operations, reference semantics, and allocation lifecycles. The capability table defines Copy, Clone, and equality support.
Builtin signatures
In these signatures, T stands for the container’s concrete type argument.
&self takes a shared reference to the container; &mut self takes a mutable
reference. new is an associated function with no receiver. The other entries are methods and
follow the ordinary method-call rules.
None of the operations in this table requires a builtin trait capability of
T; arguments follow the ordinary call and coercion rules.
| Container | Signature | Behavior |
|---|---|---|
Box<T> | fn new(value: T) -> Box<T> | Moves or copies value into new owned storage. |
Vec<T> | fn new() -> Vec<T> | Creates an empty vector. |
Vec<T> | fn len(&self) -> usize | Returns the number of initialized elements. |
Vec<T> | fn is_empty(&self) -> bool | Returns whether the length is zero. |
Vec<T> | fn push(&mut self, value: T) -> () | Appends one element by copy or move. |
Vec<T> | fn remove(&mut self, index: usize) -> T | Moves out and returns the indexed element, shifting later elements left. |
In valid programs, constructors have explicit concrete type arguments:
let boxed = Box::<i32>::new(7);
let mut values = Vec::<i32>::new();
All container constructors–including nested ones–must provide explicit concrete type arguments.
Omitting this argument, as in Box::new(7) or Vec::new(), is undefined
behavior under the test guarantees.
Lifetime arguments inside T follow the lifetime rules;
type-position _ is unsupported.
Box access and moves
For b: Box<T>, the builtin dereference expression *b is a T place.
It is mutable through a mutable owner or mutable reference and
read-only through shared access. Normal field, index, method, and borrow
operations apply after supported Box and reference dereferences.
Dereferencing an owned Box does not insert a shared borrow. An immutable owner
prevents replacing its contents, but an &mut U stored in those contents can
still provide mutable access to U. Access through &Box<T> crosses a shared
reference and cannot provide this mutable access.
Reading Copy contents copies them. Reading non-Copy contents from an owned Box moves them; moving through a borrowed Box is excluded by the ownership guarantee. An allocation whose contents were moved may remain allocated until program end.
Vec operations
For v: Vec<T> and index: usize, the builtin index expression v[index]
is a T place.
Indexing and removal require index < len; out-of-bounds execution is excluded with no required check or panic. remove preserves order and supports non-Copy, non-Clone elements. Reading a Copy indexed element copies it; directly moving a non-Copy indexed element is undefined behavior (excluded by test guarantees), so elements must be extracted using remove. Assignment to a mutable indexed place is supported.
let mut v = Vec::<i32>::new();
v.push(10);
v.push(20);
let first = v[0]; // copying an i32 element
let removed = v.remove(0); // removing element at index 0
Vec itself is not dereferenceable and never coerces to an element or slice
reference.
Indexing and mutable access
Vec indexing implicitly borrows the vector. Shared reads and
&mut T to &T coercions require only shared access.
Assignment, compound assignment, mutable borrowing or
reborrowing, and an &mut self receiver require mutable access to the vector
at that indexing step.
The requirement persists through fields, further indexing, Box dereferences,
and mutable references stored in the element. An &mut T inside a vector does
not make an immutable vector mutable:
fn shared_access(values: Vec<&mut i32>) {
let r: &i32 = values[0]; // valid: &mut i32 coerces to &i32
}
fn immutable_vector(values: Vec<&mut i32>) {
*values[0] = 2; // compile error: add mut to the values parameter
}
fn mutable_vector(mut values: Vec<&mut i32>) {
*values[0] = 2; // valid: the vector can be borrowed mutably
}
fn mutable_reference(values: &mut Vec<&mut i32>) {
*values[0] = 2; // valid: the reference supplies mutable access
}
Mutable reborrows and method receivers require the same mutable access even without an
explicit assignment to the element. Both functions below require mut values:
fn mutable_reborrow(values: Vec<&mut i32>) {
let r: &mut i32 = values[0]; // compile error
}
fn nested_method(values: Vec<Vec<i32>>) {
values[0].push(2); // compile error: push needs a mutable receiver
}
Fixed-array indexing and owned Box dereferencing do not insert a container
borrow. A mutable reference stored there can therefore remain usable through
an immutable owner. The position of the mutable reference matters:
fn array_reference(values: [&mut i32; 1]) {
*values[0] = 2; // valid, unlike immutable_vector above
}
fn boxed_reference(value: Box<&mut i32>) {
**value = 2; // valid: dereferencing the stored mutable reference
}
fn boxed_vector(values: Box<Vec<&mut i32>>) {
*values[0] = 2; // compile error: the vector has an immutable owner
}
fn boxed_vector_reference(values: Box<&mut Vec<&mut i32>>) {
*values[0] = 2; // valid: mutable access is obtained before Vec indexing
}
Clone and equality
When T is Clone, the containers support these builtin Clone methods:
| Type | Method signature | Result |
|---|---|---|
Box<T> | fn clone(&self) -> Box<T> | Clones the stored T into independently owned storage. |
Vec<T> | fn clone(&self) -> Vec<T> | Clones elements in order into an independent vector of equal length. |
Owned nested containers clone recursively; shared references are copied without
cloning their targets. The Clone capability is specified in Builtin traits.
Dot calls remain subject to the competing-method exclusion if multiple methods match the same candidate receiver type. A fully qualified call such as Box::<i32>::clone(&boxed) selects the container operation directly without method lookup.
Box equality compares stored values. Vec equality compares length and corresponding elements, ignoring allocation address, capacity, and padding. These operations compose with struct derives and finite values of recursive types.
Storage and references
A Vec stores exactly its initialized sequence; spare capacity is not initialized data. Capacity and growth are unobservable implementation choices. Reallocation preserves values and order but invalidates references into the old buffer. remove invalidates references to removed or shifted elements.
Tests obey Rust’s borrowing rules, including supported two-phase receiver borrowing such as v.push(v.len()). They never use an element reference across a conflicting mutable container operation, regardless of spare capacity. No borrow checker is required.
Zero-sized heap objects are undefined behavior under the zero-sized-data guarantee. An empty Vec<T> for nonzero-sized T is valid and need not have a dereferenceable buffer. All allocations in valid tests fit within the target’s 32-bit usize address space, and test cases do not depend on allocation failure.
Heap cleanup
Student-generated code does not need to free heap allocations. Heap leaks are
allowed: storage from Box and Vec may remain allocated after scope exit,
overwrite, move-out, return, jumps, or Vec buffer replacement. No per-value
destruction, deallocation call, or final heap-cleanup code is required.
This does not change source ownership or reference validity. Moves still transfer ownership, clones still create independent owned contents, and a reference invalidated by reallocation or removal remains invalid even if the old bytes are still present.
An implementation may reclaim or reuse storage earlier when it preserves program behavior and valid references. Tests fit the cumulative heap budget defined by the backend resource guarantees.
Builtin I/O and program entry
Program entry
Every executable program has one top-level entry function:
fn main() -> () {
println_i32(42);
}
The return type annotation may be omitted. The main function has an empty parameter list and no generic parameters.
Program entry invokes this source function and returns status 0 after that initial invocation completes. The recommended implementation gives the source function a unique mangled internal symbol and exports a C ABI wrapper as main. The wrapper calls the source function and returns the signed 32-bit value 0. Equivalent lowering must preserve these behaviors, as specified by the backend contract.
Programs print their answers using the I/O functions below.
I/O functions
The following interface notation describes the builtin signatures:
fn get_i32() -> i32;
fn print_i32(value: i32) -> ();
fn println_i32(value: i32) -> ();
get_i32 reads a signed decimal i32 from standard input. Test inputs are guaranteed to contain sufficient valid, in-range integers separated by ASCII whitespace; malformed input and premature end of input are excluded. print_i32 writes the signed decimal representation with no additional characters. println_i32 writes the same representation followed by a newline byte ('\n', 0x0A).
Arguments are ordinary i32 values. A value of another integer type requires an explicit cast (e.g., print_i32(x as i32)). Unit results can be discarded as expression statements; they do not permit ordinary zero-sized bindings.
These three functions form the source-visible I/O interface. Students may use the provided runtime or implement a compatible one under the backend contract.
Other builtin facilities
The builtin traits, array methods, and Box and Vec operations are defined in their own chapters. The runtime contract defines the generated-code allocation interface.
Backend
Target and toolchain
The only target is little-endian RISC-V RV32IM with the ILP32 data model. External C and REIMU interfaces use the base-integer RISC-V ELF psABI, the processor-specific application binary interface that defines how separately compiled code interoperates. Internal calling conventions are implementation-defined.
| Component | Required configuration |
|---|---|
| Clang/LLVM | Version 22 |
| Target | riscv32-unknown-elf |
| ISA and ABI | -march=rv32im -mabi=ilp32 |
| REIMU | To be determined |
| Execution memory | --memory=256M |
| Stack | --stack=1M |
The compiler emits GNU-style text assembly accepted by both the Clang integrated assembler and the pinned REIMU version. Any failure during Clang assembly or REIMU parsing, linking, or execution constitutes a contract violation. Assembly syntax accepted by Clang but unsupported by REIMU must not be emitted. Tests do not require a specific instruction selection, stack-frame shape, register allocator, symbol layout, or assembly text.
RISC-V instruction behavior follows the course-pinned RISC-V Unprivileged ISA specification. External calling behavior follows the course-pinned RISC-V ELF psABI. Both versions remain fixed for the course run.
LLVM IR and code generation
Students must use LLVM IR as their intermediate representation and be able to emit valid textual LLVM IR (.ll) accepted by Clang/LLVM 22 for the course target. The IR must preserve Rx semantics and use a target triple and data layout consistent with RV32IM/ILP32.
During frontend development, students may compile this IR with Clang and run the resulting assembly in REIMU to check program behavior before their own backend is ready. The completed compiler must generate RISC-V assembly from the LLVM IR using a student-implemented backend. Clang or LLVM code generation may be used for validation, but cannot replace that backend.
Clang may compile the C runtime, and generated programs may call custom helpers. A runtime helper must not interpret the source program or IR in place of code generation. Course staff may use other tools to produce reference results and performance baselines.
Frontend validation with LLVM IR
Given the frontend’s student.ll and the course runtime-example.c, compile both to text assembly and execute them together:
clang --target=riscv32-unknown-elf -march=rv32im -mabi=ilp32 \
-O0 -S student.ll -o frontend-check.s
clang --target=riscv32-unknown-elf -march=rv32im -mabi=ilp32 \
-O2 -fno-builtin -S runtime-example.c -o runtime.s
reimu --file=frontend-check.s,runtime.s --memory=256M --stack=1M \
--output=frontend-check.out
Compare frontend-check.out with the expected source behavior to test the frontend independently of the student backend. The program reads from standard input; --output keeps its output separate from REIMU’s status messages. Use the same RV32 target for this check, including 32-bit addresses and usize/isize.
Data layout
Source integers and addresses are 32 bits. The table below gives the reference storage layout; student implementations may use another internal layout when source behavior and external interfaces remain correct.
| Type | Size (bytes) | Alignment (bytes) | Representation |
|---|---|---|---|
i32, u32 | 4 | 4 | 32-bit two’s-complement or unsigned integer |
isize, usize | 4 | 4 | Same width as an address |
bool | 1 | 1 | false = 0, true = 1 |
&T, &mut T | 4 | 4 | One machine address |
() | 0 | 1 | No data |
The representation of internal registers and compiler-generated intermediate values is otherwise implementation-defined, provided that observable source behavior and all external interfaces are preserved. References carry no runtime lifetime information. Unit return values use no return register.
Reference aggregate layout
The course implementation uses the following convenient layout, but student implementations may choose another internal layout:
[T; N]hasT’s alignment and sizesize(T) * N; elementibegins ati * size(T).- Struct fields appear in declaration order, each at the first offset satisfying its alignment.
- A struct’s alignment is the maximum field alignment, and its size is rounded up to that alignment.
- Padding bytes have unspecified values and need not be preserved when a value is copied.
&[T; N]is one word, not a slice fat pointer.
Code crossing a selected runtime interface must use the same layout on both sides.
Calling conventions and value semantics
Ordinary functions, methods, recursion, and private assembly helpers may use any consistent internal convention. The psABI is recommended for convenience but is required only at actual external boundaries such as machine main, the course C runtime, and REIMU libc.
The psABI’s calling convention specifies where arguments and return values go, which registers a caller may expect to survive a call, and how the stack is aligned. For ordinary 32-bit integer or reference arguments, the first eight use a0 through a7, and further arguments use the stack; a 32-bit scalar result uses a0. Callees preserve s0 through s11 and restore sp. A caller that needs a value in caller-saved registers (a0 through a7, t0 through t6, or ra) to survive a call is responsible for saving and restoring it. At these external boundaries, the stack must follow the psABI’s 16-byte alignment rule. The linked specification covers aggregate arguments and the remaining rules.
Machine-level indirection must preserve source by-value semantics. For example, mutating the parameter inside fn f(mut x: [i32; 3]) must not modify the caller’s value. Storage may be reused after a move when the old value is no longer observable.
Methods may lower the receiver to an explicit parameter. Fixed-size arrays remain source-level by-value aggregates and do not undergo C-style array-to-pointer decay.
Symbols, entry, and runtime
The global machine symbol main must provide a C ABI entry point with behavior equivalent to int main(void). It invokes the source entry function and, after that invocation completes, returns the signed 32-bit value 0 in a0. It must obey the psABI, including stack alignment and register preservation.
The recommended lowering gives the source main a unique mangled internal symbol and generates a wrapper exporting the machine symbol main. Source calls to main, including recursive calls, target the internal source function and use its ordinary unit-returning calling convention. Returning from that function resumes its caller; returning from the wrapper ends the program normally. The source signature remains fn main() -> ().
For example, the following C-like sketch illustrates the split:
static void __rx_source_main(void) {
/* Lowered source main body. */
}
int main(void) {
__rx_source_main();
return 0;
}
The internal symbol spelling is illustrative. Source and helper symbol names are implementation-defined but must be unique and must not collide with the machine entry or runtime symbols. The source function may use any supported internal calling convention. Equivalent lowering is permitted if it preserves both ordinary unit-returning source calls and the machine entry contract; a separate wrapper and internal function need not remain in the emitted code.
The source I/O builtins use this C ABI:
int32_t get_i32(void);
void print_i32(int32_t value);
void println_i32(int32_t value);
Their input and output behavior is defined by Builtin I/O. Students may use the course runtime or provide a compatible implementation. A runtime symbol is linked exactly once.
Reference C runtime
The repository includes this complete reference implementation:
/* Reference I/O and program-lifetime heap allocation for RV32/ILP32. */
typedef int int32_t;
typedef unsigned int uint32_t;
/* Compile-time size checks: a negative array length makes compilation fail. */
typedef char rx_int32_is_four_bytes[(sizeof(int32_t) == 4) ? 1 : -1];
typedef char rx_uint32_is_four_bytes[(sizeof(uint32_t) == 4) ? 1 : -1];
extern int printf(const char *format, ...);
extern int scanf(const char *format, ...);
extern void *malloc(uint32_t size);
/*
* Valid course allocations have nonzero size and alignment 1 or 4. REIMU's
* malloc result satisfies both alignments. Objects are not individually freed.
*/
void *__rx_alloc(uint32_t size, uint32_t align) {
(void)align;
return malloc(size);
}
int32_t get_i32(void) {
int32_t value;
(void)scanf("%d", &value);
return value;
}
void print_i32(int32_t value) { (void)printf("%d", value); }
void println_i32(int32_t value) { (void)printf("%d\n", value); }
The local int32_t and uint32_t typedefs avoid requiring target C library headers. The rx_int32_is_four_bytes and rx_uint32_is_four_bytes typedefs are compile-time size checks: each declares an array type of length 1 when the corresponding integer type occupies four bytes, or an invalid negative length otherwise. They allocate no storage and generate no runtime instructions.
It can be compiled with:
clang --target=riscv32-unknown-elf -march=rv32im -mabi=ilp32 \
-O2 -fno-builtin -S runtime-example.c -o runtime.s
Heap allocation interface
Generated code using the course runtime allocates Box and Vec storage through this fixed C ABI, which is not source-visible:
void *__rx_alloc(uint32_t size, uint32_t align);
size and align are byte counts. Valid calls have nonzero size and alignment 1 or 4. The function returns at least size accessible bytes at the requested alignment, disjoint from every allocation that has not been reused. Allocation succeeds for valid tests; failure behavior is unspecified.
There is no required __rx_dealloc. A custom runtime may instead use a private allocator, call REIMU malloc, or inline equivalent behavior. In every case, the compiler computes type size, alignment, element stride, and container capacity while the runtime manages untyped storage. Valid allocation calculations fit usize, so dynamic overflow checks and panic support are unnecessary.
REIMU also provides psABI-compatible memcpy, memmove, and memset. Use memcpy only for known-disjoint ranges and memmove when ranges may overlap.
Suggested compiler/runtime split
| Operation | Compiler responsibility | Runtime responsibility |
|---|---|---|
Box construction | Evaluate, calculate layout, initialize, and return the owner | Allocate aligned bytes |
Vec growth | Calculate capacity, maintain metadata, and move live elements | Allocate a new buffer; optionally provide a helper |
| By-value operations | Select copy or move and preserve value semantics | Optionally copy raw bytes |
| Container clone | Recursively clone the concrete T | Allocate result storage |
| Program end | No typed destruction is required | Reclaim the execution’s heap |
Resource guarantees
Tests run with 256 MiB total execution memory and a 1 MiB stack.
Assembly and execution
REIMU accepts text assembly files and assembles, links, and executes them internally. After compiling the selected C runtime to runtime.s as shown above, run the student backend’s student.s with:
reimu --file=student.s,runtime.s --memory=256M --stack=1M \
--output=student.out
Both assembly inputs are text .s files; the program reads from standard input and writes to student.out. REIMU resolves calls to its supported libc functions, such as printf, scanf, and malloc. No object file or ELF binary is passed to REIMU. A custom runtime supplies its own assembly in place of runtime.s.
Normal source completion returns status 0, and every output byte, including whitespace, is observable.
Valid programs may contain integer constants and stack offsets that exceed the 12-bit signed immediate range, as well as control-flow jumps that exceed the reach of a single conditional branch instruction. The specification places no separate limit on source size, compile time, compiler memory, or generated assembly size.
Submission commands and grading policy are course administration rather than language or execution semantics.
Optimization and execution cost
No specific optimization is mandatory. A stack-slot baseline is valid if it handles calls, finite registers, and all valid control flow. Optimizations may change IR, registers, storage, and instruction sequences but must preserve observable source behavior and external interfaces.
Performance uses Total cycles reported by the pinned REIMU version with its default weights and no cost-model-changing options. The count includes generated code, runtime instructions, and priced libc operations. Baselines, aggregation, scores, and rankings are separate assessment policy.
Grammar summary
This page collects every production from the language chapters. Lexer rules define tokens and separators; syntax rules combine them into types, items, statements, and expressions. Each category has a Show syntax diagram button, and production names link to their diagrams.
Notation explains the symbols. Parser conventions specifies operator precedence and contextual punctuation disambiguation, and provides a syntax coverage table. Typing, lookup, and runtime semantics accompany the productions in their respective chapters.
Lexer summary
Lexer
CHAR → <a 7-bit ASCII source character>
SPACE → U+0020
TAB → U+0009
LF → U+000A
CR → U+000D
IDENTIFIER_OR_KEYWORD → ( ASCII_ALPHA | _ ) ASCII_CONTINUE*
ASCII_ALPHA → [a-z A-Z]
ASCII_CONTINUE → ASCII_ALPHA | DEC_DIGIT | _
NON_KEYWORD_IDENTIFIER → IDENTIFIER_OR_KEYWORDexcept _ and a strict or reserved keyword
IDENTIFIER → NON_KEYWORD_IDENTIFIER
COMMENT → LINE_COMMENT | BLOCK_COMMENT
LINE_COMMENT → // ~LF*
BLOCK_COMMENT → /* ( BLOCK_COMMENT | BLOCK_CHAR )* */
BLOCK_CHAR → CHARnot at the start of /* or */
WHITESPACE → ( SPACE | TAB | LF | CR LF )+
Token →
IDENTIFIER_OR_KEYWORD
| INTEGER_LITERAL
| LIFETIME_TOKEN
| PUNCTUATION
INTEGER_LITERAL →
( DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL ) INTEGER_SUFFIX?
DEC_LITERAL → DEC_DIGIT ( DEC_DIGIT | _ )*
BIN_LITERAL → 0b ( BIN_DIGIT | _ )* BIN_DIGIT ( BIN_DIGIT | _ )*
OCT_LITERAL → 0o ( OCT_DIGIT | _ )* OCT_DIGIT ( OCT_DIGIT | _ )*
HEX_LITERAL → 0x ( HEX_DIGIT | _ )* HEX_DIGIT ( HEX_DIGIT | _ )*
BIN_DIGIT → [0-1]
OCT_DIGIT → [0-7]
DEC_DIGIT → [0-9]
HEX_DIGIT → [0-9 a-f A-F]
INTEGER_SUFFIX → i32 | u32 | isize | usize
LIFETIME_TOKEN → ' IDENTIFIER_OR_KEYWORD
LIFETIME_OR_LABEL → ' NON_KEYWORD_IDENTIFIER
PUNCTUATION →
= | < | <= | == | != | >= | >
| && | || | !
| + | - | * | / | % | ^ | & | | | << | >>
| += | -= | *= | /= | %= | ^= | &= | |= | <<= | >>=
| . | , | ; | : | :: | -> | # | _
| { | } | [ | ] | ( | )
Items summary
Item → UseDeclaration | Function | Struct | ConstantItem | Implementation
UseDeclaration → use UseTree ;
UseTree →
( UsePath? :: )? ( * | { ( UseTree ( , UseTree )* ,? )? } )
| UsePath ( as ( IDENTIFIER | _ ) )?
UsePath → ::? UsePathSegment ( :: UsePathSegment )*
UsePathSegment → IDENTIFIER | self | super | crate
Function →
fn IDENTIFIER GenericParams?
( FunctionParameters? )
FunctionReturnType? WhereClause?
BlockExpression
FunctionParameters →
SelfParam ,?
| ( SelfParam , )? FunctionParam ( , FunctionParam )* ,?
ShorthandSelf → ( & Lifetime? )? mut? self
FunctionParam → IdentifierBinding : Type
FunctionReturnType → -> Type
Struct → OuterAttribute* StructStruct
StructStruct → struct IDENTIFIER GenericParams? WhereClause? { StructFields? }
StructFields → StructField ( , StructField )* ,?
StructField → IDENTIFIER : Type
ConstantItem → const IDENTIFIER : Type = ConstValue ;
InherentImpl → impl GenericParams? Type WhereClause? { AssociatedItem* }
AssociatedItem → ConstantItem | Function
GenericParams → < ( GenericParam ( , GenericParam )* ,? )? >
LifetimeParam → Lifetime ( : LifetimeBounds )?
WhereClause → where ( WhereClauseItem , )* WhereClauseItem?
WhereClauseItem → LifetimeWhereClauseItem | TypeBoundWhereClauseItem
Paths summary
Syntax
PathInExpression → PathExprSegment ( :: PathExprSegment )*
PathExprSegment → PathIdentSegment ( :: GenericArgs )?
PathIdentSegment → IDENTIFIER | self | Self
TypePath → TypePathSegment ( :: TypePathSegment )*
TypePathSegment → PathIdentSegment ( ::? GenericArgs )?
GenericArgs → < GenericArgList? >
GenericArgList → ( GenericArg , )* GenericArg ,?
GenericArg → Lifetime | Type
Types summary
Syntax
Lifetime → LIFETIME_OR_LABEL | 'static | '_
LifetimeBounds → ( Lifetime + )* Lifetime?
TypeParamBounds → TypeParamBound ( + TypeParamBound )* +?
TypeNoBounds →
ParenthesizedType
| TypePath
| UnitType
| ReferenceType
| ArrayType
ParenthesizedType → ( Type )
ArrayType → [ Type ; ConstValue ]
ReferenceType → & Lifetime? mut? TypeNoBounds
UnitType → ( )
Attributes summary
Syntax
OuterAttribute → # [ DeriveAttribute ]
DeriveAttribute → derive ( ( DeriveName ( , DeriveName )* ,? )? )
DeriveName → Copy | Clone | PartialEq | Eq
Statements summary
Syntax
Statement → ; | LetStatement | ExpressionStatement
LetStatement → let IdentifierBinding ( : Type )? = Expression ;
IdentifierBinding → mut? IDENTIFIER
ExpressionStatement →
ExpressionWithoutBlock ;
| ExpressionWithBlock ;?
Expressions summary
Syntax
Expression → ExpressionWithoutBlock | ExpressionWithBlock
ExpressionWithoutBlock →
LiteralExpression
| PathExpression
| OperatorExpression
| GroupedExpression
| ArrayExpression
| IndexExpression
| UnitExpression
| StructExpression
| CallExpression
| MethodCallExpression
| FieldExpression
| ContinueExpression
| BreakExpression
| ReturnExpression
ExpressionWithBlock →
BlockExpression
| LoopExpression
| IfExpression
LiteralExpression → INTEGER_LITERAL | true | false
PathExpression → PathInExpression
BlockExpression → { Statements? }
Statements →
Statement+
| Statement+ ExpressionWithoutBlock
| ExpressionWithoutBlock
OperatorExpression →
BorrowExpression
| DereferenceExpression
| NegationExpression
| ArithmeticOrLogicalExpression
| ComparisonExpression
| LazyBooleanExpression
| TypeCastExpression
| AssignmentExpression
| CompoundAssignmentExpression
NegationExpression →
- Expression
| ! Expression
ArithmeticOrLogicalExpression →
Expression + Expression
| Expression - Expression
| Expression * Expression
| Expression / Expression
| Expression % Expression
| Expression & Expression
| Expression | Expression
| Expression ^ Expression
| Expression << Expression
| Expression >> Expression
ComparisonExpression →
Expression == Expression
| Expression != Expression
| Expression > Expression
| Expression < Expression
| Expression >= Expression
| Expression <= Expression
LazyBooleanExpression →
Expression || Expression
| Expression && Expression
TypeCastExpression → Expression as TypeNoBounds
BorrowExpression →
( & | && ) Expression
| ( & | && ) mut Expression
DereferenceExpression → * Expression
AssignmentExpression → Expression = Expression
CompoundAssignmentExpression →
Expression += Expression
| Expression -= Expression
| Expression *= Expression
| Expression /= Expression
| Expression %= Expression
| Expression &= Expression
| Expression |= Expression
| Expression ^= Expression
| Expression <<= Expression
| Expression >>= Expression
GroupedExpression → ( Expression )
UnitExpression → ( )
ArrayExpression → [ ArrayElements? ]
ArrayElements →
Expression ( , Expression )* ,?
| Expression ; ConstValue
IndexExpression → Expression [ Expression ]
StructExpression → PathInExpression { StructExprFields? }
StructExprFields → StructExprField ( , StructExprField )* ,?
StructExprField → IDENTIFIER : Expression
CallExpression → Expression ( CallParams? )
CallParams → Expression ( , Expression )* ,?
MethodCallExpression → Expression . PathExprSegment ( CallParams? )
FieldExpression → Expression . IDENTIFIER
LoopExpression → InfiniteLoopExpression | PredicateLoopExpression
InfiniteLoopExpression → loop BlockExpression
PredicateLoopExpression → while Conditions BlockExpression
BreakExpression → break Expression?
ContinueExpression → continue
IfExpression →
if Conditions BlockExpression
( else ( BlockExpression | IfExpression ) )?
Conditions → Expressionexcept an unparenthesized StructExpression at the condition/body boundary
ReturnExpression → return Expression?
Constants summary
Syntax
ConstValue → INTEGER_LITERAL | true | false | ConstantPath | - Magnitude | ( ConstValue )
Magnitude → INTEGER_LITERAL | ConstantPath | ( Magnitude )