semstmts.nim 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## this module does the semantic checking of statements
  10. # included from sem.nim
  11. const
  12. errNoSymbolToBorrowFromFound = "no symbol to borrow from found"
  13. errDiscardValueX = "value of type '$1' has to be used (or discarded)"
  14. errInvalidDiscard = "statement returns no value that can be discarded"
  15. errInvalidControlFlowX = "invalid control flow: $1"
  16. errSelectorMustBeOfCertainTypes = "selector must be of an ordinal type, float or string"
  17. errExprCannotBeRaised = "only a 'ref object' can be raised"
  18. errBreakOnlyInLoop = "'break' only allowed in loop construct"
  19. errExceptionAlreadyHandled = "exception already handled"
  20. errYieldNotAllowedHere = "'yield' only allowed in an iterator"
  21. errYieldNotAllowedInTryStmt = "'yield' cannot be used within 'try' in a non-inlined iterator"
  22. errInvalidNumberOfYieldExpr = "invalid number of 'yield' expressions"
  23. errCannotReturnExpr = "current routine cannot return an expression"
  24. errGenericLambdaNotAllowed = "A nested proc can have generic parameters only when " &
  25. "it is used as an operand to another routine and the types " &
  26. "of the generic paramers can be inferred from the expected signature."
  27. errCannotInferTypeOfTheLiteral = "cannot infer the type of the $1"
  28. errCannotInferReturnType = "cannot infer the return type of '$1'"
  29. errCannotInferStaticParam = "cannot infer the value of the static param '$1'"
  30. errProcHasNoConcreteType = "'$1' doesn't have a concrete type, due to unspecified generic parameters."
  31. errLetNeedsInit = "'let' symbol requires an initialization"
  32. errThreadvarCannotInit = "a thread var cannot be initialized explicitly; this would only run for the main thread"
  33. errImplOfXexpected = "implementation of '$1' expected"
  34. errRecursiveDependencyX = "recursive dependency: '$1'"
  35. errRecursiveDependencyIteratorX = "recursion is not supported in iterators: '$1'"
  36. errPragmaOnlyInHeaderOfProcX = "pragmas are only allowed in the header of a proc; redefinition of $1"
  37. errCannotAssignToGlobal = "cannot assign local to global variable"
  38. proc implicitlyDiscardable(n: PNode): bool
  39. proc semDiscard(c: PContext, n: PNode): PNode =
  40. result = n
  41. checkSonsLen(n, 1, c.config)
  42. if n[0].kind != nkEmpty:
  43. n[0] = semExprWithType(c, n[0])
  44. let sonType = n[0].typ
  45. let sonKind = n[0].kind
  46. if isEmptyType(sonType) or sonType.kind in {tyNone, tyTypeDesc} or sonKind == nkTypeOfExpr:
  47. localError(c.config, n.info, errInvalidDiscard)
  48. if sonType.kind == tyProc and sonKind notin nkCallKinds:
  49. # tyProc is disallowed to prevent ``discard foo`` to be valid, when ``discard foo()`` is meant.
  50. localError(c.config, n.info, "illegal discard proc, did you mean: " & $n[0] & "()")
  51. proc semBreakOrContinue(c: PContext, n: PNode): PNode =
  52. result = n
  53. checkSonsLen(n, 1, c.config)
  54. if n[0].kind != nkEmpty:
  55. if n.kind != nkContinueStmt:
  56. var s: PSym
  57. case n[0].kind
  58. of nkIdent: s = lookUp(c, n[0])
  59. of nkSym: s = n[0].sym
  60. else: illFormedAst(n, c.config)
  61. s = getGenSym(c, s)
  62. if s.kind == skLabel and s.owner.id == c.p.owner.id:
  63. var x = newSymNode(s)
  64. x.info = n.info
  65. incl(s.flags, sfUsed)
  66. n[0] = x
  67. suggestSym(c.graph, x.info, s, c.graph.usageSym)
  68. onUse(x.info, s)
  69. else:
  70. localError(c.config, n.info, errInvalidControlFlowX % s.name.s)
  71. else:
  72. localError(c.config, n.info, errGenerated, "'continue' cannot have a label")
  73. elif c.p.nestedBlockCounter > 0 and n.kind == nkBreakStmt and not c.p.breakInLoop:
  74. localError(c.config, n.info, warnUnnamedBreak)
  75. elif (c.p.nestedLoopCounter <= 0) and ((c.p.nestedBlockCounter <= 0) or n.kind == nkContinueStmt):
  76. localError(c.config, n.info, errInvalidControlFlowX %
  77. renderTree(n, {renderNoComments}))
  78. proc semAsm(c: PContext, n: PNode): PNode =
  79. checkSonsLen(n, 2, c.config)
  80. var marker = pragmaAsm(c, n[0])
  81. if marker == '\0': marker = '`' # default marker
  82. result = semAsmOrEmit(c, n, marker)
  83. proc semWhile(c: PContext, n: PNode; flags: TExprFlags): PNode =
  84. result = n
  85. checkSonsLen(n, 2, c.config)
  86. openScope(c)
  87. n[0] = forceBool(c, semExprWithType(c, n[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  88. inc(c.p.nestedLoopCounter)
  89. let oldBreakInLoop = c.p.breakInLoop
  90. c.p.breakInLoop = true
  91. n[1] = semStmt(c, n[1], flags)
  92. c.p.breakInLoop = oldBreakInLoop
  93. dec(c.p.nestedLoopCounter)
  94. closeScope(c)
  95. if n[1].typ == c.enforceVoidContext:
  96. result.typ = c.enforceVoidContext
  97. elif efInTypeof in flags:
  98. result.typ = n[1].typ
  99. elif implicitlyDiscardable(n[1]):
  100. result[1].typ = c.enforceVoidContext
  101. proc semProc(c: PContext, n: PNode): PNode
  102. proc semExprBranch(c: PContext, n: PNode; flags: TExprFlags = {}; expectedType: PType = nil): PNode =
  103. result = semExpr(c, n, flags, expectedType)
  104. if result.typ != nil:
  105. # XXX tyGenericInst here?
  106. if result.typ.kind in {tyVar, tyLent}: result = newDeref(result)
  107. proc semExprBranchScope(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  108. openScope(c)
  109. result = semExprBranch(c, n, expectedType = expectedType)
  110. closeScope(c)
  111. const
  112. skipForDiscardable = {nkIfStmt, nkIfExpr, nkCaseStmt, nkOfBranch,
  113. nkElse, nkStmtListExpr, nkTryStmt, nkFinally, nkExceptBranch,
  114. nkElifBranch, nkElifExpr, nkElseExpr, nkBlockStmt, nkBlockExpr,
  115. nkHiddenStdConv, nkHiddenDeref}
  116. proc implicitlyDiscardable(n: PNode): bool =
  117. var n = n
  118. while n.kind in skipForDiscardable: n = n.lastSon
  119. result = n.kind in nkLastBlockStmts or
  120. (isCallExpr(n) and n[0].kind == nkSym and
  121. sfDiscardable in n[0].sym.flags)
  122. proc fixNilType(c: PContext; n: PNode) =
  123. if isAtom(n):
  124. if n.kind != nkNilLit and n.typ != nil:
  125. localError(c.config, n.info, errDiscardValueX % n.typ.typeToString)
  126. elif n.kind in {nkStmtList, nkStmtListExpr}:
  127. n.transitionSonsKind(nkStmtList)
  128. for it in n: fixNilType(c, it)
  129. n.typ = nil
  130. proc discardCheck(c: PContext, result: PNode, flags: TExprFlags) =
  131. if c.matchedConcept != nil or efInTypeof in flags: return
  132. if result.typ != nil and result.typ.kind notin {tyTyped, tyVoid}:
  133. if implicitlyDiscardable(result):
  134. var n = newNodeI(nkDiscardStmt, result.info, 1)
  135. n[0] = result
  136. elif result.typ.kind != tyError and c.config.cmd != cmdInteractive:
  137. if result.typ.kind == tyNone:
  138. localError(c.config, result.info, "expression has no type: " &
  139. renderTree(result, {renderNoComments}))
  140. var n = result
  141. while n.kind in skipForDiscardable:
  142. if n.kind == nkTryStmt: n = n[0]
  143. else: n = n.lastSon
  144. var s = "expression '" & $n & "' is of type '" &
  145. result.typ.typeToString & "' and has to be used (or discarded)"
  146. if result.info.line != n.info.line or
  147. result.info.fileIndex != n.info.fileIndex:
  148. s.add "; start of expression here: " & c.config$result.info
  149. if result.typ.kind == tyProc:
  150. s.add "; for a function call use ()"
  151. localError(c.config, n.info, s)
  152. proc semIf(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  153. result = n
  154. var typ = commonTypeBegin
  155. var expectedType = expectedType
  156. var hasElse = false
  157. for i in 0..<n.len:
  158. var it = n[i]
  159. if it.len == 2:
  160. openScope(c)
  161. it[0] = forceBool(c, semExprWithType(c, it[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  162. it[1] = semExprBranch(c, it[1], flags, expectedType)
  163. typ = commonType(c, typ, it[1])
  164. expectedType = typ
  165. closeScope(c)
  166. elif it.len == 1:
  167. hasElse = true
  168. it[0] = semExprBranchScope(c, it[0], expectedType)
  169. typ = commonType(c, typ, it[0])
  170. expectedType = typ
  171. else: illFormedAst(it, c.config)
  172. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped} or
  173. (not hasElse and efInTypeof notin flags):
  174. for it in n: discardCheck(c, it.lastSon, flags)
  175. result.transitionSonsKind(nkIfStmt)
  176. # propagate any enforced VoidContext:
  177. if typ == c.enforceVoidContext: result.typ = c.enforceVoidContext
  178. else:
  179. for it in n:
  180. let j = it.len-1
  181. if not endsInNoReturn(it[j]):
  182. it[j] = fitNode(c, typ, it[j], it[j].info)
  183. result.transitionSonsKind(nkIfExpr)
  184. result.typ = typ
  185. proc semTry(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  186. var check = initIntSet()
  187. template semExceptBranchType(typeNode: PNode): bool =
  188. # returns true if exception type is imported type
  189. let typ = semTypeNode(c, typeNode, nil).toObject()
  190. var isImported = false
  191. if isImportedException(typ, c.config):
  192. isImported = true
  193. elif not isException(typ):
  194. localError(c.config, typeNode.info, errExprCannotBeRaised)
  195. elif not isDefectOrCatchableError(typ):
  196. message(c.config, a.info, warnBareExcept, "catch a more precise Exception deriving from CatchableError or Defect.")
  197. if containsOrIncl(check, typ.id):
  198. localError(c.config, typeNode.info, errExceptionAlreadyHandled)
  199. typeNode = newNodeIT(nkType, typeNode.info, typ)
  200. isImported
  201. result = n
  202. checkMinSonsLen(n, 2, c.config)
  203. var typ = commonTypeBegin
  204. var expectedType = expectedType
  205. n[0] = semExprBranchScope(c, n[0], expectedType)
  206. typ = commonType(c, typ, n[0].typ)
  207. expectedType = typ
  208. var last = n.len - 1
  209. var catchAllExcepts = 0
  210. for i in 1..last:
  211. let a = n[i]
  212. checkMinSonsLen(a, 1, c.config)
  213. openScope(c)
  214. if a.kind == nkExceptBranch:
  215. if a.len == 2 and a[0].kind == nkBracket:
  216. # rewrite ``except [a, b, c]: body`` -> ```except a, b, c: body```
  217. a.sons[0..0] = move a[0].sons
  218. if a.len == 2 and a[0].isInfixAs():
  219. # support ``except Exception as ex: body``
  220. let isImported = semExceptBranchType(a[0][1])
  221. let symbol = newSymG(skLet, a[0][2], c)
  222. symbol.typ = if isImported: a[0][1].typ
  223. else: a[0][1].typ.toRef(c.idgen)
  224. addDecl(c, symbol)
  225. # Overwrite symbol in AST with the symbol in the symbol table.
  226. a[0][2] = newSymNode(symbol, a[0][2].info)
  227. elif a.len == 1:
  228. # count number of ``except: body`` blocks
  229. inc catchAllExcepts
  230. message(c.config, a.info, warnBareExcept,
  231. "The bare except clause is deprecated; use `except CatchableError:` instead")
  232. else:
  233. # support ``except KeyError, ValueError, ... : body``
  234. if catchAllExcepts > 0:
  235. # if ``except: body`` already encountered,
  236. # cannot be followed by a ``except KeyError, ... : body`` block
  237. inc catchAllExcepts
  238. var isNative, isImported: bool
  239. for j in 0..<a.len-1:
  240. let tmp = semExceptBranchType(a[j])
  241. if tmp: isImported = true
  242. else: isNative = true
  243. if isNative and isImported:
  244. localError(c.config, a[0].info, "Mix of imported and native exception types is not allowed in one except branch")
  245. elif a.kind == nkFinally:
  246. if i != n.len-1:
  247. localError(c.config, a.info, "Only one finally is allowed after all other branches")
  248. else:
  249. illFormedAst(n, c.config)
  250. if catchAllExcepts > 1:
  251. # if number of ``except: body`` blocks is greater than 1
  252. # or more specific exception follows a general except block, it is invalid
  253. localError(c.config, a.info, "Only one general except clause is allowed after more specific exceptions")
  254. # last child of an nkExcept/nkFinally branch is a statement:
  255. if a.kind != nkFinally:
  256. a[^1] = semExprBranchScope(c, a[^1], expectedType)
  257. typ = commonType(c, typ, a[^1])
  258. expectedType = typ
  259. else:
  260. a[^1] = semExprBranchScope(c, a[^1])
  261. dec last
  262. closeScope(c)
  263. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped}:
  264. discardCheck(c, n[0], flags)
  265. for i in 1..<n.len: discardCheck(c, n[i].lastSon, flags)
  266. if typ == c.enforceVoidContext:
  267. result.typ = c.enforceVoidContext
  268. else:
  269. if n.lastSon.kind == nkFinally: discardCheck(c, n.lastSon.lastSon, flags)
  270. n[0] = fitNode(c, typ, n[0], n[0].info)
  271. for i in 1..last:
  272. var it = n[i]
  273. let j = it.len-1
  274. if not endsInNoReturn(it[j]):
  275. it[j] = fitNode(c, typ, it[j], it[j].info)
  276. result.typ = typ
  277. proc fitRemoveHiddenConv(c: PContext, typ: PType, n: PNode): PNode =
  278. result = fitNode(c, typ, n, n.info)
  279. if result.kind in {nkHiddenStdConv, nkHiddenSubConv}:
  280. let r1 = result[1]
  281. if r1.kind in {nkCharLit..nkUInt64Lit} and typ.skipTypes(abstractRange).kind in {tyFloat..tyFloat128}:
  282. result = newFloatNode(nkFloatLit, BiggestFloat r1.intVal)
  283. result.info = n.info
  284. result.typ = typ
  285. if not floatRangeCheck(result.floatVal, typ):
  286. localError(c.config, n.info, errFloatToString % [$result.floatVal, typeToString(typ)])
  287. else:
  288. changeType(c, r1, typ, check=true)
  289. result = r1
  290. elif not sameType(result.typ, typ):
  291. changeType(c, result, typ, check=false)
  292. proc findShadowedVar(c: PContext, v: PSym): PSym =
  293. for scope in localScopesFrom(c, c.currentScope.parent):
  294. let shadowed = strTableGet(scope.symbols, v.name)
  295. if shadowed != nil and shadowed.kind in skLocalVars:
  296. return shadowed
  297. proc identWithin(n: PNode, s: PIdent): bool =
  298. for i in 0..n.safeLen-1:
  299. if identWithin(n[i], s): return true
  300. result = n.kind == nkSym and n.sym.name.id == s.id
  301. proc semIdentDef(c: PContext, n: PNode, kind: TSymKind, reportToNimsuggest = true): PSym =
  302. if isTopLevel(c):
  303. result = semIdentWithPragma(c, kind, n, {sfExported})
  304. incl(result.flags, sfGlobal)
  305. #if kind in {skVar, skLet}:
  306. # echo "global variable here ", n.info, " ", result.name.s
  307. else:
  308. result = semIdentWithPragma(c, kind, n, {})
  309. if result.owner.kind == skModule:
  310. incl(result.flags, sfGlobal)
  311. result.options = c.config.options
  312. proc getLineInfo(n: PNode): TLineInfo =
  313. case n.kind
  314. of nkPostfix:
  315. if len(n) > 1:
  316. return getLineInfo(n[1])
  317. of nkAccQuoted, nkPragmaExpr:
  318. if len(n) > 0:
  319. return getLineInfo(n[0])
  320. else:
  321. discard
  322. result = n.info
  323. let info = getLineInfo(n)
  324. if reportToNimsuggest:
  325. suggestSym(c.graph, info, result, c.graph.usageSym)
  326. proc checkNilable(c: PContext; v: PSym) =
  327. if {sfGlobal, sfImportc} * v.flags == {sfGlobal} and v.typ.requiresInit:
  328. if v.astdef.isNil:
  329. message(c.config, v.info, warnProveInit, v.name.s)
  330. elif tfNotNil in v.typ.flags and not v.astdef.typ.isNil and tfNotNil notin v.astdef.typ.flags:
  331. message(c.config, v.info, warnProveInit, v.name.s)
  332. #include liftdestructors
  333. proc addToVarSection(c: PContext; result: var PNode; n: PNode) =
  334. if result.kind != nkStmtList:
  335. result = makeStmtList(result)
  336. result.add n
  337. proc addToVarSection(c: PContext; result: var PNode; orig, identDefs: PNode) =
  338. if result.kind == nkStmtList:
  339. let o = copyNode(orig)
  340. o.add identDefs
  341. result.add o
  342. else:
  343. result.add identDefs
  344. proc isDiscardUnderscore(v: PSym): bool =
  345. if v.name.s == "_":
  346. v.flags.incl(sfGenSym)
  347. result = true
  348. proc semUsing(c: PContext; n: PNode): PNode =
  349. result = c.graph.emptyNode
  350. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "using")
  351. for i in 0..<n.len:
  352. var a = n[i]
  353. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  354. if a.kind == nkCommentStmt: continue
  355. if a.kind notin {nkIdentDefs, nkVarTuple, nkConstDef}: illFormedAst(a, c.config)
  356. checkMinSonsLen(a, 3, c.config)
  357. if a[^2].kind != nkEmpty:
  358. let typ = semTypeNode(c, a[^2], nil)
  359. for j in 0..<a.len-2:
  360. let v = semIdentDef(c, a[j], skParam)
  361. styleCheckDef(c, v)
  362. onDef(a[j].info, v)
  363. v.typ = typ
  364. strTableIncl(c.signatures, v)
  365. else:
  366. localError(c.config, a.info, "'using' section must have a type")
  367. var def: PNode
  368. if a[^1].kind != nkEmpty:
  369. localError(c.config, a.info, "'using' sections cannot contain assignments")
  370. proc hasEmpty(typ: PType): bool =
  371. if typ.kind in {tySequence, tyArray, tySet}:
  372. result = typ.lastSon.kind == tyEmpty
  373. elif typ.kind == tyTuple:
  374. for s in typ.sons:
  375. result = result or hasEmpty(s)
  376. proc hasUnresolvedParams(n: PNode; flags: TExprFlags): bool =
  377. result = tfUnresolved in n.typ.flags
  378. when false:
  379. case n.kind
  380. of nkSym:
  381. result = isGenericRoutineStrict(n.sym)
  382. of nkSymChoices:
  383. for ch in n:
  384. if hasUnresolvedParams(ch, flags):
  385. return true
  386. result = false
  387. else:
  388. result = false
  389. if efOperand in flags:
  390. if tfUnresolved notin n.typ.flags:
  391. result = false
  392. proc makeDeref(n: PNode): PNode =
  393. var t = n.typ
  394. if t.kind in tyUserTypeClasses and t.isResolvedUserTypeClass:
  395. t = t.lastSon
  396. t = skipTypes(t, {tyGenericInst, tyAlias, tySink, tyOwned})
  397. result = n
  398. if t.kind in {tyVar, tyLent}:
  399. result = newNodeIT(nkHiddenDeref, n.info, t[0])
  400. result.add n
  401. t = skipTypes(t[0], {tyGenericInst, tyAlias, tySink, tyOwned})
  402. while t.kind in {tyPtr, tyRef}:
  403. var a = result
  404. let baseTyp = t.lastSon
  405. result = newNodeIT(nkHiddenDeref, n.info, baseTyp)
  406. result.add a
  407. t = skipTypes(baseTyp, {tyGenericInst, tyAlias, tySink, tyOwned})
  408. proc fillPartialObject(c: PContext; n: PNode; typ: PType) =
  409. if n.len == 2:
  410. let x = semExprWithType(c, n[0])
  411. let y = considerQuotedIdent(c, n[1])
  412. let obj = x.typ.skipTypes(abstractPtrs)
  413. if obj.kind == tyObject and tfPartial in obj.flags:
  414. let field = newSym(skField, getIdent(c.cache, y.s), nextSymId c.idgen, obj.sym, n[1].info)
  415. field.typ = skipIntLit(typ, c.idgen)
  416. field.position = obj.n.len
  417. obj.n.add newSymNode(field)
  418. n[0] = makeDeref x
  419. n[1] = newSymNode(field)
  420. n.typ = field.typ
  421. else:
  422. localError(c.config, n.info, "implicit object field construction " &
  423. "requires a .partial object, but got " & typeToString(obj))
  424. else:
  425. localError(c.config, n.info, "nkDotNode requires 2 children")
  426. proc setVarType(c: PContext; v: PSym, typ: PType) =
  427. if v.typ != nil and not sameTypeOrNil(v.typ, typ):
  428. localError(c.config, v.info, "inconsistent typing for reintroduced symbol '" &
  429. v.name.s & "': previous type was: " & typeToString(v.typ, preferDesc) &
  430. "; new type is: " & typeToString(typ, preferDesc))
  431. v.typ = typ
  432. proc isPossibleMacroPragma(c: PContext, it: PNode, key: PNode): bool =
  433. # make sure it's not a normal pragma, and calls an identifier
  434. # considerQuotedIdent below will fail on non-identifiers
  435. result = whichPragma(it) == wInvalid and key.kind in nkIdentKinds
  436. if result:
  437. # make sure it's not a user pragma
  438. let ident = considerQuotedIdent(c, key)
  439. result = strTableGet(c.userPragmas, ident) == nil
  440. if result:
  441. # make sure it's not a custom pragma
  442. var amb = false
  443. let sym = searchInScopes(c, ident, amb)
  444. result = sym == nil or sfCustomPragma notin sym.flags
  445. proc copyExcept(n: PNode, i: int): PNode =
  446. result = copyNode(n)
  447. for j in 0..<n.len:
  448. if j != i: result.add(n[j])
  449. proc semVarMacroPragma(c: PContext, a: PNode, n: PNode): PNode =
  450. # Mirrored with semProcAnnotation
  451. result = nil
  452. # a, b {.prag.}: int = 3 not allowed
  453. const lhsPos = 0
  454. if a.len == 3 and a[lhsPos].kind == nkPragmaExpr:
  455. var b = a[lhsPos]
  456. const
  457. namePos = 0
  458. pragmaPos = 1
  459. let pragmas = b[pragmaPos]
  460. for i in 0 ..< pragmas.len:
  461. let it = pragmas[i]
  462. let key = if it.kind in nkPragmaCallKinds and it.len >= 1: it[0] else: it
  463. if isPossibleMacroPragma(c, it, key):
  464. # we transform ``var p {.m, rest.}`` into ``m(do: var p {.rest.})`` and
  465. # let the semantic checker deal with it:
  466. var x = newNodeI(nkCall, key.info)
  467. x.add(key)
  468. if it.kind in nkPragmaCallKinds and it.len > 1:
  469. # pass pragma arguments to the macro too:
  470. for i in 1..<it.len:
  471. x.add(it[i])
  472. # Drop the pragma from the list, this prevents getting caught in endless
  473. # recursion when the nkCall is semanticized
  474. let oldExpr = a[lhsPos]
  475. let newPragmas = copyExcept(pragmas, i)
  476. if newPragmas.kind != nkEmpty and newPragmas.len == 0:
  477. a[lhsPos] = oldExpr[namePos]
  478. else:
  479. a[lhsPos] = copyNode(oldExpr)
  480. a[lhsPos].add(oldExpr[namePos])
  481. a[lhsPos].add(newPragmas)
  482. var unarySection = newNodeI(n.kind, a.info)
  483. unarySection.add(a)
  484. x.add(unarySection)
  485. # recursion assures that this works for multiple macro annotations too:
  486. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  487. if r == nil:
  488. # Restore the old list of pragmas since we couldn't process this
  489. a[lhsPos] = oldExpr
  490. # No matching macro was found but there's always the possibility this may
  491. # be a .pragma. template instead
  492. continue
  493. doAssert r[0].kind == nkSym
  494. let m = r[0].sym
  495. case m.kind
  496. of skMacro: result = semMacroExpr(c, r, r, m, {})
  497. of skTemplate: result = semTemplateExpr(c, r, m, {})
  498. else:
  499. a[lhsPos] = oldExpr
  500. continue
  501. doAssert result != nil
  502. return result
  503. template isLocalSym(sym: PSym): bool =
  504. sym.kind in {skVar, skLet} and not
  505. ({sfGlobal, sfPure} * sym.flags != {} or
  506. sfCompileTime in sym.flags) or
  507. sym.kind in {skProc, skFunc, skIterator} and
  508. sfGlobal notin sym.flags
  509. template isLocalVarSym(n: PNode): bool =
  510. n.kind == nkSym and isLocalSym(n.sym)
  511. proc usesLocalVar(n: PNode): bool =
  512. for z in 1 ..< n.len:
  513. if n[z].isLocalVarSym:
  514. return true
  515. elif n[z].kind in nkCallKinds:
  516. if usesLocalVar(n[z]):
  517. return true
  518. proc globalVarInitCheck(c: PContext, n: PNode) =
  519. if n.isLocalVarSym or n.kind in nkCallKinds and usesLocalVar(n):
  520. localError(c.config, n.info, errCannotAssignToGlobal)
  521. proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode =
  522. var b: PNode
  523. result = copyNode(n)
  524. for i in 0..<n.len:
  525. var a = n[i]
  526. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  527. if a.kind == nkCommentStmt: continue
  528. if a.kind notin {nkIdentDefs, nkVarTuple}: illFormedAst(a, c.config)
  529. checkMinSonsLen(a, 3, c.config)
  530. b = semVarMacroPragma(c, a, n)
  531. if b != nil:
  532. addToVarSection(c, result, b)
  533. continue
  534. var typ: PType = nil
  535. if a[^2].kind != nkEmpty:
  536. typ = semTypeNode(c, a[^2], nil)
  537. var typFlags: TTypeAllowedFlags
  538. var def: PNode = c.graph.emptyNode
  539. if a[^1].kind != nkEmpty:
  540. def = semExprWithType(c, a[^1], {efTypeAllowed}, typ)
  541. if def.kind == nkSym and def.sym.kind in {skTemplate, skMacro}:
  542. typFlags.incl taIsTemplateOrMacro
  543. elif def.typ.kind == tyTypeDesc and c.p.owner.kind != skMacro:
  544. typFlags.incl taProcContextIsNotMacro
  545. if typ != nil:
  546. if typ.isMetaType:
  547. def = inferWithMetatype(c, typ, def)
  548. typ = def.typ
  549. else:
  550. # BUGFIX: ``fitNode`` is needed here!
  551. # check type compatibility between def.typ and typ
  552. def = fitNodeConsiderViewType(c, typ, def, def.info)
  553. #changeType(def.skipConv, typ, check=true)
  554. else:
  555. typ = def.typ.skipTypes({tyStatic, tySink}).skipIntLit(c.idgen)
  556. if typ.kind in tyUserTypeClasses and typ.isResolvedUserTypeClass:
  557. typ = typ.lastSon
  558. if hasEmpty(typ):
  559. localError(c.config, def.info, errCannotInferTypeOfTheLiteral % typ.kind.toHumanStr)
  560. elif typ.kind == tyProc and def.kind == nkSym and isGenericRoutine(def.sym.ast):
  561. # tfUnresolved in typ.flags:
  562. localError(c.config, def.info, errProcHasNoConcreteType % def.renderTree)
  563. when false:
  564. # XXX This typing rule is neither documented nor complete enough to
  565. # justify it. Instead use the newer 'unowned x' until we figured out
  566. # a more general solution.
  567. if symkind == skVar and typ.kind == tyOwned and def.kind notin nkCallKinds:
  568. # special type inference rule: 'var it = ownedPointer' is turned
  569. # into an unowned pointer.
  570. typ = typ.lastSon
  571. # this can only happen for errornous var statements:
  572. if typ == nil: continue
  573. if c.matchedConcept != nil:
  574. typFlags.incl taConcept
  575. typeAllowedCheck(c, a.info, typ, symkind, typFlags)
  576. var tup = skipTypes(typ, {tyGenericInst, tyAlias, tySink})
  577. if a.kind == nkVarTuple:
  578. if tup.kind != tyTuple:
  579. localError(c.config, a.info, errXExpected, "tuple")
  580. elif a.len-2 != tup.len:
  581. localError(c.config, a.info, errWrongNumberOfVariables)
  582. b = newNodeI(nkVarTuple, a.info)
  583. newSons(b, a.len)
  584. # keep type desc for doc generator
  585. # NOTE: at the moment this is always ast.emptyNode, see parser.nim
  586. b[^2] = a[^2]
  587. b[^1] = def
  588. addToVarSection(c, result, n, b)
  589. elif tup.kind == tyTuple and def.kind in {nkPar, nkTupleConstr} and
  590. a.kind == nkIdentDefs and a.len > 3:
  591. message(c.config, a.info, warnEachIdentIsTuple)
  592. for j in 0..<a.len-2:
  593. if a[j].kind == nkDotExpr:
  594. fillPartialObject(c, a[j],
  595. if a.kind != nkVarTuple: typ else: tup[j])
  596. addToVarSection(c, result, n, a)
  597. continue
  598. var v = semIdentDef(c, a[j], symkind, false)
  599. styleCheckDef(c, v)
  600. onDef(a[j].info, v)
  601. if sfGenSym notin v.flags:
  602. if not isDiscardUnderscore(v): addInterfaceDecl(c, v)
  603. else:
  604. if v.owner == nil: v.owner = c.p.owner
  605. when oKeepVariableNames:
  606. if c.inUnrolledContext > 0: v.flags.incl(sfShadowed)
  607. else:
  608. let shadowed = findShadowedVar(c, v)
  609. if shadowed != nil:
  610. shadowed.flags.incl(sfShadowed)
  611. if shadowed.kind == skResult and sfGenSym notin v.flags:
  612. message(c.config, a.info, warnResultShadowed)
  613. if a.kind != nkVarTuple:
  614. if def.kind != nkEmpty:
  615. if sfThread in v.flags: localError(c.config, def.info, errThreadvarCannotInit)
  616. setVarType(c, v, typ)
  617. # this is needed for the evaluation pass, guard checking
  618. # and custom pragmas:
  619. b = newNodeI(nkIdentDefs, a.info)
  620. if importantComments(c.config):
  621. # keep documentation information:
  622. b.comment = a.comment
  623. # postfix not generated here (to generate, get rid of it in transf)
  624. if a[j].kind == nkPragmaExpr:
  625. var p = newNodeI(nkPragmaExpr, a.info)
  626. p.add newSymNode(v)
  627. p.add a[j][1]
  628. b.add p
  629. else:
  630. b.add newSymNode(v)
  631. # keep type desc for doc generator
  632. b.add a[^2]
  633. b.add copyTree(def)
  634. addToVarSection(c, result, n, b)
  635. v.ast = b
  636. else:
  637. if def.kind in {nkPar, nkTupleConstr}: v.ast = def[j]
  638. # bug #7663, for 'nim check' this can be a non-tuple:
  639. if tup.kind == tyTuple: setVarType(c, v, tup[j])
  640. else: v.typ = tup
  641. b[j] = newSymNode(v)
  642. if def.kind == nkEmpty:
  643. let actualType = v.typ.skipTypes({tyGenericInst, tyAlias,
  644. tyUserTypeClassInst})
  645. if actualType.kind in {tyObject, tyDistinct} and
  646. actualType.requiresInit:
  647. defaultConstructionError(c, v.typ, v.info)
  648. else:
  649. checkNilable(c, v)
  650. # allow let to not be initialised if imported from C:
  651. if v.kind == skLet and sfImportc notin v.flags and (strictDefs notin c.features or not isLocalSym(v)):
  652. localError(c.config, a.info, errLetNeedsInit)
  653. if sfCompileTime in v.flags:
  654. if a.kind != nkVarTuple:
  655. var x = newNodeI(result.kind, v.info)
  656. x.add result[i]
  657. vm.setupCompileTimeVar(c.module, c.idgen, c.graph, x)
  658. else:
  659. localError(c.config, a.info, "cannot destructure to compile time variable")
  660. if v.flags * {sfGlobal, sfThread} == {sfGlobal}:
  661. message(c.config, v.info, hintGlobalVar)
  662. if {sfGlobal, sfPure} <= v.flags:
  663. globalVarInitCheck(c, def)
  664. suggestSym(c.graph, v.info, v, c.graph.usageSym)
  665. proc semConst(c: PContext, n: PNode): PNode =
  666. result = copyNode(n)
  667. inc c.inStaticContext
  668. var b: PNode
  669. for i in 0..<n.len:
  670. var a = n[i]
  671. if c.config.cmd == cmdIdeTools: suggestStmt(c, a)
  672. if a.kind == nkCommentStmt: continue
  673. if a.kind notin {nkConstDef, nkVarTuple}: illFormedAst(a, c.config)
  674. checkMinSonsLen(a, 3, c.config)
  675. b = semVarMacroPragma(c, a, n)
  676. if b != nil:
  677. addToVarSection(c, result, b)
  678. continue
  679. var typ: PType = nil
  680. if a[^2].kind != nkEmpty:
  681. typ = semTypeNode(c, a[^2], nil)
  682. var typFlags: TTypeAllowedFlags
  683. # don't evaluate here since the type compatibility check below may add a converter
  684. var def = semExprWithType(c, a[^1], {efTypeAllowed}, typ)
  685. if def.kind == nkSym and def.sym.kind in {skTemplate, skMacro}:
  686. typFlags.incl taIsTemplateOrMacro
  687. elif def.typ.kind == tyTypeDesc and c.p.owner.kind != skMacro:
  688. typFlags.incl taProcContextIsNotMacro
  689. # check type compatibility between def.typ and typ:
  690. if typ != nil:
  691. if typ.isMetaType:
  692. def = inferWithMetatype(c, typ, def)
  693. typ = def.typ
  694. else:
  695. def = fitRemoveHiddenConv(c, typ, def)
  696. else:
  697. typ = def.typ
  698. # evaluate the node
  699. def = semConstExpr(c, def)
  700. if def == nil:
  701. localError(c.config, a[^1].info, errConstExprExpected)
  702. continue
  703. if def.kind != nkNilLit:
  704. if c.matchedConcept != nil:
  705. typFlags.incl taConcept
  706. typeAllowedCheck(c, a.info, typ, skConst, typFlags)
  707. if a.kind == nkVarTuple:
  708. if typ.kind != tyTuple:
  709. localError(c.config, a.info, errXExpected, "tuple")
  710. elif a.len-2 != typ.len:
  711. localError(c.config, a.info, errWrongNumberOfVariables)
  712. b = newNodeI(nkVarTuple, a.info)
  713. newSons(b, a.len)
  714. b[^2] = a[^2]
  715. b[^1] = def
  716. for j in 0..<a.len-2:
  717. var v = semIdentDef(c, a[j], skConst)
  718. if sfGenSym notin v.flags: addInterfaceDecl(c, v)
  719. elif v.owner == nil: v.owner = getCurrOwner(c)
  720. styleCheckDef(c, v)
  721. onDef(a[j].info, v)
  722. if a.kind != nkVarTuple:
  723. setVarType(c, v, typ)
  724. when false:
  725. v.ast = def # no need to copy
  726. b = newNodeI(nkConstDef, a.info)
  727. if importantComments(c.config): b.comment = a.comment
  728. # postfix not generated here (to generate, get rid of it in transf)
  729. if a[j].kind == nkPragmaExpr:
  730. var p = newNodeI(nkPragmaExpr, a.info)
  731. p.add newSymNode(v)
  732. p.add a[j][1].copyTree
  733. b.add p
  734. else:
  735. b.add newSymNode(v)
  736. b.add a[1]
  737. b.add copyTree(def)
  738. v.ast = b
  739. else:
  740. setVarType(c, v, typ[j])
  741. v.ast = if def[j].kind != nkExprColonExpr: def[j]
  742. else: def[j][1]
  743. b[j] = newSymNode(v)
  744. addToVarSection(c, result, n, b)
  745. dec c.inStaticContext
  746. include semfields
  747. proc symForVar(c: PContext, n: PNode): PSym =
  748. let m = if n.kind == nkPragmaExpr: n[0] else: n
  749. result = newSymG(skForVar, m, c)
  750. styleCheckDef(c, result)
  751. onDef(n.info, result)
  752. if n.kind == nkPragmaExpr:
  753. pragma(c, result, n[1], forVarPragmas)
  754. proc semForVars(c: PContext, n: PNode; flags: TExprFlags): PNode =
  755. result = n
  756. let iterBase = n[^2].typ
  757. var iter = skipTypes(iterBase, {tyGenericInst, tyAlias, tySink, tyOwned})
  758. var iterAfterVarLent = iter.skipTypes({tyGenericInst, tyAlias, tyLent, tyVar})
  759. # n.len == 3 means that there is one for loop variable
  760. # and thus no tuple unpacking:
  761. if iterAfterVarLent.kind == tyEmpty:
  762. localError(c.config, n[^2].info, "cannot infer element type of $1" %
  763. renderTree(n[^2], {renderNoComments}))
  764. if iterAfterVarLent.kind != tyTuple or n.len == 3:
  765. if n.len == 3:
  766. if n[0].kind == nkVarTuple:
  767. if n[0].len-1 != iterAfterVarLent.len:
  768. return localErrorNode(c, n, n[0].info, errWrongNumberOfVariables)
  769. for i in 0..<n[0].len-1:
  770. var v = symForVar(c, n[0][i])
  771. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  772. case iter.kind
  773. of tyVar, tyLent:
  774. v.typ = newTypeS(iter.kind, c)
  775. v.typ.add iterAfterVarLent[i]
  776. if tfVarIsPtr in iter.flags:
  777. v.typ.flags.incl tfVarIsPtr
  778. else:
  779. v.typ = iter[i]
  780. n[0][i] = newSymNode(v)
  781. if sfGenSym notin v.flags and not isDiscardUnderscore(v): addDecl(c, v)
  782. elif v.owner == nil: v.owner = getCurrOwner(c)
  783. else:
  784. var v = symForVar(c, n[0])
  785. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  786. # BUGFIX: don't use `iter` here as that would strip away
  787. # the ``tyGenericInst``! See ``tests/compile/tgeneric.nim``
  788. # for an example:
  789. v.typ = iterBase
  790. n[0] = newSymNode(v)
  791. if sfGenSym notin v.flags and not isDiscardUnderscore(v): addDecl(c, v)
  792. elif v.owner == nil: v.owner = getCurrOwner(c)
  793. else:
  794. localError(c.config, n.info, errWrongNumberOfVariables)
  795. elif n.len-2 != iterAfterVarLent.len:
  796. localError(c.config, n.info, errWrongNumberOfVariables)
  797. else:
  798. for i in 0..<n.len - 2:
  799. if n[i].kind == nkVarTuple:
  800. var mutable = false
  801. var isLent = false
  802. case iter[i].kind
  803. of tyVar:
  804. mutable = true
  805. iter[i] = iter[i].skipTypes({tyVar})
  806. of tyLent:
  807. isLent = true
  808. iter[i] = iter[i].skipTypes({tyLent})
  809. else: discard
  810. if n[i].len-1 != iter[i].len:
  811. localError(c.config, n[i].info, errWrongNumberOfVariables)
  812. for j in 0..<n[i].len-1:
  813. var v = symForVar(c, n[i][j])
  814. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  815. if mutable:
  816. v.typ = newTypeS(tyVar, c)
  817. v.typ.add iter[i][j]
  818. elif isLent:
  819. v.typ = newTypeS(tyLent, c)
  820. v.typ.add iter[i][j]
  821. else:
  822. v.typ = iter[i][j]
  823. n[i][j] = newSymNode(v)
  824. if not isDiscardUnderscore(v): addDecl(c, v)
  825. elif v.owner == nil: v.owner = getCurrOwner(c)
  826. else:
  827. var v = symForVar(c, n[i])
  828. if getCurrOwner(c).kind == skModule: incl(v.flags, sfGlobal)
  829. case iter.kind
  830. of tyVar, tyLent:
  831. v.typ = newTypeS(iter.kind, c)
  832. v.typ.add iterAfterVarLent[i]
  833. if tfVarIsPtr in iter.flags:
  834. v.typ.flags.incl tfVarIsPtr
  835. else:
  836. v.typ = iter[i]
  837. n[i] = newSymNode(v)
  838. if sfGenSym notin v.flags:
  839. if not isDiscardUnderscore(v): addDecl(c, v)
  840. elif v.owner == nil: v.owner = getCurrOwner(c)
  841. inc(c.p.nestedLoopCounter)
  842. let oldBreakInLoop = c.p.breakInLoop
  843. c.p.breakInLoop = true
  844. openScope(c)
  845. n[^1] = semExprBranch(c, n[^1], flags)
  846. if efInTypeof notin flags:
  847. discardCheck(c, n[^1], flags)
  848. closeScope(c)
  849. c.p.breakInLoop = oldBreakInLoop
  850. dec(c.p.nestedLoopCounter)
  851. proc implicitIterator(c: PContext, it: string, arg: PNode): PNode =
  852. result = newNodeI(nkCall, arg.info)
  853. result.add(newIdentNode(getIdent(c.cache, it), arg.info))
  854. if arg.typ != nil and arg.typ.kind in {tyVar, tyLent}:
  855. result.add newDeref(arg)
  856. else:
  857. result.add arg
  858. result = semExprNoDeref(c, result, {efWantIterator})
  859. proc isTrivalStmtExpr(n: PNode): bool =
  860. for i in 0..<n.len-1:
  861. if n[i].kind notin {nkEmpty, nkCommentStmt}:
  862. return false
  863. result = true
  864. proc handleStmtMacro(c: PContext; n, selector: PNode; magicType: string;
  865. flags: TExprFlags): PNode =
  866. if selector.kind in nkCallKinds:
  867. # we transform
  868. # n := for a, b, c in m(x, y, z): Y
  869. # to
  870. # m(n)
  871. let maType = magicsys.getCompilerProc(c.graph, magicType)
  872. if maType == nil: return
  873. let headSymbol = selector[0]
  874. var o: TOverloadIter
  875. var match: PSym = nil
  876. var symx = initOverloadIter(o, c, headSymbol)
  877. while symx != nil:
  878. if symx.kind in {skTemplate, skMacro}:
  879. if symx.typ.len == 2 and symx.typ[1] == maType.typ:
  880. if match == nil:
  881. match = symx
  882. else:
  883. localError(c.config, n.info, errAmbiguousCallXYZ % [
  884. getProcHeader(c.config, match),
  885. getProcHeader(c.config, symx), $selector])
  886. symx = nextOverloadIter(o, c, headSymbol)
  887. if match == nil: return
  888. var callExpr = newNodeI(nkCall, n.info)
  889. callExpr.add newSymNode(match)
  890. callExpr.add n
  891. case match.kind
  892. of skMacro: result = semMacroExpr(c, callExpr, callExpr, match, flags)
  893. of skTemplate: result = semTemplateExpr(c, callExpr, match, flags)
  894. else: result = nil
  895. proc handleForLoopMacro(c: PContext; n: PNode; flags: TExprFlags): PNode =
  896. result = handleStmtMacro(c, n, n[^2], "ForLoopStmt", flags)
  897. proc handleCaseStmtMacro(c: PContext; n: PNode; flags: TExprFlags): PNode =
  898. # n[0] has been sem'checked and has a type. We use this to resolve
  899. # '`case`(n[0])' but then we pass 'n' to the `case` macro. This seems to
  900. # be the best solution.
  901. var toResolve = newNodeI(nkCall, n.info)
  902. toResolve.add newIdentNode(getIdent(c.cache, "case"), n.info)
  903. toResolve.add n[0]
  904. var errors: CandidateErrors
  905. var r = resolveOverloads(c, toResolve, toResolve, {skTemplate, skMacro}, {efNoDiagnostics},
  906. errors, false)
  907. if r.state == csMatch:
  908. var match = r.calleeSym
  909. markUsed(c, n[0].info, match)
  910. onUse(n[0].info, match)
  911. # but pass 'n' to the `case` macro, not 'n[0]':
  912. r.call[1] = n
  913. let toExpand = semResolvedCall(c, r, r.call, {})
  914. case match.kind
  915. of skMacro: result = semMacroExpr(c, toExpand, toExpand, match, flags)
  916. of skTemplate: result = semTemplateExpr(c, toExpand, match, flags)
  917. else: result = errorNode(c, n[0])
  918. elif r.state == csNoMatch:
  919. result = errorNode(c, n[0])
  920. if result.kind == nkEmpty:
  921. localError(c.config, n[0].info, errSelectorMustBeOfCertainTypes)
  922. # this would be the perfectly consistent solution with 'for loop macros',
  923. # but it kinda sucks for pattern matching as the matcher is not attached to
  924. # a type then:
  925. when false:
  926. result = handleStmtMacro(c, n, n[0], "CaseStmt")
  927. proc semFor(c: PContext, n: PNode; flags: TExprFlags): PNode =
  928. checkMinSonsLen(n, 3, c.config)
  929. result = handleForLoopMacro(c, n, flags)
  930. if result != nil: return result
  931. openScope(c)
  932. result = n
  933. n[^2] = semExprNoDeref(c, n[^2], {efWantIterator})
  934. var call = n[^2]
  935. if call.kind == nkStmtListExpr and isTrivalStmtExpr(call):
  936. call = call.lastSon
  937. n[^2] = call
  938. let isCallExpr = call.kind in nkCallKinds
  939. if isCallExpr and call[0].kind == nkSym and
  940. call[0].sym.magic in {mFields, mFieldPairs, mOmpParFor}:
  941. if call[0].sym.magic == mOmpParFor:
  942. result = semForVars(c, n, flags)
  943. result.transitionSonsKind(nkParForStmt)
  944. else:
  945. result = semForFields(c, n, call[0].sym.magic)
  946. elif isCallExpr and isClosureIterator(call[0].typ.skipTypes(abstractInst)):
  947. # first class iterator:
  948. result = semForVars(c, n, flags)
  949. elif not isCallExpr or call[0].kind != nkSym or
  950. call[0].sym.kind != skIterator:
  951. if n.len == 3:
  952. n[^2] = implicitIterator(c, "items", n[^2])
  953. elif n.len == 4:
  954. n[^2] = implicitIterator(c, "pairs", n[^2])
  955. else:
  956. localError(c.config, n[^2].info, "iterator within for loop context expected")
  957. result = semForVars(c, n, flags)
  958. else:
  959. result = semForVars(c, n, flags)
  960. # propagate any enforced VoidContext:
  961. if n[^1].typ == c.enforceVoidContext:
  962. result.typ = c.enforceVoidContext
  963. elif efInTypeof in flags:
  964. result.typ = result.lastSon.typ
  965. closeScope(c)
  966. proc semCase(c: PContext, n: PNode; flags: TExprFlags; expectedType: PType = nil): PNode =
  967. result = n
  968. checkMinSonsLen(n, 2, c.config)
  969. openScope(c)
  970. pushCaseContext(c, n)
  971. n[0] = semExprWithType(c, n[0])
  972. var chckCovered = false
  973. var covered: Int128 = toInt128(0)
  974. var typ = commonTypeBegin
  975. var expectedType = expectedType
  976. var hasElse = false
  977. let caseTyp = skipTypes(n[0].typ, abstractVar-{tyTypeDesc})
  978. const shouldChckCovered = {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt64, tyBool}
  979. case caseTyp.kind
  980. of shouldChckCovered:
  981. chckCovered = true
  982. of tyRange:
  983. if skipTypes(caseTyp[0], abstractInst).kind in shouldChckCovered:
  984. chckCovered = true
  985. of tyFloat..tyFloat128, tyString, tyCstring, tyError:
  986. discard
  987. else:
  988. popCaseContext(c)
  989. closeScope(c)
  990. return handleCaseStmtMacro(c, n, flags)
  991. template invalidOrderOfBranches(n: PNode) =
  992. localError(c.config, n.info, "invalid order of case branches")
  993. break
  994. for i in 1..<n.len:
  995. setCaseContextIdx(c, i)
  996. var x = n[i]
  997. when defined(nimsuggest):
  998. if c.config.ideCmd == ideSug and exactEquals(c.config.m.trackPos, x.info) and caseTyp.kind == tyEnum:
  999. suggestEnum(c, x, caseTyp)
  1000. case x.kind
  1001. of nkOfBranch:
  1002. if hasElse: invalidOrderOfBranches(x)
  1003. checkMinSonsLen(x, 2, c.config)
  1004. semCaseBranch(c, n, x, i, covered)
  1005. var last = x.len-1
  1006. x[last] = semExprBranchScope(c, x[last], expectedType)
  1007. typ = commonType(c, typ, x[last])
  1008. expectedType = typ
  1009. of nkElifBranch:
  1010. if hasElse: invalidOrderOfBranches(x)
  1011. chckCovered = false
  1012. checkSonsLen(x, 2, c.config)
  1013. openScope(c)
  1014. x[0] = forceBool(c, semExprWithType(c, x[0], expectedType = getSysType(c.graph, n.info, tyBool)))
  1015. x[1] = semExprBranch(c, x[1], expectedType = expectedType)
  1016. typ = commonType(c, typ, x[1])
  1017. expectedType = typ
  1018. closeScope(c)
  1019. of nkElse:
  1020. checkSonsLen(x, 1, c.config)
  1021. x[0] = semExprBranchScope(c, x[0], expectedType)
  1022. typ = commonType(c, typ, x[0])
  1023. expectedType = typ
  1024. if (chckCovered and covered == toCover(c, n[0].typ)) or hasElse:
  1025. message(c.config, x.info, warnUnreachableElse)
  1026. hasElse = true
  1027. chckCovered = false
  1028. else:
  1029. illFormedAst(x, c.config)
  1030. if chckCovered:
  1031. if covered == toCover(c, n[0].typ):
  1032. hasElse = true
  1033. elif n[0].typ.skipTypes(abstractRange).kind in {tyEnum, tyChar}:
  1034. localError(c.config, n.info, "not all cases are covered; missing: $1" %
  1035. formatMissingEnums(c, n))
  1036. else:
  1037. localError(c.config, n.info, "not all cases are covered")
  1038. popCaseContext(c)
  1039. closeScope(c)
  1040. if isEmptyType(typ) or typ.kind in {tyNil, tyUntyped} or
  1041. (not hasElse and efInTypeof notin flags):
  1042. for i in 1..<n.len: discardCheck(c, n[i].lastSon, flags)
  1043. # propagate any enforced VoidContext:
  1044. if typ == c.enforceVoidContext:
  1045. result.typ = c.enforceVoidContext
  1046. else:
  1047. for i in 1..<n.len:
  1048. var it = n[i]
  1049. let j = it.len-1
  1050. if not endsInNoReturn(it[j]):
  1051. it[j] = fitNode(c, typ, it[j], it[j].info)
  1052. result.typ = typ
  1053. proc semRaise(c: PContext, n: PNode): PNode =
  1054. result = n
  1055. checkSonsLen(n, 1, c.config)
  1056. if n[0].kind != nkEmpty:
  1057. n[0] = semExprWithType(c, n[0])
  1058. var typ = n[0].typ
  1059. if not isImportedException(typ, c.config):
  1060. typ = typ.skipTypes({tyAlias, tyGenericInst, tyOwned})
  1061. if typ.kind != tyRef:
  1062. localError(c.config, n.info, errExprCannotBeRaised)
  1063. if typ.len > 0 and not isException(typ.lastSon):
  1064. localError(c.config, n.info, "raised object of type $1 does not inherit from Exception" % typeToString(typ))
  1065. proc addGenericParamListToScope(c: PContext, n: PNode) =
  1066. if n.kind != nkGenericParams: illFormedAst(n, c.config)
  1067. for i in 0..<n.len:
  1068. var a = n[i]
  1069. if a.kind == nkSym: addDecl(c, a.sym)
  1070. else: illFormedAst(a, c.config)
  1071. proc typeSectionTypeName(c: PContext; n: PNode): PNode =
  1072. if n.kind == nkPragmaExpr:
  1073. if n.len == 0: illFormedAst(n, c.config)
  1074. result = n[0]
  1075. else:
  1076. result = n
  1077. if result.kind != nkSym: illFormedAst(n, c.config)
  1078. proc typeDefLeftSidePass(c: PContext, typeSection: PNode, i: int) =
  1079. let typeDef = typeSection[i]
  1080. checkSonsLen(typeDef, 3, c.config)
  1081. var name = typeDef[0]
  1082. var s: PSym
  1083. if name.kind == nkDotExpr and typeDef[2].kind == nkObjectTy:
  1084. let pkgName = considerQuotedIdent(c, name[0])
  1085. let typName = considerQuotedIdent(c, name[1])
  1086. let pkg = c.graph.packageSyms.strTableGet(pkgName)
  1087. if pkg.isNil or pkg.kind != skPackage:
  1088. localError(c.config, name.info, "unknown package name: " & pkgName.s)
  1089. else:
  1090. let typsym = c.graph.packageTypes.strTableGet(typName)
  1091. if typsym.isNil:
  1092. s = semIdentDef(c, name[1], skType)
  1093. onDef(name[1].info, s)
  1094. s.typ = newTypeS(tyObject, c)
  1095. s.typ.sym = s
  1096. s.flags.incl sfForward
  1097. c.graph.packageTypes.strTableAdd s
  1098. addInterfaceDecl(c, s)
  1099. elif typsym.kind == skType and sfForward in typsym.flags:
  1100. s = typsym
  1101. addInterfaceDecl(c, s)
  1102. # PRTEMP no onDef here?
  1103. else:
  1104. localError(c.config, name.info, typsym.name.s & " is not a type that can be forwarded")
  1105. s = typsym
  1106. else:
  1107. s = semIdentDef(c, name, skType)
  1108. onDef(name.info, s)
  1109. s.typ = newTypeS(tyForward, c)
  1110. s.typ.sym = s # process pragmas:
  1111. if name.kind == nkPragmaExpr:
  1112. let rewritten = applyTypeSectionPragmas(c, name[1], typeDef)
  1113. if rewritten != nil:
  1114. case rewritten.kind
  1115. of nkTypeDef:
  1116. typeSection[i] = rewritten
  1117. of nkTypeSection:
  1118. typeSection.sons[i .. i] = rewritten.sons
  1119. else: illFormedAst(rewritten, c.config)
  1120. typeDefLeftSidePass(c, typeSection, i)
  1121. return
  1122. pragma(c, s, name[1], typePragmas)
  1123. if sfForward in s.flags:
  1124. # check if the symbol already exists:
  1125. let pkg = c.module.owner
  1126. if not isTopLevel(c) or pkg.isNil:
  1127. localError(c.config, name.info, "only top level types in a package can be 'package'")
  1128. else:
  1129. let typsym = c.graph.packageTypes.strTableGet(s.name)
  1130. if typsym != nil:
  1131. if sfForward notin typsym.flags or sfNoForward notin typsym.flags:
  1132. typeCompleted(typsym)
  1133. typsym.info = s.info
  1134. else:
  1135. localError(c.config, name.info, "cannot complete type '" & s.name.s & "' twice; " &
  1136. "previous type completion was here: " & c.config$typsym.info)
  1137. s = typsym
  1138. # add it here, so that recursive types are possible:
  1139. if sfGenSym notin s.flags: addInterfaceDecl(c, s)
  1140. elif s.owner == nil: s.owner = getCurrOwner(c)
  1141. if name.kind == nkPragmaExpr:
  1142. typeDef[0][0] = newSymNode(s)
  1143. else:
  1144. typeDef[0] = newSymNode(s)
  1145. proc typeSectionLeftSidePass(c: PContext, n: PNode) =
  1146. # process the symbols on the left side for the whole type section, before
  1147. # we even look at the type definitions on the right
  1148. var i = 0
  1149. while i < n.len: # n may grow due to type pragma macros
  1150. var a = n[i]
  1151. when defined(nimsuggest):
  1152. if c.config.cmd == cmdIdeTools:
  1153. inc c.inTypeContext
  1154. suggestStmt(c, a)
  1155. dec c.inTypeContext
  1156. case a.kind
  1157. of nkCommentStmt: discard
  1158. of nkTypeDef: typeDefLeftSidePass(c, n, i)
  1159. else: illFormedAst(a, c.config)
  1160. inc i
  1161. proc checkCovariantParamsUsages(c: PContext; genericType: PType) =
  1162. var body = genericType[^1]
  1163. proc traverseSubTypes(c: PContext; t: PType): bool =
  1164. template error(msg) = localError(c.config, genericType.sym.info, msg)
  1165. result = false
  1166. template subresult(r) =
  1167. let sub = r
  1168. result = result or sub
  1169. case t.kind
  1170. of tyGenericParam:
  1171. t.flags.incl tfWeakCovariant
  1172. return true
  1173. of tyObject:
  1174. for field in t.n:
  1175. subresult traverseSubTypes(c, field.typ)
  1176. of tyArray:
  1177. return traverseSubTypes(c, t[1])
  1178. of tyProc:
  1179. for subType in t.sons:
  1180. if subType != nil:
  1181. subresult traverseSubTypes(c, subType)
  1182. if result:
  1183. error("non-invariant type param used in a proc type: " & $t)
  1184. of tySequence:
  1185. return traverseSubTypes(c, t[0])
  1186. of tyGenericInvocation:
  1187. let targetBody = t[0]
  1188. for i in 1..<t.len:
  1189. let param = t[i]
  1190. if param.kind == tyGenericParam:
  1191. if tfCovariant in param.flags:
  1192. let formalFlags = targetBody[i-1].flags
  1193. if tfCovariant notin formalFlags:
  1194. error("covariant param '" & param.sym.name.s &
  1195. "' used in a non-covariant position")
  1196. elif tfWeakCovariant in formalFlags:
  1197. param.flags.incl tfWeakCovariant
  1198. result = true
  1199. elif tfContravariant in param.flags:
  1200. let formalParam = targetBody[i-1].sym
  1201. if tfContravariant notin formalParam.typ.flags:
  1202. error("contravariant param '" & param.sym.name.s &
  1203. "' used in a non-contravariant position")
  1204. result = true
  1205. else:
  1206. subresult traverseSubTypes(c, param)
  1207. of tyAnd, tyOr, tyNot, tyStatic, tyBuiltInTypeClass, tyCompositeTypeClass:
  1208. error("non-invariant type parameters cannot be used with types such '" & $t & "'")
  1209. of tyUserTypeClass, tyUserTypeClassInst:
  1210. error("non-invariant type parameters are not supported in concepts")
  1211. of tyTuple:
  1212. for fieldType in t.sons:
  1213. subresult traverseSubTypes(c, fieldType)
  1214. of tyPtr, tyRef, tyVar, tyLent:
  1215. if t.base.kind == tyGenericParam: return true
  1216. return traverseSubTypes(c, t.base)
  1217. of tyDistinct, tyAlias, tySink, tyOwned:
  1218. return traverseSubTypes(c, t.lastSon)
  1219. of tyGenericInst:
  1220. internalAssert c.config, false
  1221. else:
  1222. discard
  1223. discard traverseSubTypes(c, body)
  1224. proc typeSectionRightSidePass(c: PContext, n: PNode) =
  1225. for i in 0..<n.len:
  1226. var a = n[i]
  1227. if a.kind == nkCommentStmt: continue
  1228. if a.kind != nkTypeDef: illFormedAst(a, c.config)
  1229. checkSonsLen(a, 3, c.config)
  1230. let name = typeSectionTypeName(c, a[0])
  1231. var s = name.sym
  1232. if s.magic == mNone and a[2].kind == nkEmpty:
  1233. localError(c.config, a.info, errImplOfXexpected % s.name.s)
  1234. if s.magic != mNone: processMagicType(c, s)
  1235. let oldFlags = s.typ.flags
  1236. if a[1].kind != nkEmpty:
  1237. # We have a generic type declaration here. In generic types,
  1238. # symbol lookup needs to be done here.
  1239. openScope(c)
  1240. pushOwner(c, s)
  1241. if s.magic == mNone: s.typ.kind = tyGenericBody
  1242. # XXX for generic type aliases this is not correct! We need the
  1243. # underlying Id really:
  1244. #
  1245. # type
  1246. # TGObj[T] = object
  1247. # TAlias[T] = TGObj[T]
  1248. #
  1249. s.typ.n = semGenericParamList(c, a[1], s.typ)
  1250. a[1] = s.typ.n
  1251. s.typ.size = -1 # could not be computed properly
  1252. # we fill it out later. For magic generics like 'seq', it won't be filled
  1253. # so we use tyNone instead of nil to not crash for strange conversions
  1254. # like: mydata.seq
  1255. rawAddSon(s.typ, newTypeS(tyNone, c))
  1256. s.ast = a
  1257. inc c.inGenericContext
  1258. var body = semTypeNode(c, a[2], s.typ)
  1259. dec c.inGenericContext
  1260. if body != nil:
  1261. body.sym = s
  1262. body.size = -1 # could not be computed properly
  1263. if body.kind == tyObject:
  1264. # add flags applied to generic type to object (nominal) type
  1265. incl(body.flags, oldFlags)
  1266. # {.inheritable, final.} is already disallowed, but
  1267. # object might have been assumed to be final
  1268. if tfInheritable in oldFlags and tfFinal in body.flags:
  1269. excl(body.flags, tfFinal)
  1270. s.typ[^1] = body
  1271. if tfCovariant in s.typ.flags:
  1272. checkCovariantParamsUsages(c, s.typ)
  1273. # XXX: This is a temporary limitation:
  1274. # The codegen currently produces various failures with
  1275. # generic imported types that have fields, but we need
  1276. # the fields specified in order to detect weak covariance.
  1277. # The proper solution is to teach the codegen how to handle
  1278. # such types, because this would offer various interesting
  1279. # possibilities such as instantiating C++ generic types with
  1280. # garbage collected Nim types.
  1281. if sfImportc in s.flags:
  1282. var body = s.typ.lastSon
  1283. if body.kind == tyObject:
  1284. # erases all declared fields
  1285. body.n.sons = @[]
  1286. popOwner(c)
  1287. closeScope(c)
  1288. elif a[2].kind != nkEmpty:
  1289. # process the type's body:
  1290. pushOwner(c, s)
  1291. var t = semTypeNode(c, a[2], s.typ)
  1292. if s.typ == nil:
  1293. s.typ = t
  1294. elif t != s.typ and (s.typ == nil or s.typ.kind != tyAlias):
  1295. # this can happen for e.g. tcan_alias_specialised_generic:
  1296. assignType(s.typ, t)
  1297. #debug s.typ
  1298. s.ast = a
  1299. popOwner(c)
  1300. # If the right hand side expression was a macro call we replace it with
  1301. # its evaluated result here so that we don't execute it once again in the
  1302. # final pass
  1303. if a[2].kind in nkCallKinds:
  1304. incl a[2].flags, nfSem # bug #10548
  1305. if sfExportc in s.flags and s.typ.kind == tyAlias:
  1306. localError(c.config, name.info, "{.exportc.} not allowed for type aliases")
  1307. if tfBorrowDot in s.typ.flags and s.typ.skipTypes({tyGenericBody}).kind != tyDistinct:
  1308. excl s.typ.flags, tfBorrowDot
  1309. localError(c.config, name.info, "only a 'distinct' type can borrow `.`")
  1310. let aa = a[2]
  1311. if aa.kind in {nkRefTy, nkPtrTy} and aa.len == 1 and
  1312. aa[0].kind == nkObjectTy:
  1313. # give anonymous object a dummy symbol:
  1314. var st = s.typ
  1315. if st.kind == tyGenericBody: st = st.lastSon
  1316. internalAssert c.config, st.kind in {tyPtr, tyRef}
  1317. internalAssert c.config, st.lastSon.sym == nil
  1318. incl st.flags, tfRefsAnonObj
  1319. let objTy = st.lastSon
  1320. # add flags for `ref object` etc to underlying `object`
  1321. incl(objTy.flags, oldFlags)
  1322. # {.inheritable, final.} is already disallowed, but
  1323. # object might have been assumed to be final
  1324. if tfInheritable in oldFlags and tfFinal in objTy.flags:
  1325. excl(objTy.flags, tfFinal)
  1326. let obj = newSym(skType, getIdent(c.cache, s.name.s & ":ObjectType"),
  1327. nextSymId c.idgen, getCurrOwner(c), s.info)
  1328. obj.flags.incl sfGeneratedType
  1329. let symNode = newSymNode(obj)
  1330. obj.ast = a.shallowCopy
  1331. case a[0].kind
  1332. of nkSym: obj.ast[0] = symNode
  1333. of nkPragmaExpr:
  1334. obj.ast[0] = a[0].shallowCopy
  1335. obj.ast[0][0] = symNode
  1336. obj.ast[0][1] = a[0][1]
  1337. else: assert(false)
  1338. obj.ast[1] = a[1]
  1339. obj.ast[2] = a[2][0]
  1340. if sfPure in s.flags:
  1341. obj.flags.incl sfPure
  1342. obj.typ = objTy
  1343. objTy.sym = obj
  1344. proc checkForMetaFields(c: PContext; n: PNode) =
  1345. proc checkMeta(c: PContext; n: PNode; t: PType) =
  1346. if t != nil and t.isMetaType and tfGenericTypeParam notin t.flags:
  1347. if t.kind == tyBuiltInTypeClass and t.len == 1 and t[0].kind == tyProc:
  1348. localError(c.config, n.info, ("'$1' is not a concrete type; " &
  1349. "for a callback without parameters use 'proc()'") % t.typeToString)
  1350. else:
  1351. localError(c.config, n.info, errTIsNotAConcreteType % t.typeToString)
  1352. if n.isNil: return
  1353. case n.kind
  1354. of nkRecList, nkRecCase:
  1355. for s in n: checkForMetaFields(c, s)
  1356. of nkOfBranch, nkElse:
  1357. checkForMetaFields(c, n.lastSon)
  1358. of nkSym:
  1359. let t = n.sym.typ
  1360. case t.kind
  1361. of tySequence, tySet, tyArray, tyOpenArray, tyVar, tyLent, tyPtr, tyRef,
  1362. tyProc, tyGenericInvocation, tyGenericInst, tyAlias, tySink, tyOwned:
  1363. let start = ord(t.kind in {tyGenericInvocation, tyGenericInst})
  1364. for i in start..<t.len:
  1365. checkMeta(c, n, t[i])
  1366. else:
  1367. checkMeta(c, n, t)
  1368. else:
  1369. internalAssert c.config, false
  1370. proc typeSectionFinalPass(c: PContext, n: PNode) =
  1371. for i in 0..<n.len:
  1372. var a = n[i]
  1373. if a.kind == nkCommentStmt: continue
  1374. let name = typeSectionTypeName(c, a[0])
  1375. var s = name.sym
  1376. # check the style here after the pragmas have been processed:
  1377. styleCheckDef(c, s)
  1378. # compute the type's size and check for illegal recursions:
  1379. if a[1].kind == nkEmpty:
  1380. var x = a[2]
  1381. if x.kind in nkCallKinds and nfSem in x.flags:
  1382. discard "already semchecked, see line marked with bug #10548"
  1383. else:
  1384. while x.kind in {nkStmtList, nkStmtListExpr} and x.len > 0:
  1385. x = x.lastSon
  1386. # we need the 'safeSkipTypes' here because illegally recursive types
  1387. # can enter at this point, see bug #13763
  1388. if x.kind notin {nkObjectTy, nkDistinctTy, nkEnumTy, nkEmpty} and
  1389. s.typ.safeSkipTypes(abstractPtrs).kind notin {tyObject, tyEnum}:
  1390. # type aliases are hard:
  1391. var t = semTypeNode(c, x, nil)
  1392. assert t != nil
  1393. if s.typ != nil and s.typ.kind notin {tyAlias, tySink}:
  1394. if t.kind in {tyProc, tyGenericInst} and not t.isMetaType:
  1395. assignType(s.typ, t)
  1396. s.typ.itemId = t.itemId
  1397. elif t.kind in {tyObject, tyEnum, tyDistinct}:
  1398. assert s.typ != nil
  1399. assignType(s.typ, t)
  1400. s.typ.itemId = t.itemId # same id
  1401. checkConstructedType(c.config, s.info, s.typ)
  1402. if s.typ.kind in {tyObject, tyTuple} and not s.typ.n.isNil:
  1403. checkForMetaFields(c, s.typ.n)
  1404. # fix bug #5170, bug #17162, bug #15526: ensure locally scoped types get a unique name:
  1405. if s.typ.kind in {tyEnum, tyRef, tyObject} and not isTopLevel(c):
  1406. incl(s.flags, sfGenSym)
  1407. #instAllTypeBoundOp(c, n.info)
  1408. proc semAllTypeSections(c: PContext; n: PNode): PNode =
  1409. proc gatherStmts(c: PContext; n: PNode; result: PNode) {.nimcall.} =
  1410. case n.kind
  1411. of nkIncludeStmt:
  1412. for i in 0..<n.len:
  1413. var f = checkModuleName(c.config, n[i])
  1414. if f != InvalidFileIdx:
  1415. if containsOrIncl(c.includedFiles, f.int):
  1416. localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
  1417. else:
  1418. let code = c.graph.includeFileCallback(c.graph, c.module, f)
  1419. gatherStmts c, code, result
  1420. excl(c.includedFiles, f.int)
  1421. of nkStmtList:
  1422. for i in 0..<n.len:
  1423. gatherStmts(c, n[i], result)
  1424. of nkTypeSection:
  1425. incl n.flags, nfSem
  1426. typeSectionLeftSidePass(c, n)
  1427. result.add n
  1428. else:
  1429. result.add n
  1430. result = newNodeI(nkStmtList, n.info)
  1431. gatherStmts(c, n, result)
  1432. template rec(name) =
  1433. for i in 0..<result.len:
  1434. if result[i].kind == nkTypeSection:
  1435. name(c, result[i])
  1436. rec typeSectionRightSidePass
  1437. rec typeSectionFinalPass
  1438. when false:
  1439. # too beautiful to delete:
  1440. template rec(name; setbit=false) =
  1441. proc `name rec`(c: PContext; n: PNode) {.nimcall.} =
  1442. if n.kind == nkTypeSection:
  1443. when setbit: incl n.flags, nfSem
  1444. name(c, n)
  1445. elif n.kind == nkStmtList:
  1446. for i in 0..<n.len:
  1447. `name rec`(c, n[i])
  1448. `name rec`(c, n)
  1449. rec typeSectionLeftSidePass, true
  1450. rec typeSectionRightSidePass
  1451. rec typeSectionFinalPass
  1452. proc semTypeSection(c: PContext, n: PNode): PNode =
  1453. ## Processes a type section. This must be done in separate passes, in order
  1454. ## to allow the type definitions in the section to reference each other
  1455. ## without regard for the order of their definitions.
  1456. if sfNoForward notin c.module.flags or nfSem notin n.flags:
  1457. inc c.inTypeContext
  1458. typeSectionLeftSidePass(c, n)
  1459. typeSectionRightSidePass(c, n)
  1460. typeSectionFinalPass(c, n)
  1461. dec c.inTypeContext
  1462. result = n
  1463. proc semParamList(c: PContext, n, genericParams: PNode, s: PSym) =
  1464. s.typ = semProcTypeNode(c, n, genericParams, nil, s.kind)
  1465. proc addParams(c: PContext, n: PNode, kind: TSymKind) =
  1466. for i in 1..<n.len:
  1467. if n[i].kind == nkSym: addParamOrResult(c, n[i].sym, kind)
  1468. else: illFormedAst(n, c.config)
  1469. proc semBorrow(c: PContext, n: PNode, s: PSym) =
  1470. # search for the correct alias:
  1471. var b = searchForBorrowProc(c, c.currentScope.parent, s)
  1472. if b != nil:
  1473. # store the alias:
  1474. n[bodyPos] = newSymNode(b)
  1475. # Carry over the original symbol magic, this is necessary in order to ensure
  1476. # the semantic pass is correct
  1477. s.magic = b.magic
  1478. if b.typ != nil and b.typ.len > 0:
  1479. s.typ.n[0] = b.typ.n[0]
  1480. s.typ.flags = b.typ.flags
  1481. else:
  1482. localError(c.config, n.info, errNoSymbolToBorrowFromFound)
  1483. proc swapResult(n: PNode, sRes: PSym, dNode: PNode) =
  1484. ## Swap nodes that are (skResult) symbols to d(estination)Node.
  1485. for i in 0..<n.safeLen:
  1486. if n[i].kind == nkSym and n[i].sym == sRes:
  1487. n[i] = dNode
  1488. swapResult(n[i], sRes, dNode)
  1489. proc addResult(c: PContext, n: PNode, t: PType, owner: TSymKind) =
  1490. template genResSym(s) =
  1491. var s = newSym(skResult, getIdent(c.cache, "result"), nextSymId c.idgen,
  1492. getCurrOwner(c), n.info)
  1493. s.typ = t
  1494. incl(s.flags, sfUsed)
  1495. if owner == skMacro or t != nil:
  1496. if n.len > resultPos and n[resultPos] != nil:
  1497. if n[resultPos].sym.kind != skResult:
  1498. localError(c.config, n.info, "incorrect result proc symbol")
  1499. if n[resultPos].sym.owner != getCurrOwner(c):
  1500. # re-write result with new ownership, and re-write the proc accordingly
  1501. let sResSym = n[resultPos].sym
  1502. genResSym(s)
  1503. n[resultPos] = newSymNode(s)
  1504. swapResult(n, sResSym, n[resultPos])
  1505. c.p.resultSym = n[resultPos].sym
  1506. else:
  1507. genResSym(s)
  1508. c.p.resultSym = s
  1509. n.add newSymNode(c.p.resultSym)
  1510. addParamOrResult(c, c.p.resultSym, owner)
  1511. proc semProcAnnotation(c: PContext, prc: PNode;
  1512. validPragmas: TSpecialWords): PNode =
  1513. # Mirrored with semVarMacroPragma
  1514. var n = prc[pragmasPos]
  1515. if n == nil or n.kind == nkEmpty: return
  1516. for i in 0..<n.len:
  1517. let it = n[i]
  1518. let key = if it.kind in nkPragmaCallKinds and it.len >= 1: it[0] else: it
  1519. if isPossibleMacroPragma(c, it, key):
  1520. # we transform ``proc p {.m, rest.}`` into ``m(do: proc p {.rest.})`` and
  1521. # let the semantic checker deal with it:
  1522. var x = newNodeI(nkCall, key.info)
  1523. x.add(key)
  1524. if it.kind in nkPragmaCallKinds and it.len > 1:
  1525. # pass pragma arguments to the macro too:
  1526. for i in 1..<it.len:
  1527. x.add(it[i])
  1528. # Drop the pragma from the list, this prevents getting caught in endless
  1529. # recursion when the nkCall is semanticized
  1530. prc[pragmasPos] = copyExcept(n, i)
  1531. if prc[pragmasPos].kind != nkEmpty and prc[pragmasPos].len == 0:
  1532. prc[pragmasPos] = c.graph.emptyNode
  1533. x.add(prc)
  1534. # recursion assures that this works for multiple macro annotations too:
  1535. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  1536. if r == nil:
  1537. # Restore the old list of pragmas since we couldn't process this
  1538. prc[pragmasPos] = n
  1539. # No matching macro was found but there's always the possibility this may
  1540. # be a .pragma. template instead
  1541. continue
  1542. doAssert r[0].kind == nkSym
  1543. let m = r[0].sym
  1544. case m.kind
  1545. of skMacro: result = semMacroExpr(c, r, r, m, {})
  1546. of skTemplate: result = semTemplateExpr(c, r, m, {})
  1547. else:
  1548. prc[pragmasPos] = n
  1549. continue
  1550. doAssert result != nil
  1551. return result
  1552. proc semInferredLambda(c: PContext, pt: TIdTable, n: PNode): PNode {.nosinks.} =
  1553. ## used for resolving 'auto' in lambdas based on their callsite
  1554. var n = n
  1555. let original = n[namePos].sym
  1556. let s = original #copySym(original, false)
  1557. #incl(s.flags, sfFromGeneric)
  1558. #s.owner = original
  1559. n = replaceTypesInBody(c, pt, n, original)
  1560. result = n
  1561. s.ast = result
  1562. n[namePos].sym = s
  1563. n[genericParamsPos] = c.graph.emptyNode
  1564. # for LL we need to avoid wrong aliasing
  1565. let params = copyTree n.typ.n
  1566. n[paramsPos] = params
  1567. s.typ = n.typ
  1568. for i in 1..<params.len:
  1569. if params[i].typ.kind in {tyTypeDesc, tyGenericParam,
  1570. tyFromExpr}+tyTypeClasses:
  1571. localError(c.config, params[i].info, "cannot infer type of parameter: " &
  1572. params[i].sym.name.s)
  1573. #params[i].sym.owner = s
  1574. openScope(c)
  1575. pushOwner(c, s)
  1576. addParams(c, params, skProc)
  1577. pushProcCon(c, s)
  1578. addResult(c, n, n.typ[0], skProc)
  1579. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], n.typ[0]))
  1580. trackProc(c, s, s.ast[bodyPos])
  1581. popProcCon(c)
  1582. popOwner(c)
  1583. closeScope(c)
  1584. if optOwnedRefs in c.config.globalOptions and result.typ != nil:
  1585. result.typ = makeVarType(c, result.typ, tyOwned)
  1586. # alternative variant (not quite working):
  1587. # var prc = arg[0].sym
  1588. # let inferred = c.semGenerateInstance(c, prc, m.bindings, arg.info)
  1589. # result = inferred.ast
  1590. # result.kind = arg.kind
  1591. proc activate(c: PContext, n: PNode) =
  1592. # XXX: This proc is part of my plan for getting rid of
  1593. # forward declarations. stay tuned.
  1594. when false:
  1595. # well for now it breaks code ...
  1596. case n.kind
  1597. of nkLambdaKinds:
  1598. discard semLambda(c, n, {})
  1599. of nkCallKinds:
  1600. for i in 1..<n.len: activate(c, n[i])
  1601. else:
  1602. discard
  1603. proc maybeAddResult(c: PContext, s: PSym, n: PNode) =
  1604. if s.kind == skMacro:
  1605. let resultType = sysTypeFromName(c.graph, n.info, "NimNode")
  1606. addResult(c, n, resultType, s.kind)
  1607. elif s.typ[0] != nil and not isInlineIterator(s.typ):
  1608. addResult(c, n, s.typ[0], s.kind)
  1609. proc canonType(c: PContext, t: PType): PType =
  1610. if t.kind == tySequence:
  1611. result = c.graph.sysTypes[tySequence]
  1612. else:
  1613. result = t
  1614. proc prevDestructor(c: PContext; prevOp: PSym; obj: PType; info: TLineInfo) =
  1615. var msg = "cannot bind another '" & prevOp.name.s & "' to: " & typeToString(obj)
  1616. if sfOverriden notin prevOp.flags:
  1617. msg.add "; previous declaration was constructed here implicitly: " & (c.config $ prevOp.info)
  1618. else:
  1619. msg.add "; previous declaration was here: " & (c.config $ prevOp.info)
  1620. localError(c.config, info, errGenerated, msg)
  1621. proc whereToBindTypeHook(c: PContext; t: PType): PType =
  1622. result = t
  1623. while true:
  1624. if result.kind in {tyGenericBody, tyGenericInst}: result = result.lastSon
  1625. elif result.kind == tyGenericInvocation: result = result[0]
  1626. else: break
  1627. if result.kind in {tyObject, tyDistinct, tySequence, tyString}:
  1628. result = canonType(c, result)
  1629. proc bindTypeHook(c: PContext; s: PSym; n: PNode; op: TTypeAttachedOp) =
  1630. let t = s.typ
  1631. var noError = false
  1632. let cond = if op == attachedDestructor:
  1633. t.len == 2 and t[0] == nil and t[1].kind == tyVar
  1634. elif op == attachedTrace:
  1635. t.len == 3 and t[0] == nil and t[1].kind == tyVar and t[2].kind == tyPointer
  1636. else:
  1637. t.len >= 2 and t[0] == nil
  1638. if cond:
  1639. var obj = t[1].skipTypes({tyVar})
  1640. while true:
  1641. incl(obj.flags, tfHasAsgn)
  1642. if obj.kind in {tyGenericBody, tyGenericInst}: obj = obj.lastSon
  1643. elif obj.kind == tyGenericInvocation: obj = obj[0]
  1644. else: break
  1645. if obj.kind in {tyObject, tyDistinct, tySequence, tyString}:
  1646. obj = canonType(c, obj)
  1647. let ao = getAttachedOp(c.graph, obj, op)
  1648. if ao == s:
  1649. discard "forward declared destructor"
  1650. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  1651. setAttachedOp(c.graph, c.module.position, obj, op, s)
  1652. else:
  1653. prevDestructor(c, ao, obj, n.info)
  1654. noError = true
  1655. if obj.owner.getModule != s.getModule:
  1656. localError(c.config, n.info, errGenerated,
  1657. "type bound operation `" & s.name.s & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  1658. if not noError and sfSystemModule notin s.owner.flags:
  1659. if op == attachedTrace:
  1660. localError(c.config, n.info, errGenerated,
  1661. "signature for '=trace' must be proc[T: object](x: var T; env: pointer)")
  1662. else:
  1663. localError(c.config, n.info, errGenerated,
  1664. "signature for '" & s.name.s & "' must be proc[T: object](x: var T)")
  1665. incl(s.flags, sfUsed)
  1666. incl(s.flags, sfOverriden)
  1667. proc semOverride(c: PContext, s: PSym, n: PNode) =
  1668. let name = s.name.s.normalize
  1669. case name
  1670. of "=destroy":
  1671. bindTypeHook(c, s, n, attachedDestructor)
  1672. of "deepcopy", "=deepcopy":
  1673. if s.typ.len == 2 and
  1674. s.typ[1].skipTypes(abstractInst).kind in {tyRef, tyPtr} and
  1675. sameType(s.typ[1], s.typ[0]):
  1676. # Note: we store the deepCopy in the base of the pointer to mitigate
  1677. # the problem that pointers are structural types:
  1678. var t = s.typ[1].skipTypes(abstractInst).lastSon.skipTypes(abstractInst)
  1679. while true:
  1680. if t.kind == tyGenericBody: t = t.lastSon
  1681. elif t.kind == tyGenericInvocation: t = t[0]
  1682. else: break
  1683. if t.kind in {tyObject, tyDistinct, tyEnum, tySequence, tyString}:
  1684. if getAttachedOp(c.graph, t, attachedDeepCopy).isNil:
  1685. setAttachedOp(c.graph, c.module.position, t, attachedDeepCopy, s)
  1686. else:
  1687. localError(c.config, n.info, errGenerated,
  1688. "cannot bind another 'deepCopy' to: " & typeToString(t))
  1689. else:
  1690. localError(c.config, n.info, errGenerated,
  1691. "cannot bind 'deepCopy' to: " & typeToString(t))
  1692. if t.owner.getModule != s.getModule:
  1693. localError(c.config, n.info, errGenerated,
  1694. "type bound operation `" & name & "` can be defined only in the same module with its type (" & t.typeToString() & ")")
  1695. else:
  1696. localError(c.config, n.info, errGenerated,
  1697. "signature for 'deepCopy' must be proc[T: ptr|ref](x: T): T")
  1698. incl(s.flags, sfUsed)
  1699. incl(s.flags, sfOverriden)
  1700. of "=", "=copy", "=sink":
  1701. if s.magic == mAsgn: return
  1702. incl(s.flags, sfUsed)
  1703. incl(s.flags, sfOverriden)
  1704. if name == "=":
  1705. message(c.config, n.info, warnDeprecated, "Overriding `=` hook is deprecated; Override `=copy` hook instead")
  1706. let t = s.typ
  1707. if t.len == 3 and t[0] == nil and t[1].kind == tyVar:
  1708. var obj = t[1][0]
  1709. while true:
  1710. incl(obj.flags, tfHasAsgn)
  1711. if obj.kind == tyGenericBody: obj = obj.lastSon
  1712. elif obj.kind == tyGenericInvocation: obj = obj[0]
  1713. else: break
  1714. var objB = t[2]
  1715. while true:
  1716. if objB.kind == tyGenericBody: objB = objB.lastSon
  1717. elif objB.kind in {tyGenericInvocation, tyGenericInst}:
  1718. objB = objB[0]
  1719. else: break
  1720. if obj.kind in {tyObject, tyDistinct, tySequence, tyString} and sameType(obj, objB):
  1721. # attach these ops to the canonical tySequence
  1722. obj = canonType(c, obj)
  1723. #echo "ATTACHING TO ", obj.id, " ", s.name.s, " ", cast[int](obj)
  1724. let k = if name == "=" or name == "=copy": attachedAsgn else: attachedSink
  1725. let ao = getAttachedOp(c.graph, obj, k)
  1726. if ao == s:
  1727. discard "forward declared op"
  1728. elif ao.isNil and tfCheckedForDestructor notin obj.flags:
  1729. setAttachedOp(c.graph, c.module.position, obj, k, s)
  1730. else:
  1731. prevDestructor(c, ao, obj, n.info)
  1732. if obj.owner.getModule != s.getModule:
  1733. localError(c.config, n.info, errGenerated,
  1734. "type bound operation `" & name & "` can be defined only in the same module with its type (" & obj.typeToString() & ")")
  1735. return
  1736. if sfSystemModule notin s.owner.flags:
  1737. localError(c.config, n.info, errGenerated,
  1738. "signature for '" & s.name.s & "' must be proc[T: object](x: var T; y: T)")
  1739. of "=trace":
  1740. if s.magic != mTrace:
  1741. bindTypeHook(c, s, n, attachedTrace)
  1742. else:
  1743. if sfOverriden in s.flags:
  1744. localError(c.config, n.info, errGenerated,
  1745. "'destroy' or 'deepCopy' expected for 'override'")
  1746. proc cursorInProcAux(conf: ConfigRef; n: PNode): bool =
  1747. if inCheckpoint(n.info, conf.m.trackPos) != cpNone: return true
  1748. for i in 0..<n.safeLen:
  1749. if cursorInProcAux(conf, n[i]): return true
  1750. proc cursorInProc(conf: ConfigRef; n: PNode): bool =
  1751. if n.info.fileIndex == conf.m.trackPos.fileIndex:
  1752. result = cursorInProcAux(conf, n)
  1753. proc hasObjParam(s: PSym): bool =
  1754. var t = s.typ
  1755. for col in 1..<t.len:
  1756. if skipTypes(t[col], skipPtrs).kind == tyObject:
  1757. return true
  1758. proc finishMethod(c: PContext, s: PSym) =
  1759. if hasObjParam(s):
  1760. methodDef(c.graph, c.idgen, s)
  1761. proc semMethodPrototype(c: PContext; s: PSym; n: PNode) =
  1762. if s.isGenericRoutine:
  1763. let tt = s.typ
  1764. var foundObj = false
  1765. # we start at 1 for now so that tparsecombnum continues to compile.
  1766. # XXX Revisit this problem later.
  1767. for col in 1..<tt.len:
  1768. let t = tt[col]
  1769. if t != nil and t.kind == tyGenericInvocation:
  1770. var x = skipTypes(t[0], {tyVar, tyLent, tyPtr, tyRef, tyGenericInst,
  1771. tyGenericInvocation, tyGenericBody,
  1772. tyAlias, tySink, tyOwned})
  1773. if x.kind == tyObject and t.len-1 == n[genericParamsPos].len:
  1774. foundObj = true
  1775. addMethodToGeneric(c.graph, c.module.position, x, col, s)
  1776. message(c.config, n.info, warnDeprecated, "generic methods are deprecated")
  1777. #if not foundObj:
  1778. # message(c.config, n.info, warnDeprecated, "generic method not attachable to object type is deprecated")
  1779. else:
  1780. # why check for the body? bug #2400 has none. Checking for sfForward makes
  1781. # no sense either.
  1782. # and result[bodyPos].kind != nkEmpty:
  1783. if hasObjParam(s):
  1784. methodDef(c.graph, c.idgen, s)
  1785. else:
  1786. localError(c.config, n.info, "'method' needs a parameter that has an object type")
  1787. proc semProcAux(c: PContext, n: PNode, kind: TSymKind,
  1788. validPragmas: TSpecialWords, flags: TExprFlags = {}): PNode =
  1789. result = semProcAnnotation(c, n, validPragmas)
  1790. if result != nil: return result
  1791. result = n
  1792. checkMinSonsLen(n, bodyPos + 1, c.config)
  1793. let isAnon = n[namePos].kind == nkEmpty
  1794. var s: PSym
  1795. case n[namePos].kind
  1796. of nkEmpty:
  1797. s = newSym(kind, c.cache.idAnon, nextSymId c.idgen, c.getCurrOwner, n.info)
  1798. s.flags.incl sfUsed
  1799. n[namePos] = newSymNode(s)
  1800. of nkSym:
  1801. s = n[namePos].sym
  1802. s.owner = c.getCurrOwner
  1803. else:
  1804. s = semIdentDef(c, n[namePos], kind)
  1805. n[namePos] = newSymNode(s)
  1806. when false:
  1807. # disable for now
  1808. if sfNoForward in c.module.flags and
  1809. sfSystemModule notin c.module.flags:
  1810. addInterfaceOverloadableSymAt(c, c.currentScope, s)
  1811. s.flags.incl sfForward
  1812. return
  1813. assert s.kind in skProcKinds
  1814. s.ast = n
  1815. s.options = c.config.options
  1816. #s.scope = c.currentScope
  1817. # before compiling the proc params & body, set as current the scope
  1818. # where the proc was declared
  1819. let declarationScope = c.currentScope
  1820. pushOwner(c, s)
  1821. openScope(c)
  1822. # process parameters:
  1823. # generic parameters, parameters, and also the implicit generic parameters
  1824. # within are analysed. This is often the entirety of their semantic analysis
  1825. # but later we will have to do a check for forward declarations, which can by
  1826. # way of pragmas, default params, and so on invalidate this parsing.
  1827. # Nonetheless, we need to carry out this analysis to perform the search for a
  1828. # potential forward declaration.
  1829. setGenericParamsMisc(c, n)
  1830. if n[paramsPos].kind != nkEmpty:
  1831. semParamList(c, n[paramsPos], n[genericParamsPos], s)
  1832. else:
  1833. s.typ = newProcType(c, n.info)
  1834. if n[genericParamsPos].safeLen == 0:
  1835. # if there exist no explicit or implicit generic parameters, then this is
  1836. # at most a nullary generic (generic with no type params). Regardless of
  1837. # whether it's a nullary generic or non-generic, we restore the original.
  1838. # In the case of `nkEmpty` it's non-generic and an empty `nkGeneircParams`
  1839. # is a nullary generic.
  1840. #
  1841. # Remarks about nullary generics vs non-generics:
  1842. # The difference between a non-generic and nullary generic is minor in
  1843. # most cases but there are subtle and significant differences as well.
  1844. # Due to instantiation that generic procs go through, a static echo in the
  1845. # body of a nullary generic will not be executed immediately, as it's
  1846. # instantiated and not immediately evaluated.
  1847. n[genericParamsPos] = n[miscPos][1]
  1848. n[miscPos] = c.graph.emptyNode
  1849. if tfTriggersCompileTime in s.typ.flags: incl(s.flags, sfCompileTime)
  1850. if n[patternPos].kind != nkEmpty:
  1851. n[patternPos] = semPattern(c, n[patternPos], s)
  1852. if s.kind == skIterator:
  1853. s.typ.flags.incl(tfIterator)
  1854. elif s.kind == skFunc:
  1855. incl(s.flags, sfNoSideEffect)
  1856. incl(s.typ.flags, tfNoSideEffect)
  1857. var (proto, comesFromShadowScope) =
  1858. if isAnon: (nil, false)
  1859. else: searchForProc(c, declarationScope, s)
  1860. if proto == nil and sfForward in s.flags and n[bodyPos].kind != nkEmpty:
  1861. ## In cases such as a macro generating a proc with a gensymmed name we
  1862. ## know `searchForProc` will not find it and sfForward will be set. In
  1863. ## such scenarios the sym is shared between forward declaration and we
  1864. ## can treat the `s` as the proto.
  1865. ## To differentiate between that happening and a macro just returning a
  1866. ## forward declaration that has been typed before we check if the body
  1867. ## is not empty. This has the sideeffect of allowing multiple forward
  1868. ## declarations if they share the same sym.
  1869. ## See the "doubly-typed forward decls" case in tmacros_issues.nim
  1870. proto = s
  1871. let hasProto = proto != nil
  1872. # set the default calling conventions
  1873. case s.kind
  1874. of skIterator:
  1875. if s.typ.callConv != ccClosure:
  1876. s.typ.callConv = if isAnon: ccClosure else: ccInline
  1877. of skMacro, skTemplate:
  1878. # we don't bother setting calling conventions for macros and templates
  1879. discard
  1880. else:
  1881. # NB: procs with a forward decl have theirs determined by the forward decl
  1882. if not hasProto:
  1883. # in this case we're either a forward declaration or we're an impl without
  1884. # a forward decl. We set the calling convention or will be set during
  1885. # pragma analysis further down.
  1886. s.typ.callConv = lastOptionEntry(c).defaultCC
  1887. if not hasProto and sfGenSym notin s.flags: #and not isAnon:
  1888. if s.kind in OverloadableSyms:
  1889. addInterfaceOverloadableSymAt(c, declarationScope, s)
  1890. else:
  1891. addInterfaceDeclAt(c, declarationScope, s)
  1892. pragmaCallable(c, s, n, validPragmas)
  1893. if not hasProto:
  1894. implicitPragmas(c, s, n.info, validPragmas)
  1895. if n[pragmasPos].kind != nkEmpty and sfBorrow notin s.flags:
  1896. setEffectsForProcType(c.graph, s.typ, n[pragmasPos], s)
  1897. s.typ.flags.incl tfEffectSystemWorkaround
  1898. # To ease macro generation that produce forwarded .async procs we now
  1899. # allow a bit redundancy in the pragma declarations. The rule is
  1900. # a prototype's pragma list must be a superset of the current pragma
  1901. # list.
  1902. # XXX This needs more checks eventually, for example that external
  1903. # linking names do agree:
  1904. if hasProto and (
  1905. # calling convention mismatch
  1906. tfExplicitCallConv in s.typ.flags and proto.typ.callConv != s.typ.callConv or
  1907. # implementation has additional pragmas
  1908. proto.typ.flags < s.typ.flags):
  1909. localError(c.config, n[pragmasPos].info, errPragmaOnlyInHeaderOfProcX %
  1910. ("'" & proto.name.s & "' from " & c.config$proto.info &
  1911. " '" & s.name.s & "' from " & c.config$s.info))
  1912. styleCheckDef(c, s)
  1913. if hasProto:
  1914. onDefResolveForward(n[namePos].info, proto)
  1915. else:
  1916. onDef(n[namePos].info, s)
  1917. if hasProto:
  1918. if sfForward notin proto.flags and proto.magic == mNone:
  1919. wrongRedefinition(c, n.info, proto.name.s, proto.info)
  1920. if not comesFromShadowScope:
  1921. excl(proto.flags, sfForward)
  1922. incl(proto.flags, sfWasForwarded)
  1923. suggestSym(c.graph, s.info, proto, c.graph.usageSym)
  1924. closeScope(c) # close scope with wrong parameter symbols
  1925. openScope(c) # open scope for old (correct) parameter symbols
  1926. if proto.ast[genericParamsPos].isGenericParams:
  1927. addGenericParamListToScope(c, proto.ast[genericParamsPos])
  1928. addParams(c, proto.typ.n, proto.kind)
  1929. proto.info = s.info # more accurate line information
  1930. proto.options = s.options
  1931. s = proto
  1932. n[genericParamsPos] = proto.ast[genericParamsPos]
  1933. n[paramsPos] = proto.ast[paramsPos]
  1934. n[pragmasPos] = proto.ast[pragmasPos]
  1935. if n[namePos].kind != nkSym: internalError(c.config, n.info, "semProcAux")
  1936. n[namePos].sym = proto
  1937. if importantComments(c.config) and proto.ast.comment.len > 0:
  1938. n.comment = proto.ast.comment
  1939. proto.ast = n # needed for code generation
  1940. popOwner(c)
  1941. pushOwner(c, s)
  1942. if not isAnon:
  1943. if sfOverriden in s.flags or s.name.s[0] == '=': semOverride(c, s, n)
  1944. elif s.name.s[0] in {'.', '('}:
  1945. if s.name.s in [".", ".()", ".="] and {Feature.destructor, dotOperators} * c.features == {}:
  1946. localError(c.config, n.info, "the overloaded " & s.name.s &
  1947. " operator has to be enabled with {.experimental: \"dotOperators\".}")
  1948. elif s.name.s == "()" and callOperator notin c.features:
  1949. localError(c.config, n.info, "the overloaded " & s.name.s &
  1950. " operator has to be enabled with {.experimental: \"callOperator\".}")
  1951. if sfBorrow in s.flags and c.config.cmd notin cmdDocLike:
  1952. result[bodyPos] = c.graph.emptyNode
  1953. if n[bodyPos].kind != nkEmpty and sfError notin s.flags:
  1954. # for DLL generation we allow sfImportc to have a body, for use in VM
  1955. if c.config.ideCmd in {ideSug, ideCon} and s.kind notin {skMacro, skTemplate} and not
  1956. cursorInProc(c.config, n[bodyPos]):
  1957. # speed up nimsuggest
  1958. if s.kind == skMethod: semMethodPrototype(c, s, n)
  1959. elif isAnon:
  1960. let gp = n[genericParamsPos]
  1961. if gp.kind == nkEmpty or (gp.len == 1 and tfRetType in gp[0].typ.flags):
  1962. # absolutely no generics (empty) or a single generic return type are
  1963. # allowed, everything else, including a nullary generic is an error.
  1964. pushProcCon(c, s)
  1965. addResult(c, n, s.typ[0], skProc)
  1966. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], s.typ[0]))
  1967. trackProc(c, s, s.ast[bodyPos])
  1968. popProcCon(c)
  1969. elif efOperand notin flags:
  1970. localError(c.config, n.info, errGenericLambdaNotAllowed)
  1971. else:
  1972. pushProcCon(c, s)
  1973. if n[genericParamsPos].kind == nkEmpty or s.kind in {skMacro, skTemplate}:
  1974. # Macros and Templates can have generic parameters, but they are only
  1975. # used for overload resolution (there is no instantiation of the symbol)
  1976. if s.kind notin {skMacro, skTemplate} and s.magic == mNone: paramsTypeCheck(c, s.typ)
  1977. maybeAddResult(c, s, n)
  1978. let resultType =
  1979. if s.kind == skMacro:
  1980. sysTypeFromName(c.graph, n.info, "NimNode")
  1981. elif not isInlineIterator(s.typ):
  1982. s.typ[0]
  1983. else:
  1984. nil
  1985. # semantic checking also needed with importc in case used in VM
  1986. s.ast[bodyPos] = hloBody(c, semProcBody(c, n[bodyPos], resultType))
  1987. # unfortunately we cannot skip this step when in 'system.compiles'
  1988. # context as it may even be evaluated in 'system.compiles':
  1989. trackProc(c, s, s.ast[bodyPos])
  1990. else:
  1991. if (s.typ[0] != nil and s.kind != skIterator):
  1992. addDecl(c, newSym(skUnknown, getIdent(c.cache, "result"), nextSymId c.idgen, s, n.info))
  1993. openScope(c)
  1994. n[bodyPos] = semGenericStmt(c, n[bodyPos])
  1995. closeScope(c)
  1996. if s.magic == mNone:
  1997. fixupInstantiatedSymbols(c, s)
  1998. if s.kind == skMethod: semMethodPrototype(c, s, n)
  1999. popProcCon(c)
  2000. else:
  2001. if s.kind == skMethod: semMethodPrototype(c, s, n)
  2002. if hasProto: localError(c.config, n.info, errImplOfXexpected % proto.name.s)
  2003. if {sfImportc, sfBorrow, sfError} * s.flags == {} and s.magic == mNone:
  2004. # this is a forward declaration and we're building the prototype
  2005. if s.kind in {skProc, skFunc} and s.typ[0] != nil and s.typ[0].kind == tyAnything:
  2006. localError(c.config, n[paramsPos][0].info, "return type 'auto' cannot be used in forward declarations")
  2007. incl(s.flags, sfForward)
  2008. incl(s.flags, sfWasForwarded)
  2009. elif sfBorrow in s.flags: semBorrow(c, n, s)
  2010. sideEffectsCheck(c, s)
  2011. closeScope(c) # close scope for parameters
  2012. # c.currentScope = oldScope
  2013. popOwner(c)
  2014. if n[patternPos].kind != nkEmpty:
  2015. c.patterns.add(s)
  2016. if isAnon:
  2017. n.transitionSonsKind(nkLambda)
  2018. result.typ = s.typ
  2019. if optOwnedRefs in c.config.globalOptions:
  2020. result.typ = makeVarType(c, result.typ, tyOwned)
  2021. elif isTopLevel(c) and s.kind != skIterator and s.typ.callConv == ccClosure:
  2022. localError(c.config, s.info, "'.closure' calling convention for top level routines is invalid")
  2023. proc determineType(c: PContext, s: PSym) =
  2024. if s.typ != nil: return
  2025. #if s.magic != mNone: return
  2026. #if s.ast.isNil: return
  2027. discard semProcAux(c, s.ast, s.kind, {})
  2028. proc semIterator(c: PContext, n: PNode): PNode =
  2029. # gensym'ed iterator?
  2030. if n[namePos].kind == nkSym:
  2031. # gensym'ed iterators might need to become closure iterators:
  2032. n[namePos].sym.owner = getCurrOwner(c)
  2033. n[namePos].sym.transitionRoutineSymKind(skIterator)
  2034. result = semProcAux(c, n, skIterator, iteratorPragmas)
  2035. # bug #7093: if after a macro transformation we don't have an
  2036. # nkIteratorDef aynmore, return. The iterator then might have been
  2037. # sem'checked already. (Or not, if the macro skips it.)
  2038. if result.kind != n.kind: return
  2039. var s = result[namePos].sym
  2040. var t = s.typ
  2041. if t[0] == nil and s.typ.callConv != ccClosure:
  2042. localError(c.config, n.info, "iterator needs a return type")
  2043. # iterators are either 'inline' or 'closure'; for backwards compatibility,
  2044. # we require first class iterators to be marked with 'closure' explicitly
  2045. # -- at least for 0.9.2.
  2046. if s.typ.callConv == ccClosure:
  2047. incl(s.typ.flags, tfCapturesEnv)
  2048. else:
  2049. s.typ.callConv = ccInline
  2050. if n[bodyPos].kind == nkEmpty and s.magic == mNone and c.inConceptDecl == 0:
  2051. localError(c.config, n.info, errImplOfXexpected % s.name.s)
  2052. if optOwnedRefs in c.config.globalOptions and result.typ != nil:
  2053. result.typ = makeVarType(c, result.typ, tyOwned)
  2054. result.typ.callConv = ccClosure
  2055. proc semProc(c: PContext, n: PNode): PNode =
  2056. result = semProcAux(c, n, skProc, procPragmas)
  2057. proc semFunc(c: PContext, n: PNode): PNode =
  2058. let validPragmas = if n[namePos].kind != nkEmpty: procPragmas
  2059. else: lambdaPragmas
  2060. result = semProcAux(c, n, skFunc, validPragmas)
  2061. proc semMethod(c: PContext, n: PNode): PNode =
  2062. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "method")
  2063. result = semProcAux(c, n, skMethod, methodPragmas)
  2064. # macros can transform converters to nothing:
  2065. if namePos >= result.safeLen: return result
  2066. # bug #7093: if after a macro transformation we don't have an
  2067. # nkIteratorDef aynmore, return. The iterator then might have been
  2068. # sem'checked already. (Or not, if the macro skips it.)
  2069. if result.kind != nkMethodDef: return
  2070. var s = result[namePos].sym
  2071. # we need to fix the 'auto' return type for the dispatcher here (see tautonotgeneric
  2072. # test case):
  2073. let disp = getDispatcher(s)
  2074. # auto return type?
  2075. if disp != nil and disp.typ[0] != nil and disp.typ[0].kind == tyUntyped:
  2076. let ret = s.typ[0]
  2077. disp.typ[0] = ret
  2078. if disp.ast[resultPos].kind == nkSym:
  2079. if isEmptyType(ret): disp.ast[resultPos] = c.graph.emptyNode
  2080. else: disp.ast[resultPos].sym.typ = ret
  2081. proc semConverterDef(c: PContext, n: PNode): PNode =
  2082. if not isTopLevel(c): localError(c.config, n.info, errXOnlyAtModuleScope % "converter")
  2083. checkSonsLen(n, bodyPos + 1, c.config)
  2084. result = semProcAux(c, n, skConverter, converterPragmas)
  2085. # macros can transform converters to nothing:
  2086. if namePos >= result.safeLen: return result
  2087. # bug #7093: if after a macro transformation we don't have an
  2088. # nkIteratorDef aynmore, return. The iterator then might have been
  2089. # sem'checked already. (Or not, if the macro skips it.)
  2090. if result.kind != nkConverterDef: return
  2091. var s = result[namePos].sym
  2092. var t = s.typ
  2093. if t[0] == nil: localError(c.config, n.info, errXNeedsReturnType % "converter")
  2094. if t.len != 2: localError(c.config, n.info, "a converter takes exactly one argument")
  2095. addConverterDef(c, LazySym(sym: s))
  2096. proc semMacroDef(c: PContext, n: PNode): PNode =
  2097. checkSonsLen(n, bodyPos + 1, c.config)
  2098. result = semProcAux(c, n, skMacro, macroPragmas)
  2099. # macros can transform macros to nothing:
  2100. if namePos >= result.safeLen: return result
  2101. # bug #7093: if after a macro transformation we don't have an
  2102. # nkIteratorDef aynmore, return. The iterator then might have been
  2103. # sem'checked already. (Or not, if the macro skips it.)
  2104. if result.kind != nkMacroDef: return
  2105. var s = result[namePos].sym
  2106. var t = s.typ
  2107. var allUntyped = true
  2108. for i in 1..<t.n.len:
  2109. let param = t.n[i].sym
  2110. if param.typ.kind != tyUntyped: allUntyped = false
  2111. if allUntyped: incl(s.flags, sfAllUntyped)
  2112. if n[bodyPos].kind == nkEmpty:
  2113. localError(c.config, n.info, errImplOfXexpected % s.name.s)
  2114. proc incMod(c: PContext, n: PNode, it: PNode, includeStmtResult: PNode) =
  2115. var f = checkModuleName(c.config, it)
  2116. if f != InvalidFileIdx:
  2117. addIncludeFileDep(c, f)
  2118. onProcessing(c.graph, f, "include", c.module)
  2119. if containsOrIncl(c.includedFiles, f.int):
  2120. localError(c.config, n.info, errRecursiveDependencyX % toMsgFilename(c.config, f))
  2121. else:
  2122. includeStmtResult.add semStmt(c, c.graph.includeFileCallback(c.graph, c.module, f), {})
  2123. excl(c.includedFiles, f.int)
  2124. proc evalInclude(c: PContext, n: PNode): PNode =
  2125. result = newNodeI(nkStmtList, n.info)
  2126. result.add n
  2127. for i in 0..<n.len:
  2128. var imp: PNode
  2129. let it = n[i]
  2130. if it.kind == nkInfix and it.len == 3 and it[0].ident.s != "/":
  2131. localError(c.config, it.info, "Cannot use '" & it[0].ident.s & "' in 'include'.")
  2132. if it.kind == nkInfix and it.len == 3 and it[2].kind == nkBracket:
  2133. let sep = it[0]
  2134. let dir = it[1]
  2135. imp = newNodeI(nkInfix, it.info)
  2136. imp.add sep
  2137. imp.add dir
  2138. imp.add sep # dummy entry, replaced in the loop
  2139. for x in it[2]:
  2140. imp[2] = x
  2141. incMod(c, n, imp, result)
  2142. else:
  2143. incMod(c, n, it, result)
  2144. proc recursiveSetFlag(n: PNode, flag: TNodeFlag) =
  2145. if n != nil:
  2146. for i in 0..<n.safeLen: recursiveSetFlag(n[i], flag)
  2147. incl(n.flags, flag)
  2148. proc semPragmaBlock(c: PContext, n: PNode; expectedType: PType = nil): PNode =
  2149. checkSonsLen(n, 2, c.config)
  2150. let pragmaList = n[0]
  2151. pragma(c, nil, pragmaList, exprPragmas, isStatement = true)
  2152. var inUncheckedAssignSection = 0
  2153. for p in pragmaList:
  2154. if whichPragma(p) == wCast:
  2155. case whichPragma(p[1])
  2156. of wGcSafe, wNoSideEffect, wTags, wForbids, wRaises:
  2157. discard "handled in sempass2"
  2158. of wUncheckedAssign:
  2159. inUncheckedAssignSection = 1
  2160. else:
  2161. localError(c.config, p.info, "invalid pragma block: " & $p)
  2162. inc c.inUncheckedAssignSection, inUncheckedAssignSection
  2163. n[1] = semExpr(c, n[1], expectedType = expectedType)
  2164. dec c.inUncheckedAssignSection, inUncheckedAssignSection
  2165. result = n
  2166. result.typ = n[1].typ
  2167. for i in 0..<pragmaList.len:
  2168. case whichPragma(pragmaList[i])
  2169. of wLine: setInfoRecursive(result, pragmaList[i].info)
  2170. of wNoRewrite: recursiveSetFlag(result, nfNoRewrite)
  2171. else: discard
  2172. proc semStaticStmt(c: PContext, n: PNode): PNode =
  2173. #echo "semStaticStmt"
  2174. #writeStackTrace()
  2175. inc c.inStaticContext
  2176. openScope(c)
  2177. let a = semStmt(c, n[0], {})
  2178. closeScope(c)
  2179. dec c.inStaticContext
  2180. n[0] = a
  2181. evalStaticStmt(c.module, c.idgen, c.graph, a, c.p.owner)
  2182. when false:
  2183. # for incremental replays, keep the AST as required for replays:
  2184. result = n
  2185. else:
  2186. result = newNodeI(nkDiscardStmt, n.info, 1)
  2187. result[0] = c.graph.emptyNode
  2188. proc usesResult(n: PNode): bool =
  2189. # nkStmtList(expr) properly propagates the void context,
  2190. # so we don't need to process that all over again:
  2191. if n.kind notin {nkStmtList, nkStmtListExpr,
  2192. nkMacroDef, nkTemplateDef} + procDefs:
  2193. if isAtom(n):
  2194. result = n.kind == nkSym and n.sym.kind == skResult
  2195. elif n.kind == nkReturnStmt:
  2196. result = true
  2197. else:
  2198. for c in n:
  2199. if usesResult(c): return true
  2200. proc inferConceptStaticParam(c: PContext, inferred, n: PNode) =
  2201. var typ = inferred.typ
  2202. let res = semConstExpr(c, n)
  2203. if not sameType(res.typ, typ.base):
  2204. localError(c.config, n.info,
  2205. "cannot infer the concept parameter '%s', due to a type mismatch. " &
  2206. "attempt to equate '%s' and '%s'." % [inferred.renderTree, $res.typ, $typ.base])
  2207. typ.n = res
  2208. proc semStmtList(c: PContext, n: PNode, flags: TExprFlags, expectedType: PType = nil): PNode =
  2209. result = n
  2210. result.transitionSonsKind(nkStmtList)
  2211. var voidContext = false
  2212. var last = n.len-1
  2213. # by not allowing for nkCommentStmt etc. we ensure nkStmtListExpr actually
  2214. # really *ends* in the expression that produces the type: The compiler now
  2215. # relies on this fact and it's too much effort to change that. And arguably
  2216. # 'R(); #comment' shouldn't produce R's type anyway.
  2217. #while last > 0 and n[last].kind in {nkPragma, nkCommentStmt,
  2218. # nkNilLit, nkEmpty}:
  2219. # dec last
  2220. for i in 0..<n.len:
  2221. var x = semExpr(c, n[i], flags, if i == n.len - 1: expectedType else: nil)
  2222. n[i] = x
  2223. if c.matchedConcept != nil and x.typ != nil and
  2224. (nfFromTemplate notin n.flags or i != last):
  2225. case x.typ.kind
  2226. of tyBool:
  2227. if x.kind == nkInfix and
  2228. x[0].kind == nkSym and
  2229. x[0].sym.name.s == "==":
  2230. if x[1].typ.isUnresolvedStatic:
  2231. inferConceptStaticParam(c, x[1], x[2])
  2232. continue
  2233. elif x[2].typ.isUnresolvedStatic:
  2234. inferConceptStaticParam(c, x[2], x[1])
  2235. continue
  2236. let verdict = semConstExpr(c, n[i])
  2237. if verdict == nil or verdict.kind != nkIntLit or verdict.intVal == 0:
  2238. localError(c.config, result.info, "concept predicate failed")
  2239. of tyUnknown: continue
  2240. else: discard
  2241. if n[i].typ == c.enforceVoidContext: #or usesResult(n[i]):
  2242. voidContext = true
  2243. n.typ = c.enforceVoidContext
  2244. if i == last and (n.len == 1 or ({efWantValue, efInTypeof} * flags != {})):
  2245. n.typ = n[i].typ
  2246. if not isEmptyType(n.typ): n.transitionSonsKind(nkStmtListExpr)
  2247. elif i != last or voidContext:
  2248. discardCheck(c, n[i], flags)
  2249. else:
  2250. n.typ = n[i].typ
  2251. if not isEmptyType(n.typ): n.transitionSonsKind(nkStmtListExpr)
  2252. var m = n[i]
  2253. while m.kind in {nkStmtListExpr, nkStmtList} and m.len > 0: # from templates
  2254. m = m.lastSon
  2255. if m.kind in nkLastBlockStmts or
  2256. m.kind in nkCallKinds and m[0].kind == nkSym and
  2257. sfNoReturn in m[0].sym.flags:
  2258. for j in i + 1..<n.len:
  2259. case n[j].kind
  2260. of nkPragma, nkCommentStmt, nkNilLit, nkEmpty, nkState: discard
  2261. else: message(c.config, n[j].info, warnUnreachableCode)
  2262. else: discard
  2263. if result.len == 1 and
  2264. # concept bodies should be preserved as a stmt list:
  2265. c.matchedConcept == nil and
  2266. # also, don't make life complicated for macros.
  2267. # they will always expect a proper stmtlist:
  2268. nfBlockArg notin n.flags and
  2269. result[0].kind != nkDefer:
  2270. result = result[0]
  2271. when defined(nimfix):
  2272. if result.kind == nkCommentStmt and not result.comment.isNil and
  2273. not (result.comment[0] == '#' and result.comment[1] == '#'):
  2274. # it is an old-style comment statement: we replace it with 'discard ""':
  2275. prettybase.replaceComment(result.info)
  2276. proc semStmt(c: PContext, n: PNode; flags: TExprFlags): PNode =
  2277. if efInTypeof notin flags:
  2278. result = semExprNoType(c, n)
  2279. else:
  2280. result = semExpr(c, n, flags)