Guest User

Untitled

a guest
Feb 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.77 KB | None | 0 0
  1. ---
  2. layout: doc-page
  3. title: "Scala Syntax Summary"
  4. ---
  5.  
  6. The following descriptions of Scala tokens uses literal characters `‘c’` when
  7. referring to the ASCII fragment `\u0000` – `\u007F`.
  8.  
  9. _Unicode escapes_ are used to represent the Unicode character with the given
  10. hexadecimal code:
  11.  
  12. ```ebnf
  13. UnicodeEscape ::= ‘\’ ‘u’ {‘u’} hexDigit hexDigit hexDigit hexDigit
  14. hexDigit ::= ‘0’ | … | ‘9’ | ‘A’ | … | ‘F’ | ‘a’ | … | ‘f’
  15. ```
  16.  
  17. Informal descriptions are typeset as `“some comment”`.
  18.  
  19. ### Lexical Syntax
  20. The lexical syntax of Scala is given by the following grammar in EBNF
  21. form.
  22.  
  23. ```ebnf
  24. whiteSpace ::= ‘\u0020’ | ‘\u0009’ | ‘\u000D’ | ‘\u000A’
  25. upper ::= ‘A’ | … | ‘Z’ | ‘\$’ | ‘_’ “… and Unicode category Lu”
  26. lower ::= ‘a’ | … | ‘z’ “… and Unicode category Ll”
  27. letter ::= upper | lower “… and Unicode categories Lo, Lt, Nl”
  28. digit ::= ‘0’ | … | ‘9’
  29. paren ::= ‘(’ | ‘)’ | ‘[’ | ‘]’ | ‘{’ | ‘}’ | ‘'(’ | ‘'[’ | ‘'{’
  30. delim ::= ‘`’ | ‘'’ | ‘"’ | ‘.’ | ‘;’ | ‘,’
  31. opchar ::= “printableChar not matched by (whiteSpace | upper | lower |
  32. letter | digit | paren | delim | opchar | Unicode_Sm |
  33. Unicode_So)”
  34. printableChar ::= “all characters in [\u0020, \u007F] inclusive”
  35. charEscapeSeq ::= ‘\’ (‘b’ | ‘t’ | ‘n’ | ‘f’ | ‘r’ | ‘"’ | ‘'’ | ‘\’)
  36.  
  37. op ::= opchar {opchar}
  38. varid ::= lower idrest
  39. alphaid ::= upper idrest
  40. | varid
  41. plainid ::= alphaid
  42. | op
  43. id ::= plainid
  44. | ‘`’ { charNoBackQuoteOrNewline | UnicodeEscape | charEscapeSeq } ‘`’
  45. | INT // interpolation id, only for quasi-quotes
  46. idrest ::= {letter | digit} [‘_’ op]
  47.  
  48. integerLiteral ::= (decimalNumeral | hexNumeral) [‘L’ | ‘l’]
  49. decimalNumeral ::= ‘0’ | nonZeroDigit {digit}
  50. hexNumeral ::= ‘0’ (‘x’ | ‘X’) hexDigit {hexDigit}
  51. digit ::= ‘0’ | nonZeroDigit
  52. nonZeroDigit ::= ‘1’ | … | ‘9’
  53.  
  54. floatingPointLiteral
  55. ::= digit {digit} ‘.’ {digit} [exponentPart] [floatType]
  56. | ‘.’ digit {digit} [exponentPart] [floatType]
  57. | digit {digit} exponentPart [floatType]
  58. | digit {digit} [exponentPart] floatType
  59. exponentPart ::= (‘E’ | ‘e’) [‘+’ | ‘-’] digit {digit}
  60. floatType ::= ‘F’ | ‘f’ | ‘D’ | ‘d’
  61.  
  62. booleanLiteral ::= ‘true’ | ‘false’
  63.  
  64. characterLiteral ::= ‘'’ (printableChar | charEscapeSeq) ‘'’
  65.  
  66. stringLiteral ::= ‘"’ {stringElement} ‘"’
  67. | ‘"""’ multiLineChars ‘"""’
  68. stringElement ::= printableChar \ (‘"’ | ‘\’)
  69. | UnicodeEscape
  70. | charEscapeSeq
  71. multiLineChars ::= {[‘"’] [‘"’] char \ ‘"’} {‘"’}
  72. processedStringLiteral
  73. ::= alphaid ‘"’ {printableChar \ (‘"’ | ‘$’) | escape} ‘"’
  74. | alphaid ‘"""’ {[‘"’] [‘"’] char \ (‘"’ | ‘$’) | escape} {‘"’} ‘"""’
  75. escape ::= ‘$$’
  76. | ‘$’ letter { letter | digit }
  77. | ‘{’ Block [‘;’ whiteSpace stringFormat whiteSpace] ‘}’
  78. stringFormat ::= {printableChar \ (‘"’ | ‘}’ | ‘ ’ | ‘\t’ | ‘\n’)}
  79.  
  80. symbolLiteral ::= ‘'’ plainid
  81.  
  82. comment ::= ‘/*’ “any sequence of characters; nested comments are allowed” ‘*/’
  83. | ‘//’ “any sequence of characters up to end of line”
  84.  
  85. nl ::= “new line character”
  86. semi ::= ‘;’ | nl {nl}
  87. ```
  88.  
  89.  
  90. ## Context-free Syntax
  91.  
  92. The context-free syntax of Scala is given by the following EBNF
  93. grammar:
  94.  
  95. ### Literals and Paths
  96. ```ebnf
  97. SimpleLiteral ::= [‘-’] integerLiteral
  98. | [‘-’] floatingPointLiteral
  99. | booleanLiteral
  100. | characterLiteral
  101. | stringLiteral
  102. | symbolLiteral
  103. Literal ::= SimpleLiteral
  104. | processedStringLiteral
  105. | ‘null’
  106.  
  107. QualId ::= id {‘.’ id}
  108. ids ::= id {‘,’ id}
  109.  
  110. Path ::= StableId
  111. | [id ‘.’] ‘this’
  112. StableId ::= id
  113. | Path ‘.’ id
  114. | [id ‘.’] ‘super’ [ClassQualifier] ‘.’ id
  115. ClassQualifier ::= ‘[’ id ‘]’
  116. ```
  117.  
  118. ### Types
  119. ```ebnf
  120. Type ::= [‘implicit’] FunArgTypes ‘=>’ Type Function(ts, t)
  121. | HkTypeParamClause ‘=>’ Type TypeLambda(ps, t)
  122. | InfixType
  123. FunArgTypes ::= InfixType
  124. | ‘(’ [ FunArgType {‘,’ FunArgType } ] ‘)’
  125. | '(' TypedFunParam {',' TypedFunParam } ')'
  126. TypedFunParam ::= id ':' Type
  127. InfixType ::= RefinedType {id [nl] RefinedType} InfixOp(t1, op, t2)
  128. RefinedType ::= WithType {[nl] Refinement} RefinedTypeTree(t, ds)
  129. WithType ::= AnnotType {‘with’ AnnotType} (deprecated)
  130. AnnotType ::= SimpleType {Annotation} Annotated(t, annot)
  131. SimpleType ::= SimpleType TypeArgs AppliedTypeTree(t, args)
  132. | SimpleType ‘#’ id Select(t, name)
  133. | StableId
  134. | [‘-’ | ‘+’ | ‘~’ | ‘!’] StableId PrefixOp(expr, op)
  135. | Path ‘.’ ‘type’ SingletonTypeTree(p)
  136. | ‘(’ ArgTypes ‘)’ Tuple(ts)
  137. | ‘_’ TypeBounds
  138. | Refinement RefinedTypeTree(EmptyTree, refinement)
  139. | SimpleLiteral SingletonTypeTree(l)
  140. ArgTypes ::= Type {‘,’ Type}
  141. | NamedTypeArg {‘,’ NamedTypeArg}
  142. FunArgType ::= Type
  143. | ‘=>’ Type PrefixOp(=>, t)
  144. ParamType ::= [‘=>’] ParamValueType
  145. ParamValueType ::= Type [‘*’] PostfixOp(t, "*")
  146. TypeArgs ::= ‘[’ ArgTypes ‘]’ ts
  147. NamedTypeArg ::= id ‘=’ Type NamedArg(id, t)
  148. NamedTypeArgs ::= ‘[’ NamedTypeArg {‘,’ NamedTypeArg} ‘]’ nts
  149. Refinement ::= ‘{’ [Dcl] {semi [Dcl]} ‘}’ ds
  150. TypeBounds ::= [‘>:’ Type] [‘<:’ Type] | INT TypeBoundsTree(lo, hi)
  151. TypeParamBounds ::= TypeBounds {‘<%’ Type} {‘:’ Type} ContextBounds(typeBounds, tps)
  152. ```
  153.  
  154. ### Expressions
  155. ```scala
  156. Expr ::= [‘implicit’] FunParams ‘=>’ Expr Function(args, expr), Function(ValDef([implicit], id, TypeTree(), EmptyTree), expr)
  157. | Expr1
  158. BlockResult ::= [‘implicit’] FunParams ‘=>’ Block
  159. | Expr1
  160. FunParams ::= Bindings
  161. | id
  162. | ‘_’
  163. Expr1 ::= ‘if’ ‘(’ Expr ‘)’ {nl} Expr [[semi] ‘else’ Expr] If(Parens(cond), thenp, elsep?)
  164. | ‘if’ Expr ‘then’ Expr [[semi] ‘else’ Expr] If(cond, thenp, elsep?)
  165. | ‘while’ ‘(’ Expr ‘)’ {nl} Expr WhileDo(Parens(cond), body)
  166. | ‘while’ Expr ‘do’ Expr WhileDo(cond, body)
  167. | ‘do’ Expr [semi] ‘while’ Expr DoWhile(expr, cond)
  168. | ‘try’ Expr Catches [‘finally’ Expr] Try(expr, catches, expr?)
  169. | ‘try’ Expr [‘finally’ Expr] Try(expr, Nil, expr?)
  170. | ‘throw’ Expr Throw(expr)
  171. | ‘return’ [Expr] Return(expr?)
  172. | ForExpr
  173. | [SimpleExpr ‘.’] id ‘=’ Expr Assign(expr, expr)
  174. | SimpleExpr1 ArgumentExprs ‘=’ Expr Assign(expr, expr)
  175. | PostfixExpr [Ascription]
  176. | PostfixExpr ‘match’ ‘{’ CaseClauses ‘}’ Match(expr, cases) -- point on match
  177. Ascription ::= ‘:’ InfixType Typed(expr, tp)
  178. | ‘:’ Annotation {Annotation} Typed(expr, Annotated(EmptyTree, annot)*)
  179. Catches ::= ‘catch’ Expr
  180. PostfixExpr ::= InfixExpr [id] PostfixOp(expr, op)
  181. InfixExpr ::= PrefixExpr
  182. | InfixExpr id [nl] InfixExpr InfixOp(expr, op, expr)
  183. PrefixExpr ::= [‘-’ | ‘+’ | ‘~’ | ‘!’] SimpleExpr PrefixOp(expr, op)
  184. SimpleExpr ::= ‘new’ Template New(templ)
  185. | BlockExpr
  186. | ''{’ BlockExprContents ‘}’
  187. | ‘'(’ ExprsInParens ‘)’
  188. | ‘'[’ Type ‘]’
  189. | SimpleExpr1 [‘_’] PostfixOp(expr, _)
  190. SimpleExpr1 ::= Literal
  191. | Path
  192. | ‘_’
  193. | ‘(’ ExprsInParens ‘)’ Parens(exprs)
  194. | SimpleExpr ‘.’ id Select(expr, id)
  195. | SimpleExpr (TypeArgs | NamedTypeArgs) TypeApply(expr, args)
  196. | SimpleExpr1 ArgumentExprs Apply(expr, args)
  197. | XmlExpr
  198. ExprsInParens ::= ExprInParens {‘,’ ExprInParens}
  199. ExprInParens ::= PostfixExpr ‘:’ Type
  200. | Expr
  201. ParArgumentExprs ::= ‘(’ ExprsInParens ‘)’ exprs
  202. | ‘(’ [ExprsInParens] PostfixExpr ‘:’ ‘_’ ‘*’ ‘)’ exprs :+ Typed(expr, Ident(wildcardStar))
  203. ArgumentExprs ::= ParArgumentExprs
  204. | [nl] BlockExpr
  205. BlockExpr ::= ‘{’ BlockExprContents ‘}’
  206. BlockExprContents ::= CaseClauses | Block
  207. Block ::= {BlockStat semi} [BlockResult] Block(stats, expr?)
  208. BlockStat ::= Import
  209. | {Annotation} [‘implicit’ | ‘lazy’] Def
  210. | {Annotation} {LocalModifier} TmplDef
  211. | Expr1
  212.  
  213. ForExpr ::= ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’) ForYield(enums, expr)
  214. {nl} [‘yield’] Expr
  215. | ‘for’ Enumerators (‘do’ Expr | ‘yield’ Expr) ForDo(enums, expr)
  216. Enumerators ::= Generator {semi Enumerator | Guard}
  217. Enumerator ::= Generator
  218. | Guard
  219. | Pattern1 ‘=’ Expr GenAlias(pat, expr)
  220. Generator ::= Pattern1 ‘<-’ Expr GenFrom(pat, expr)
  221. Guard ::= ‘if’ PostfixExpr
  222.  
  223. CaseClauses ::= CaseClause { CaseClause } Match(EmptyTree, cases)
  224. CaseClause ::= ‘case’ (Pattern [Guard] ‘=>’ Block | INT) CaseDef(pat, guard?, block) // block starts at =>
  225.  
  226. Pattern ::= Pattern1 { ‘|’ Pattern1 } Alternative(pats)
  227. Pattern1 ::= PatVar ‘:’ RefinedType Bind(name, Typed(Ident(wildcard), tpe))
  228. | Pattern2
  229. Pattern2 ::= [id ‘@’] InfixPattern Bind(name, pat)
  230. InfixPattern ::= SimplePattern { id [nl] SimplePattern } InfixOp(pat, op, pat)
  231. SimplePattern ::= PatVar Ident(wildcard)
  232. | Literal Bind(name, Ident(wildcard))
  233. | ‘(’ [Patterns] ‘)’ Parens(pats) Tuple(pats)
  234. | XmlPattern
  235. | SimplePattern1 [TypeArgs] [ArgumentPatterns]
  236. SimplePattern1 ::= Path
  237. | SimplePattern1 ‘.’ id
  238. PatVar ::= varid
  239. | ‘_’
  240. Patterns ::= Pattern {‘,’ Pattern}
  241. ArgumentPatterns ::= ‘(’ [Patterns] ‘)’ Apply(fn, pats)
  242. | ‘(’ [Patterns ‘,’] Pattern2 ‘:’ ‘_’ ‘*’ ‘)’
  243. ```
  244.  
  245. ### Type and Value Parameters
  246. ```ebnf
  247. ClsTypeParamClause::= ‘[’ ClsTypeParam {‘,’ ClsTypeParam} ‘]’
  248. ClsTypeParam ::= {Annotation} [‘+’ | ‘-’] TypeDef(Modifiers, name, tparams, bounds)
  249. id [HkTypeParamClause] TypeParamBounds Bound(below, above, context)
  250.  
  251. DefTypeParamClause::= ‘[’ DefTypeParam {‘,’ DefTypeParam} ‘]’
  252. DefTypeParam ::= {Annotation} id [HkTypeParamClause] TypeParamBounds
  253.  
  254. TypTypeParamClause::= ‘[’ TypTypeParam {‘,’ TypTypeParam} ‘]’
  255. TypTypeParam ::= {Annotation} id [HkTypeParamClause] TypeBounds
  256.  
  257. HkTypeParamClause ::= ‘[’ HkTypeParam {‘,’ HkTypeParam} ‘]’
  258. HkTypeParam ::= {Annotation} [‘+’ | ‘-’] (Id[HkTypeParamClause] | ‘_’)
  259. TypeBounds
  260.  
  261. ClsParamClauses ::= {ClsParamClause} [[nl] ‘(’ ‘implicit’ ClsParams ‘)’]
  262. ClsParamClause ::= [nl] ‘(’ [ClsParams] ‘)’
  263. ClsParams ::= ClsParam {‘,’ ClsParam}
  264. ClsParam ::= {Annotation} ValDef(mods, id, tpe, expr) -- point of mods on val/var
  265. [{Modifier} (‘val’ | ‘var’) | ‘inline’] Param
  266. Param ::= id ‘:’ ParamType [‘=’ Expr]
  267. | INT
  268.  
  269. DefParamClauses ::= {DefParamClause} [[nl] ‘(’ ‘implicit’ DefParams ‘)’]
  270. DefParamClause ::= [nl] ‘(’ [DefParams] ‘)’
  271. DefParams ::= DefParam {‘,’ DefParam}
  272. DefParam ::= {Annotation} [‘inline’] Param ValDef(mods, id, tpe, expr) -- point of mods at id.
  273. ```
  274.  
  275. ### Bindings and Imports
  276. ```ebnf
  277. Bindings ::= ‘(’ Binding {‘,’ Binding} ‘)’
  278. Binding ::= (id | ‘_’) [‘:’ Type] ValDef(_, id, tpe, EmptyTree)
  279.  
  280. Modifier ::= LocalModifier
  281. | AccessModifier
  282. | ‘override’
  283. LocalModifier ::= ‘abstract’
  284. | ‘final’
  285. | ‘sealed’
  286. | ‘implicit’
  287. | ‘lazy’
  288. AccessModifier ::= (‘private’ | ‘protected’) [AccessQualifier]
  289. AccessQualifier ::= ‘[’ (id | ‘this’) ‘]’
  290.  
  291. Annotation ::= ‘@’ SimpleType {ParArgumentExprs} Apply(tpe, args)
  292.  
  293. TemplateBody ::= [nl] ‘{’ [SelfType] TemplateStat {semi TemplateStat} ‘}’ (self, stats)
  294. TemplateStat ::= Import
  295. | {Annotation [nl]} {Modifier} Def
  296. | {Annotation [nl]} {Modifier} Dcl
  297. | EnumCaseStat
  298. | Expr1
  299. |
  300. SelfType ::= id [‘:’ InfixType] ‘=>’ ValDef(_, name, tpt, _)
  301. | ‘this’ ‘:’ InfixType ‘=>’
  302.  
  303. Import ::= ‘import’ ImportExpr {‘,’ ImportExpr}
  304. ImportExpr ::= StableId ‘.’ (id | ‘_’ | ImportSelectors) Import(expr, sels)
  305. ImportSelectors ::= ‘{’ {ImportSelector ‘,’} (ImportSelector | ‘_’) ‘}’
  306. ImportSelector ::= id [‘=>’ id | ‘=>’ ‘_’] Ident(name), Pair(id, id)
  307. ```
  308.  
  309. ### Declarations and Definitions
  310. ```ebnf
  311. Dcl ::= ‘val’ ValDcl
  312. | ‘var’ VarDcl
  313. | ‘def’ DefDcl
  314. | ‘type’ {nl} TypeDcl
  315. | INT
  316.  
  317. ValDcl ::= ids ‘:’ Type PatDef(_, ids, tpe, EmptyTree)
  318. VarDcl ::= ids ‘:’ Type PatDef(_, ids, tpe, EmptyTree)
  319. DefDcl ::= DefSig [‘:’ Type] DefDef(_, name, tparams, vparamss, tpe, EmptyTree)
  320. DefSig ::= id [DefTypeParamClause] DefParamClauses
  321. TypeDcl ::= id [TypTypeParamClause] [‘=’ Type] TypeDefTree(_, name, tparams, tpt)
  322. | id [HkTypeParamClause] TypeBounds TypeDefTree(_, name, tparams, bounds)
  323.  
  324. Def ::= ‘val’ PatDef
  325. | ‘var’ VarDef
  326. | ‘def’ DefDef
  327. | ‘type’ {nl} TypeDcl
  328. | TmplDef
  329. | INT
  330. PatDef ::= Pattern2 {‘,’ Pattern2} [‘:’ Type] ‘=’ Expr PatDef(_, pats, tpe?, expr)
  331. VarDef ::= PatDef
  332. | ids ‘:’ Type ‘=’ ‘_’
  333. DefDef ::= DefSig [‘:’ Type] ‘=’ Expr DefDef(_, name, tparams, vparamss, tpe, expr)
  334. | DefSig [nl] ‘{’ Block ‘}’ DefDef(_, name, tparams, vparamss, tpe, Block)
  335. | ‘this’ DefParamClause DefParamClauses DefDef(_, <init>, Nil, vparamss, EmptyTree, expr | Block)
  336. (‘=’ ConstrExpr | [nl] ConstrBlock)
  337.  
  338. TmplDef ::= ([‘case’ | `enum'] ‘class’ | trait’) ClassDef
  339. | [‘case’] ‘object’ ObjectDef
  340. | `enum' EnumDef
  341. ClassDef ::= id ClassConstr TemplateOpt ClassDef(mods, name, tparams, templ)
  342. ClassConstr ::= [ClsTypeParamClause] [ConstrMods] ClsParamClauses with DefDef(_, <init>, Nil, vparamss, EmptyTree, EmptyTree) as first stat
  343. ConstrMods ::= {Annotation} [AccessModifier]
  344. ObjectDef ::= id TemplateOpt ModuleDef(mods, name, template) // no constructor
  345. EnumDef ::= id ClassConstr [`extends' [ConstrApps]] EnumDef(mods, name, tparams, template)
  346. [nl] ‘{’ EnumCaseStat {semi EnumCaseStat} ‘}’
  347. EnumCaseStat ::= {Annotation [nl]} {Modifier} EnumCase
  348. EnumCase ::= `case' (EnumClassDef | ObjectDef | ids)
  349. EnumClassDef ::= id [ClsTpeParamClause | ClsParamClause] ClassDef(mods, name, tparams, templ)
  350. ClsParamClauses TemplateOpt
  351. TemplateOpt ::= [‘extends’ Template | [nl] TemplateBody]
  352. Template ::= ConstrApps [TemplateBody] | TemplateBody Template(constr, parents, self, stats)
  353. ConstrApps ::= ConstrApp {‘with’ ConstrApp}
  354. ConstrApp ::= AnnotType {ArgumentExprs} Apply(tp, args)
  355. ConstrExpr ::= SelfInvocation
  356. | ConstrBlock
  357. SelfInvocation ::= ‘this’ ArgumentExprs {ArgumentExprs}
  358. ConstrBlock ::= ‘{’ SelfInvocation {semi BlockStat} ‘}’
  359.  
  360. TopStatSeq ::= TopStat {semi TopStat}
  361. TopStat ::= {Annotation [nl]} {Modifier} TmplDef
  362. | Import
  363. | Packaging
  364. | PackageObject
  365. Packaging ::= ‘package’ QualId [nl] ‘{’ TopStatSeq ‘}’ Package(qid, stats)
  366. PackageObject ::= ‘package’ ‘object’ ObjectDef object with package in mods.
  367.  
  368. CompilationUnit ::= {‘package’ QualId semi} TopStatSeq Package(qid, stats)
  369. ```
Add Comment
Please, Sign In to add comment