semstmts.nim 93 KB

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