parser.nim 83 KB

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