parser.nim 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements the parser of the standard Nim syntax.
  10. # The parser strictly reflects the grammar ("doc/grammar.txt"); however
  11. # it uses several helper routines to keep the parser small. A special
  12. # efficient algorithm is used for the precedence levels. The parser here can
  13. # be seen as a refinement of the grammar, as it specifies how the AST is built
  14. # from the grammar and how comments belong to the AST.
  15. # In fact the grammar is generated from this file:
  16. when isMainModule:
  17. # Leave a note in grammar.txt that it is generated:
  18. #| # This file is generated by compiler/parser.nim.
  19. import pegs
  20. var outp = open("doc/grammar.txt", fmWrite)
  21. for line in lines("compiler/parser.nim"):
  22. if line =~ peg" \s* '#| ' {.*}":
  23. outp.write matches[0], "\L"
  24. outp.close
  25. import ".." / tools / grammar_nanny
  26. checkGrammarFile()
  27. import
  28. llstream, lexer, idents, strutils, ast, msgs, options, lineinfos,
  29. pathutils
  30. when defined(nimpretty):
  31. import layouter
  32. type
  33. TParser* = object # A TParser object represents a file that
  34. # is being parsed
  35. currInd: int # current indentation level
  36. firstTok: bool # Has the first token been read?
  37. hasProgress: bool # some while loop requires progress ensurance
  38. lex*: TLexer # The lexer that is used for parsing
  39. tok*: TToken # The current token
  40. inPragma*: int # Pragma level
  41. inSemiStmtList*: int
  42. emptyNode: PNode
  43. when defined(nimpretty):
  44. em*: Emitter
  45. SymbolMode = enum
  46. smNormal, smAllowNil, smAfterDot
  47. TPrimaryMode = enum
  48. pmNormal, pmTypeDesc, pmTypeDef, pmSkipSuffix
  49. proc parseAll*(p: var TParser): PNode
  50. proc closeParser*(p: var TParser)
  51. proc parseTopLevelStmt*(p: var TParser): PNode
  52. # helpers for the other parsers
  53. proc isOperator*(tok: TToken): bool
  54. proc getTok*(p: var TParser)
  55. proc parMessage*(p: TParser, msg: TMsgKind, arg: string = "")
  56. proc skipComment*(p: var TParser, node: PNode)
  57. proc newNodeP*(kind: TNodeKind, p: TParser): PNode
  58. proc newIntNodeP*(kind: TNodeKind, intVal: BiggestInt, p: TParser): PNode
  59. proc newFloatNodeP*(kind: TNodeKind, floatVal: BiggestFloat, p: TParser): PNode
  60. proc newStrNodeP*(kind: TNodeKind, strVal: string, p: TParser): PNode
  61. proc newIdentNodeP*(ident: PIdent, p: TParser): PNode
  62. proc expectIdentOrKeyw*(p: TParser)
  63. proc expectIdent*(p: TParser)
  64. proc parLineInfo*(p: TParser): TLineInfo
  65. proc eat*(p: var TParser, tokType: TTokType)
  66. proc skipInd*(p: var TParser)
  67. proc optPar*(p: var TParser)
  68. proc optInd*(p: var TParser, n: PNode)
  69. proc indAndComment*(p: var TParser, n: PNode)
  70. proc setBaseFlags*(n: PNode, base: TNumericalBase)
  71. proc parseSymbol*(p: var TParser, mode = smNormal): PNode
  72. proc parseTry(p: var TParser; isExpr: bool): PNode
  73. proc parseCase(p: var TParser): PNode
  74. proc parseStmtPragma(p: var TParser): PNode
  75. proc parsePragma(p: var TParser): PNode
  76. proc postExprBlocks(p: var TParser, x: PNode): PNode
  77. proc parseExprStmt(p: var TParser): PNode
  78. proc parseBlock(p: var TParser): PNode
  79. proc primary(p: var TParser, mode: TPrimaryMode): PNode
  80. proc simpleExprAux(p: var TParser, limit: int, mode: TPrimaryMode): PNode
  81. # implementation
  82. template prettySection(body) =
  83. when defined(nimpretty): beginSection(p.em)
  84. body
  85. when defined(nimpretty): endSection(p.em)
  86. proc getTok(p: var TParser) =
  87. ## Get the next token from the parser's lexer, and store it in the parser's
  88. ## `tok` member.
  89. rawGetTok(p.lex, p.tok)
  90. p.hasProgress = true
  91. when defined(nimpretty):
  92. emitTok(p.em, p.lex, p.tok)
  93. # skip the additional tokens that nimpretty needs but the parser has no
  94. # interest in:
  95. while p.tok.tokType == tkComment:
  96. rawGetTok(p.lex, p.tok)
  97. emitTok(p.em, p.lex, p.tok)
  98. proc openParser*(p: var TParser, fileIdx: FileIndex, inputStream: PLLStream,
  99. cache: IdentCache; config: ConfigRef) =
  100. ## Open a parser, using the given arguments to set up its internal state.
  101. ##
  102. initToken(p.tok)
  103. openLexer(p.lex, fileIdx, inputStream, cache, config)
  104. when defined(nimpretty):
  105. openEmitter(p.em, cache, config, fileIdx)
  106. getTok(p) # read the first token
  107. p.firstTok = true
  108. p.emptyNode = newNode(nkEmpty)
  109. proc openParser*(p: var TParser, filename: AbsoluteFile, inputStream: PLLStream,
  110. cache: IdentCache; config: ConfigRef) =
  111. openParser(p, fileInfoIdx(config, filename), inputStream, cache, config)
  112. proc closeParser(p: var TParser) =
  113. ## Close a parser, freeing up its resources.
  114. closeLexer(p.lex)
  115. when defined(nimpretty):
  116. closeEmitter(p.em)
  117. proc parMessage(p: TParser, msg: TMsgKind, arg = "") =
  118. ## Produce and emit the parser message `arg` to output.
  119. lexMessageTok(p.lex, msg, p.tok, arg)
  120. proc parMessage(p: TParser, msg: string, tok: TToken) =
  121. ## Produce and emit a parser message to output about the token `tok`
  122. parMessage(p, errGenerated, msg % prettyTok(tok))
  123. proc parMessage(p: TParser, arg: string) =
  124. ## Produce and emit the parser message `arg` to output.
  125. lexMessageTok(p.lex, errGenerated, p.tok, arg)
  126. template withInd(p, body: untyped) =
  127. let oldInd = p.currInd
  128. p.currInd = p.tok.indent
  129. body
  130. p.currInd = oldInd
  131. template newlineWasSplitting(p: var TParser) =
  132. when defined(nimpretty):
  133. layouter.newlineWasSplitting(p.em)
  134. template realInd(p): bool = p.tok.indent > p.currInd
  135. template sameInd(p): bool = p.tok.indent == p.currInd
  136. template sameOrNoInd(p): bool = p.tok.indent == p.currInd or p.tok.indent < 0
  137. proc validInd(p: var TParser): bool {.inline.} =
  138. result = p.tok.indent < 0 or p.tok.indent > p.currInd
  139. proc rawSkipComment(p: var TParser, node: PNode) =
  140. if p.tok.tokType == tkComment:
  141. if node != nil:
  142. when not defined(nimNoNilSeqs):
  143. if node.comment == nil: node.comment = ""
  144. when defined(nimpretty):
  145. if p.tok.commentOffsetB > p.tok.commentOffsetA:
  146. node.comment.add fileSection(p.lex.config, p.lex.fileIdx, p.tok.commentOffsetA, p.tok.commentOffsetB)
  147. else:
  148. node.comment.add p.tok.literal
  149. else:
  150. node.comment.add p.tok.literal
  151. else:
  152. parMessage(p, errInternal, "skipComment")
  153. getTok(p)
  154. proc skipComment(p: var TParser, node: PNode) =
  155. if p.tok.indent < 0: rawSkipComment(p, node)
  156. proc flexComment(p: var TParser, node: PNode) =
  157. if p.tok.indent < 0 or realInd(p): rawSkipComment(p, node)
  158. const
  159. errInvalidIndentation = "invalid indentation"
  160. errIdentifierExpected = "identifier expected, but got '$1'"
  161. errExprExpected = "expression expected, but found '$1'"
  162. errTokenExpected = "'$1' expected"
  163. proc skipInd(p: var TParser) =
  164. if p.tok.indent >= 0:
  165. if not realInd(p): parMessage(p, errInvalidIndentation)
  166. proc optPar(p: var TParser) =
  167. if p.tok.indent >= 0:
  168. if p.tok.indent < p.currInd: parMessage(p, errInvalidIndentation)
  169. proc optInd(p: var TParser, n: PNode) =
  170. skipComment(p, n)
  171. skipInd(p)
  172. proc getTokNoInd(p: var TParser) =
  173. getTok(p)
  174. if p.tok.indent >= 0: parMessage(p, errInvalidIndentation)
  175. proc expectIdentOrKeyw(p: TParser) =
  176. if p.tok.tokType != tkSymbol and not isKeyword(p.tok.tokType):
  177. lexMessage(p.lex, errGenerated, errIdentifierExpected % prettyTok(p.tok))
  178. proc expectIdent(p: TParser) =
  179. if p.tok.tokType != tkSymbol:
  180. lexMessage(p.lex, errGenerated, errIdentifierExpected % prettyTok(p.tok))
  181. proc eat(p: var TParser, tokType: TTokType) =
  182. ## Move the parser to the next token if the current token is of type
  183. ## `tokType`, otherwise error.
  184. if p.tok.tokType == tokType:
  185. getTok(p)
  186. else:
  187. lexMessage(p.lex, errGenerated,
  188. "expected: '" & TokTypeToStr[tokType] & "', but got: '" & prettyTok(p.tok) & "'")
  189. proc parLineInfo(p: TParser): TLineInfo =
  190. ## Retrieve the line information associated with the parser's current state.
  191. result = getLineInfo(p.lex, p.tok)
  192. proc indAndComment(p: var TParser, n: PNode) =
  193. if p.tok.indent > p.currInd:
  194. if p.tok.tokType == tkComment: rawSkipComment(p, n)
  195. else: parMessage(p, errInvalidIndentation)
  196. else:
  197. skipComment(p, n)
  198. proc newNodeP(kind: TNodeKind, p: TParser): PNode =
  199. result = newNodeI(kind, parLineInfo(p))
  200. proc newIntNodeP(kind: TNodeKind, intVal: BiggestInt, p: TParser): PNode =
  201. result = newNodeP(kind, p)
  202. result.intVal = intVal
  203. proc newFloatNodeP(kind: TNodeKind, floatVal: BiggestFloat,
  204. p: TParser): PNode =
  205. result = newNodeP(kind, p)
  206. result.floatVal = floatVal
  207. proc newStrNodeP(kind: TNodeKind, strVal: string, p: TParser): PNode =
  208. result = newNodeP(kind, p)
  209. result.strVal = strVal
  210. proc newIdentNodeP(ident: PIdent, p: TParser): PNode =
  211. result = newNodeP(nkIdent, p)
  212. result.ident = ident
  213. proc parseExpr(p: var TParser): PNode
  214. proc parseStmt(p: var TParser): PNode
  215. proc parseTypeDesc(p: var TParser): PNode
  216. proc parseParamList(p: var TParser, retColon = true): PNode
  217. proc isSigilLike(tok: TToken): bool {.inline.} =
  218. result = tok.tokType == tkOpr and tok.ident.s[0] == '@'
  219. proc isRightAssociative(tok: TToken): bool {.inline.} =
  220. ## Determines whether the token is right assocative.
  221. result = tok.tokType == tkOpr and tok.ident.s[0] == '^'
  222. # or (tok.ident.s.len > 1 and tok.ident.s[^1] == '>')
  223. proc isOperator(tok: TToken): bool =
  224. ## Determines if the given token is an operator type token.
  225. tok.tokType in {tkOpr, tkDiv, tkMod, tkShl, tkShr, tkIn, tkNotin, tkIs,
  226. tkIsnot, tkNot, tkOf, tkAs, tkFrom, tkDotDot, tkAnd,
  227. tkOr, tkXor}
  228. proc isUnary(p: TParser): bool =
  229. ## Check if the current parser token is a unary operator
  230. if p.tok.tokType in {tkOpr, tkDotDot} and
  231. p.tok.strongSpaceB == 0 and
  232. p.tok.strongSpaceA > 0:
  233. result = true
  234. proc checkBinary(p: TParser) {.inline.} =
  235. ## Check if the current parser token is a binary operator.
  236. # we don't check '..' here as that's too annoying
  237. if p.tok.tokType == tkOpr:
  238. if p.tok.strongSpaceB > 0 and p.tok.strongSpaceA == 0:
  239. parMessage(p, warnInconsistentSpacing, prettyTok(p.tok))
  240. #| module = stmt ^* (';' / IND{=})
  241. #|
  242. #| comma = ',' COMMENT?
  243. #| semicolon = ';' COMMENT?
  244. #| colon = ':' COMMENT?
  245. #| colcom = ':' COMMENT?
  246. #|
  247. #| operator = OP0 | OP1 | OP2 | OP3 | OP4 | OP5 | OP6 | OP7 | OP8 | OP9
  248. #| | 'or' | 'xor' | 'and'
  249. #| | 'is' | 'isnot' | 'in' | 'notin' | 'of' | 'as' | 'from'
  250. #| | 'div' | 'mod' | 'shl' | 'shr' | 'not' | 'static' | '..'
  251. #|
  252. #| prefixOperator = operator
  253. #|
  254. #| optInd = COMMENT? IND?
  255. #| optPar = (IND{>} | IND{=})?
  256. #|
  257. #| simpleExpr = arrowExpr (OP0 optInd arrowExpr)* pragma?
  258. #| arrowExpr = assignExpr (OP1 optInd assignExpr)*
  259. #| assignExpr = orExpr (OP2 optInd orExpr)*
  260. #| orExpr = andExpr (OP3 optInd andExpr)*
  261. #| andExpr = cmpExpr (OP4 optInd cmpExpr)*
  262. #| cmpExpr = sliceExpr (OP5 optInd sliceExpr)*
  263. #| sliceExpr = ampExpr (OP6 optInd ampExpr)*
  264. #| ampExpr = plusExpr (OP7 optInd plusExpr)*
  265. #| plusExpr = mulExpr (OP8 optInd mulExpr)*
  266. #| mulExpr = dollarExpr (OP9 optInd dollarExpr)*
  267. #| dollarExpr = primary (OP10 optInd primary)*
  268. proc colcom(p: var TParser, n: PNode) =
  269. eat(p, tkColon)
  270. skipComment(p, n)
  271. const tkBuiltInMagics = {tkType, tkStatic, tkAddr}
  272. proc parseSymbol(p: var TParser, mode = smNormal): PNode =
  273. #| symbol = '`' (KEYW|IDENT|literal|(operator|'('|')'|'['|']'|'{'|'}'|'=')+)+ '`'
  274. #| | IDENT | KEYW
  275. case p.tok.tokType
  276. of tkSymbol:
  277. result = newIdentNodeP(p.tok.ident, p)
  278. getTok(p)
  279. of tokKeywordLow..tokKeywordHigh:
  280. if p.tok.tokType in tkBuiltInMagics or mode == smAfterDot:
  281. # for backwards compatibility these 2 are always valid:
  282. result = newIdentNodeP(p.tok.ident, p)
  283. getTok(p)
  284. elif p.tok.tokType == tkNil and mode == smAllowNil:
  285. result = newNodeP(nkNilLit, p)
  286. getTok(p)
  287. else:
  288. parMessage(p, errIdentifierExpected, p.tok)
  289. result = p.emptyNode
  290. of tkAccent:
  291. result = newNodeP(nkAccQuoted, p)
  292. getTok(p)
  293. # progress guaranteed
  294. while true:
  295. case p.tok.tokType
  296. of tkAccent:
  297. if result.len == 0:
  298. parMessage(p, errIdentifierExpected, p.tok)
  299. break
  300. of tkOpr, tkDot, tkDotDot, tkEquals, tkParLe..tkParDotRi:
  301. let lineinfo = parLineInfo(p)
  302. var accm = ""
  303. while p.tok.tokType in {tkOpr, tkDot, tkDotDot, tkEquals,
  304. tkParLe..tkParDotRi}:
  305. accm.add($p.tok)
  306. getTok(p)
  307. let node = newNodeI(nkIdent, lineinfo)
  308. node.ident = p.lex.cache.getIdent(accm)
  309. result.add(node)
  310. of tokKeywordLow..tokKeywordHigh, tkSymbol, tkIntLit..tkCharLit:
  311. result.add(newIdentNodeP(p.lex.cache.getIdent($p.tok), p))
  312. getTok(p)
  313. else:
  314. parMessage(p, errIdentifierExpected, p.tok)
  315. break
  316. eat(p, tkAccent)
  317. else:
  318. parMessage(p, errIdentifierExpected, p.tok)
  319. # BUGFIX: We must consume a token here to prevent endless loops!
  320. # But: this really sucks for idetools and keywords, so we don't do it
  321. # if it is a keyword:
  322. #if not isKeyword(p.tok.tokType): getTok(p)
  323. result = p.emptyNode
  324. proc colonOrEquals(p: var TParser, a: PNode): PNode =
  325. if p.tok.tokType == tkColon:
  326. result = newNodeP(nkExprColonExpr, p)
  327. getTok(p)
  328. newlineWasSplitting(p)
  329. #optInd(p, result)
  330. result.add(a)
  331. result.add(parseExpr(p))
  332. elif p.tok.tokType == tkEquals:
  333. result = newNodeP(nkExprEqExpr, p)
  334. getTok(p)
  335. #optInd(p, result)
  336. result.add(a)
  337. result.add(parseExpr(p))
  338. else:
  339. result = a
  340. proc exprColonEqExpr(p: var TParser): PNode =
  341. #| exprColonEqExpr = expr (':'|'=' expr)?
  342. var a = parseExpr(p)
  343. if p.tok.tokType == tkDo:
  344. result = postExprBlocks(p, a)
  345. else:
  346. result = colonOrEquals(p, a)
  347. proc exprList(p: var TParser, endTok: TTokType, result: PNode) =
  348. #| exprList = expr ^+ comma
  349. when defined(nimpretty):
  350. inc p.em.doIndentMore
  351. getTok(p)
  352. optInd(p, result)
  353. # progress guaranteed
  354. while (p.tok.tokType != endTok) and (p.tok.tokType != tkEof):
  355. var a = parseExpr(p)
  356. result.add(a)
  357. if p.tok.tokType != tkComma: break
  358. getTok(p)
  359. optInd(p, a)
  360. when defined(nimpretty):
  361. dec p.em.doIndentMore
  362. proc exprColonEqExprListAux(p: var TParser, endTok: TTokType, result: PNode) =
  363. assert(endTok in {tkCurlyRi, tkCurlyDotRi, tkBracketRi, tkParRi})
  364. getTok(p)
  365. flexComment(p, result)
  366. optPar(p)
  367. # progress guaranteed
  368. while p.tok.tokType != endTok and p.tok.tokType != tkEof:
  369. var a = exprColonEqExpr(p)
  370. result.add(a)
  371. if p.tok.tokType != tkComma: break
  372. getTok(p)
  373. # (1,) produces a tuple expression
  374. if endTok == tkParRi and p.tok.tokType == tkParRi and result.kind == nkPar:
  375. result.transitionSonsKind(nkTupleConstr)
  376. skipComment(p, a)
  377. optPar(p)
  378. eat(p, endTok)
  379. proc exprColonEqExprList(p: var TParser, kind: TNodeKind,
  380. endTok: TTokType): PNode =
  381. #| exprColonEqExprList = exprColonEqExpr (comma exprColonEqExpr)* (comma)?
  382. result = newNodeP(kind, p)
  383. exprColonEqExprListAux(p, endTok, result)
  384. proc dotExpr(p: var TParser, a: PNode): PNode =
  385. #| dotExpr = expr '.' optInd (symbol | '[:' exprList ']')
  386. #| explicitGenericInstantiation = '[:' exprList ']' ( '(' exprColonEqExpr ')' )?
  387. var info = p.parLineInfo
  388. getTok(p)
  389. result = newNodeI(nkDotExpr, info)
  390. optInd(p, result)
  391. result.add(a)
  392. result.add(parseSymbol(p, smAfterDot))
  393. if p.tok.tokType == tkBracketLeColon and p.tok.strongSpaceA <= 0:
  394. var x = newNodeI(nkBracketExpr, p.parLineInfo)
  395. # rewrite 'x.y[:z]()' to 'y[z](x)'
  396. x.add result[1]
  397. exprList(p, tkBracketRi, x)
  398. eat(p, tkBracketRi)
  399. var y = newNodeI(nkCall, p.parLineInfo)
  400. y.add x
  401. y.add result[0]
  402. if p.tok.tokType == tkParLe and p.tok.strongSpaceA <= 0:
  403. exprColonEqExprListAux(p, tkParRi, y)
  404. result = y
  405. proc qualifiedIdent(p: var TParser): PNode =
  406. #| qualifiedIdent = symbol ('.' optInd symbol)?
  407. result = parseSymbol(p)
  408. if p.tok.tokType == tkDot: result = dotExpr(p, result)
  409. proc setOrTableConstr(p: var TParser): PNode =
  410. #| setOrTableConstr = '{' ((exprColonEqExpr comma)* | ':' ) '}'
  411. result = newNodeP(nkCurly, p)
  412. getTok(p) # skip '{'
  413. optInd(p, result)
  414. if p.tok.tokType == tkColon:
  415. getTok(p) # skip ':'
  416. result.transitionSonsKind(nkTableConstr)
  417. else:
  418. # progress guaranteed
  419. while p.tok.tokType notin {tkCurlyRi, tkEof}:
  420. var a = exprColonEqExpr(p)
  421. if a.kind == nkExprColonExpr: result.transitionSonsKind(nkTableConstr)
  422. result.add(a)
  423. if p.tok.tokType != tkComma: break
  424. getTok(p)
  425. skipComment(p, a)
  426. optPar(p)
  427. eat(p, tkCurlyRi) # skip '}'
  428. proc parseCast(p: var TParser): PNode =
  429. #| castExpr = 'cast' '[' optInd typeDesc optPar ']' '(' optInd expr optPar ')'
  430. result = newNodeP(nkCast, p)
  431. getTok(p)
  432. eat(p, tkBracketLe)
  433. optInd(p, result)
  434. result.add(parseTypeDesc(p))
  435. optPar(p)
  436. eat(p, tkBracketRi)
  437. eat(p, tkParLe)
  438. optInd(p, result)
  439. result.add(parseExpr(p))
  440. optPar(p)
  441. eat(p, tkParRi)
  442. proc setBaseFlags(n: PNode, base: TNumericalBase) =
  443. case base
  444. of base10: discard
  445. of base2: incl(n.flags, nfBase2)
  446. of base8: incl(n.flags, nfBase8)
  447. of base16: incl(n.flags, nfBase16)
  448. proc parseGStrLit(p: var TParser, a: PNode): PNode =
  449. case p.tok.tokType
  450. of tkGStrLit:
  451. result = newNodeP(nkCallStrLit, p)
  452. result.add(a)
  453. result.add(newStrNodeP(nkRStrLit, p.tok.literal, p))
  454. getTok(p)
  455. of tkGTripleStrLit:
  456. result = newNodeP(nkCallStrLit, p)
  457. result.add(a)
  458. result.add(newStrNodeP(nkTripleStrLit, p.tok.literal, p))
  459. getTok(p)
  460. else:
  461. result = a
  462. proc complexOrSimpleStmt(p: var TParser): PNode
  463. proc simpleExpr(p: var TParser, mode = pmNormal): PNode
  464. proc semiStmtList(p: var TParser, result: PNode) =
  465. inc p.inSemiStmtList
  466. result.add(complexOrSimpleStmt(p))
  467. # progress guaranteed
  468. while p.tok.tokType == tkSemiColon:
  469. getTok(p)
  470. optInd(p, result)
  471. result.add(complexOrSimpleStmt(p))
  472. dec p.inSemiStmtList
  473. result.transitionSonsKind(nkStmtListExpr)
  474. proc parsePar(p: var TParser): PNode =
  475. #| parKeyw = 'discard' | 'include' | 'if' | 'while' | 'case' | 'try'
  476. #| | 'finally' | 'except' | 'for' | 'block' | 'const' | 'let'
  477. #| | 'when' | 'var' | 'mixin'
  478. #| par = '(' optInd
  479. #| ( &parKeyw complexOrSimpleStmt ^+ ';'
  480. #| | ';' complexOrSimpleStmt ^+ ';'
  481. #| | pragmaStmt
  482. #| | simpleExpr ( ('=' expr (';' complexOrSimpleStmt ^+ ';' )? )
  483. #| | (':' expr (',' exprColonEqExpr ^+ ',' )? ) ) )
  484. #| optPar ')'
  485. #
  486. # unfortunately it's ambiguous: (expr: expr) vs (exprStmt); however a
  487. # leading ';' could be used to enforce a 'stmt' context ...
  488. result = newNodeP(nkPar, p)
  489. getTok(p)
  490. optInd(p, result)
  491. flexComment(p, result)
  492. if p.tok.tokType in {tkDiscard, tkInclude, tkIf, tkWhile, tkCase,
  493. tkTry, tkDefer, tkFinally, tkExcept, tkBlock,
  494. tkConst, tkLet, tkWhen, tkVar, tkFor,
  495. tkMixin}:
  496. # XXX 'bind' used to be an expression, so we exclude it here;
  497. # tests/reject/tbind2 fails otherwise.
  498. semiStmtList(p, result)
  499. elif p.tok.tokType == tkSemiColon:
  500. # '(;' enforces 'stmt' context:
  501. getTok(p)
  502. optInd(p, result)
  503. semiStmtList(p, result)
  504. elif p.tok.tokType == tkCurlyDotLe:
  505. result.add(parseStmtPragma(p))
  506. elif p.tok.tokType != tkParRi:
  507. var a = simpleExpr(p)
  508. if p.tok.tokType == tkDo:
  509. result = postExprBlocks(p, a)
  510. elif p.tok.tokType == tkEquals:
  511. # special case: allow assignments
  512. let asgn = newNodeP(nkAsgn, p)
  513. getTok(p)
  514. optInd(p, result)
  515. let b = parseExpr(p)
  516. asgn.add a
  517. asgn.add b
  518. result.add(asgn)
  519. if p.tok.tokType == tkSemiColon:
  520. semiStmtList(p, result)
  521. elif p.tok.tokType == tkSemiColon:
  522. # stmt context:
  523. result.add(a)
  524. semiStmtList(p, result)
  525. else:
  526. a = colonOrEquals(p, a)
  527. result.add(a)
  528. if p.tok.tokType == tkComma:
  529. getTok(p)
  530. skipComment(p, a)
  531. # (1,) produces a tuple expression:
  532. if p.tok.tokType == tkParRi:
  533. result.transitionSonsKind(nkTupleConstr)
  534. # progress guaranteed
  535. while p.tok.tokType != tkParRi and p.tok.tokType != tkEof:
  536. var a = exprColonEqExpr(p)
  537. result.add(a)
  538. if p.tok.tokType != tkComma: break
  539. getTok(p)
  540. skipComment(p, a)
  541. optPar(p)
  542. eat(p, tkParRi)
  543. proc identOrLiteral(p: var TParser, mode: TPrimaryMode): PNode =
  544. #| literal = | INT_LIT | INT8_LIT | INT16_LIT | INT32_LIT | INT64_LIT
  545. #| | UINT_LIT | UINT8_LIT | UINT16_LIT | UINT32_LIT | UINT64_LIT
  546. #| | FLOAT_LIT | FLOAT32_LIT | FLOAT64_LIT
  547. #| | STR_LIT | RSTR_LIT | TRIPLESTR_LIT
  548. #| | CHAR_LIT
  549. #| | NIL
  550. #| generalizedLit = GENERALIZED_STR_LIT | GENERALIZED_TRIPLESTR_LIT
  551. #| identOrLiteral = generalizedLit | symbol | literal
  552. #| | par | arrayConstr | setOrTableConstr
  553. #| | castExpr
  554. #| tupleConstr = '(' optInd (exprColonEqExpr comma?)* optPar ')'
  555. #| arrayConstr = '[' optInd (exprColonEqExpr comma?)* optPar ']'
  556. case p.tok.tokType
  557. of tkSymbol, tkBuiltInMagics, tkOut:
  558. result = newIdentNodeP(p.tok.ident, p)
  559. getTok(p)
  560. result = parseGStrLit(p, result)
  561. of tkAccent:
  562. result = parseSymbol(p) # literals
  563. of tkIntLit:
  564. result = newIntNodeP(nkIntLit, p.tok.iNumber, p)
  565. setBaseFlags(result, p.tok.base)
  566. getTok(p)
  567. of tkInt8Lit:
  568. result = newIntNodeP(nkInt8Lit, p.tok.iNumber, p)
  569. setBaseFlags(result, p.tok.base)
  570. getTok(p)
  571. of tkInt16Lit:
  572. result = newIntNodeP(nkInt16Lit, p.tok.iNumber, p)
  573. setBaseFlags(result, p.tok.base)
  574. getTok(p)
  575. of tkInt32Lit:
  576. result = newIntNodeP(nkInt32Lit, p.tok.iNumber, p)
  577. setBaseFlags(result, p.tok.base)
  578. getTok(p)
  579. of tkInt64Lit:
  580. result = newIntNodeP(nkInt64Lit, p.tok.iNumber, p)
  581. setBaseFlags(result, p.tok.base)
  582. getTok(p)
  583. of tkUIntLit:
  584. result = newIntNodeP(nkUIntLit, p.tok.iNumber, p)
  585. setBaseFlags(result, p.tok.base)
  586. getTok(p)
  587. of tkUInt8Lit:
  588. result = newIntNodeP(nkUInt8Lit, p.tok.iNumber, p)
  589. setBaseFlags(result, p.tok.base)
  590. getTok(p)
  591. of tkUInt16Lit:
  592. result = newIntNodeP(nkUInt16Lit, p.tok.iNumber, p)
  593. setBaseFlags(result, p.tok.base)
  594. getTok(p)
  595. of tkUInt32Lit:
  596. result = newIntNodeP(nkUInt32Lit, p.tok.iNumber, p)
  597. setBaseFlags(result, p.tok.base)
  598. getTok(p)
  599. of tkUInt64Lit:
  600. result = newIntNodeP(nkUInt64Lit, p.tok.iNumber, p)
  601. setBaseFlags(result, p.tok.base)
  602. getTok(p)
  603. of tkFloatLit:
  604. result = newFloatNodeP(nkFloatLit, p.tok.fNumber, p)
  605. setBaseFlags(result, p.tok.base)
  606. getTok(p)
  607. of tkFloat32Lit:
  608. result = newFloatNodeP(nkFloat32Lit, p.tok.fNumber, p)
  609. setBaseFlags(result, p.tok.base)
  610. getTok(p)
  611. of tkFloat64Lit:
  612. result = newFloatNodeP(nkFloat64Lit, p.tok.fNumber, p)
  613. setBaseFlags(result, p.tok.base)
  614. getTok(p)
  615. of tkFloat128Lit:
  616. result = newFloatNodeP(nkFloat128Lit, p.tok.fNumber, p)
  617. setBaseFlags(result, p.tok.base)
  618. getTok(p)
  619. of tkStrLit:
  620. result = newStrNodeP(nkStrLit, p.tok.literal, p)
  621. getTok(p)
  622. of tkRStrLit:
  623. result = newStrNodeP(nkRStrLit, p.tok.literal, p)
  624. getTok(p)
  625. of tkTripleStrLit:
  626. result = newStrNodeP(nkTripleStrLit, p.tok.literal, p)
  627. getTok(p)
  628. of tkCharLit:
  629. result = newIntNodeP(nkCharLit, ord(p.tok.literal[0]), p)
  630. getTok(p)
  631. of tkNil:
  632. result = newNodeP(nkNilLit, p)
  633. getTok(p)
  634. of tkParLe:
  635. # () constructor
  636. if mode in {pmTypeDesc, pmTypeDef}:
  637. result = exprColonEqExprList(p, nkPar, tkParRi)
  638. else:
  639. result = parsePar(p)
  640. of tkCurlyLe:
  641. # {} constructor
  642. result = setOrTableConstr(p)
  643. of tkBracketLe:
  644. # [] constructor
  645. result = exprColonEqExprList(p, nkBracket, tkBracketRi)
  646. of tkCast:
  647. result = parseCast(p)
  648. else:
  649. parMessage(p, errExprExpected, p.tok)
  650. getTok(p) # we must consume a token here to prevent endless loops!
  651. result = p.emptyNode
  652. proc namedParams(p: var TParser, callee: PNode,
  653. kind: TNodeKind, endTok: TTokType): PNode =
  654. let a = callee
  655. result = newNodeP(kind, p)
  656. result.add(a)
  657. # progress guaranteed
  658. exprColonEqExprListAux(p, endTok, result)
  659. proc commandParam(p: var TParser, isFirstParam: var bool; mode: TPrimaryMode): PNode =
  660. if mode == pmTypeDesc:
  661. result = simpleExpr(p, mode)
  662. else:
  663. result = parseExpr(p)
  664. if p.tok.tokType == tkDo:
  665. result = postExprBlocks(p, result)
  666. elif p.tok.tokType == tkEquals and not isFirstParam:
  667. let lhs = result
  668. result = newNodeP(nkExprEqExpr, p)
  669. getTok(p)
  670. result.add(lhs)
  671. result.add(parseExpr(p))
  672. isFirstParam = false
  673. proc commandExpr(p: var TParser; r: PNode; mode: TPrimaryMode): PNode =
  674. result = newNodeP(nkCommand, p)
  675. result.add(r)
  676. var isFirstParam = true
  677. # progress NOT guaranteed
  678. p.hasProgress = false
  679. result.add commandParam(p, isFirstParam, mode)
  680. proc primarySuffix(p: var TParser, r: PNode,
  681. baseIndent: int, mode: TPrimaryMode): PNode =
  682. #| primarySuffix = '(' (exprColonEqExpr comma?)* ')'
  683. #| | '.' optInd symbol generalizedLit?
  684. #| | '[' optInd exprColonEqExprList optPar ']'
  685. #| | '{' optInd exprColonEqExprList optPar '}'
  686. #| | &( '`'|IDENT|literal|'cast'|'addr'|'type') expr # command syntax
  687. result = r
  688. # progress guaranteed
  689. while p.tok.indent < 0 or
  690. (p.tok.tokType == tkDot and p.tok.indent >= baseIndent):
  691. case p.tok.tokType
  692. of tkParLe:
  693. # progress guaranteed
  694. if p.tok.strongSpaceA > 0:
  695. # inside type sections, expressions such as `ref (int, bar)`
  696. # are parsed as a nkCommand with a single tuple argument (nkPar)
  697. if mode == pmTypeDef:
  698. result = newNodeP(nkCommand, p)
  699. result.add r
  700. result.add primary(p, pmNormal)
  701. else:
  702. result = commandExpr(p, result, mode)
  703. break
  704. result = namedParams(p, result, nkCall, tkParRi)
  705. if result.len > 1 and result[1].kind == nkExprColonExpr:
  706. result.transitionSonsKind(nkObjConstr)
  707. of tkDot:
  708. # progress guaranteed
  709. result = dotExpr(p, result)
  710. result = parseGStrLit(p, result)
  711. of tkBracketLe:
  712. # progress guaranteed
  713. if p.tok.strongSpaceA > 0:
  714. result = commandExpr(p, result, mode)
  715. break
  716. result = namedParams(p, result, nkBracketExpr, tkBracketRi)
  717. of tkCurlyLe:
  718. # progress guaranteed
  719. if p.tok.strongSpaceA > 0:
  720. result = commandExpr(p, result, mode)
  721. break
  722. result = namedParams(p, result, nkCurlyExpr, tkCurlyRi)
  723. of tkSymbol, tkAccent, tkIntLit..tkCharLit, tkNil, tkCast,
  724. tkOpr, tkDotDot, tkVar, tkOut, tkStatic, tkType, tkEnum, tkTuple,
  725. tkObject, tkProc:
  726. # XXX: In type sections we allow the free application of the
  727. # command syntax, with the exception of expressions such as
  728. # `foo ref` or `foo ptr`. Unfortunately, these two are also
  729. # used as infix operators for the memory regions feature and
  730. # the current parsing rules don't play well here.
  731. if p.inPragma == 0 and (isUnary(p) or p.tok.tokType notin {tkOpr, tkDotDot}):
  732. # actually parsing {.push hints:off.} as {.push(hints:off).} is a sweet
  733. # solution, but pragmas.nim can't handle that
  734. result = commandExpr(p, result, mode)
  735. break
  736. else:
  737. break
  738. proc parseOperators(p: var TParser, headNode: PNode,
  739. limit: int, mode: TPrimaryMode): PNode =
  740. result = headNode
  741. # expand while operators have priorities higher than 'limit'
  742. var opPrec = getPrecedence(p.tok, false)
  743. let modeB = if mode == pmTypeDef: pmTypeDesc else: mode
  744. # the operator itself must not start on a new line:
  745. # progress guaranteed
  746. while opPrec >= limit and p.tok.indent < 0 and not isUnary(p):
  747. checkBinary(p)
  748. var leftAssoc = 1-ord(isRightAssociative(p.tok))
  749. var a = newNodeP(nkInfix, p)
  750. var opNode = newIdentNodeP(p.tok.ident, p) # skip operator:
  751. getTok(p)
  752. flexComment(p, a)
  753. optPar(p)
  754. # read sub-expression with higher priority:
  755. var b = simpleExprAux(p, opPrec + leftAssoc, modeB)
  756. a.add(opNode)
  757. a.add(result)
  758. a.add(b)
  759. result = a
  760. opPrec = getPrecedence(p.tok, false)
  761. proc simpleExprAux(p: var TParser, limit: int, mode: TPrimaryMode): PNode =
  762. result = primary(p, mode)
  763. if p.tok.tokType == tkCurlyDotLe and (p.tok.indent < 0 or realInd(p)) and
  764. mode == pmNormal:
  765. var pragmaExp = newNodeP(nkPragmaExpr, p)
  766. pragmaExp.add result
  767. pragmaExp.add p.parsePragma
  768. result = pragmaExp
  769. result = parseOperators(p, result, limit, mode)
  770. proc simpleExpr(p: var TParser, mode = pmNormal): PNode =
  771. when defined(nimpretty):
  772. inc p.em.doIndentMore
  773. result = simpleExprAux(p, -1, mode)
  774. when defined(nimpretty):
  775. dec p.em.doIndentMore
  776. proc parseIfExpr(p: var TParser, kind: TNodeKind): PNode =
  777. #| condExpr = expr colcom expr optInd
  778. #| ('elif' expr colcom expr optInd)*
  779. #| 'else' colcom expr
  780. #| ifExpr = 'if' condExpr
  781. #| whenExpr = 'when' condExpr
  782. when true:
  783. result = newNodeP(kind, p)
  784. while true:
  785. getTok(p) # skip `if`, `when`, `elif`
  786. var branch = newNodeP(nkElifExpr, p)
  787. optInd(p, branch)
  788. branch.add(parseExpr(p))
  789. colcom(p, branch)
  790. branch.add(parseStmt(p))
  791. skipComment(p, branch)
  792. result.add(branch)
  793. if p.tok.tokType != tkElif: break # or not sameOrNoInd(p): break
  794. if p.tok.tokType == tkElse: # and sameOrNoInd(p):
  795. var branch = newNodeP(nkElseExpr, p)
  796. eat(p, tkElse)
  797. colcom(p, branch)
  798. branch.add(parseStmt(p))
  799. result.add(branch)
  800. else:
  801. var
  802. b: PNode
  803. wasIndented = false
  804. result = newNodeP(kind, p)
  805. getTok(p)
  806. let branch = newNodeP(nkElifExpr, p)
  807. branch.add(parseExpr(p))
  808. colcom(p, branch)
  809. let oldInd = p.currInd
  810. if realInd(p):
  811. p.currInd = p.tok.indent
  812. wasIndented = true
  813. branch.add(parseExpr(p))
  814. result.add branch
  815. while sameInd(p) or not wasIndented:
  816. case p.tok.tokType
  817. of tkElif:
  818. b = newNodeP(nkElifExpr, p)
  819. getTok(p)
  820. optInd(p, b)
  821. b.add(parseExpr(p))
  822. of tkElse:
  823. b = newNodeP(nkElseExpr, p)
  824. getTok(p)
  825. else: break
  826. colcom(p, b)
  827. b.add(parseStmt(p))
  828. result.add(b)
  829. if b.kind == nkElseExpr: break
  830. if wasIndented:
  831. p.currInd = oldInd
  832. proc parsePragma(p: var TParser): PNode =
  833. #| pragma = '{.' optInd (exprColonEqExpr comma?)* optPar ('.}' | '}')
  834. result = newNodeP(nkPragma, p)
  835. inc p.inPragma
  836. when defined(nimpretty):
  837. inc p.em.doIndentMore
  838. inc p.em.keepIndents
  839. getTok(p)
  840. optInd(p, result)
  841. while p.tok.tokType notin {tkCurlyDotRi, tkCurlyRi, tkEof}:
  842. p.hasProgress = false
  843. var a = exprColonEqExpr(p)
  844. if not p.hasProgress: break
  845. result.add(a)
  846. if p.tok.tokType == tkComma:
  847. getTok(p)
  848. skipComment(p, a)
  849. optPar(p)
  850. if p.tok.tokType in {tkCurlyDotRi, tkCurlyRi}:
  851. when defined(nimpretty):
  852. if p.tok.tokType == tkCurlyRi: curlyRiWasPragma(p.em)
  853. getTok(p)
  854. else:
  855. parMessage(p, "expected '.}'")
  856. dec p.inPragma
  857. when defined(nimpretty):
  858. dec p.em.doIndentMore
  859. dec p.em.keepIndents
  860. proc identVis(p: var TParser; allowDot=false): PNode =
  861. #| identVis = symbol OPR? # postfix position
  862. #| identVisDot = symbol '.' optInd symbol OPR?
  863. var a = parseSymbol(p)
  864. if p.tok.tokType == tkOpr:
  865. when defined(nimpretty):
  866. starWasExportMarker(p.em)
  867. result = newNodeP(nkPostfix, p)
  868. result.add(newIdentNodeP(p.tok.ident, p))
  869. result.add(a)
  870. getTok(p)
  871. elif p.tok.tokType == tkDot and allowDot:
  872. result = dotExpr(p, a)
  873. else:
  874. result = a
  875. proc identWithPragma(p: var TParser; allowDot=false): PNode =
  876. #| identWithPragma = identVis pragma?
  877. #| identWithPragmaDot = identVisDot pragma?
  878. var a = identVis(p, allowDot)
  879. if p.tok.tokType == tkCurlyDotLe:
  880. result = newNodeP(nkPragmaExpr, p)
  881. result.add(a)
  882. result.add(parsePragma(p))
  883. else:
  884. result = a
  885. type
  886. TDeclaredIdentFlag = enum
  887. withPragma, # identifier may have pragma
  888. withBothOptional # both ':' and '=' parts are optional
  889. withDot # allow 'var ident.ident = value'
  890. TDeclaredIdentFlags = set[TDeclaredIdentFlag]
  891. proc parseIdentColonEquals(p: var TParser, flags: TDeclaredIdentFlags): PNode =
  892. #| declColonEquals = identWithPragma (comma identWithPragma)* comma?
  893. #| (':' optInd typeDesc)? ('=' optInd expr)?
  894. #| identColonEquals = IDENT (comma IDENT)* comma?
  895. #| (':' optInd typeDesc)? ('=' optInd expr)?)
  896. var a: PNode
  897. result = newNodeP(nkIdentDefs, p)
  898. # progress guaranteed
  899. while true:
  900. case p.tok.tokType
  901. of tkSymbol, tkAccent:
  902. if withPragma in flags: a = identWithPragma(p, allowDot=withDot in flags)
  903. else: a = parseSymbol(p)
  904. if a.kind == nkEmpty: return
  905. else: break
  906. result.add(a)
  907. if p.tok.tokType != tkComma: break
  908. getTok(p)
  909. optInd(p, a)
  910. if p.tok.tokType == tkColon:
  911. getTok(p)
  912. optInd(p, result)
  913. result.add(parseTypeDesc(p))
  914. else:
  915. result.add(newNodeP(nkEmpty, p))
  916. if p.tok.tokType != tkEquals and withBothOptional notin flags:
  917. parMessage(p, "':' or '=' expected, but got '$1'", p.tok)
  918. if p.tok.tokType == tkEquals:
  919. getTok(p)
  920. optInd(p, result)
  921. result.add(parseExpr(p))
  922. else:
  923. result.add(newNodeP(nkEmpty, p))
  924. proc parseTuple(p: var TParser, indentAllowed = false): PNode =
  925. #| inlTupleDecl = 'tuple'
  926. #| '[' optInd (identColonEquals (comma/semicolon)?)* optPar ']'
  927. #| extTupleDecl = 'tuple'
  928. #| COMMENT? (IND{>} identColonEquals (IND{=} identColonEquals)*)?
  929. #| tupleClass = 'tuple'
  930. result = newNodeP(nkTupleTy, p)
  931. getTok(p)
  932. if p.tok.tokType == tkBracketLe:
  933. getTok(p)
  934. optInd(p, result)
  935. # progress guaranteed
  936. while p.tok.tokType in {tkSymbol, tkAccent}:
  937. var a = parseIdentColonEquals(p, {})
  938. result.add(a)
  939. if p.tok.tokType notin {tkComma, tkSemiColon}: break
  940. when defined(nimpretty):
  941. commaWasSemicolon(p.em)
  942. getTok(p)
  943. skipComment(p, a)
  944. optPar(p)
  945. eat(p, tkBracketRi)
  946. elif indentAllowed:
  947. skipComment(p, result)
  948. if realInd(p):
  949. withInd(p):
  950. rawSkipComment(p, result)
  951. # progress guaranteed
  952. while true:
  953. case p.tok.tokType
  954. of tkSymbol, tkAccent:
  955. var a = parseIdentColonEquals(p, {})
  956. if p.tok.indent < 0 or p.tok.indent >= p.currInd:
  957. rawSkipComment(p, a)
  958. result.add(a)
  959. of tkEof: break
  960. else:
  961. parMessage(p, errIdentifierExpected, p.tok)
  962. break
  963. if not sameInd(p): break
  964. elif p.tok.tokType == tkParLe:
  965. parMessage(p, errGenerated, "the syntax for tuple types is 'tuple[...]', not 'tuple(...)'")
  966. else:
  967. result = newNodeP(nkTupleClassTy, p)
  968. proc parseParamList(p: var TParser, retColon = true): PNode =
  969. #| paramList = '(' declColonEquals ^* (comma/semicolon) ')'
  970. #| paramListArrow = paramList? ('->' optInd typeDesc)?
  971. #| paramListColon = paramList? (':' optInd typeDesc)?
  972. var a: PNode
  973. result = newNodeP(nkFormalParams, p)
  974. result.add(p.emptyNode) # return type
  975. when defined(nimpretty):
  976. inc p.em.doIndentMore
  977. inc p.em.keepIndents
  978. let hasParLe = p.tok.tokType == tkParLe and p.tok.indent < 0
  979. if hasParLe:
  980. getTok(p)
  981. optInd(p, result)
  982. # progress guaranteed
  983. while true:
  984. case p.tok.tokType
  985. of tkSymbol, tkAccent:
  986. a = parseIdentColonEquals(p, {withBothOptional, withPragma})
  987. of tkParRi:
  988. break
  989. of tkVar:
  990. parMessage(p, errGenerated, "the syntax is 'parameter: var T', not 'var parameter: T'")
  991. break
  992. else:
  993. parMessage(p, "expected closing ')'")
  994. break
  995. result.add(a)
  996. if p.tok.tokType notin {tkComma, tkSemiColon}: break
  997. when defined(nimpretty):
  998. commaWasSemicolon(p.em)
  999. getTok(p)
  1000. skipComment(p, a)
  1001. optPar(p)
  1002. eat(p, tkParRi)
  1003. let hasRet = if retColon: p.tok.tokType == tkColon
  1004. else: p.tok.tokType == tkOpr and p.tok.ident.s == "->"
  1005. if hasRet and p.tok.indent < 0:
  1006. getTok(p)
  1007. optInd(p, result)
  1008. result[0] = parseTypeDesc(p)
  1009. elif not retColon and not hasParLe:
  1010. # Mark as "not there" in order to mark for deprecation in the semantic pass:
  1011. result = p.emptyNode
  1012. when defined(nimpretty):
  1013. dec p.em.doIndentMore
  1014. dec p.em.keepIndents
  1015. proc optPragmas(p: var TParser): PNode =
  1016. if p.tok.tokType == tkCurlyDotLe and (p.tok.indent < 0 or realInd(p)):
  1017. result = parsePragma(p)
  1018. else:
  1019. result = p.emptyNode
  1020. proc parseDoBlock(p: var TParser; info: TLineInfo): PNode =
  1021. #| doBlock = 'do' paramListArrow pragma? colcom stmt
  1022. let params = parseParamList(p, retColon=false)
  1023. let pragmas = optPragmas(p)
  1024. colcom(p, result)
  1025. result = parseStmt(p)
  1026. if params.kind != nkEmpty:
  1027. result = newProcNode(nkDo, info,
  1028. body = result, params = params, name = p.emptyNode, pattern = p.emptyNode,
  1029. genericParams = p.emptyNode, pragmas = pragmas, exceptions = p.emptyNode)
  1030. proc parseProcExpr(p: var TParser; isExpr: bool; kind: TNodeKind): PNode =
  1031. #| procExpr = 'proc' paramListColon pragma? ('=' COMMENT? stmt)?
  1032. # either a proc type or a anonymous proc
  1033. let info = parLineInfo(p)
  1034. getTok(p)
  1035. let hasSignature = p.tok.tokType in {tkParLe, tkColon} and p.tok.indent < 0
  1036. let params = parseParamList(p)
  1037. let pragmas = optPragmas(p)
  1038. if p.tok.tokType == tkEquals and isExpr:
  1039. getTok(p)
  1040. skipComment(p, result)
  1041. result = newProcNode(kind, info, body = parseStmt(p),
  1042. params = params, name = p.emptyNode, pattern = p.emptyNode,
  1043. genericParams = p.emptyNode, pragmas = pragmas, exceptions = p.emptyNode)
  1044. else:
  1045. result = newNodeI(nkProcTy, info)
  1046. if hasSignature:
  1047. result.add(params)
  1048. if kind == nkFuncDef:
  1049. parMessage(p, "func keyword is not allowed in type descriptions, use proc with {.noSideEffect.} pragma instead")
  1050. result.add(pragmas)
  1051. proc isExprStart(p: TParser): bool =
  1052. case p.tok.tokType
  1053. of tkSymbol, tkAccent, tkOpr, tkNot, tkNil, tkCast, tkIf, tkFor,
  1054. tkProc, tkFunc, tkIterator, tkBind, tkBuiltInMagics,
  1055. tkParLe, tkBracketLe, tkCurlyLe, tkIntLit..tkCharLit, tkVar, tkRef, tkPtr,
  1056. tkTuple, tkObject, tkWhen, tkCase, tkOut:
  1057. result = true
  1058. else: result = false
  1059. proc parseSymbolList(p: var TParser, result: PNode) =
  1060. # progress guaranteed
  1061. while true:
  1062. var s = parseSymbol(p, smAllowNil)
  1063. if s.kind == nkEmpty: break
  1064. result.add(s)
  1065. if p.tok.tokType != tkComma: break
  1066. getTok(p)
  1067. optInd(p, s)
  1068. proc parseTypeDescKAux(p: var TParser, kind: TNodeKind,
  1069. mode: TPrimaryMode): PNode =
  1070. #| distinct = 'distinct' optInd typeDesc
  1071. result = newNodeP(kind, p)
  1072. getTok(p)
  1073. if p.tok.indent != -1 and p.tok.indent <= p.currInd: return
  1074. optInd(p, result)
  1075. if not isOperator(p.tok) and isExprStart(p):
  1076. result.add(primary(p, mode))
  1077. if kind == nkDistinctTy and p.tok.tokType == tkSymbol:
  1078. # XXX document this feature!
  1079. var nodeKind: TNodeKind
  1080. if p.tok.ident.s == "with":
  1081. nodeKind = nkWith
  1082. elif p.tok.ident.s == "without":
  1083. nodeKind = nkWithout
  1084. else:
  1085. return result
  1086. getTok(p)
  1087. let list = newNodeP(nodeKind, p)
  1088. result.add list
  1089. parseSymbolList(p, list)
  1090. proc parseVarTuple(p: var TParser): PNode
  1091. proc parseFor(p: var TParser): PNode =
  1092. #| forStmt = 'for' (identWithPragma ^+ comma) 'in' expr colcom stmt
  1093. #| forExpr = forStmt
  1094. getTokNoInd(p)
  1095. result = newNodeP(nkForStmt, p)
  1096. if p.tok.tokType == tkParLe:
  1097. result.add(parseVarTuple(p))
  1098. else:
  1099. var a = identWithPragma(p)
  1100. result.add(a)
  1101. while p.tok.tokType == tkComma:
  1102. getTok(p)
  1103. optInd(p, a)
  1104. if p.tok.tokType == tkParLe:
  1105. result.add(parseVarTuple(p))
  1106. break
  1107. a = identWithPragma(p)
  1108. result.add(a)
  1109. eat(p, tkIn)
  1110. result.add(parseExpr(p))
  1111. colcom(p, result)
  1112. result.add(parseStmt(p))
  1113. template nimprettyDontTouch(body) =
  1114. when defined(nimpretty):
  1115. inc p.em.keepIndents
  1116. body
  1117. when defined(nimpretty):
  1118. dec p.em.keepIndents
  1119. proc parseExpr(p: var TParser): PNode =
  1120. #| expr = (blockExpr
  1121. #| | ifExpr
  1122. #| | whenExpr
  1123. #| | caseStmt
  1124. #| | forExpr
  1125. #| | tryExpr)
  1126. #| / simpleExpr
  1127. case p.tok.tokType
  1128. of tkBlock:
  1129. nimprettyDontTouch:
  1130. result = parseBlock(p)
  1131. of tkIf:
  1132. nimprettyDontTouch:
  1133. result = parseIfExpr(p, nkIfExpr)
  1134. of tkFor:
  1135. nimprettyDontTouch:
  1136. result = parseFor(p)
  1137. of tkWhen:
  1138. nimprettyDontTouch:
  1139. result = parseIfExpr(p, nkWhenExpr)
  1140. of tkCase:
  1141. # Currently we think nimpretty is good enough with case expressions,
  1142. # so it is allowed to touch them:
  1143. #nimprettyDontTouch:
  1144. result = parseCase(p)
  1145. of tkTry:
  1146. nimprettyDontTouch:
  1147. result = parseTry(p, isExpr=true)
  1148. else: result = simpleExpr(p)
  1149. proc parseEnum(p: var TParser): PNode
  1150. proc parseObject(p: var TParser): PNode
  1151. proc parseTypeClass(p: var TParser): PNode
  1152. proc primary(p: var TParser, mode: TPrimaryMode): PNode =
  1153. #| typeKeyw = 'var' | 'out' | 'ref' | 'ptr' | 'shared' | 'tuple'
  1154. #| | 'proc' | 'iterator' | 'distinct' | 'object' | 'enum'
  1155. #| primary = typeKeyw optInd typeDesc
  1156. #| / prefixOperator* identOrLiteral primarySuffix*
  1157. #| / 'bind' primary
  1158. if isOperator(p.tok):
  1159. let isSigil = isSigilLike(p.tok)
  1160. result = newNodeP(nkPrefix, p)
  1161. var a = newIdentNodeP(p.tok.ident, p)
  1162. result.add(a)
  1163. getTok(p)
  1164. optInd(p, a)
  1165. if isSigil:
  1166. #XXX prefix operators
  1167. let baseInd = p.lex.currLineIndent
  1168. result.add(primary(p, pmSkipSuffix))
  1169. result = primarySuffix(p, result, baseInd, mode)
  1170. else:
  1171. result.add(primary(p, pmNormal))
  1172. return
  1173. case p.tok.tokType
  1174. of tkTuple: result = parseTuple(p, mode == pmTypeDef)
  1175. of tkProc: result = parseProcExpr(p, mode notin {pmTypeDesc, pmTypeDef}, nkLambda)
  1176. of tkFunc: result = parseProcExpr(p, mode notin {pmTypeDesc, pmTypeDef}, nkFuncDef)
  1177. of tkIterator:
  1178. result = parseProcExpr(p, mode notin {pmTypeDesc, pmTypeDef}, nkLambda)
  1179. if result.kind == nkLambda: result.transitionSonsKind(nkIteratorDef)
  1180. else: result.transitionSonsKind(nkIteratorTy)
  1181. of tkEnum:
  1182. if mode == pmTypeDef:
  1183. prettySection:
  1184. result = parseEnum(p)
  1185. else:
  1186. result = newNodeP(nkEnumTy, p)
  1187. getTok(p)
  1188. of tkObject:
  1189. if mode == pmTypeDef:
  1190. prettySection:
  1191. result = parseObject(p)
  1192. else:
  1193. result = newNodeP(nkObjectTy, p)
  1194. getTok(p)
  1195. of tkConcept:
  1196. if mode == pmTypeDef:
  1197. result = parseTypeClass(p)
  1198. else:
  1199. parMessage(p, "the 'concept' keyword is only valid in 'type' sections")
  1200. of tkBind:
  1201. result = newNodeP(nkBind, p)
  1202. getTok(p)
  1203. optInd(p, result)
  1204. result.add(primary(p, pmNormal))
  1205. of tkVar: result = parseTypeDescKAux(p, nkVarTy, mode)
  1206. of tkOut:
  1207. # I like this parser extension to be in 1.4 as it still might turn out
  1208. # useful in the long run.
  1209. result = parseTypeDescKAux(p, nkMutableTy, mode)
  1210. of tkRef: result = parseTypeDescKAux(p, nkRefTy, mode)
  1211. of tkPtr: result = parseTypeDescKAux(p, nkPtrTy, mode)
  1212. of tkDistinct: result = parseTypeDescKAux(p, nkDistinctTy, mode)
  1213. else:
  1214. let baseInd = p.lex.currLineIndent
  1215. result = identOrLiteral(p, mode)
  1216. if mode != pmSkipSuffix:
  1217. result = primarySuffix(p, result, baseInd, mode)
  1218. proc binaryNot(p: var TParser; a: PNode): PNode =
  1219. if p.tok.tokType == tkNot:
  1220. let notOpr = newIdentNodeP(p.tok.ident, p)
  1221. getTok(p)
  1222. optInd(p, notOpr)
  1223. let b = parseExpr(p)
  1224. result = newNodeP(nkInfix, p)
  1225. result.add notOpr
  1226. result.add a
  1227. result.add b
  1228. else:
  1229. result = a
  1230. proc parseTypeDesc(p: var TParser): PNode =
  1231. #| typeDesc = simpleExpr ('not' expr)?
  1232. newlineWasSplitting(p)
  1233. result = simpleExpr(p, pmTypeDesc)
  1234. result = binaryNot(p, result)
  1235. proc parseTypeDefAux(p: var TParser): PNode =
  1236. #| typeDefAux = simpleExpr ('not' expr)?
  1237. #| | 'concept' typeClass
  1238. result = simpleExpr(p, pmTypeDef)
  1239. result = binaryNot(p, result)
  1240. proc makeCall(n: PNode): PNode =
  1241. ## Creates a call if the given node isn't already a call.
  1242. if n.kind in nkCallKinds:
  1243. result = n
  1244. else:
  1245. result = newNodeI(nkCall, n.info)
  1246. result.add n
  1247. proc postExprBlocks(p: var TParser, x: PNode): PNode =
  1248. #| postExprBlocks = ':' stmt? ( IND{=} doBlock
  1249. #| | IND{=} 'of' exprList ':' stmt
  1250. #| | IND{=} 'elif' expr ':' stmt
  1251. #| | IND{=} 'except' exprList ':' stmt
  1252. #| | IND{=} 'else' ':' stmt )*
  1253. result = x
  1254. if p.tok.indent >= 0: return
  1255. var
  1256. openingParams = p.emptyNode
  1257. openingPragmas = p.emptyNode
  1258. if p.tok.tokType == tkDo:
  1259. getTok(p)
  1260. openingParams = parseParamList(p, retColon=false)
  1261. openingPragmas = optPragmas(p)
  1262. if p.tok.tokType == tkColon:
  1263. result = makeCall(result)
  1264. getTok(p)
  1265. skipComment(p, result)
  1266. if p.tok.tokType notin {tkOf, tkElif, tkElse, tkExcept}:
  1267. var stmtList = newNodeP(nkStmtList, p)
  1268. stmtList.add parseStmt(p)
  1269. # to keep backwards compatibility (see tests/vm/tstringnil)
  1270. if stmtList[0].kind == nkStmtList: stmtList = stmtList[0]
  1271. stmtList.flags.incl nfBlockArg
  1272. if openingParams.kind != nkEmpty:
  1273. result.add newProcNode(nkDo, stmtList.info, body = stmtList,
  1274. params = openingParams,
  1275. name = p.emptyNode, pattern = p.emptyNode,
  1276. genericParams = p.emptyNode,
  1277. pragmas = openingPragmas,
  1278. exceptions = p.emptyNode)
  1279. else:
  1280. result.add stmtList
  1281. while sameInd(p):
  1282. var nextBlock: PNode
  1283. let nextToken = p.tok.tokType
  1284. if nextToken == tkDo:
  1285. let info = parLineInfo(p)
  1286. getTok(p)
  1287. nextBlock = parseDoBlock(p, info)
  1288. else:
  1289. case nextToken
  1290. of tkOf:
  1291. nextBlock = newNodeP(nkOfBranch, p)
  1292. exprList(p, tkColon, nextBlock)
  1293. of tkElif:
  1294. nextBlock = newNodeP(nkElifBranch, p)
  1295. getTok(p)
  1296. optInd(p, nextBlock)
  1297. nextBlock.add parseExpr(p)
  1298. of tkExcept:
  1299. nextBlock = newNodeP(nkExceptBranch, p)
  1300. exprList(p, tkColon, nextBlock)
  1301. of tkElse:
  1302. nextBlock = newNodeP(nkElse, p)
  1303. getTok(p)
  1304. else: break
  1305. eat(p, tkColon)
  1306. nextBlock.add parseStmt(p)
  1307. nextBlock.flags.incl nfBlockArg
  1308. result.add nextBlock
  1309. if nextBlock.kind == nkElse: break
  1310. else:
  1311. if openingParams.kind != nkEmpty:
  1312. parMessage(p, "expected ':'")
  1313. proc parseExprStmt(p: var TParser): PNode =
  1314. #| exprStmt = simpleExpr
  1315. #| (( '=' optInd expr colonBody? )
  1316. #| / ( expr ^+ comma
  1317. #| postExprBlocks
  1318. #| ))?
  1319. var a = simpleExpr(p)
  1320. if p.tok.tokType == tkEquals:
  1321. result = newNodeP(nkAsgn, p)
  1322. getTok(p)
  1323. optInd(p, result)
  1324. var b = parseExpr(p)
  1325. b = postExprBlocks(p, b)
  1326. result.add(a)
  1327. result.add(b)
  1328. else:
  1329. # simpleExpr parsed 'p a' from 'p a, b'?
  1330. var isFirstParam = false
  1331. if p.tok.indent < 0 and p.tok.tokType == tkComma and a.kind == nkCommand:
  1332. result = a
  1333. while true:
  1334. getTok(p)
  1335. optInd(p, result)
  1336. result.add(commandParam(p, isFirstParam, pmNormal))
  1337. if p.tok.tokType != tkComma: break
  1338. elif p.tok.indent < 0 and isExprStart(p):
  1339. result = newNode(nkCommand, a.info, @[a])
  1340. while true:
  1341. result.add(commandParam(p, isFirstParam, pmNormal))
  1342. if p.tok.tokType != tkComma: break
  1343. getTok(p)
  1344. optInd(p, result)
  1345. else:
  1346. result = a
  1347. result = postExprBlocks(p, result)
  1348. proc parseModuleName(p: var TParser, kind: TNodeKind): PNode =
  1349. result = parseExpr(p)
  1350. when false:
  1351. # parseExpr already handles 'as' syntax ...
  1352. if p.tok.tokType == tkAs and kind == nkImportStmt:
  1353. let a = result
  1354. result = newNodeP(nkImportAs, p)
  1355. getTok(p)
  1356. result.add(a)
  1357. result.add(parseExpr(p))
  1358. proc parseImport(p: var TParser, kind: TNodeKind): PNode =
  1359. #| importStmt = 'import' optInd expr
  1360. #| ((comma expr)*
  1361. #| / 'except' optInd (expr ^+ comma))
  1362. #| exportStmt = 'export' optInd expr
  1363. #| ((comma expr)*
  1364. #| / 'except' optInd (expr ^+ comma))
  1365. result = newNodeP(kind, p)
  1366. getTok(p) # skip `import` or `export`
  1367. optInd(p, result)
  1368. var a = parseModuleName(p, kind)
  1369. result.add(a)
  1370. if p.tok.tokType in {tkComma, tkExcept}:
  1371. if p.tok.tokType == tkExcept:
  1372. result.transitionSonsKind(succ(kind))
  1373. getTok(p)
  1374. optInd(p, result)
  1375. while true:
  1376. # was: while p.tok.tokType notin {tkEof, tkSad, tkDed}:
  1377. p.hasProgress = false
  1378. a = parseModuleName(p, kind)
  1379. if a.kind == nkEmpty or not p.hasProgress: break
  1380. result.add(a)
  1381. if p.tok.tokType != tkComma: break
  1382. getTok(p)
  1383. optInd(p, a)
  1384. #expectNl(p)
  1385. proc parseIncludeStmt(p: var TParser): PNode =
  1386. #| includeStmt = 'include' optInd expr ^+ comma
  1387. result = newNodeP(nkIncludeStmt, p)
  1388. getTok(p) # skip `import` or `include`
  1389. optInd(p, result)
  1390. while true:
  1391. # was: while p.tok.tokType notin {tkEof, tkSad, tkDed}:
  1392. p.hasProgress = false
  1393. var a = parseExpr(p)
  1394. if a.kind == nkEmpty or not p.hasProgress: break
  1395. result.add(a)
  1396. if p.tok.tokType != tkComma: break
  1397. getTok(p)
  1398. optInd(p, a)
  1399. #expectNl(p)
  1400. proc parseFromStmt(p: var TParser): PNode =
  1401. #| fromStmt = 'from' expr 'import' optInd expr (comma expr)*
  1402. result = newNodeP(nkFromStmt, p)
  1403. getTok(p) # skip `from`
  1404. optInd(p, result)
  1405. var a = parseModuleName(p, nkImportStmt)
  1406. result.add(a) #optInd(p, a);
  1407. eat(p, tkImport)
  1408. optInd(p, result)
  1409. while true:
  1410. # p.tok.tokType notin {tkEof, tkSad, tkDed}:
  1411. p.hasProgress = false
  1412. a = parseExpr(p)
  1413. if a.kind == nkEmpty or not p.hasProgress: break
  1414. result.add(a)
  1415. if p.tok.tokType != tkComma: break
  1416. getTok(p)
  1417. optInd(p, a)
  1418. #expectNl(p)
  1419. proc parseReturnOrRaise(p: var TParser, kind: TNodeKind): PNode =
  1420. #| returnStmt = 'return' optInd expr?
  1421. #| raiseStmt = 'raise' optInd expr?
  1422. #| yieldStmt = 'yield' optInd expr?
  1423. #| discardStmt = 'discard' optInd expr?
  1424. #| breakStmt = 'break' optInd expr?
  1425. #| continueStmt = 'break' optInd expr?
  1426. result = newNodeP(kind, p)
  1427. getTok(p)
  1428. if p.tok.tokType == tkComment:
  1429. skipComment(p, result)
  1430. result.add(p.emptyNode)
  1431. elif p.tok.indent >= 0 and p.tok.indent <= p.currInd or not isExprStart(p):
  1432. # NL terminates:
  1433. result.add(p.emptyNode)
  1434. # nimpretty here!
  1435. else:
  1436. var e = parseExpr(p)
  1437. e = postExprBlocks(p, e)
  1438. result.add(e)
  1439. proc parseIfOrWhen(p: var TParser, kind: TNodeKind): PNode =
  1440. #| condStmt = expr colcom stmt COMMENT?
  1441. #| (IND{=} 'elif' expr colcom stmt)*
  1442. #| (IND{=} 'else' colcom stmt)?
  1443. #| ifStmt = 'if' condStmt
  1444. #| whenStmt = 'when' condStmt
  1445. result = newNodeP(kind, p)
  1446. while true:
  1447. getTok(p) # skip `if`, `when`, `elif`
  1448. var branch = newNodeP(nkElifBranch, p)
  1449. optInd(p, branch)
  1450. branch.add(parseExpr(p))
  1451. colcom(p, branch)
  1452. branch.add(parseStmt(p))
  1453. skipComment(p, branch)
  1454. result.add(branch)
  1455. if p.tok.tokType != tkElif or not sameOrNoInd(p): break
  1456. if p.tok.tokType == tkElse and sameOrNoInd(p):
  1457. var branch = newNodeP(nkElse, p)
  1458. eat(p, tkElse)
  1459. colcom(p, branch)
  1460. branch.add(parseStmt(p))
  1461. result.add(branch)
  1462. proc parseWhile(p: var TParser): PNode =
  1463. #| whileStmt = 'while' expr colcom stmt
  1464. result = newNodeP(nkWhileStmt, p)
  1465. getTok(p)
  1466. optInd(p, result)
  1467. result.add(parseExpr(p))
  1468. colcom(p, result)
  1469. result.add(parseStmt(p))
  1470. proc parseCase(p: var TParser): PNode =
  1471. #| ofBranch = 'of' exprList colcom stmt
  1472. #| ofBranches = ofBranch (IND{=} ofBranch)*
  1473. #| (IND{=} 'elif' expr colcom stmt)*
  1474. #| (IND{=} 'else' colcom stmt)?
  1475. #| caseStmt = 'case' expr ':'? COMMENT?
  1476. #| (IND{>} ofBranches DED
  1477. #| | IND{=} ofBranches)
  1478. var
  1479. b: PNode
  1480. inElif = false
  1481. wasIndented = false
  1482. result = newNodeP(nkCaseStmt, p)
  1483. getTok(p)
  1484. result.add(parseExpr(p))
  1485. if p.tok.tokType == tkColon: getTok(p)
  1486. skipComment(p, result)
  1487. let oldInd = p.currInd
  1488. if realInd(p):
  1489. p.currInd = p.tok.indent
  1490. wasIndented = true
  1491. while sameInd(p):
  1492. case p.tok.tokType
  1493. of tkOf:
  1494. if inElif: break
  1495. b = newNodeP(nkOfBranch, p)
  1496. exprList(p, tkColon, b)
  1497. of tkElif:
  1498. inElif = true
  1499. b = newNodeP(nkElifBranch, p)
  1500. getTok(p)
  1501. optInd(p, b)
  1502. b.add(parseExpr(p))
  1503. of tkElse:
  1504. b = newNodeP(nkElse, p)
  1505. getTok(p)
  1506. else: break
  1507. colcom(p, b)
  1508. b.add(parseStmt(p))
  1509. result.add(b)
  1510. if b.kind == nkElse: break
  1511. if wasIndented:
  1512. p.currInd = oldInd
  1513. proc parseTry(p: var TParser; isExpr: bool): PNode =
  1514. #| tryStmt = 'try' colcom stmt &(IND{=}? 'except'|'finally')
  1515. #| (IND{=}? 'except' exprList colcom stmt)*
  1516. #| (IND{=}? 'finally' colcom stmt)?
  1517. #| tryExpr = 'try' colcom stmt &(optInd 'except'|'finally')
  1518. #| (optInd 'except' exprList colcom stmt)*
  1519. #| (optInd 'finally' colcom stmt)?
  1520. result = newNodeP(nkTryStmt, p)
  1521. getTok(p)
  1522. colcom(p, result)
  1523. result.add(parseStmt(p))
  1524. var b: PNode = nil
  1525. while sameOrNoInd(p) or isExpr:
  1526. case p.tok.tokType
  1527. of tkExcept:
  1528. b = newNodeP(nkExceptBranch, p)
  1529. exprList(p, tkColon, b)
  1530. of tkFinally:
  1531. b = newNodeP(nkFinally, p)
  1532. getTok(p)
  1533. else: break
  1534. colcom(p, b)
  1535. b.add(parseStmt(p))
  1536. result.add(b)
  1537. if b == nil: parMessage(p, "expected 'except'")
  1538. proc parseExceptBlock(p: var TParser, kind: TNodeKind): PNode =
  1539. #| exceptBlock = 'except' colcom stmt
  1540. result = newNodeP(kind, p)
  1541. getTok(p)
  1542. colcom(p, result)
  1543. result.add(parseStmt(p))
  1544. proc parseBlock(p: var TParser): PNode =
  1545. #| blockStmt = 'block' symbol? colcom stmt
  1546. #| blockExpr = 'block' symbol? colcom stmt
  1547. result = newNodeP(nkBlockStmt, p)
  1548. getTokNoInd(p)
  1549. if p.tok.tokType == tkColon: result.add(p.emptyNode)
  1550. else: result.add(parseSymbol(p))
  1551. colcom(p, result)
  1552. result.add(parseStmt(p))
  1553. proc parseStaticOrDefer(p: var TParser; k: TNodeKind): PNode =
  1554. #| staticStmt = 'static' colcom stmt
  1555. #| deferStmt = 'defer' colcom stmt
  1556. result = newNodeP(k, p)
  1557. getTok(p)
  1558. colcom(p, result)
  1559. result.add(parseStmt(p))
  1560. proc parseAsm(p: var TParser): PNode =
  1561. #| asmStmt = 'asm' pragma? (STR_LIT | RSTR_LIT | TRIPLESTR_LIT)
  1562. result = newNodeP(nkAsmStmt, p)
  1563. getTokNoInd(p)
  1564. if p.tok.tokType == tkCurlyDotLe: result.add(parsePragma(p))
  1565. else: result.add(p.emptyNode)
  1566. case p.tok.tokType
  1567. of tkStrLit: result.add(newStrNodeP(nkStrLit, p.tok.literal, p))
  1568. of tkRStrLit: result.add(newStrNodeP(nkRStrLit, p.tok.literal, p))
  1569. of tkTripleStrLit: result.add(newStrNodeP(nkTripleStrLit, p.tok.literal, p))
  1570. else:
  1571. parMessage(p, "the 'asm' statement takes a string literal")
  1572. result.add(p.emptyNode)
  1573. return
  1574. getTok(p)
  1575. proc parseGenericParam(p: var TParser): PNode =
  1576. #| genericParam = symbol (comma symbol)* (colon expr)? ('=' optInd expr)?
  1577. var a: PNode
  1578. result = newNodeP(nkIdentDefs, p)
  1579. # progress guaranteed
  1580. while true:
  1581. case p.tok.tokType
  1582. of tkIn, tkOut:
  1583. let x = p.lex.cache.getIdent(if p.tok.tokType == tkIn: "in" else: "out")
  1584. a = newNodeP(nkPrefix, p)
  1585. a.add newIdentNodeP(x, p)
  1586. getTok(p)
  1587. expectIdent(p)
  1588. a.add(parseSymbol(p))
  1589. of tkSymbol, tkAccent:
  1590. a = parseSymbol(p)
  1591. if a.kind == nkEmpty: return
  1592. else: break
  1593. result.add(a)
  1594. if p.tok.tokType != tkComma: break
  1595. getTok(p)
  1596. optInd(p, a)
  1597. if p.tok.tokType == tkColon:
  1598. getTok(p)
  1599. optInd(p, result)
  1600. result.add(parseExpr(p))
  1601. else:
  1602. result.add(p.emptyNode)
  1603. if p.tok.tokType == tkEquals:
  1604. getTok(p)
  1605. optInd(p, result)
  1606. result.add(parseExpr(p))
  1607. else:
  1608. result.add(p.emptyNode)
  1609. proc parseGenericParamList(p: var TParser): PNode =
  1610. #| genericParamList = '[' optInd
  1611. #| genericParam ^* (comma/semicolon) optPar ']'
  1612. result = newNodeP(nkGenericParams, p)
  1613. getTok(p)
  1614. optInd(p, result)
  1615. # progress guaranteed
  1616. while p.tok.tokType in {tkSymbol, tkAccent, tkIn, tkOut}:
  1617. var a = parseGenericParam(p)
  1618. result.add(a)
  1619. if p.tok.tokType notin {tkComma, tkSemiColon}: break
  1620. when defined(nimpretty):
  1621. commaWasSemicolon(p.em)
  1622. getTok(p)
  1623. skipComment(p, a)
  1624. optPar(p)
  1625. eat(p, tkBracketRi)
  1626. proc parsePattern(p: var TParser): PNode =
  1627. #| pattern = '{' stmt '}'
  1628. eat(p, tkCurlyLe)
  1629. result = parseStmt(p)
  1630. eat(p, tkCurlyRi)
  1631. proc parseRoutine(p: var TParser, kind: TNodeKind): PNode =
  1632. #| indAndComment = (IND{>} COMMENT)? | COMMENT?
  1633. #| routine = optInd identVis pattern? genericParamList?
  1634. #| paramListColon pragma? ('=' COMMENT? stmt)? indAndComment
  1635. result = newNodeP(kind, p)
  1636. getTok(p)
  1637. optInd(p, result)
  1638. result.add(identVis(p))
  1639. if p.tok.tokType == tkCurlyLe and p.validInd: result.add(p.parsePattern)
  1640. else: result.add(p.emptyNode)
  1641. if p.tok.tokType == tkBracketLe and p.validInd:
  1642. result.add(p.parseGenericParamList)
  1643. else:
  1644. result.add(p.emptyNode)
  1645. result.add(p.parseParamList)
  1646. if p.tok.tokType == tkCurlyDotLe and p.validInd: result.add(p.parsePragma)
  1647. else: result.add(p.emptyNode)
  1648. # empty exception tracking:
  1649. result.add(p.emptyNode)
  1650. if p.tok.tokType == tkEquals and p.validInd:
  1651. getTok(p)
  1652. skipComment(p, result)
  1653. result.add(parseStmt(p))
  1654. else:
  1655. result.add(p.emptyNode)
  1656. indAndComment(p, result)
  1657. proc newCommentStmt(p: var TParser): PNode =
  1658. #| commentStmt = COMMENT
  1659. result = newNodeP(nkCommentStmt, p)
  1660. result.comment = p.tok.literal
  1661. getTok(p)
  1662. type
  1663. TDefParser = proc (p: var TParser): PNode {.nimcall.}
  1664. proc parseSection(p: var TParser, kind: TNodeKind,
  1665. defparser: TDefParser): PNode =
  1666. #| section(RULE) = COMMENT? RULE / (IND{>} (RULE / COMMENT)^+IND{=} DED)
  1667. result = newNodeP(kind, p)
  1668. if kind != nkTypeSection: getTok(p)
  1669. skipComment(p, result)
  1670. if realInd(p):
  1671. withInd(p):
  1672. skipComment(p, result)
  1673. # progress guaranteed
  1674. while sameInd(p):
  1675. case p.tok.tokType
  1676. of tkSymbol, tkAccent, tkParLe:
  1677. var a = defparser(p)
  1678. skipComment(p, a)
  1679. result.add(a)
  1680. of tkComment:
  1681. var a = newCommentStmt(p)
  1682. result.add(a)
  1683. else:
  1684. parMessage(p, errIdentifierExpected, p.tok)
  1685. break
  1686. if result.len == 0: parMessage(p, errIdentifierExpected, p.tok)
  1687. elif p.tok.tokType in {tkSymbol, tkAccent, tkParLe} and p.tok.indent < 0:
  1688. # tkParLe is allowed for ``var (x, y) = ...`` tuple parsing
  1689. result.add(defparser(p))
  1690. else:
  1691. parMessage(p, errIdentifierExpected, p.tok)
  1692. proc parseEnum(p: var TParser): PNode =
  1693. #| enum = 'enum' optInd (symbol pragma? optInd ('=' optInd expr COMMENT?)? comma?)+
  1694. result = newNodeP(nkEnumTy, p)
  1695. getTok(p)
  1696. result.add(p.emptyNode)
  1697. optInd(p, result)
  1698. flexComment(p, result)
  1699. # progress guaranteed
  1700. while true:
  1701. var a = parseSymbol(p)
  1702. if a.kind == nkEmpty: return
  1703. var symPragma = a
  1704. var pragma: PNode
  1705. if p.tok.tokType == tkCurlyDotLe:
  1706. pragma = optPragmas(p)
  1707. symPragma = newNodeP(nkPragmaExpr, p)
  1708. symPragma.add(a)
  1709. symPragma.add(pragma)
  1710. # nimpretty support here
  1711. if p.tok.indent >= 0 and p.tok.indent <= p.currInd:
  1712. result.add(symPragma)
  1713. break
  1714. if p.tok.tokType == tkEquals and p.tok.indent < 0:
  1715. getTok(p)
  1716. optInd(p, symPragma)
  1717. var b = symPragma
  1718. symPragma = newNodeP(nkEnumFieldDef, p)
  1719. symPragma.add(b)
  1720. symPragma.add(parseExpr(p))
  1721. if p.tok.indent < 0 or p.tok.indent >= p.currInd:
  1722. rawSkipComment(p, symPragma)
  1723. if p.tok.tokType == tkComma and p.tok.indent < 0:
  1724. getTok(p)
  1725. rawSkipComment(p, symPragma)
  1726. else:
  1727. if p.tok.indent < 0 or p.tok.indent >= p.currInd:
  1728. rawSkipComment(p, symPragma)
  1729. result.add(symPragma)
  1730. if p.tok.indent >= 0 and p.tok.indent <= p.currInd or
  1731. p.tok.tokType == tkEof:
  1732. break
  1733. if result.len <= 1:
  1734. parMessage(p, errIdentifierExpected, p.tok)
  1735. proc parseObjectPart(p: var TParser): PNode
  1736. proc parseObjectWhen(p: var TParser): PNode =
  1737. #| objectWhen = 'when' expr colcom objectPart COMMENT?
  1738. #| ('elif' expr colcom objectPart COMMENT?)*
  1739. #| ('else' colcom objectPart COMMENT?)?
  1740. result = newNodeP(nkRecWhen, p)
  1741. # progress guaranteed
  1742. while sameInd(p):
  1743. getTok(p) # skip `when`, `elif`
  1744. var branch = newNodeP(nkElifBranch, p)
  1745. optInd(p, branch)
  1746. branch.add(parseExpr(p))
  1747. colcom(p, branch)
  1748. branch.add(parseObjectPart(p))
  1749. flexComment(p, branch)
  1750. result.add(branch)
  1751. if p.tok.tokType != tkElif: break
  1752. if p.tok.tokType == tkElse and sameInd(p):
  1753. var branch = newNodeP(nkElse, p)
  1754. eat(p, tkElse)
  1755. colcom(p, branch)
  1756. branch.add(parseObjectPart(p))
  1757. flexComment(p, branch)
  1758. result.add(branch)
  1759. proc parseObjectCase(p: var TParser): PNode =
  1760. #| objectBranch = 'of' exprList colcom objectPart
  1761. #| objectBranches = objectBranch (IND{=} objectBranch)*
  1762. #| (IND{=} 'elif' expr colcom objectPart)*
  1763. #| (IND{=} 'else' colcom objectPart)?
  1764. #| objectCase = 'case' identWithPragma ':' typeDesc ':'? COMMENT?
  1765. #| (IND{>} objectBranches DED
  1766. #| | IND{=} objectBranches)
  1767. result = newNodeP(nkRecCase, p)
  1768. getTokNoInd(p)
  1769. var a = newNodeP(nkIdentDefs, p)
  1770. a.add(identWithPragma(p))
  1771. eat(p, tkColon)
  1772. a.add(parseTypeDesc(p))
  1773. a.add(p.emptyNode)
  1774. result.add(a)
  1775. if p.tok.tokType == tkColon: getTok(p)
  1776. flexComment(p, result)
  1777. var wasIndented = false
  1778. let oldInd = p.currInd
  1779. if realInd(p):
  1780. p.currInd = p.tok.indent
  1781. wasIndented = true
  1782. # progress guaranteed
  1783. while sameInd(p):
  1784. var b: PNode
  1785. case p.tok.tokType
  1786. of tkOf:
  1787. b = newNodeP(nkOfBranch, p)
  1788. exprList(p, tkColon, b)
  1789. of tkElse:
  1790. b = newNodeP(nkElse, p)
  1791. getTok(p)
  1792. else: break
  1793. colcom(p, b)
  1794. var fields = parseObjectPart(p)
  1795. if fields.kind == nkEmpty:
  1796. parMessage(p, errIdentifierExpected, p.tok)
  1797. fields = newNodeP(nkNilLit, p) # don't break further semantic checking
  1798. b.add(fields)
  1799. result.add(b)
  1800. if b.kind == nkElse: break
  1801. if wasIndented:
  1802. p.currInd = oldInd
  1803. proc parseObjectPart(p: var TParser): PNode =
  1804. #| objectPart = IND{>} objectPart^+IND{=} DED
  1805. #| / objectWhen / objectCase / 'nil' / 'discard' / declColonEquals
  1806. if realInd(p):
  1807. result = newNodeP(nkRecList, p)
  1808. withInd(p):
  1809. rawSkipComment(p, result)
  1810. while sameInd(p):
  1811. case p.tok.tokType
  1812. of tkCase, tkWhen, tkSymbol, tkAccent, tkNil, tkDiscard:
  1813. result.add(parseObjectPart(p))
  1814. else:
  1815. parMessage(p, errIdentifierExpected, p.tok)
  1816. break
  1817. else:
  1818. case p.tok.tokType
  1819. of tkWhen:
  1820. result = parseObjectWhen(p)
  1821. of tkCase:
  1822. result = parseObjectCase(p)
  1823. of tkSymbol, tkAccent:
  1824. result = parseIdentColonEquals(p, {withPragma})
  1825. if p.tok.indent < 0 or p.tok.indent >= p.currInd:
  1826. rawSkipComment(p, result)
  1827. of tkNil, tkDiscard:
  1828. result = newNodeP(nkNilLit, p)
  1829. getTok(p)
  1830. else:
  1831. result = p.emptyNode
  1832. proc parseObject(p: var TParser): PNode =
  1833. #| object = 'object' pragma? ('of' typeDesc)? COMMENT? objectPart
  1834. result = newNodeP(nkObjectTy, p)
  1835. getTok(p)
  1836. if p.tok.tokType == tkCurlyDotLe and p.validInd:
  1837. # Deprecated since v0.20.0
  1838. parMessage(p, warnDeprecated, "type pragmas follow the type name; this form of writing pragmas is deprecated")
  1839. result.add(parsePragma(p))
  1840. else:
  1841. result.add(p.emptyNode)
  1842. if p.tok.tokType == tkOf and p.tok.indent < 0:
  1843. var a = newNodeP(nkOfInherit, p)
  1844. getTok(p)
  1845. a.add(parseTypeDesc(p))
  1846. result.add(a)
  1847. else:
  1848. result.add(p.emptyNode)
  1849. if p.tok.tokType == tkComment:
  1850. skipComment(p, result)
  1851. # an initial IND{>} HAS to follow:
  1852. if not realInd(p):
  1853. result.add(p.emptyNode)
  1854. else:
  1855. result.add(parseObjectPart(p))
  1856. proc parseTypeClassParam(p: var TParser): PNode =
  1857. let modifier = case p.tok.tokType
  1858. of tkOut, tkVar: nkVarTy
  1859. of tkPtr: nkPtrTy
  1860. of tkRef: nkRefTy
  1861. of tkStatic: nkStaticTy
  1862. of tkType: nkTypeOfExpr
  1863. else: nkEmpty
  1864. if modifier != nkEmpty:
  1865. result = newNodeP(modifier, p)
  1866. getTok(p)
  1867. result.add(p.parseSymbol)
  1868. else:
  1869. result = p.parseSymbol
  1870. proc parseTypeClass(p: var TParser): PNode =
  1871. #| typeClassParam = ('var' | 'out')? symbol
  1872. #| typeClass = typeClassParam ^* ',' (pragma)? ('of' typeDesc ^* ',')?
  1873. #| &IND{>} stmt
  1874. result = newNodeP(nkTypeClassTy, p)
  1875. getTok(p)
  1876. var args = newNodeP(nkArgList, p)
  1877. result.add(args)
  1878. args.add(p.parseTypeClassParam)
  1879. while p.tok.tokType == tkComma:
  1880. getTok(p)
  1881. args.add(p.parseTypeClassParam)
  1882. if p.tok.tokType == tkCurlyDotLe and p.validInd:
  1883. result.add(parsePragma(p))
  1884. else:
  1885. result.add(p.emptyNode)
  1886. if p.tok.tokType == tkOf and p.tok.indent < 0:
  1887. var a = newNodeP(nkOfInherit, p)
  1888. getTok(p)
  1889. # progress guaranteed
  1890. while true:
  1891. a.add(parseTypeDesc(p))
  1892. if p.tok.tokType != tkComma: break
  1893. getTok(p)
  1894. result.add(a)
  1895. else:
  1896. result.add(p.emptyNode)
  1897. if p.tok.tokType == tkComment:
  1898. skipComment(p, result)
  1899. # an initial IND{>} HAS to follow:
  1900. if not realInd(p):
  1901. result.add(p.emptyNode)
  1902. else:
  1903. result.add(parseStmt(p))
  1904. proc parseTypeDef(p: var TParser): PNode =
  1905. #|
  1906. #| typeDef = identWithPragmaDot genericParamList? '=' optInd typeDefAux
  1907. #| indAndComment? / identVisDot genericParamList? pragma '=' optInd typeDefAux
  1908. #| indAndComment?
  1909. result = newNodeP(nkTypeDef, p)
  1910. var identifier = identVis(p, allowDot=true)
  1911. var identPragma = identifier
  1912. var pragma: PNode
  1913. var genericParam: PNode
  1914. var noPragmaYet = true
  1915. if p.tok.tokType == tkCurlyDotLe:
  1916. pragma = optPragmas(p)
  1917. identPragma = newNodeP(nkPragmaExpr, p)
  1918. identPragma.add(identifier)
  1919. identPragma.add(pragma)
  1920. noPragmaYet = false
  1921. if p.tok.tokType == tkBracketLe and p.validInd:
  1922. if not noPragmaYet:
  1923. # Deprecated since v0.20.0
  1924. parMessage(p, warnDeprecated, "pragma before generic parameter list is deprecated")
  1925. genericParam = parseGenericParamList(p)
  1926. else:
  1927. genericParam = p.emptyNode
  1928. if noPragmaYet:
  1929. pragma = optPragmas(p)
  1930. if pragma.kind != nkEmpty:
  1931. identPragma = newNodeP(nkPragmaExpr, p)
  1932. identPragma.add(identifier)
  1933. identPragma.add(pragma)
  1934. elif p.tok.tokType == tkCurlyDotLe:
  1935. parMessage(p, errGenerated, "pragma already present")
  1936. result.add(identPragma)
  1937. result.add(genericParam)
  1938. if p.tok.tokType == tkEquals:
  1939. result.info = parLineInfo(p)
  1940. getTok(p)
  1941. optInd(p, result)
  1942. result.add(parseTypeDefAux(p))
  1943. else:
  1944. result.add(p.emptyNode)
  1945. indAndComment(p, result) # special extension!
  1946. proc parseVarTuple(p: var TParser): PNode =
  1947. #| varTuple = '(' optInd identWithPragma ^+ comma optPar ')' '=' optInd expr
  1948. result = newNodeP(nkVarTuple, p)
  1949. getTok(p) # skip '('
  1950. optInd(p, result)
  1951. # progress guaranteed
  1952. while p.tok.tokType in {tkSymbol, tkAccent}:
  1953. var a = identWithPragma(p, allowDot=true)
  1954. result.add(a)
  1955. if p.tok.tokType != tkComma: break
  1956. getTok(p)
  1957. skipComment(p, a)
  1958. result.add(p.emptyNode) # no type desc
  1959. optPar(p)
  1960. eat(p, tkParRi)
  1961. proc parseVariable(p: var TParser): PNode =
  1962. #| colonBody = colcom stmt postExprBlocks?
  1963. #| variable = (varTuple / identColonEquals) colonBody? indAndComment
  1964. if p.tok.tokType == tkParLe:
  1965. result = parseVarTuple(p)
  1966. eat(p, tkEquals)
  1967. optInd(p, result)
  1968. result.add(parseExpr(p))
  1969. else: result = parseIdentColonEquals(p, {withPragma, withDot})
  1970. result[^1] = postExprBlocks(p, result[^1])
  1971. indAndComment(p, result)
  1972. proc parseConstant(p: var TParser): PNode =
  1973. #| constant = (varTuple / identWithPragma) (colon typeDesc)? '=' optInd expr indAndComment
  1974. if p.tok.tokType == tkParLe: result = parseVarTuple(p)
  1975. else:
  1976. result = newNodeP(nkConstDef, p)
  1977. result.add(identWithPragma(p))
  1978. if p.tok.tokType == tkColon:
  1979. getTok(p)
  1980. optInd(p, result)
  1981. result.add(parseTypeDesc(p))
  1982. else:
  1983. result.add(p.emptyNode)
  1984. eat(p, tkEquals)
  1985. optInd(p, result)
  1986. #add(result, parseStmtListExpr(p))
  1987. result.add(parseExpr(p))
  1988. result[^1] = postExprBlocks(p, result[^1])
  1989. indAndComment(p, result)
  1990. proc parseBind(p: var TParser, k: TNodeKind): PNode =
  1991. #| bindStmt = 'bind' optInd qualifiedIdent ^+ comma
  1992. #| mixinStmt = 'mixin' optInd qualifiedIdent ^+ comma
  1993. result = newNodeP(k, p)
  1994. getTok(p)
  1995. optInd(p, result)
  1996. # progress guaranteed
  1997. while true:
  1998. var a = qualifiedIdent(p)
  1999. result.add(a)
  2000. if p.tok.tokType != tkComma: break
  2001. getTok(p)
  2002. optInd(p, a)
  2003. #expectNl(p)
  2004. proc parseStmtPragma(p: var TParser): PNode =
  2005. #| pragmaStmt = pragma (':' COMMENT? stmt)?
  2006. result = parsePragma(p)
  2007. if p.tok.tokType == tkColon and p.tok.indent < 0:
  2008. let a = result
  2009. result = newNodeI(nkPragmaBlock, a.info)
  2010. getTok(p)
  2011. skipComment(p, result)
  2012. result.add a
  2013. result.add parseStmt(p)
  2014. proc simpleStmt(p: var TParser): PNode =
  2015. #| simpleStmt = ((returnStmt | raiseStmt | yieldStmt | discardStmt | breakStmt
  2016. #| | continueStmt | pragmaStmt | importStmt | exportStmt | fromStmt
  2017. #| | includeStmt | commentStmt) / exprStmt) COMMENT?
  2018. #|
  2019. case p.tok.tokType
  2020. of tkReturn: result = parseReturnOrRaise(p, nkReturnStmt)
  2021. of tkRaise: result = parseReturnOrRaise(p, nkRaiseStmt)
  2022. of tkYield: result = parseReturnOrRaise(p, nkYieldStmt)
  2023. of tkDiscard: result = parseReturnOrRaise(p, nkDiscardStmt)
  2024. of tkBreak: result = parseReturnOrRaise(p, nkBreakStmt)
  2025. of tkContinue: result = parseReturnOrRaise(p, nkContinueStmt)
  2026. of tkCurlyDotLe: result = parseStmtPragma(p)
  2027. of tkImport: result = parseImport(p, nkImportStmt)
  2028. of tkExport: result = parseImport(p, nkExportStmt)
  2029. of tkFrom: result = parseFromStmt(p)
  2030. of tkInclude: result = parseIncludeStmt(p)
  2031. of tkComment: result = newCommentStmt(p)
  2032. else:
  2033. if isExprStart(p): result = parseExprStmt(p)
  2034. else: result = p.emptyNode
  2035. if result.kind notin {nkEmpty, nkCommentStmt}: skipComment(p, result)
  2036. proc complexOrSimpleStmt(p: var TParser): PNode =
  2037. #| complexOrSimpleStmt = (ifStmt | whenStmt | whileStmt
  2038. #| | tryStmt | forStmt
  2039. #| | blockStmt | staticStmt | deferStmt | asmStmt
  2040. #| | 'proc' routine
  2041. #| | 'method' routine
  2042. #| | 'func' routine
  2043. #| | 'iterator' routine
  2044. #| | 'macro' routine
  2045. #| | 'template' routine
  2046. #| | 'converter' routine
  2047. #| | 'type' section(typeDef)
  2048. #| | 'const' section(constant)
  2049. #| | ('let' | 'var' | 'using') section(variable)
  2050. #| | bindStmt | mixinStmt)
  2051. #| / simpleStmt
  2052. case p.tok.tokType
  2053. of tkIf: result = parseIfOrWhen(p, nkIfStmt)
  2054. of tkWhile: result = parseWhile(p)
  2055. of tkCase: result = parseCase(p)
  2056. of tkTry: result = parseTry(p, isExpr=false)
  2057. of tkFinally: result = parseExceptBlock(p, nkFinally)
  2058. of tkExcept: result = parseExceptBlock(p, nkExceptBranch)
  2059. of tkFor: result = parseFor(p)
  2060. of tkBlock: result = parseBlock(p)
  2061. of tkStatic: result = parseStaticOrDefer(p, nkStaticStmt)
  2062. of tkDefer: result = parseStaticOrDefer(p, nkDefer)
  2063. of tkAsm: result = parseAsm(p)
  2064. of tkProc: result = parseRoutine(p, nkProcDef)
  2065. of tkFunc: result = parseRoutine(p, nkFuncDef)
  2066. of tkMethod: result = parseRoutine(p, nkMethodDef)
  2067. of tkIterator: result = parseRoutine(p, nkIteratorDef)
  2068. of tkMacro: result = parseRoutine(p, nkMacroDef)
  2069. of tkTemplate: result = parseRoutine(p, nkTemplateDef)
  2070. of tkConverter: result = parseRoutine(p, nkConverterDef)
  2071. of tkType:
  2072. getTok(p)
  2073. if p.tok.tokType == tkParLe:
  2074. getTok(p)
  2075. result = newNodeP(nkTypeOfExpr, p)
  2076. result.add(primary(p, pmTypeDesc))
  2077. eat(p, tkParRi)
  2078. result = parseOperators(p, result, -1, pmNormal)
  2079. else:
  2080. result = parseSection(p, nkTypeSection, parseTypeDef)
  2081. of tkConst:
  2082. prettySection:
  2083. result = parseSection(p, nkConstSection, parseConstant)
  2084. of tkLet:
  2085. prettySection:
  2086. result = parseSection(p, nkLetSection, parseVariable)
  2087. of tkVar:
  2088. prettySection:
  2089. result = parseSection(p, nkVarSection, parseVariable)
  2090. of tkWhen: result = parseIfOrWhen(p, nkWhenStmt)
  2091. of tkBind: result = parseBind(p, nkBindStmt)
  2092. of tkMixin: result = parseBind(p, nkMixinStmt)
  2093. of tkUsing: result = parseSection(p, nkUsingStmt, parseVariable)
  2094. else: result = simpleStmt(p)
  2095. proc parseStmt(p: var TParser): PNode =
  2096. #| stmt = (IND{>} complexOrSimpleStmt^+(IND{=} / ';') DED)
  2097. #| / simpleStmt ^+ ';'
  2098. if p.tok.indent > p.currInd:
  2099. # nimpretty support here
  2100. result = newNodeP(nkStmtList, p)
  2101. withInd(p):
  2102. while true:
  2103. if p.tok.indent == p.currInd:
  2104. discard
  2105. elif p.tok.tokType == tkSemiColon:
  2106. getTok(p)
  2107. if p.tok.indent < 0 or p.tok.indent == p.currInd: discard
  2108. else: break
  2109. else:
  2110. if p.tok.indent > p.currInd and p.tok.tokType != tkDot:
  2111. parMessage(p, errInvalidIndentation)
  2112. break
  2113. if p.tok.tokType in {tkCurlyRi, tkParRi, tkCurlyDotRi, tkBracketRi}:
  2114. # XXX this ensures tnamedparamanonproc still compiles;
  2115. # deprecate this syntax later
  2116. break
  2117. p.hasProgress = false
  2118. var a = complexOrSimpleStmt(p)
  2119. if a.kind != nkEmpty:
  2120. result.add(a)
  2121. else:
  2122. # This is done to make the new 'if' expressions work better.
  2123. # XXX Eventually we need to be more strict here.
  2124. if p.tok.tokType notin {tkElse, tkElif}:
  2125. parMessage(p, errExprExpected, p.tok)
  2126. getTok(p)
  2127. else:
  2128. break
  2129. if not p.hasProgress and p.tok.tokType == tkEof: break
  2130. else:
  2131. # the case statement is only needed for better error messages:
  2132. case p.tok.tokType
  2133. of tkIf, tkWhile, tkCase, tkTry, tkFor, tkBlock, tkAsm, tkProc, tkFunc,
  2134. tkIterator, tkMacro, tkType, tkConst, tkWhen, tkVar:
  2135. parMessage(p, "nestable statement requires indentation")
  2136. result = p.emptyNode
  2137. else:
  2138. if p.inSemiStmtList > 0:
  2139. result = simpleStmt(p)
  2140. if result.kind == nkEmpty: parMessage(p, errExprExpected, p.tok)
  2141. else:
  2142. result = newNodeP(nkStmtList, p)
  2143. while true:
  2144. if p.tok.indent >= 0:
  2145. parMessage(p, errInvalidIndentation)
  2146. p.hasProgress = false
  2147. let a = simpleStmt(p)
  2148. let err = not p.hasProgress
  2149. if a.kind == nkEmpty: parMessage(p, errExprExpected, p.tok)
  2150. result.add(a)
  2151. if p.tok.tokType != tkSemiColon: break
  2152. getTok(p)
  2153. if err and p.tok.tokType == tkEof: break
  2154. proc parseAll(p: var TParser): PNode =
  2155. ## Parses the rest of the input stream held by the parser into a PNode.
  2156. result = newNodeP(nkStmtList, p)
  2157. while p.tok.tokType != tkEof:
  2158. p.hasProgress = false
  2159. var a = complexOrSimpleStmt(p)
  2160. if a.kind != nkEmpty and p.hasProgress:
  2161. result.add(a)
  2162. else:
  2163. parMessage(p, errExprExpected, p.tok)
  2164. # bugfix: consume a token here to prevent an endless loop:
  2165. getTok(p)
  2166. if p.tok.indent != 0:
  2167. parMessage(p, errInvalidIndentation)
  2168. proc parseTopLevelStmt(p: var TParser): PNode =
  2169. ## Implements an iterator which, when called repeatedly, returns the next
  2170. ## top-level statement or emptyNode if end of stream.
  2171. result = p.emptyNode
  2172. # progress guaranteed
  2173. while true:
  2174. # nimpretty support here
  2175. if p.tok.indent != 0:
  2176. if p.firstTok and p.tok.indent < 0: discard
  2177. elif p.tok.tokType != tkSemiColon:
  2178. # special casing for better error messages:
  2179. if p.tok.tokType == tkOpr and p.tok.ident.s == "*":
  2180. parMessage(p, errGenerated,
  2181. "invalid indentation; an export marker '*' follows the declared identifier")
  2182. else:
  2183. parMessage(p, errInvalidIndentation)
  2184. p.firstTok = false
  2185. case p.tok.tokType
  2186. of tkSemiColon:
  2187. getTok(p)
  2188. if p.tok.indent <= 0: discard
  2189. else: parMessage(p, errInvalidIndentation)
  2190. p.firstTok = true
  2191. of tkEof: break
  2192. else:
  2193. result = complexOrSimpleStmt(p)
  2194. if result.kind == nkEmpty: parMessage(p, errExprExpected, p.tok)
  2195. break
  2196. proc parseString*(s: string; cache: IdentCache; config: ConfigRef;
  2197. filename: string = ""; line: int = 0;
  2198. errorHandler: TErrorHandler = nil): PNode =
  2199. ## Parses a string into an AST, returning the top node.
  2200. ## `filename` and `line`, although optional, provide info so that the
  2201. ## compiler can generate correct error messages referring to the original
  2202. ## source.
  2203. var stream = llStreamOpen(s)
  2204. stream.lineOffset = line
  2205. var parser: TParser
  2206. parser.lex.errorHandler = errorHandler
  2207. openParser(parser, AbsoluteFile filename, stream, cache, config)
  2208. result = parser.parseAll
  2209. closeParser(parser)