semstmts.nim 109 KB

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