semstmts.nim 111 KB

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