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 formDefining productionsExamples
Identifiers and integersIDENTIFIER, INTEGER_LITERAL_value, 123_i32, 0b1010
Lifetime tokens and formsLIFETIME_TOKEN, Lifetime'a, 'static, '_
Lifetime parameters and boundsGenericParams, LifetimeParam, WhereClausefn f<'a>(x: &'a i32), where 'a: 'b
Source compilation unitCrate, ItemTop-level use declarations, functions, structs, constants, impls
Use declarationsUseDeclaration, UseTree, UsePathuse rx::core::*;, use rx::core::{get_i32, println_i32};
Functions and receiversFunction, FunctionParameters, ShorthandSelffn f(v: Vec<i32>) -> Box<i32> { ... }, &mut self
Struct declarations and constructionStructStruct, StructExpressionstruct S { x: i32 }, S { x: 1 }, Self { x: 1 }
Associated itemsInherentImpl, AssociatedItemimpl S { fn new() -> Self { ... } }
Derive attributesOuterAttribute, DeriveAttribute#[derive(Clone, PartialEq, Eq)]
Bindings and statementsLetStatement, ExpressionStatementlet mut v = Vec::<i32>::new();, v.push(1);
Type names, arrays, references, and unitTypePath, ArrayType, ReferenceType, UnitTypeSelf, [Vec<i32>; 2], &mut Box<i32>, ()
Container typesTypePath, TypePathSegment, GenericArgsBox<[i32; 4]>, Vec<Box<Node>>, Vec<Vec<i32,>,>
Container constructionCallExpression, PathInExpressionBox::<i32>::new(7), Vec::<Box<i32>>::new()
Paths, calls, fields, and indexingPathExpression, CallExpression, MethodCallExpression, FieldExpression, IndexExpressionS::new(), value.clone(), value.field, values[0]
Arrays, grouping, and unit valuesArrayExpression, GroupedExpression, UnitExpression[1, 2, 3], [0; 4], (value), ()
OperatorsOperatorExpression*p, &mut values[0], a + b, x += &y
Blocks and branchingBlockExpression, IfExpression{ make() }.field, if flag { a } else { b }
Loops and jumpsLoopExpression, BreakExpression, ContinueExpression, ReturnExpressionloop { break 3; }, while condition { ... }, return value
Constant contextsConstValue, Magnitude123, 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
TopicDefining chapter
Use declarationsUse declarations
Type and expression argumentsPaths
Lifetime declarations and boundsLifetime parameters
Derive attributesAttribute grammar
Operator precedenceExpressions
Casts followed by comparison or shiftCast parsing
Struct construction in a conditionIf expressions
Expression-statement boundariesStatements
Block tailsBlock expressions
Break/continue targets and loop resultsLoops
Never and unreachable codeNever type
Assignment placesAssignment 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 tokenContextInterpretation
&&Reference type or prefix borrowTwo & tokens, as in &&i32 or &&x
>>Closing nested type argumentsTwo closing > tokens
>=Closing type arguments before assignmentA closing > followed by =
>>=Closing nested type arguments before assignmentTwo 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();