CARVIEW |
Scala 3 Syntax Summary
The following description of Scala tokens uses literal characters βcβ
when referring to the ASCII fragment \u0000
β \u007F
.
Informal descriptions are typeset as βsome commentβ
.
Lexical Syntax
The lexical syntax of Scala is given by the following grammar in EBNF form:
whiteSpace ::= β\u0020β | β\u0009β | β\u000Dβ | β\u000Aβ
upper ::= βAβ | ... | βZβ | β$β and any character in Unicode categories Lu, Lt or Nl,
and any character in Unicode categories Lo and Lm that doesn't have
contributory property Other_Lowercase
lower ::= βaβ | ... | βzβ | β_β and any character in Unicode category Ll,
and any character in Unicode categories Lo or Lm that has contributory
property Other_Lowercase
letter ::= upper | lower
digit ::= β0β | ... | β9β
paren ::= β(β | β)β | β[β | β]β | β{β | β}β
delim ::= β`β | β'β | β"β | β.β | β;β | β,β
opchar ::= β!β | β#β | β%β | β&β | β*β | β+β | β-β | β/β | β:β |
β<β | β=β | β>β | β?β | β@β | β\β | β^β | β|β | β~β
and any character in Unicode categories Sm or So
printableChar ::= all characters in [\u0020, \u007E] inclusive
UnicodeEscape ::= β\β βuβ {βuβ} hexDigit hexDigit hexDigit hexDigit
hexDigit ::= β0β | ... | β9β | βAβ | ... | βFβ | βaβ | ... | βfβ
charEscapeSeq ::= β\β (βbβ | βtβ | βnβ | βfβ | βrβ | β"β | β'β | β\β)
escapeSeq ::= UnicodeEscape | charEscapeSeq
op ::= opchar {opchar}
varid ::= lower idrest
boundvarid ::= varid
| β`β varid β`β
plainid ::= alphaid
| op
id ::= plainid
| β`β { charNoBackQuoteOrNewline | escapeSeq } β`β
idrest ::= {letter | digit} [β_β op]
quoteId ::= β'β alphaid
spliceId ::= β$β alphaid ;
integerLiteral ::= (decimalNumeral | hexNumeral | binaryNumeral) [βLβ | βlβ]
decimalNumeral ::= β0β | digit [{digit | β_β} digit]
hexNumeral ::= β0β (βxβ | βXβ) hexDigit [{hexDigit | β_β} hexDigit]
binaryNumeral ::= β0β (βbβ | βBβ) binaryDigit [{binaryDigit | β_β} binaryDigit]
floatingPointLiteral
::= [decimalNumeral] β.β digit [{digit | β_β} digit] [exponentPart] [floatType]
| decimalNumeral exponentPart [floatType]
| decimalNumeral floatType
exponentPart ::= (βEβ | βeβ) [β+β | β-β] digit [{digit | β_β} digit]
floatType ::= βFβ | βfβ | βDβ | βdβ
booleanLiteral ::= βtrueβ | βfalseβ
characterLiteral ::= β'β (charNoQuoteOrNewline | escapeSeq) β'β
stringLiteral ::= β"β {stringElement} β"β
| β"""β multiLineChars β"""β
stringElement ::= charNoDoubleQuoteOrNewline
| escapeSeq
multiLineChars ::= {[β"β] [β"β] charNoDoubleQuote} {β"β}
interpolatedString
::= alphaid β"β {[β\β] interpolatedStringPart | β\\β | β\"β} β"β
| alphaid β"""β {[β"β] [β"β] char \ (β"β | β\$β) | escape} {β"β} β"""β
interpolatedStringPart
::= printableChar \ (β"β | β$β | β\β) | escape
escape ::= β\$\$β
| β\$"β
| β\$β alphaid
| β\$β BlockExpr
alphaid ::= upper idrest
| varid
comment ::= β/*β βany sequence of characters; nested comments are allowedβ β*/β
| β//β βany sequence of characters up to end of lineβ
nl ::= βnew line characterβ
semi ::= β;β | nl {nl}
Optional Braces
The principle of optional braces is that any keyword that can be followed by {
can also be followed by an indented block, without needing an intervening :
. (Allowing an optional :
would be counterproductive since it would introduce several ways to do the same thing.)
The lexical analyzer inserts indent
and outdent
tokens that represent regions of indented code at certain points.
In the context-free productions below we use the notation <<< ts >>>
to indicate a token sequence ts
that is either enclosed in a pair of braces { ts }
or that constitutes an indented region indent ts outdent
. Analogously, the notation :<<< ts >>>
indicates a token sequence ts
that is either enclosed in a pair of braces { ts }
or that constitutes an indented region indent ts outdent
that follows a colon
token.
A colon
token reads as the standard colon ":
" but is generated instead of it where colon
is legal according to the context free syntax, but only if the previous token is an alphanumeric identifier, a backticked identifier, or one of the tokens this
, super
, new
, ")
", and "]
".
colon ::= ':' -- with side conditions explained above
<<< ts >>> ::= β{β ts β}β
| indent ts outdent
:<<< ts >>> ::= [nl] β{β ts β}β
| colon indent ts outdent
Keywords
Regular keywords
abstract case catch class def do else
enum export extends false final finally for
given if implicit import lazy match new
null object override package private protected return
sealed super then throw trait true try
type val var while with yield
: = <- => <: >: #
@ =>> ?=>
Soft keywords
as derives end extension infix inline opaque open transparent using | * + -
See the separate section on soft keywords for additional details on where a soft keyword is recognized.
Context-free Syntax
The context-free syntax of Scala is given by the following EBNF grammar:
Literals and Paths
SimpleLiteral ::= [β-β] integerLiteral
| [β-β] floatingPointLiteral
| booleanLiteral
| characterLiteral
| stringLiteral
Literal ::= SimpleLiteral
| interpolatedStringLiteral
| symbolLiteral
| βnullβ
QualId ::= id {β.β id}
ids ::= id {β,β id}
SimpleRef ::= id
| [id β.β] βthisβ
| [id β.β] βsuperβ [ClassQualifier] β.β id
ClassQualifier ::= β[β id β]β
Types
Type ::= FunType
| TypTypeParamClause β=>>β Type
| MatchType
| InfixType
FunType ::= FunTypeArgs (β=>β | β?=>β) Type
| TypTypeParamClause '=>' Type
FunTypeArgs ::= InfixType
| β(β [ FunArgTypes ] β)β
| FunParamClause
FunParamClause ::= β(β TypedFunParam {β,β TypedFunParam } β)β
TypedFunParam ::= id β:β Type
MatchType ::= InfixType `match` <<< TypeCaseClauses >>>
InfixType ::= RefinedType {id [nl] RefinedType}
RefinedType ::= AnnotType {[nl] Refinement}
AnnotType ::= SimpleType {Annotation}
SimpleType ::= SimpleLiteral
| β?β TypeBounds
| id
| Singleton β.β id
| Singleton β.β βtypeβ
| β(β [Types] β)β
| Refinement
| SimpleType TypeArgs
| SimpleType β#β id
Singleton ::= SimpleRef
| SimpleLiteral
| Singleton β.β id
FunArgType ::= Type
| β=>β Type
FunArgTypes ::= FunArgType { β,β FunArgType }
ParamType ::= [β=>β] ParamValueType
ParamValueType ::= Type [β*β]
TypeArgs ::= β[β Types β]β
Refinement ::= :<<< [RefineDcl] {semi [RefineDcl]} >>>
TypeBounds ::= [β>:β Type] [β<:β Type]
TypeAndCtxBounds ::= TypeBounds [':' ContextBounds]
ContextBounds ::= ContextBound
| ContextBound ':' ContextBounds -- to be deprecated
| '{' ContextBound {',' ContextBound} '}'
ContextBound ::= Type ['as' id]
Types ::= Type {β,β Type}
Expressions
Expr ::= FunParams (β=>β | β?=>β) Expr
| TypTypeParamClause β=>β Expr
| Expr1
BlockResult ::= FunParams (β=>β | β?=>β) Block
| TypTypeParamClause β=>β Block
| Expr1
FunParams ::= Bindings
| id
| β_β
Expr1 ::= [βinlineβ] βifβ β(β Expr β)β {nl} Expr [[semi] βelseβ Expr]
| [βinlineβ] βifβ Expr βthenβ Expr [[semi] βelseβ Expr]
| βwhileβ β(β Expr β)β {nl} Expr
| βwhileβ Expr βdoβ Expr
| βtryβ Expr Catches [βfinallyβ Expr]
| βtryβ Expr [βfinallyβ Expr]
| βthrowβ Expr
| βreturnβ [Expr]
| ForExpr
| [SimpleExpr β.β] id β=β Expr
| PrefixOperator SimpleExpr β=β Expr
| SimpleExpr ArgumentExprs β=β Expr
| PostfixExpr [Ascription]
| βinlineβ InfixExpr MatchClause
Ascription ::= β:β InfixType
| β:β Annotation {Annotation}
Catches ::= βcatchβ (Expr | ExprCaseClause)
PostfixExpr ::= InfixExpr [id] -- only if language.postfixOperators is enabled
InfixExpr ::= PrefixExpr
| InfixExpr id [nl] InfixExpr
| InfixExpr id ColonArgument
| InfixExpr MatchClause
MatchClause ::= βmatchβ <<< CaseClauses >>>
PrefixExpr ::= [PrefixOperator] SimpleExpr
PrefixOperator ::= β-β | β+β | β~β | β!β -- unless backquoted
SimpleExpr ::= SimpleRef
| Literal
| β_β
| BlockExpr
| ExprSplice
| Quoted
| quoteId -- only inside splices
| βnewβ ConstrApp {βwithβ ConstrApp} [TemplateBody]
| βnewβ TemplateBody
| β(β [ExprsInParens] β)β
| SimpleExpr β.β id
| SimpleExpr β.β MatchClause
| SimpleExpr TypeArgs
| SimpleExpr ArgumentExprs
| SimpleExpr ColonArgument
ColonArgument ::= colon [LambdaStart]
indent (CaseClauses | Block) outdent
LambdaStart ::= FunParams (β=>β | β?=>β)
| TypTypeParamClause β=>β
Quoted ::= β'β β{β Block β}β
| β'β β[β TypeBlock β]β
ExprSplice ::= spliceId -- if inside quoted block
| β$β β{β Block β}β -- unless inside quoted pattern
| β$β β{β Pattern β}β -- when inside quoted pattern
ExprsInParens ::= ExprInParens {β,β ExprInParens}
ExprInParens ::= PostfixExpr β:β Type | Expr
ParArgumentExprs ::= β(β [ExprsInParens] β)β
| β(β βusingβ ExprsInParens β)β
| β(β [ExprsInParens β,β] PostfixExpr β*β β)β
ArgumentExprs ::= ParArgumentExprs
| BlockExpr
BlockExpr ::= <<< (CaseClauses | Block) >>>
Block ::= {BlockStat semi} [BlockResult]
BlockStat ::= Import
| {Annotation {nl}} {LocalModifier} Def
| Extension
| Expr1
| EndMarker
TypeBlock ::= {TypeBlockStat semi} Type
TypeBlockStat ::= βtypeβ {nl} TypeDef
ForExpr ::= βforβ β(β Enumerators0 β)β {nl} [βdoβ | βyieldβ] Expr
| βforβ β{β Enumerators0 β}β {nl} [βdoβ | βyieldβ] Expr
| βforβ Enumerators0 (βdoβ | βyieldβ) Expr
Enumerators0 ::= {nl} Enumerators [semi]
Enumerators ::= Generator {semi Enumerator | Guard}
Enumerator ::= Generator
| Guard {Guard}
| Pattern1 β=β Expr
Generator ::= [βcaseβ] Pattern1 β<-β Expr
Guard ::= βifβ PostfixExpr
CaseClauses ::= CaseClause { CaseClause }
CaseClause ::= βcaseβ Pattern [Guard] β=>β Block
ExprCaseClause ::= βcaseβ Pattern [Guard] β=>β Expr
TypeCaseClauses ::= TypeCaseClause { TypeCaseClause }
TypeCaseClause ::= βcaseβ (InfixType | β_β) β=>β Type [semi]
Pattern ::= Pattern1 { β|β Pattern1 }
Pattern1 ::= PatVar β:β RefinedType
| [β-β] integerLiteral β:β RefinedType
| [β-β] floatingPointLiteral β:β RefinedType
| Pattern2
Pattern2 ::= [id β@β] InfixPattern
InfixPattern ::= SimplePattern { id [nl] SimplePattern }
SimplePattern ::= PatVar
| Literal
| β(β [Patterns] β)β
| Quoted
| SimplePattern1 [TypeArgs] [ArgumentPatterns]
| βgivenβ RefinedType
SimplePattern1 ::= SimpleRef
| SimplePattern1 β.β id
PatVar ::= varid
| β_β
Patterns ::= Pattern {β,β Pattern}
ArgumentPatterns ::= β(β [Patterns] β)β
| β(β [Patterns β,β] PatVar β*β β)β
Type and Value Parameters
ClsTypeParamClause::= β[β ClsTypeParam {β,β ClsTypeParam} β]β
ClsTypeParam ::= {Annotation} [β+β | β-β] id [HkTypeParamClause] TypeAndCtxBounds
DefTypeParamClause::= [nl] β[β DefTypeParam {β,β DefTypeParam} β]β
DefTypeParam ::= {Annotation} id [HkTypeParamClause] TypeAndCtxBounds
TypTypeParamClause::= β[β TypTypeParam {β,β TypTypeParam} β]β
TypTypeParam ::= {Annotation} (id | β_β) [HkTypeParamClause] TypeBounds
HkTypeParamClause ::= β[β HkTypeParam {β,β HkTypeParam} β]β
HkTypeParam ::= {Annotation} [β+β | β-β] (id | β_β) [HkTypeParamClause] TypeBounds
ClsParamClauses ::= {ClsParamClause} [[nl] β(β [βimplicitβ] ClsParams β)β]
ClsParamClause ::= [nl] β(β ClsParams β)β
| [nl] β(β βusingβ (ClsParams | FunArgTypes) β)β
ClsParams ::= ClsParam {β,β ClsParam}
ClsParam ::= {Annotation} [{Modifier} (βvalβ | βvarβ)] Param
DefParamClauses ::= DefParamClause { DefParamClause } -- and two DefTypeParamClause cannot be adjacent
DefParamClause ::= DefTypeParamClause
| DefTermParamClause
| UsingParamClause
ConstrParamClauses::= ConstrParamClause {ConstrParamClause}
ConstrParamClause ::= DefTermParamClause
| UsingParamClause
DefTermParamClause::= [nl] β(β [DefTermParams] β)β
UsingParamClause ::= [nl] β(β βusingβ (DefTermParams | FunArgTypes) β)β
DefImplicitClause ::= [nl] β(β βimplicitβ DefTermParams β)β
DefTermParams ::= DefTermParam {β,β DefTermParam}
DefTermParam ::= {Annotation} [βinlineβ] Param
Param ::= id β:β ParamType [β=β Expr]
Bindings and Imports
Bindings ::= β(β [Binding {β,β Binding}] β)β
Binding ::= (id | β_β) [β:β Type]
Modifier ::= LocalModifier
| AccessModifier
| βoverrideβ
| βopaqueβ
LocalModifier ::= βabstractβ
| βfinalβ
| βsealedβ
| βopenβ
| βimplicitβ
| βlazyβ
| βinlineβ
| βtransparentβ
| βinfixβ
AccessModifier ::= (βprivateβ | βprotectedβ) [AccessQualifier]
AccessQualifier ::= β[β id β]β
Annotation ::= β@β SimpleType {ParArgumentExprs}
Import ::= βimportβ ImportExpr {β,β ImportExpr}
Export ::= βexportβ ImportExpr {β,β ImportExpr}
ImportExpr ::= SimpleRef {β.β id} β.β ImportSpec
| SimpleRef βasβ id
ImportSpec ::= NamedSelector
| WildCardSelector
| β{β ImportSelectors) β}β
NamedSelector ::= id [βasβ (id | β_β)]
WildCardSelector ::= β*β | βgivenβ [InfixType]
ImportSelectors ::= NamedSelector [β,β ImportSelectors]
| WildCardSelector {β,β WildCardSelector}
EndMarker ::= βendβ EndMarkerTag -- when followed by EOL
EndMarkerTag ::= id | βifβ | βwhileβ | βforβ | βmatchβ | βtryβ
| βnewβ | βthisβ | βgivenβ | βextensionβ | βvalβ
Declarations and Definitions
RefineDcl ::= βvalβ ValDcl
| βdefβ DefDcl
| βvarβ ValDcl
| βtypeβ {nl} TypeDef
ValDcl ::= ids β:β Type
DefDcl ::= DefSig β:β Type
Def ::= βvalβ PatDef
| βvarβ PatDef
| βdefβ DefDef
| βtypeβ {nl} TypeDef
| TmplDef
PatDef ::= ids [β:β Type] [β=β Expr]
| Pattern2 [β:β Type] [β=β Expr] PatDef(_, pats, tpe?, expr)
DefDef ::= DefSig [β:β Type] [β=β Expr] DefDef(_, name, paramss, tpe, expr)
| βthisβ ConstrParamClauses [DefImplicitClause] β=β ConstrExpr DefDef(_, <init>, vparamss, EmptyTree, expr | Block)
DefSig ::= id [DefParamClauses] [DefImplicitClause]
TypeDef ::= id [HkTypeParamClause] {FunParamClause}TypeBounds TypeDefTree(_, name, tparams, bound
[β=β Type]
TmplDef ::= ([βcaseβ] βclassβ | βtraitβ) ClassDef
| [βcaseβ] βobjectβ ObjectDef
| βenumβ EnumDef
| 'given' (GivenDef | OldGivenDef)
ClassDef ::= id ClassConstr [Template]
ClassConstr ::= [ClsTypeParamClause] [ConstrMods] ClsParamClauses
ConstrMods ::= {Annotation} [AccessModifier]
ObjectDef ::= id [Template]
EnumDef ::= id ClassConstr InheritClauses EnumBody
GivenDef ::= [id ':'] GivenSig
GivenSig ::= GivenImpl
| '(' ')' '=>' GivenImpl
| GivenConditional '=>' GivenSig
GivenImpl ::= GivenType ([β=β Expr] | TemplateBody)
| ConstrApps TemplateBody
GivenConditional ::= DefTypeParamClause
| DefTermParamClause
| '(' FunArgTypes ')'
| GivenType
GivenType ::= AnnotType1 {id [nl] AnnotType1}
OldGivenDef ::= [OldGivenSig] (AnnotType [β=β Expr] | StructuralInstance) -- syntax up to Scala 3.5, to be deprecated in the future
OldGivenSig ::= [id] [DefTypeParamClause] {UsingParamClause} β:β -- one of `id`, `DefTypeParamClause`, `UsingParamClause` must be present
StructuralInstance ::= ConstrApp {βwithβ ConstrApp} [βwithβ WithTemplateBody]
Extension ::= βextensionβ [DefTypeParamClause] {UsingParamClause}
β(β DefTermParam β)β {UsingParamClause} ExtMethods
ExtMethods ::= ExtMethod | [nl] <<< ExtMethod {semi ExtMethod} >>>
ExtMethod ::= {Annotation [nl]} {Modifier} βdefβ DefDef
| Export
Template ::= InheritClauses [TemplateBody]
InheritClauses ::= [βextendsβ ConstrApps] [βderivesβ QualId {β,β QualId}]
ConstrApps ::= ConstrApp ({β,β ConstrApp} | {βwithβ ConstrApp})
ConstrApp ::= SimpleType {Annotation} {ParArgumentExprs}
ConstrExpr ::= SelfInvocation
| <<< SelfInvocation {semi BlockStat} >>>
SelfInvocation ::= βthisβ ArgumentExprs {ArgumentExprs}
WithTemplateBody ::= <<< [SelfType] TemplateStat {semi TemplateStat} >>>
TemplateBody ::= :<<< [SelfType] TemplateStat {semi TemplateStat} >>>
TemplateStat ::= Import
| Export
| {Annotation [nl]} {Modifier} Def
| Extension
| Expr1
| EndMarker
|
SelfType ::= id [β:β InfixType] β=>β
| βthisβ β:β InfixType β=>β
EnumBody ::= :<<< [SelfType] EnumStat {semi EnumStat} >>>
EnumStat ::= TemplateStat
| {Annotation [nl]} {Modifier} EnumCase
EnumCase ::= βcaseβ (id ClassConstr [βextendsβ ConstrApps]] | ids)
TopStats ::= TopStat {semi TopStat}
TopStat ::= Import
| Export
| {Annotation [nl]} {Modifier} Def
| Extension
| Packaging
| PackageObject
| EndMarker
|
Packaging ::= βpackageβ QualId :<<< TopStats >>>
PackageObject ::= βpackageβ βobjectβ ObjectDef
CompilationUnit ::= {βpackageβ QualId semi} TopStats