parser.nim 83 KB

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