semstmts.nim 109 KB

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