parser.nim 73 KB

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