Rust logo
Rust 1.29.2
17a9dc751

Grammar

1 Introduction

This document is the primary reference for the Rust programming language grammar. It provides only one kind of material:

This document does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate guide is available to help acquire such background.

This document also does not serve as a reference to the standard library included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you're looking for may be there, not here.

2 Notation

Rust's grammar is defined over Unicode codepoints, each conventionally denoted U+XXXX, for 4 or more hexadecimal digits X. Most of Rust's grammar is confined to the ASCII range of Unicode, and is described in this document by a dialect of Extended Backus-Naur Form (EBNF), specifically a dialect of EBNF supported by common automated LL(k) parsing tools such as llgen, rather than the dialect given in ISO 14977. The dialect can be defined self-referentially as follows:

grammar : rule + ;
rule    : nonterminal ':' productionrule ';' ;
productionrule : production [ '|' production ] * ;
production : term * ;
term : element repeats ;
element : LITERAL | IDENTIFIER | '[' productionrule ']' ;
repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;

Where:

This EBNF dialect should hopefully be familiar to many readers.

2.1 Unicode productions

A few productions in Rust's grammar permit Unicode codepoints outside the ASCII range. We define these productions in terms of character properties specified in the Unicode standard, rather than in terms of ASCII-range codepoints. The section Special Unicode Productions lists these productions.

2.2 String table productions

Some rules in the grammar — notably unary operators, binary operators, and keywords — are given in a simplified form: as a listing of a table of unquoted, printable whitespace-separated strings. These cases form a subset of the rules regarding the token rule, and are assumed to be the result of a lexical-analysis phase feeding the parser, driven by a DFA, operating over the disjunction of all such string table entries.

When such a string enclosed in double-quotes (") occurs inside the grammar, it is an implicit reference to a single member of such a string table production. See tokens for more information.

3 Lexical structure

3.1 Input format

Rust input is interpreted as a sequence of Unicode codepoints encoded in UTF-8. Most Rust grammar rules are defined in terms of printable ASCII-range codepoints, but a small number are defined in terms of Unicode properties or explicit codepoint lists. 1

3.2 Special Unicode Productions

The following productions in the Rust grammar are defined in terms of Unicode properties: ident, non_null, non_eol, non_single_quote and non_double_quote.

3.2.1 Identifiers

The ident production is any nonempty Unicode string of the following form:

as long as the identifier does not occur in the set of keywords.

3.2.2 Delimiter-restricted productions

Some productions are defined by exclusion of particular Unicode characters:

3.3 Comments

comment : block_comment | line_comment ;
block_comment : "/*" block_comment_body * "*/" ;
block_comment_body : [block_comment | character] * ;
line_comment : "//" non_eol * ;

FIXME: add doc grammar?

3.4 Whitespace

whitespace_char : '\x20' | '\x09' | '\x0a' | '\x0d' ;
whitespace : [ whitespace_char | comment ] + ;

3.5 Tokens

simple_token : keyword | unop | binop ;
token : simple_token | ident | literal | symbol | whitespace token ;

3.5.1 Keywords

_ abstract alignof as become
box break const continue crate
do else enum extern false
final fn for if impl
in let loop macro match
mod move mut offsetof override
priv proc pub pure ref
return Self self sizeof static
struct super trait true type
typeof unsafe unsized use virtual
where while yield

Each of these keywords has special meaning in its grammar, and all of them are excluded from the ident rule.

Not all of these keywords are used by the language. Some of them were used before Rust 1.0, and were left reserved once their implementations were removed. Some of them were reserved before 1.0 to make space for possible future features.

3.5.2 Literals

lit_suffix : ident;
literal : [ string_lit | char_lit | byte_string_lit | byte_lit | num_lit | bool_lit ] lit_suffix ?;

The optional lit_suffix production is only used for certain numeric literals, but is reserved for future extension. That is, the above gives the lexical grammar, but a Rust parser will reject everything but the 12 special cases mentioned in Number literals in the reference.

3.5.2.1 Character and string literals

char_lit : '\x27' char_body '\x27' ;
string_lit : '"' string_body * '"' | 'r' raw_string ;

char_body : non_single_quote
          | '\x5c' [ '\x27' | common_escape | unicode_escape ] ;

string_body : non_double_quote
            | '\x5c' [ '\x22' | common_escape | unicode_escape ] ;
raw_string : '"' raw_string_body '"' | '#' raw_string '#' ;

common_escape : '\x5c'
              | 'n' | 'r' | 't' | '0'
              | 'x' hex_digit 2
unicode_escape : 'u' '{' hex_digit+ 6 '}';

hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
          | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
          | dec_digit ;
oct_digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' ;
dec_digit : '0' | nonzero_dec ;
nonzero_dec: '1' | '2' | '3' | '4'
           | '5' | '6' | '7' | '8' | '9' ;

3.5.2.2 Byte and byte string literals

byte_lit : "b\x27" byte_body '\x27' ;
byte_string_lit : "b\x22" string_body * '\x22' | "br" raw_byte_string ;

byte_body : ascii_non_single_quote
          | '\x5c' [ '\x27' | common_escape ] ;

byte_string_body : ascii_non_double_quote
            | '\x5c' [ '\x22' | common_escape ] ;
raw_byte_string : '"' raw_byte_string_body '"' | '#' raw_byte_string '#' ;

3.5.2.3 Number literals

num_lit : nonzero_dec [ dec_digit | '_' ] * float_suffix ?
        | '0' [       [ dec_digit | '_' ] * float_suffix ?
              | 'b'   [ '1' | '0' | '_' ] +
              | 'o'   [ oct_digit | '_' ] +
              | 'x'   [ hex_digit | '_' ] +  ] ;

float_suffix : [ exponent | '.' dec_lit exponent ? ] ? ;

exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
dec_lit : [ dec_digit | '_' ] + ;

3.5.2.4 Boolean literals

bool_lit : [ "true" | "false" ] ;

The two values of the boolean type are written true and false.

3.5.3 Symbols

symbol : "::" | "->"
       | '#' | '[' | ']' | '(' | ')' | '{' | '}'
       | ',' | ';' ;

Symbols are a general class of printable tokens that play structural roles in a variety of grammar productions. They are cataloged here for completeness as the set of remaining miscellaneous printable tokens that do not otherwise appear as unary operators, binary operators, or keywords.

3.6 Paths

expr_path : [ "::" ] ident [ "::" expr_path_tail ] + ;
expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
               | expr_path ;

type_path : ident [ type_path_tail ] + ;
type_path_tail : '<' type_expr [ ',' type_expr ] + '>'
               | "::" type_path ;

4 Syntax extensions

4.1 Macros

expr_macro_rules : "macro_rules" '!' ident '(' macro_rule * ')' ';'
                 | "macro_rules" '!' ident '{' macro_rule * '}' ;
macro_rule : '(' matcher * ')' "=>" '(' transcriber * ')' ';' ;
matcher : '(' matcher * ')' | '[' matcher * ']'
        | '{' matcher * '}' | '$' ident ':' ident
        | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]
        | non_special_token ;
transcriber : '(' transcriber * ')' | '[' transcriber * ']'
            | '{' transcriber * '}' | '$' ident
            | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]
            | non_special_token ;

5 Crates and source files

FIXME: grammar? What production covers #![crate_id = "foo"] ?

6 Items and attributes

FIXME: grammar?

6.1 Items

item : vis ? mod_item | fn_item | type_item | struct_item | enum_item
     | const_item | static_item | trait_item | impl_item | extern_block_item ;

6.1.1 Type Parameters

FIXME: grammar?

6.1.2 Modules

mod_item : "mod" ident ( ';' | '{' mod '}' );
mod : [ view_item | item ] * ;

6.1.2.1 View items

view_item : extern_crate_decl | use_decl ';' ;
6.1.2.1.1 Extern crate declarations
extern_crate_decl : "extern" "crate" crate_name
crate_name: ident | ( ident "as" ident )
6.1.2.1.2 Use declarations
use_decl : vis ? "use" [ path "as" ident
                        | path_glob ] ;

path_glob : ident [ "::" [ path_glob
                          | '*' ] ] ?
          | '{' path_item [ ',' path_item ] * '}' ;

path_item : ident | "self" ;

6.1.3 Functions

FIXME: grammar?

6.1.3.1 Generic functions

FIXME: grammar?

6.1.3.2 Unsafety

FIXME: grammar?

6.1.3.2.1 Unsafe functions

FIXME: grammar?

6.1.3.2.2 Unsafe blocks

FIXME: grammar?

6.1.3.3 Diverging functions

FIXME: grammar?

6.1.4 Type definitions

FIXME: grammar?

6.1.5 Structures

FIXME: grammar?

6.1.6 Enumerations

FIXME: grammar?

6.1.7 Constant items

const_item : "const" ident ':' type '=' expr ';' ;

6.1.8 Static items

static_item : "static" ident ':' type '=' expr ';' ;

6.1.8.1 Mutable statics

FIXME: grammar?

6.1.9 Traits

FIXME: grammar?

6.1.10 Implementations

FIXME: grammar?

6.1.11 External blocks

extern_block_item : "extern" '{' extern_block '}' ;
extern_block : [ foreign_fn ] * ;

6.2 Visibility and Privacy

vis : "pub" ;

6.2.1 Re-exporting and Visibility

See Use declarations.

6.3 Attributes

attribute : '#' '!' ? '[' meta_item ']' ;
meta_item : ident [ '=' literal
                  | '(' meta_seq ')' ] ? ;
meta_seq : meta_item [ ',' meta_seq ] ? ;

7 Statements and expressions

7.1 Statements

stmt : decl_stmt | expr_stmt | ';' ;

7.1.1 Declaration statements

decl_stmt : item | let_decl ;

7.1.1.1 Item declarations

See Items.

7.1.1.2 Variable declarations

let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
init : [ '=' ] expr ;

7.1.2 Expression statements

expr_stmt : expr ';' ;

7.2 Expressions

expr : literal | path | tuple_expr | unit_expr | struct_expr
     | block_expr | method_call_expr | field_expr | array_expr
     | idx_expr | range_expr | unop_expr | binop_expr
     | paren_expr | call_expr | lambda_expr | while_expr
     | loop_expr | break_expr | continue_expr | for_expr
     | if_expr | match_expr | if_let_expr | while_let_expr
     | return_expr ;

7.2.0.1 Lvalues, rvalues and temporaries

FIXME: grammar?

7.2.0.2 Moved and copied types

FIXME: Do we want to capture this in the grammar as different productions?

7.2.1 Literal expressions

See Literals.

7.2.2 Path expressions

See Paths.

7.2.3 Tuple expressions

tuple_expr : '(' [ expr [ ',' expr ] * | expr ',' ] ? ')' ;

7.2.4 Unit expressions

unit_expr : "()" ;

7.2.5 Structure expressions

struct_expr_field_init : ident | ident ':' expr ;
struct_expr : expr_path '{' struct_expr_field_init
                      [ ',' struct_expr_field_init ] *
                      [ ".." expr ] '}' |
              expr_path '(' expr
                      [ ',' expr ] * ')' |
              expr_path ;

7.2.6 Block expressions

block_expr : '{' [ stmt | item ] *
                 [ expr ] '}' ;

7.2.7 Method-call expressions

method_call_expr : expr '.' ident paren_expr_list ;

7.2.8 Field expressions

field_expr : expr '.' ident ;

7.2.9 Array expressions

array_expr : '[' "mut" ? array_elems? ']' ;

array_elems : [expr [',' expr]*] | [expr ';' expr] ;

7.2.10 Index expressions

idx_expr : expr '[' expr ']' ;

7.2.11 Range expressions

range_expr : expr ".." expr |
             expr ".." |
             ".." expr |
             ".." ;

7.2.12 Unary operator expressions

unop_expr : unop expr ;
unop : '-' | '*' | '!' ;

7.2.13 Binary operator expressions

binop_expr : expr binop expr | type_cast_expr
           | assignment_expr | compound_assignment_expr ;
binop : arith_op | bitwise_op | lazy_bool_op | comp_op

7.2.13.1 Arithmetic operators

arith_op : '+' | '-' | '*' | '/' | '%' ;

7.2.13.2 Bitwise operators

bitwise_op : '&' | '|' | '^' | "<<" | ">>" ;

7.2.13.3 Lazy boolean operators

lazy_bool_op : "&&" | "||" ;

7.2.13.4 Comparison operators

comp_op : "==" | "!=" | '<' | '>' | "<=" | ">=" ;

7.2.13.5 Type cast expressions

type_cast_expr : value "as" type ;

7.2.13.6 Assignment expressions

assignment_expr : expr '=' expr ;

7.2.13.7 Compound assignment expressions

compound_assignment_expr : expr [ arith_op | bitwise_op ] '=' expr ;

7.2.14 Grouped expressions

paren_expr : '(' expr ')' ;

7.2.15 Call expressions

expr_list : [ expr [ ',' expr ]* ] ? ;
paren_expr_list : '(' expr_list ')' ;
call_expr : expr paren_expr_list ;

7.2.16 Lambda expressions

ident_list : [ ident [ ',' ident ]* ] ? ;
lambda_expr : '|' ident_list '|' expr ;

7.2.17 While loops

while_expr : [ lifetime ':' ] ? "while" no_struct_literal_expr '{' block '}' ;

7.2.18 Infinite loops

loop_expr : [ lifetime ':' ] ? "loop" '{' block '}';

7.2.19 Break expressions

break_expr : "break" [ lifetime ] ?;

7.2.20 Continue expressions

continue_expr : "continue" [ lifetime ] ?;

7.2.21 For expressions

for_expr : [ lifetime ':' ] ? "for" pat "in" no_struct_literal_expr '{' block '}' ;

7.2.22 If expressions

if_expr : "if" no_struct_literal_expr '{' block '}'
          else_tail ? ;

else_tail : "else" [ if_expr | if_let_expr
                   | '{' block '}' ] ;

7.2.23 Match expressions

match_expr : "match" no_struct_literal_expr '{' match_arm * '}' ;

match_arm : attribute * match_pat "=>" [ expr "," | '{' block '}' ] ;

match_pat : pat [ '|' pat ] * [ "if" expr ] ? ;

7.2.24 If let expressions

if_let_expr : "if" "let" pat '=' expr '{' block '}'
               else_tail ? ;

7.2.25 While let loops

while_let_expr : [ lifetime ':' ] ? "while" "let" pat '=' expr '{' block '}' ;

7.2.26 Return expressions

return_expr : "return" expr ? ;

8 Type system

FIXME: is this entire chapter relevant here? Or should it all have been covered by some production already?

8.1 Types

8.1.1 Primitive types

FIXME: grammar?

8.1.1.1 Machine types

FIXME: grammar?

8.1.1.2 Machine-dependent integer types

FIXME: grammar?

8.1.2 Textual types

FIXME: grammar?

8.1.3 Tuple types

FIXME: grammar?

8.1.4 Array, and Slice types

FIXME: grammar?

8.1.5 Structure types

FIXME: grammar?

8.1.6 Enumerated types

FIXME: grammar?

8.1.7 Pointer types

FIXME: grammar?

8.1.8 Function types

FIXME: grammar?

8.1.9 Closure types

closure_type := [ 'unsafe' ] [ '<' lifetime-list '>' ] '|' arg-list '|'
                [ ':' bound-list ] [ '->' type ]
lifetime-list := lifetime | lifetime ',' lifetime-list
arg-list := ident ':' type | ident ':' type ',' arg-list

8.1.10 Never type

An empty type

never_type : "!" ;

8.1.11 Object types

FIXME: grammar?

8.1.12 Type parameters

FIXME: grammar?

8.1.13 Type parameter bounds

bound-list := bound | bound '+' bound-list '+' ?
bound := ty_bound | lt_bound
lt_bound := lifetime
ty_bound := ty_bound_noparen | (ty_bound_noparen)
ty_bound_noparen := [?] [ for<lt_param_defs> ] simple_path

8.1.14 Self types

FIXME: grammar?

8.2 Type kinds

FIXME: this is probably not relevant to the grammar...

9 Memory and concurrency models

FIXME: is this entire chapter relevant here? Or should it all have been covered by some production already?

9.1 Memory model

9.1.1 Memory allocation and lifetime

9.1.2 Memory ownership

9.1.3 Variables

9.1.4 Boxes

9.2 Threads

9.2.1 Communication between threads

9.2.2 Thread lifecycle


  1. Substitute definitions for the special Unicode productions are provided to the grammar verifier, restricted to ASCII range, when verifying the grammar in this document.