semstmts.nim 106 KB

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