semstmts.nim 94 KB

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