semtypinst.nim 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 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 instantiation of generic types.
  10. import ast, astalgo, msgs, types, magicsys, semdata, renderer, options,
  11. lineinfos
  12. const
  13. tfInstClearedFlags = {tfHasMeta, tfUnresolved}
  14. proc checkPartialConstructedType(conf: ConfigRef; info: TLineInfo, t: PType) =
  15. if tfAcyclic in t.flags and skipTypes(t, abstractInst).kind != tyObject:
  16. localError(conf, info, "invalid pragma: acyclic")
  17. elif t.kind in {tyVar, tyLent} and t.sons[0].kind in {tyVar, tyLent}:
  18. localError(conf, info, "type 'var var' is not allowed")
  19. proc checkConstructedType*(conf: ConfigRef; info: TLineInfo, typ: PType) =
  20. var t = typ.skipTypes({tyDistinct})
  21. if t.kind in tyTypeClasses: discard
  22. elif tfAcyclic in t.flags and skipTypes(t, abstractInst).kind != tyObject:
  23. localError(conf, info, "invalid pragma: acyclic")
  24. elif t.kind in {tyVar, tyLent} and t.sons[0].kind in {tyVar, tyLent}:
  25. localError(conf, info, "type 'var var' is not allowed")
  26. elif computeSize(conf, t) == szIllegalRecursion:
  27. localError(conf, info, "illegal recursion in type '" & typeToString(t) & "'")
  28. when false:
  29. if t.kind == tyObject and t.sons[0] != nil:
  30. if t.sons[0].kind != tyObject or tfFinal in t.sons[0].flags:
  31. localError(info, errInheritanceOnlyWithNonFinalObjects)
  32. proc searchInstTypes*(key: PType): PType =
  33. let genericTyp = key.sons[0]
  34. if not (genericTyp.kind == tyGenericBody and
  35. key.sons[0] == genericTyp and genericTyp.sym != nil): return
  36. when not defined(nimNoNilSeqs):
  37. if genericTyp.sym.typeInstCache == nil: return
  38. for inst in genericTyp.sym.typeInstCache:
  39. if inst.id == key.id: return inst
  40. if inst.sons.len < key.sons.len:
  41. # XXX: This happens for prematurely cached
  42. # types such as Channel[empty]. Why?
  43. # See the notes for PActor in handleGenericInvocation
  44. return
  45. if not sameFlags(inst, key):
  46. continue
  47. block matchType:
  48. for j in 1 .. high(key.sons):
  49. # XXX sameType is not really correct for nested generics?
  50. if not compareTypes(inst.sons[j], key.sons[j],
  51. flags = {ExactGenericParams}):
  52. break matchType
  53. return inst
  54. proc cacheTypeInst*(inst: PType) =
  55. # XXX: add to module's generics
  56. # update the refcount
  57. let gt = inst.sons[0]
  58. let t = if gt.kind == tyGenericBody: gt.lastSon else: gt
  59. if t.kind in {tyStatic, tyGenericParam} + tyTypeClasses:
  60. return
  61. gt.sym.typeInstCache.add(inst)
  62. type
  63. LayeredIdTable* = object
  64. topLayer*: TIdTable
  65. nextLayer*: ptr LayeredIdTable
  66. TReplTypeVars* = object
  67. c*: PContext
  68. typeMap*: ptr LayeredIdTable # map PType to PType
  69. symMap*: TIdTable # map PSym to PSym
  70. localCache*: TIdTable # local cache for remembering alraedy replaced
  71. # types during instantiation of meta types
  72. # (they are not stored in the global cache)
  73. info*: TLineInfo
  74. allowMetaTypes*: bool # allow types such as seq[Number]
  75. # i.e. the result contains unresolved generics
  76. skipTypedesc*: bool # wether we should skip typeDescs
  77. owner*: PSym # where this instantiation comes from
  78. recursionLimit: int
  79. proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType
  80. proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym
  81. proc replaceTypeVarsN*(cl: var TReplTypeVars, n: PNode; start=0): PNode
  82. proc initLayeredTypeMap*(pt: TIdTable): LayeredIdTable =
  83. copyIdTable(result.topLayer, pt)
  84. proc newTypeMapLayer*(cl: var TReplTypeVars): LayeredIdTable =
  85. result.nextLayer = cl.typeMap
  86. initIdTable(result.topLayer)
  87. proc lookup(typeMap: ptr LayeredIdTable, key: PType): PType =
  88. var tm = typeMap
  89. while tm != nil:
  90. result = PType(idTableGet(tm.topLayer, key))
  91. if result != nil: return
  92. tm = tm.nextLayer
  93. template put(typeMap: ptr LayeredIdTable, key, value: PType) =
  94. idTablePut(typeMap.topLayer, key, value)
  95. template checkMetaInvariants(cl: TReplTypeVars, t: PType) =
  96. when false:
  97. if t != nil and tfHasMeta in t.flags and
  98. cl.allowMetaTypes == false:
  99. echo "UNEXPECTED META ", t.id, " ", instantiationInfo(-1)
  100. debug t
  101. writeStackTrace()
  102. proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType =
  103. result = replaceTypeVarsTAux(cl, t)
  104. checkMetaInvariants(cl, result)
  105. proc prepareNode(cl: var TReplTypeVars, n: PNode): PNode =
  106. let t = replaceTypeVarsT(cl, n.typ)
  107. if t != nil and t.kind == tyStatic and t.n != nil:
  108. return if tfUnresolved in t.flags: prepareNode(cl, t.n)
  109. else: t.n
  110. result = copyNode(n)
  111. result.typ = t
  112. if result.kind == nkSym: result.sym = replaceTypeVarsS(cl, n.sym)
  113. let isCall = result.kind in nkCallKinds
  114. for i in 0 ..< n.safeLen:
  115. # XXX HACK: ``f(a, b)``, avoid to instantiate `f`
  116. if isCall and i == 0: result.add(n[i])
  117. else: result.add(prepareNode(cl, n[i]))
  118. proc isTypeParam(n: PNode): bool =
  119. # XXX: generic params should use skGenericParam instead of skType
  120. return n.kind == nkSym and
  121. (n.sym.kind == skGenericParam or
  122. (n.sym.kind == skType and sfFromGeneric in n.sym.flags))
  123. proc reResolveCallsWithTypedescParams(cl: var TReplTypeVars, n: PNode): PNode =
  124. # This is needed for tgenericshardcases
  125. # It's possible that a generic param will be used in a proc call to a
  126. # typedesc accepting proc. After generic param substitution, such procs
  127. # should be optionally instantiated with the correct type. In order to
  128. # perform this instantiation, we need to re-run the generateInstance path
  129. # in the compiler, but it's quite complicated to do so at the moment so we
  130. # resort to a mild hack; the head symbol of the call is temporary reset and
  131. # overload resolution is executed again (which may trigger generateInstance).
  132. if n.kind in nkCallKinds and sfFromGeneric in n[0].sym.flags:
  133. var needsFixing = false
  134. for i in 1 ..< n.safeLen:
  135. if isTypeParam(n[i]): needsFixing = true
  136. if needsFixing:
  137. n.sons[0] = newSymNode(n.sons[0].sym.owner)
  138. return cl.c.semOverloadedCall(cl.c, n, n, {skProc, skFunc}, {})
  139. for i in 0 ..< n.safeLen:
  140. n.sons[i] = reResolveCallsWithTypedescParams(cl, n[i])
  141. return n
  142. proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode; start=0): PNode =
  143. if n == nil: return
  144. result = copyNode(n)
  145. if n.typ != nil:
  146. result.typ = replaceTypeVarsT(cl, n.typ)
  147. checkMetaInvariants(cl, result.typ)
  148. case n.kind
  149. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit:
  150. discard
  151. of nkSym:
  152. result.sym = replaceTypeVarsS(cl, n.sym)
  153. if result.sym.typ.kind == tyVoid:
  154. # don't add the 'void' field
  155. result = newNode(nkRecList, n.info)
  156. of nkRecWhen:
  157. var branch: PNode = nil # the branch to take
  158. for i in countup(0, sonsLen(n) - 1):
  159. var it = n.sons[i]
  160. if it == nil: illFormedAst(n, cl.c.config)
  161. case it.kind
  162. of nkElifBranch:
  163. checkSonsLen(it, 2, cl.c.config)
  164. var cond = prepareNode(cl, it.sons[0])
  165. var e = cl.c.semConstExpr(cl.c, cond)
  166. if e.kind != nkIntLit:
  167. internalError(cl.c.config, e.info, "ReplaceTypeVarsN: when condition not a bool")
  168. if e.intVal != 0 and branch == nil: branch = it.sons[1]
  169. of nkElse:
  170. checkSonsLen(it, 1, cl.c.config)
  171. if branch == nil: branch = it.sons[0]
  172. else: illFormedAst(n, cl.c.config)
  173. if branch != nil:
  174. result = replaceTypeVarsN(cl, branch)
  175. else:
  176. result = newNodeI(nkRecList, n.info)
  177. of nkStaticExpr:
  178. var n = prepareNode(cl, n)
  179. n = reResolveCallsWithTypedescParams(cl, n)
  180. result = if cl.allowMetaTypes: n
  181. else: cl.c.semExpr(cl.c, n)
  182. else:
  183. var length = sonsLen(n)
  184. if length > 0:
  185. newSons(result, length)
  186. if start > 0:
  187. result.sons[0] = n.sons[0]
  188. for i in countup(start, length - 1):
  189. result.sons[i] = replaceTypeVarsN(cl, n.sons[i])
  190. proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym =
  191. if s == nil: return nil
  192. # symbol is not our business:
  193. if cl.owner != nil and s.owner != cl.owner:
  194. return s
  195. # XXX: Bound symbols in default parameter expressions may reach here.
  196. # We cannot process them, becase `sym.n` may point to a proc body with
  197. # cyclic references that will lead to an infinite recursion.
  198. # Perhaps we should not use a black-list here, but a whitelist instead
  199. # (e.g. skGenericParam and skType).
  200. # Note: `s.magic` may be `mType` in an example such as:
  201. # proc foo[T](a: T, b = myDefault(type(a)))
  202. if s.kind == skProc or s.magic != mNone:
  203. return s
  204. #result = PSym(idTableGet(cl.symMap, s))
  205. #if result == nil:
  206. result = copySym(s, false)
  207. incl(result.flags, sfFromGeneric)
  208. #idTablePut(cl.symMap, s, result)
  209. result.owner = s.owner
  210. result.typ = replaceTypeVarsT(cl, s.typ)
  211. result.ast = replaceTypeVarsN(cl, s.ast)
  212. proc lookupTypeVar(cl: var TReplTypeVars, t: PType): PType =
  213. result = cl.typeMap.lookup(t)
  214. if result == nil:
  215. if cl.allowMetaTypes or tfRetType in t.flags: return
  216. localError(cl.c.config, t.sym.info, "cannot instantiate: '" & typeToString(t) & "'")
  217. result = errorType(cl.c)
  218. # In order to prevent endless recursions, we must remember
  219. # this bad lookup and replace it with errorType everywhere.
  220. # These code paths are only active in "nim check"
  221. cl.typeMap.put(t, result)
  222. elif result.kind == tyGenericParam and not cl.allowMetaTypes:
  223. internalError(cl.c.config, cl.info, "substitution with generic parameter")
  224. proc instCopyType*(cl: var TReplTypeVars, t: PType): PType =
  225. # XXX: relying on allowMetaTypes is a kludge
  226. result = copyType(t, t.owner, cl.allowMetaTypes)
  227. if cl.allowMetaTypes: return
  228. result.flags.incl tfFromGeneric
  229. if not (t.kind in tyMetaTypes or
  230. (t.kind == tyStatic and t.n == nil)):
  231. result.flags.excl tfInstClearedFlags
  232. when false:
  233. if newDestructors:
  234. result.assignment = nil
  235. #result.destructor = nil
  236. result.sink = nil
  237. template typeBound(c, newty, oldty, field, info) =
  238. let opr = newty.field
  239. if opr != nil and sfFromGeneric notin opr.flags:
  240. # '=' needs to be instantiated for generics when the type is constructed:
  241. newty.field = c.instTypeBoundOp(c, opr, oldty, info, attachedAsgn, 1)
  242. proc handleGenericInvocation(cl: var TReplTypeVars, t: PType): PType =
  243. # tyGenericInvocation[A, tyGenericInvocation[A, B]]
  244. # is difficult to handle:
  245. const eqFlags = eqTypeFlags + {tfGcSafe}
  246. var body = t.sons[0]
  247. if body.kind != tyGenericBody:
  248. internalError(cl.c.config, cl.info, "no generic body")
  249. var header: PType = t
  250. # search for some instantiation here:
  251. if cl.allowMetaTypes:
  252. result = PType(idTableGet(cl.localCache, t))
  253. else:
  254. result = searchInstTypes(t)
  255. if result != nil and eqFlags*result.flags == eqFlags*t.flags: return
  256. for i in countup(1, sonsLen(t) - 1):
  257. var x = t.sons[i]
  258. if x.kind in {tyGenericParam}:
  259. x = lookupTypeVar(cl, x)
  260. if x != nil:
  261. if header == t: header = instCopyType(cl, t)
  262. header.sons[i] = x
  263. propagateToOwner(header, x)
  264. else:
  265. propagateToOwner(header, x)
  266. if header != t:
  267. # search again after first pass:
  268. result = searchInstTypes(header)
  269. if result != nil and eqFlags*result.flags == eqFlags*t.flags: return
  270. else:
  271. header = instCopyType(cl, t)
  272. result = newType(tyGenericInst, t.sons[0].owner)
  273. result.flags = header.flags
  274. # be careful not to propagate unnecessary flags here (don't use rawAddSon)
  275. result.sons = @[header.sons[0]]
  276. # ugh need another pass for deeply recursive generic types (e.g. PActor)
  277. # we need to add the candidate here, before it's fully instantiated for
  278. # recursive instantions:
  279. if not cl.allowMetaTypes:
  280. cacheTypeInst(result)
  281. else:
  282. idTablePut(cl.localCache, t, result)
  283. let oldSkipTypedesc = cl.skipTypedesc
  284. cl.skipTypedesc = true
  285. var typeMapLayer = newTypeMapLayer(cl)
  286. cl.typeMap = addr(typeMapLayer)
  287. for i in countup(1, sonsLen(t) - 1):
  288. var x = replaceTypeVarsT(cl, t.sons[i])
  289. assert x.kind != tyGenericInvocation
  290. header.sons[i] = x
  291. propagateToOwner(header, x)
  292. cl.typeMap.put(body.sons[i-1], x)
  293. for i in countup(1, sonsLen(t) - 1):
  294. # if one of the params is not concrete, we cannot do anything
  295. # but we already raised an error!
  296. rawAddSon(result, header.sons[i])
  297. let bbody = lastSon body
  298. var newbody = replaceTypeVarsT(cl, bbody)
  299. let bodyIsNew = newbody != bbody
  300. cl.skipTypedesc = oldSkipTypedesc
  301. newbody.flags = newbody.flags + (t.flags + body.flags - tfInstClearedFlags)
  302. result.flags = result.flags + newbody.flags - tfInstClearedFlags
  303. cl.typeMap = cl.typeMap.nextLayer
  304. # This is actually wrong: tgeneric_closure fails with this line:
  305. #newbody.callConv = body.callConv
  306. # This type may be a generic alias and we want to resolve it here.
  307. # One step is enough, because the recursive nature of
  308. # handleGenericInvocation will handle the alias-to-alias-to-alias case
  309. if newbody.isGenericAlias: newbody = newbody.skipGenericAlias
  310. rawAddSon(result, newbody)
  311. checkPartialConstructedType(cl.c.config, cl.info, newbody)
  312. let dc = newbody.deepCopy
  313. if cl.allowMetaTypes == false:
  314. if dc != nil and sfFromGeneric notin newbody.deepCopy.flags:
  315. # 'deepCopy' needs to be instantiated for
  316. # generics *when the type is constructed*:
  317. newbody.deepCopy = cl.c.instTypeBoundOp(cl.c, dc, result, cl.info,
  318. attachedDeepCopy, 1)
  319. if bodyIsNew and newbody.typeInst == nil:
  320. #doassert newbody.typeInst == nil
  321. newbody.typeInst = result
  322. if tfRefsAnonObj in newbody.flags and newbody.kind != tyGenericInst:
  323. # can come here for tyGenericInst too, see tests/metatype/ttypeor.nim
  324. # need to look into this issue later
  325. assert newbody.kind in {tyRef, tyPtr}
  326. if newbody.lastSon.typeInst != nil:
  327. #internalError(cl.c.config, cl.info, "ref already has a 'typeInst' field")
  328. discard
  329. else:
  330. newbody.lastSon.typeInst = result
  331. cl.c.typesWithOps.add((newbody, result))
  332. let mm = skipTypes(bbody, abstractPtrs)
  333. if tfFromGeneric notin mm.flags:
  334. # bug #5479, prevent endless recursions here:
  335. incl mm.flags, tfFromGeneric
  336. let methods = mm.methods
  337. for col, meth in items(methods):
  338. # we instantiate the known methods belonging to that type, this causes
  339. # them to be registered and that's enough, so we 'discard' the result.
  340. discard cl.c.instTypeBoundOp(cl.c, meth, result, cl.info,
  341. attachedAsgn, col)
  342. excl mm.flags, tfFromGeneric
  343. proc eraseVoidParams*(t: PType) =
  344. # transform '(): void' into '()' because old parts of the compiler really
  345. # don't deal with '(): void':
  346. if t.sons[0] != nil and t.sons[0].kind == tyVoid:
  347. t.sons[0] = nil
  348. for i in 1 ..< t.sonsLen:
  349. # don't touch any memory unless necessary
  350. if t.sons[i].kind == tyVoid:
  351. var pos = i
  352. for j in i+1 ..< t.sonsLen:
  353. if t.sons[j].kind != tyVoid:
  354. t.sons[pos] = t.sons[j]
  355. t.n.sons[pos] = t.n.sons[j]
  356. inc pos
  357. setLen t.sons, pos
  358. setLen t.n.sons, pos
  359. return
  360. proc skipIntLiteralParams*(t: PType) =
  361. for i in 0 ..< t.sonsLen:
  362. let p = t.sons[i]
  363. if p == nil: continue
  364. let skipped = p.skipIntLit
  365. if skipped != p:
  366. t.sons[i] = skipped
  367. if i > 0: t.n.sons[i].sym.typ = skipped
  368. # when the typeof operator is used on a static input
  369. # param, the results gets infected with static as well:
  370. if t.sons[0] != nil and t.sons[0].kind == tyStatic:
  371. t.sons[0] = t.sons[0].base
  372. proc propagateFieldFlags(t: PType, n: PNode) =
  373. # This is meant for objects and tuples
  374. # The type must be fully instantiated!
  375. if n.isNil:
  376. return
  377. #internalAssert n.kind != nkRecWhen
  378. case n.kind
  379. of nkSym:
  380. propagateToOwner(t, n.sym.typ)
  381. of nkRecList, nkRecCase, nkOfBranch, nkElse:
  382. for son in n:
  383. propagateFieldFlags(t, son)
  384. else: discard
  385. proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
  386. template bailout =
  387. if cl.recursionLimit > 100:
  388. # bail out, see bug #2509. But note this caching is in general wrong,
  389. # look at this example where TwoVectors should not share the generic
  390. # instantiations (bug #3112):
  391. # type
  392. # Vector[N: static[int]] = array[N, float64]
  393. # TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb])
  394. result = PType(idTableGet(cl.localCache, t))
  395. if result != nil: return result
  396. inc cl.recursionLimit
  397. result = t
  398. if t == nil: return
  399. if t.kind in {tyStatic, tyGenericParam} + tyTypeClasses:
  400. let lookup = cl.typeMap.lookup(t)
  401. if lookup != nil: return lookup
  402. case t.kind
  403. of tyGenericInvocation:
  404. result = handleGenericInvocation(cl, t)
  405. if result.lastSon.kind == tyUserTypeClass:
  406. result.kind = tyUserTypeClassInst
  407. of tyGenericBody:
  408. localError(cl.c.config, cl.info, "cannot instantiate: '" & typeToString(t) & "'")
  409. result = errorType(cl.c)
  410. #result = replaceTypeVarsT(cl, lastSon(t))
  411. of tyFromExpr:
  412. if cl.allowMetaTypes: return
  413. # This assert is triggered when a tyFromExpr was created in a cyclic
  414. # way. You should break the cycle at the point of creation by introducing
  415. # a call such as: `n.typ = makeTypeFromExpr(c, n.copyTree)`
  416. # Otherwise, the cycle will be fatal for the prepareNode call below
  417. assert t.n.typ != t
  418. var n = prepareNode(cl, t.n)
  419. if n.kind != nkEmpty:
  420. n = cl.c.semConstExpr(cl.c, n)
  421. if n.typ.kind == tyTypeDesc:
  422. # XXX: sometimes, chained typedescs enter here.
  423. # It may be worth investigating why this is happening,
  424. # because it may cause other bugs elsewhere.
  425. result = n.typ.skipTypes({tyTypeDesc})
  426. # result = n.typ.base
  427. else:
  428. if n.typ.kind != tyStatic:
  429. # XXX: In the future, semConstExpr should
  430. # return tyStatic values to let anyone make
  431. # use of this knowledge. The patching here
  432. # won't be necessary then.
  433. result = newTypeS(tyStatic, cl.c)
  434. result.sons = @[n.typ]
  435. result.n = n
  436. else:
  437. result = n.typ
  438. of tyInt, tyFloat:
  439. result = skipIntLit(t)
  440. of tyTypeDesc:
  441. let lookup = cl.typeMap.lookup(t)
  442. if lookup != nil:
  443. result = lookup
  444. if tfUnresolved in t.flags or cl.skipTypedesc: result = result.base
  445. elif t.sons[0].kind != tyNone:
  446. result = makeTypeDesc(cl.c, replaceTypeVarsT(cl, t.sons[0]))
  447. of tyUserTypeClass, tyStatic:
  448. result = t
  449. of tyGenericInst, tyUserTypeClassInst:
  450. bailout()
  451. result = instCopyType(cl, t)
  452. idTablePut(cl.localCache, t, result)
  453. for i in 1 ..< result.sonsLen:
  454. result.sons[i] = replaceTypeVarsT(cl, result.sons[i])
  455. propagateToOwner(result, result.lastSon)
  456. else:
  457. if containsGenericType(t):
  458. #if not cl.allowMetaTypes:
  459. bailout()
  460. result = instCopyType(cl, t)
  461. result.size = -1 # needs to be recomputed
  462. #if not cl.allowMetaTypes:
  463. idTablePut(cl.localCache, t, result)
  464. for i in countup(0, sonsLen(result) - 1):
  465. if result.sons[i] != nil:
  466. var r = replaceTypeVarsT(cl, result.sons[i])
  467. if result.kind == tyObject:
  468. # carefully coded to not skip the precious tyGenericInst:
  469. let r2 = r.skipTypes({tyAlias, tySink})
  470. if r2.kind in {tyPtr, tyRef}:
  471. r = skipTypes(r2, {tyPtr, tyRef})
  472. result.sons[i] = r
  473. if result.kind != tyArray or i != 0:
  474. propagateToOwner(result, r)
  475. # bug #4677: Do not instantiate effect lists
  476. result.n = replaceTypeVarsN(cl, result.n, ord(result.kind==tyProc))
  477. case result.kind
  478. of tyArray:
  479. let idx = result.sons[0]
  480. internalAssert cl.c.config, idx.kind != tyStatic
  481. of tyObject, tyTuple:
  482. propagateFieldFlags(result, result.n)
  483. of tyProc:
  484. eraseVoidParams(result)
  485. skipIntLiteralParams(result)
  486. else: discard
  487. proc instAllTypeBoundOp*(c: PContext, info: TLineInfo) =
  488. var i = 0
  489. while i < c.typesWithOps.len:
  490. let (newty, oldty) = c.typesWithOps[i]
  491. typeBound(c, newty, oldty, destructor, info)
  492. typeBound(c, newty, oldty, sink, info)
  493. typeBound(c, newty, oldty, assignment, info)
  494. inc i
  495. setLen(c.typesWithOps, 0)
  496. proc initTypeVars*(p: PContext, typeMap: ptr LayeredIdTable, info: TLineInfo;
  497. owner: PSym): TReplTypeVars =
  498. initIdTable(result.symMap)
  499. initIdTable(result.localCache)
  500. result.typeMap = typeMap
  501. result.info = info
  502. result.c = p
  503. result.owner = owner
  504. proc replaceTypesInBody*(p: PContext, pt: TIdTable, n: PNode;
  505. owner: PSym, allowMetaTypes = false): PNode =
  506. var typeMap = initLayeredTypeMap(pt)
  507. var cl = initTypeVars(p, addr(typeMap), n.info, owner)
  508. cl.allowMetaTypes = allowMetaTypes
  509. pushInfoContext(p.config, n.info)
  510. result = replaceTypeVarsN(cl, n)
  511. popInfoContext(p.config)
  512. proc replaceTypesForLambda*(p: PContext, pt: TIdTable, n: PNode;
  513. original, new: PSym): PNode =
  514. var typeMap = initLayeredTypeMap(pt)
  515. var cl = initTypeVars(p, addr(typeMap), n.info, original)
  516. idTablePut(cl.symMap, original, new)
  517. pushInfoContext(p.config, n.info)
  518. result = replaceTypeVarsN(cl, n)
  519. popInfoContext(p.config)
  520. proc generateTypeInstance*(p: PContext, pt: TIdTable, info: TLineInfo,
  521. t: PType): PType =
  522. var typeMap = initLayeredTypeMap(pt)
  523. var cl = initTypeVars(p, addr(typeMap), info, nil)
  524. pushInfoContext(p.config, info)
  525. result = replaceTypeVarsT(cl, t)
  526. popInfoContext(p.config)
  527. proc prepareMetatypeForSigmatch*(p: PContext, pt: TIdTable, info: TLineInfo,
  528. t: PType): PType =
  529. var typeMap = initLayeredTypeMap(pt)
  530. var cl = initTypeVars(p, addr(typeMap), info, nil)
  531. cl.allowMetaTypes = true
  532. pushInfoContext(p.config, info)
  533. result = replaceTypeVarsT(cl, t)
  534. popInfoContext(p.config)
  535. template generateTypeInstance*(p: PContext, pt: TIdTable, arg: PNode,
  536. t: PType): untyped =
  537. generateTypeInstance(p, pt, arg.info, t)