Grammar

Lexical productions

Keywords

KW_AS : as
KW_BREAK : break
KW_CONST : const
KW_CONTINUE : continue
KW_CRATE : crate
KW_ELSE : else
KW_ENUM : enum
KW_EXTERN : extern
KW_FALSE : false
KW_FN : fn
KW_FOR : for
KW_IF : if
KW_IMPL : impl
KW_IN : in
KW_LET : let
KW_LOOP : loop
KW_MATCH : match
KW_MOD : mod
KW_MOVE : move
KW_MUT : mut
KW_PUB : pub
KW_REF : ref
KW_RETURN : return
KW_SELFVALUE : self
KW_SELFTYPE : Self
KW_STATIC : static
KW_STRUCT : struct
KW_SUPER : super
KW_TRAIT : trait
KW_TRUE : true
KW_TYPE : type
KW_UNSAFE : unsafe
KW_USE : use
KW_WHERE : where
KW_WHILE : while

KW_ABSTRACT : abstract
KW_ALIGNOF : alignof
KW_BECOME : become
KW_BOX : box
KW_DO : do
KW_FINAL : final
KW_MACRO : macro
KW_OFFSETOF : offsetof
KW_OVERRIDE : override
KW_PRIV : priv
KW_PROC : proc
KW_PURE : pure
KW_SIZEOF : sizeof
KW_TYPEOF : typeof
KW_UNSIZED : unsized
KW_VIRTUAL : virtual
KW_YIELD : yield

KW_UNION : union
KW_STATICLIFETIME : 'static

Identifiers

IDENTIFIER_OR_KEYWORD :
      [a-z A-Z] [a-z A-Z 0-9 _]*
   | _ [a-z A-Z 0-9 _]+

IDENTIFIER :
IDENTIFIER_OR_KEYWORD Except a [strict] or [reserved] keyword

Comments

LINE_COMMENT :
      // (~[/ !] | //) ~\n*
   | //

BLOCK_COMMENT :
      /* (~[* !] | ** | BlockCommentOrDoc) (BlockCommentOrDoc | ~*/)* */
   | /**/
   | /***/

INNER_LINE_DOC :
   //! ~[\n IsolatedCR]*

INNER_BLOCK_DOC :
   /*! ( BlockCommentOrDoc | ~[*/ IsolatedCR] )* */

OUTER_LINE_DOC :
   /// (~/ ~[\n IsolatedCR]*)?

OUTER_BLOCK_DOC :
   /** (~* | BlockCommentOrDoc ) (BlockCommentOrDoc | ~[*/ IsolatedCR])* */

BlockCommentOrDoc :
      BLOCK_COMMENT
   | OUTER_BLOCK_DOC
   | INNER_BLOCK_DOC

IsolatedCR :
   A \r not followed by a \n

Tokens

CHAR_LITERAL :
   ' ( ~[' \ \n \r \t] | QUOTE_ESCAPE | ASCII_ESCAPE | UNICODE_ESCAPE ) '

QUOTE_ESCAPE :
   \' | \"

ASCII_ESCAPE :
      \x OCT_DIGIT HEX_DIGIT
   | \n | \r | \t | \\ | \0

UNICODE_ESCAPE :
   \u{ ( HEX_DIGIT _* )1..6 }

STRING_LITERAL :
   " (
      ~[" \ IsolatedCR]
      | QUOTE_ESCAPE
      | ASCII_ESCAPE
      | UNICODE_ESCAPE
      | STRING_CONTINUE
   )* "

STRING_CONTINUE :
   \ followed by \n

RAW_STRING_LITERAL :
   r RAW_STRING_CONTENT

RAW_STRING_CONTENT :
      " ( ~ IsolatedCR )* (non-greedy) "
   | # RAW_STRING_CONTENT #

BYTE_LITERAL :
   b' ( ASCII_FOR_CHAR | BYTE_ESCAPE ) '

ASCII_FOR_CHAR :
   any ASCII (i.e. 0x00 to 0x7F), except ', /, \n, \r or \t

BYTE_ESCAPE :
      \x HEX_DIGIT HEX_DIGIT
   | \n | \r | \t | \\ | \0

BYTE_STRING_LITERAL :
   b" ( ASCII_FOR_STRING | BYTE_ESCAPE | STRING_CONTINUE )* "

ASCII_FOR_STRING :
   any ASCII (i.e 0x00 to 0x7F), except ", / and IsolatedCR

RAW_BYTE_STRING_LITERAL :
   br RAW_BYTE_STRING_CONTENT

RAW_BYTE_STRING_CONTENT :
      " ASCII* (non-greedy) "
   | # RAW_STRING_CONTENT #

ASCII :
   any ASCII (i.e. 0x00 to 0x7F)

INTEGER_LITERAL :
   ( DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL ) INTEGER_SUFFIX?

DEC_LITERAL :
   DEC_DIGIT (DEC_DIGIT|_)*

TUPLE_INDEX :
      0    | NON_ZERO_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]

NON_ZERO_DEC_DIGIT : [1-9]

HEX_DIGIT : [0-9 a-f A-F]

INTEGER_SUFFIX :
      u8 | u16 | u32 | u64 | usize
   | i8 | i16 | i32 | i64 | isize

FLOAT_LITERAL :
      DEC_LITERAL . (not immediately followed by ., _ or an identifier)
   | DEC_LITERAL FLOAT_EXPONENT
   | DEC_LITERAL . DEC_LITERAL FLOAT_EXPONENT?
   | DEC_LITERAL (. DEC_LITERAL)? FLOAT_EXPONENT? FLOAT_SUFFIX

FLOAT_EXPONENT :
   (e|E) (+|-)? (DEC_DIGIT|_)* DEC_DIGIT (DEC_DIGIT|_)*

FLOAT_SUFFIX :
   f32 | f64

BOOLEAN_LITERAL :
      true
   | false

LIFETIME_TOKEN       ' IDENTIFIER_OR_KEYWORD
   | '_

LIFETIME_OR_LABEL:
      ' IDENTIFIER

EQ : =
LT : <
LE : <=
EQEQ : ==
NE : !=
GE : >=
GT : >
ANDAND : &&
OROR : ||
NOT : !
TILDE : ~

AT : @
DOT : .
DOTDOT : ..
DOTDOTDOT : ...
COMMA : ,
SEMI : ;
COLON : :
MOD_SEPARATOR : ::
RIGHT_ARROW : ->
LEFT_ARROW : <-
FAT_ARROW : =>
POUND : #
DOLLAR : $
QUESTION : ?

UNDERSCORE : _
LIFETIME_OR_LABEL : ' IDENTIFIER

OPEN_PAREN : (
CLOSE_PAREN : )
OPEN_BRACKET : [
CLOSE_BRACKET : ]
OPEN_BRACE : {
CLOSE_BRACE : }

Crates and source files

UTF8BOM : \uFEFF
SHEBANG : #! ~[[ \n] ~\n*

Syntactical productions

Crates and source files

Crate :
   UTF8BOM?
   SHEBANG?
   InnerAttribute*
   [Item]*

Items

Item:
   OuterAttribute* Visibility
   (
         Module
      | ExternCrate
      | UseDeclaration
      | [Function]
      | TypeAlias
      | Struct
      | Enumeration
      | Union
      | ConstantItem
      | StaticItem
      | Trait
      | Implementation
      | ExternBlock
      | Macro
      | MacroDefinition
   )

Generics :
   < GenericParams? >

GenericParams :
      LifetimeParams ,?
   | TypeParams ,?
   | LifetimeParams , TypeParams ,?

LifetimeParams :
   LifetimeParam (, LifetimeParam)*

LifetimeParam :
   LIFETIME_OR_LABEL LifetimeBounds?

TypeParams:
   TypeParam (, TypeParam)*

TypeParam :
   IDENTIFIER TypeParamBounds? ( = Type )?

TypeParamBounds :
      LIFETIME_OR_LABEL
   | ( LIFETIME_OR_LABEL )
   | ?? LateBoundLifetimeDefs? TypePath
   | ( ?? LateBoundLifetimeDefs? TypePath )

LifetimeBounds :
   : LIFETIME_OR_LABEL ( + LIFETIME_OR_LABEL )* +?

LateBoundLifetimeDefs :
   for < LifetimeParams ,? >

WhereClause :
   where ( WhereClauseItem ( , WhereClauseItem )* ,? )?

WhereClauseItem :
      LifetimeWhereClauseItem
   | TypeBoundWhereClauseItem
   | TypeEqualWhereClauseItem

LifetimeWhereClauseItem :
   LIFETIME_OR_LABEL LifetimeBounds

TypeBoundWhereClauseItem :
   LateBoundLifetimeDefs? Type : TypeParamBounds

TypeEqualWhereClauseItem :
   LateBoundLifetimeDefs? Type (=|==) Type

Modules

Module :
      mod IDENTIFIER ;
   | mod IDENTIFIER {
        InnerAttribute*
        [Item]*
      }

Extern crates

ExternCrate :
   extern crate IDENTIFIER (as IDENTIFIER)? ;

Use declarations

UseDeclaration :
   (Visibility)? use UseTree ;

UseTree :
      (SimplePath? ::)? *
   | (SimplePath? ::)? { (UseTree ( , UseTree )* ,?)? }
   | SimplePath as IDENTIFIER

Functions

Function:
   unsafe? (extern Abi?)? fn IDENTIFIER Generics?
      ( FunctionParameters? ) FunctionReturnType? WhereClause?
      BlockWithInnerAttributes

Abi:
   STRING_LITERAL

FunctionParameters:
   FunctionParam (, FunctionParam)* ,?

FunctionParam :
   Pattern : Type

FunctionReturnType:
   -> Type

BlockWithInnerAttributes :
   {
      InnerAttribute*
      Statement*
   }

Type aliases

TypeAlias :
   type IDENTIFIER Generics? WhereClause? = Type ;

Structs

Struct :
      StructStruct
   | TupleStruct

StructStruct :
   struct IDENTIFIER  Generics? WhereClause? ( { StructFields? } | ; )

TupleStruct :
   struct IDENTIFIER  Generics? ( TupleFields? ) WhereClause? ;

StructFields :
   StructField (, StructField)* ,?

StructField :
   OuterAttribute*
   Visibility    IDENTIFIER : Type

TupleFields :
   TupleField (, TupleField)* ,?

TupleField :
   OuterAttribute*
   Visibility    Type

Enumerations

Enumeration :
   enum IDENTIFIER  Generics? WhereClause? { EnumItems? }

EnumItems :
   EnumItem ( , EnumItem )* ,?

EnumItem :
   OuterAttribute*
   IDENTIFIER ( EnumItemTuple | EnumItemStruct | EnumItemDiscriminant )?

EnumItemTuple :
   ( TupleFields? )

EnumItemStruct :
   { StructFields? }

EnumItemDiscriminant :
   = Expression

Unions

Union :
   union IDENTIFIER Generics? WhereClause? {StructFields }

Constant items

ConstantItem :
   const IDENTIFIER : Type = Expression ;

Static items

StaticItem :
   static mut? IDENTIFIER : Type = Expression ;

Traits

Trait :
   unsafe? trait IDENTIFIER  [GenericsDecl]? WhereClause? {
     TraitItem*
   }

TraitItem :
   TraitMethod | TraitConst | TraitType

TraitMethod :
   TypeMethod | Method

Implementations

Implementation :
unsafe? impl [GenericsDecl] (!? [Path] for)? (TypeName | ..) {
   InnerAttributes?
   ImplementationItems?
}

External blocks

ExternBlock :
   extern [Abi]? {
      InnerAttribute*
      ExternalItem*
   }

ExternalItem :
   OuterAttribute*
   [VisibilityNoTuple]?
   ( ExternalStaticItem | ExternalFunctionItem )

ExternalStaticItem :
   static mut? IDENTIFIER : Type ;

ExternalFunctionItem :
   fn IDENTIFIER Generics?
   ( [FunctionParameters] | FunctionParametersWithVariadics )
   [FunctionReturnType]? WhereClause? ;

FunctionParametersWithVariadics :
   ( ( FunctionParam , )* VariadicFunctionParam )

VariadicFunctionParam :
   FunctionParam , ...

Visibility and Privacy

Visibility :
      EMPTY
   | pub
   | pub ( crate )
   | pub ( in ModulePath )
   | pub ( in? self )
   | pub ( in? super )

Attributes

Attribute :
   InnerAttribute | OuterAttribute

InnerAttribute :
   #![ MetaItem ]

OuterAttribute :
   #[ MetaItem ]

MetaItem :
      IDENTIFIER
   | IDENTIFIER = LITERAL
   | IDENTIFIER ( LITERAL )
   | IDENTIFIER ( MetaSeq )
   | IDENTIFIER ( MetaSeq , )

MetaSeq :
      EMPTY
   | MetaItem
   | MetaSeq , MetaItem

Statements

Statement :
   DeclarationStatement | Expression | ;

DeclarationStatement :
   [Item] | LocalVariablesDeclaration

FIXME

LocalVariablesDeclaration :
   let Pattern ( : Type )? (= Expression )? ;

ExpressionStatement :
      ExpressionWithBlock
   | ExpressionWithoutBlock ;

ExpressionWithBlock :
      BlockExpression
   | LoopExpression
   | IfExpression
   | IfLetExpression
   | MatchExpression
   | WhileExpression
   | WhileLetExpression

ExpressionWithoutBlock: all other expression types

Expressions

Expression :
      LiteralExpression
   | [PathExpression]
   | BlockExpression
   | OperatorExpression
   | GroupedExpression
   | ArrayExpression
   | IndexExpression
   | [TupleExpression]
   | [TupleIndexingExpression]
   | [StructExpression]
   | [EnumerationVariantExpression]
   | CallExpression
   | [MethodCallExpression]
   | FieldExpression
   | ClosureExpression
   | LoopExpression
   | ContinueExpression
   | BreakExpression
   | RangeExpression
   | IfExpression
   | IfLetExpression
   | MatchExpression
   | ReturnExpression

Literal expressions

LiteralExpression :
      CHAR_LITERAL
   | STRING_LITERAL
   | RAW_STRING_LITERAL
   | BYTE_LITERAL
   | BYTE_STRING_LITERAL
   | RAW_BYTE_STRING_LITERAL
   | INTEGER_LITERAL
   | FLOAT_LITERAL
   | BOOLEAN_LITERAL

Block expressions

BlockExpression :
   {
      InnerAttribute*
      Statement*
      Expression?
   }

UnsafeBlockExpression :
   unsafe BlockExpression

Operator expressions

OperatorExpression :
      BorrowExpression
   | DereferenceExpression
   | ErrorPropagationExpression
   | NegationExpression
   | ArithmeticOrLogicalExpression
   | ComparisonExpression
   | LazyBooleanExpression
   | TypeCastExpression
   | AssignmentExpression
   | CompoundAssignmentExpression

BorrowExpression :
      (&|&&) Expression
   | (&|&&) mut Expression

DereferenceExpression :
   * Expression

ErrorPropagationExpression :
   Expression ?

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 [PathInExpression]

AssignmentExpression :
   | Expression = Expression

CompoundAssignmentExpression :
      Expression += Expression
   | Expression -= Expression
   | Expression *= Expression
   | Expression /= Expression
   | Expression %= Expression
   | Expression &= Expression
   | Expression |= Expression
   | Expression ^= Expression
   | Expression <<= Expression
   | Expression >>= Expression

Grouped expressions

GroupedExpression :
   ( Expression )

Array and index expressions

ArrayExpression :
      [ ]
   | [ Expression ( , Expression )* ,? ]
   | [ Expression ; Expression ]

IndexExpression :
   Expression [ Expression ]

Call expressions

CallExpression :
   Expression ( CallParams? )

CallParams :
   Expression ( , Expression )* ,?

Field access expressions

FieldExpression :
   Expression . IDENTIFIER

Closure expressions

ClosureExpression :
   move?
   ( || | | [FunctionParameters]? | )
   (Expression | -> TypeNoBounds BlockExpression)

Loop expressions

LoopExpression :
   LoopLabel? (
         InfiniteLoopExpression
      | PredicateLoopExpression
      | PredicatePatternLoopExpression
      | IteratorLoopExpression
   )

InfiniteLoopExpression :
   loop BlockExpression

PredicateLoopExpression :
   while Expressionexcept struct expression BlockExpression

PredicatePatternLoopExpression :
   while let Pattern = Expressionexcept struct expression BlockExpression

IteratorLoopExpression :
   for Pattern in Expressionexcept struct expression BlockExpression

LoopLabel :
   LIFETIME_OR_LABEL :

BreakExpression :
   break LIFETIME_OR_LABEL? Expression?

ContinueExpression :
   continue LIFETIME_OR_LABEL?

Range expressions

RangeExpression :
      RangeExpr
   | RangeFromExpr
   | RangeToExpr
   | RangeFullExpr

RangeExpr :
   Expression .. Expression

RangeFromExpr :
   Expression ..

RangeToExpr :
   .. Expression

RangeFullExpr :
   ..

If and if let expressions

IfExpression :
   if Expressionexcept struct expression BlockExpression
   (else ( BlockExpression | IfExpression | IfLetExpression ) )?

IfLetExpression :
   if let Pattern = Expressionexcept struct expression BlockExpression
   (else ( BlockExpression | IfExpression | IfLetExpression ) )?

Match expressions

MatchExpression :
   match Expressionexcept struct expression {
      InnerAttribute*
      MatchArms?
   }

MatchArms :
   ( MatchArm => ( BlockExpression ,? | Expression , ) )*
   MatchArm => ( BlockExpression | Expression ) ,?

MatchArm :
   OuterAttribute* MatchArmPatterns MatchArmGuard

MatchArmPatterns :
   |? Pattern ( | Pattern )*

MatchArmGuard :
   if Expression

Return expressions

ReturnExpression :
   return Expression?

Paths

SimplePath :
   ::? PathSegmentIdentifier (:: PathSegmentIdentifier)*

PathSegmentIdentifier :
   IDENTIFIER | super | self | Self FIXME

PathInExpr :
   ::? PathSegmentIdentifier (:: (PathSegmentIdentifier | GenericsForType) )*

QualifiedPathInExpr :
   < type_ (as TypePath)? > :: PathInExpr

TypePath :
   ::? TypePathElement (:: TypePathElement)*

TypePathElement :
   PathSegmentIdentifier (GenericsForType | FunctionSignature)?

GenericsForType :
      < (LifetimeParams (, TypeParamsForTypes)? (, BindingParams)? ,? )? >
   | < TypeParamsForTypes (, BindingParams)? ,? >
   | < BindingParams ,? >

TypeParamsForTypes :
   Type (, Type)*

BindingParams :
   TypeBindingParam (, TypeBindingParam)*

TypeBindingParam :
   IDENTIFIER = type_ FIXME

Qualified_TypePath_ :
   < Type (as TypePath)? > :: TypePath FIXME

Patterns

Pattern :
      LiteralPattern
   | WildcardPattern
   | RangePattern
   | ReferencePattern
   | IdentifierPattern
   | StructPattern
   | TuplePattern
   | TupleStructPattern
   | PathPattern

LiteralPattern :
      BOOLEAN_LITERAL
   | CHAR_LITERAL
   | BYTE_LITERAL
   | STRING_LITERAL
   | RAW_STRING_LITERAL
   | BYTE_STRING_LITERAL
   | RAW_BYTE_STRING_LITERAL
   | -? INTEGER_LITERAL
   | -? FLOAT_LITERAL

WildcardPattern :
   _

RangePattern :
   RangePatternBound ... RangePatternBound

RangePatternBound :
      CHAR_LITERAL
   | BYTE_LITERAL
   | -? INTEGER_LITERAL
   | -? FLOAT_LITERAL
   | [PathInExpression]
   | [QualifiedPathInExpression]

ReferencePattern :
   (&|&&) mut? Pattern

IdentifierPattern :
      mut? IDENTIFIER (@ Pattern ) ?
   | ref mut? IDENTIFIER (@ Pattern ) ?

StructPattern :
   Path {
      StructPatternElements ?
   }

StructPatternElements :
      StructPatternFields (, | , StructPatternEtCetera)?
   | StructPatternEtCetera

StructPatternFields :
   StructPatternField (, StructPatternField) *

StructPatternField :
   OuterAttribute *
   (
         INTEGER_LITERAL : Pattern
      | IDENTIFIER : Pattern
      | ref? mut? IDENTIFIER
   )

StructPatternEtCetera :
   OuterAttribute *
   ..

TupleStructPattern :
   Path ( TupleStructItems )

TupleStructItems :
      Pattern ( , Pattern )* ,?
   | (Pattern ,)* .. ( (, Pattern)+ ,? )?

TuplePattern :
   ( TupplePatternItems? )

TuplePatternItems :
      Pattern ,
   | Pattern (, Pattern)+ ,?
   | (Pattern ,)* .. ( (, Pattern)+ ,? )?

PathPattern :
      PathForExpression
   | QualifiedPathForExpression

Types

Type :
      ParenthesizedType (+ TypeParamBounds)?
   | TupleType
   | NeverType
   | RawPointerType
   | ReferenceType
   | ArrayType
   | SliceType
   | InferredType
   | [QualifiedTypePath]
   | TypePath (+ TypeParamBounds)?
   | [BareFunctionType]
   | [MacroInvocationType]
   | TypeParamBounds

TypeNoBounds :
      ParenthesizedType
   | TupleType
   | NeverType
   | RawPointerType
   | ReferenceType
   | ArrayType
   | SliceType
   | InferredType
   | [QualifiedTypePath]
   | TypePath
   | [BareFunctionType]
   | [MacroInvocationType]

ParenthesizedType :
      ( Type )

TupleType :
      ( )
   | ( Type , )
   | ( Type ( , Type ) + ,? )

ArrayType :
   [ _type ; Expression ] FIXME

SliceType :
   [ _type ] FIXME

NeverType : !

InferredType : _

ReferenceType :
   & Lifetime? mut? _type FIXME

RawPointerType :
   * ( mut | const ) _type **FIXME

TraitObjectType :
   LifetimeOrPath ( + LifetimeOrPath )* +?

LifetimeOrPath :    [Path] | [LIFETIME_OR_LABEL]