semtypinst.nim 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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.safeAdd(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 methods = skipTypes(bbody, abstractPtrs).methods
  333. for col, meth in items(methods):
  334. # we instantiate the known methods belonging to that type, this causes
  335. # them to be registered and that's enough, so we 'discard' the result.
  336. discard cl.c.instTypeBoundOp(cl.c, meth, result, cl.info,
  337. attachedAsgn, col)
  338. proc eraseVoidParams*(t: PType) =
  339. # transform '(): void' into '()' because old parts of the compiler really
  340. # don't deal with '(): void':
  341. if t.sons[0] != nil and t.sons[0].kind == tyVoid:
  342. t.sons[0] = nil
  343. for i in 1 ..< t.sonsLen:
  344. # don't touch any memory unless necessary
  345. if t.sons[i].kind == tyVoid:
  346. var pos = i
  347. for j in i+1 ..< t.sonsLen:
  348. if t.sons[j].kind != tyVoid:
  349. t.sons[pos] = t.sons[j]
  350. t.n.sons[pos] = t.n.sons[j]
  351. inc pos
  352. setLen t.sons, pos
  353. setLen t.n.sons, pos
  354. return
  355. proc skipIntLiteralParams*(t: PType) =
  356. for i in 0 ..< t.sonsLen:
  357. let p = t.sons[i]
  358. if p == nil: continue
  359. let skipped = p.skipIntLit
  360. if skipped != p:
  361. t.sons[i] = skipped
  362. if i > 0: t.n.sons[i].sym.typ = skipped
  363. # when the typeof operator is used on a static input
  364. # param, the results gets infected with static as well:
  365. if t.sons[0] != nil and t.sons[0].kind == tyStatic:
  366. t.sons[0] = t.sons[0].base
  367. proc propagateFieldFlags(t: PType, n: PNode) =
  368. # This is meant for objects and tuples
  369. # The type must be fully instantiated!
  370. if n.isNil:
  371. return
  372. #internalAssert n.kind != nkRecWhen
  373. case n.kind
  374. of nkSym:
  375. propagateToOwner(t, n.sym.typ)
  376. of nkRecList, nkRecCase, nkOfBranch, nkElse:
  377. for son in n:
  378. propagateFieldFlags(t, son)
  379. else: discard
  380. proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
  381. template bailout =
  382. if cl.recursionLimit > 100:
  383. # bail out, see bug #2509. But note this caching is in general wrong,
  384. # look at this example where TwoVectors should not share the generic
  385. # instantiations (bug #3112):
  386. # type
  387. # Vector[N: static[int]] = array[N, float64]
  388. # TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb])
  389. result = PType(idTableGet(cl.localCache, t))
  390. if result != nil: return result
  391. inc cl.recursionLimit
  392. result = t
  393. if t == nil: return
  394. if t.kind in {tyStatic, tyGenericParam} + tyTypeClasses:
  395. let lookup = cl.typeMap.lookup(t)
  396. if lookup != nil: return lookup
  397. case t.kind
  398. of tyGenericInvocation:
  399. result = handleGenericInvocation(cl, t)
  400. if result.lastSon.kind == tyUserTypeClass:
  401. result.kind = tyUserTypeClassInst
  402. of tyGenericBody:
  403. localError(cl.c.config, cl.info, "cannot instantiate: '" & typeToString(t) & "'")
  404. result = errorType(cl.c)
  405. #result = replaceTypeVarsT(cl, lastSon(t))
  406. of tyFromExpr:
  407. if cl.allowMetaTypes: return
  408. # This assert is triggered when a tyFromExpr was created in a cyclic
  409. # way. You should break the cycle at the point of creation by introducing
  410. # a call such as: `n.typ = makeTypeFromExpr(c, n.copyTree)`
  411. # Otherwise, the cycle will be fatal for the prepareNode call below
  412. assert t.n.typ != t
  413. var n = prepareNode(cl, t.n)
  414. if n.kind != nkEmpty:
  415. n = cl.c.semConstExpr(cl.c, n)
  416. if n.typ.kind == tyTypeDesc:
  417. # XXX: sometimes, chained typedescs enter here.
  418. # It may be worth investigating why this is happening,
  419. # because it may cause other bugs elsewhere.
  420. result = n.typ.skipTypes({tyTypeDesc})
  421. # result = n.typ.base
  422. else:
  423. if n.typ.kind != tyStatic:
  424. # XXX: In the future, semConstExpr should
  425. # return tyStatic values to let anyone make
  426. # use of this knowledge. The patching here
  427. # won't be necessary then.
  428. result = newTypeS(tyStatic, cl.c)
  429. result.sons = @[n.typ]
  430. result.n = n
  431. else:
  432. result = n.typ
  433. of tyInt, tyFloat:
  434. result = skipIntLit(t)
  435. of tyTypeDesc:
  436. let lookup = cl.typeMap.lookup(t)
  437. if lookup != nil:
  438. result = lookup
  439. if tfUnresolved in t.flags or cl.skipTypedesc: result = result.base
  440. elif t.sons[0].kind != tyNone:
  441. result = makeTypeDesc(cl.c, replaceTypeVarsT(cl, t.sons[0]))
  442. of tyUserTypeClass, tyStatic:
  443. result = t
  444. of tyGenericInst, tyUserTypeClassInst:
  445. bailout()
  446. result = instCopyType(cl, t)
  447. idTablePut(cl.localCache, t, result)
  448. for i in 1 ..< result.sonsLen:
  449. result.sons[i] = replaceTypeVarsT(cl, result.sons[i])
  450. propagateToOwner(result, result.lastSon)
  451. else:
  452. if containsGenericType(t):
  453. #if not cl.allowMetaTypes:
  454. bailout()
  455. result = instCopyType(cl, t)
  456. result.size = -1 # needs to be recomputed
  457. #if not cl.allowMetaTypes:
  458. idTablePut(cl.localCache, t, result)
  459. for i in countup(0, sonsLen(result) - 1):
  460. if result.sons[i] != nil:
  461. var r = replaceTypeVarsT(cl, result.sons[i])
  462. if result.kind == tyObject:
  463. # carefully coded to not skip the precious tyGenericInst:
  464. let r2 = r.skipTypes({tyAlias, tySink})
  465. if r2.kind in {tyPtr, tyRef}:
  466. r = skipTypes(r2, {tyPtr, tyRef})
  467. result.sons[i] = r
  468. if result.kind != tyArray or i != 0:
  469. propagateToOwner(result, r)
  470. # bug #4677: Do not instantiate effect lists
  471. result.n = replaceTypeVarsN(cl, result.n, ord(result.kind==tyProc))
  472. case result.kind
  473. of tyArray:
  474. let idx = result.sons[0]
  475. internalAssert cl.c.config, idx.kind != tyStatic
  476. of tyObject, tyTuple:
  477. propagateFieldFlags(result, result.n)
  478. of tyProc:
  479. eraseVoidParams(result)
  480. skipIntLiteralParams(result)
  481. else: discard
  482. proc instAllTypeBoundOp*(c: PContext, info: TLineInfo) =
  483. var i = 0
  484. while i < c.typesWithOps.len:
  485. let (newty, oldty) = c.typesWithOps[i]
  486. typeBound(c, newty, oldty, destructor, info)
  487. typeBound(c, newty, oldty, sink, info)
  488. typeBound(c, newty, oldty, assignment, info)
  489. inc i
  490. setLen(c.typesWithOps, 0)
  491. proc initTypeVars*(p: PContext, typeMap: ptr LayeredIdTable, info: TLineInfo;
  492. owner: PSym): TReplTypeVars =
  493. initIdTable(result.symMap)
  494. initIdTable(result.localCache)
  495. result.typeMap = typeMap
  496. result.info = info
  497. result.c = p
  498. result.owner = owner
  499. proc replaceTypesInBody*(p: PContext, pt: TIdTable, n: PNode;
  500. owner: PSym, allowMetaTypes = false): PNode =
  501. var typeMap = initLayeredTypeMap(pt)
  502. var cl = initTypeVars(p, addr(typeMap), n.info, owner)
  503. cl.allowMetaTypes = allowMetaTypes
  504. pushInfoContext(p.config, n.info)
  505. result = replaceTypeVarsN(cl, n)
  506. popInfoContext(p.config)
  507. proc replaceTypesForLambda*(p: PContext, pt: TIdTable, n: PNode;
  508. original, new: PSym): PNode =
  509. var typeMap = initLayeredTypeMap(pt)
  510. var cl = initTypeVars(p, addr(typeMap), n.info, original)
  511. idTablePut(cl.symMap, original, new)
  512. pushInfoContext(p.config, n.info)
  513. result = replaceTypeVarsN(cl, n)
  514. popInfoContext(p.config)
  515. proc generateTypeInstance*(p: PContext, pt: TIdTable, info: TLineInfo,
  516. t: PType): PType =
  517. var typeMap = initLayeredTypeMap(pt)
  518. var cl = initTypeVars(p, addr(typeMap), info, nil)
  519. pushInfoContext(p.config, info)
  520. result = replaceTypeVarsT(cl, t)
  521. popInfoContext(p.config)
  522. proc prepareMetatypeForSigmatch*(p: PContext, pt: TIdTable, info: TLineInfo,
  523. t: PType): PType =
  524. var typeMap = initLayeredTypeMap(pt)
  525. var cl = initTypeVars(p, addr(typeMap), info, nil)
  526. cl.allowMetaTypes = true
  527. pushInfoContext(p.config, info)
  528. result = replaceTypeVarsT(cl, t)
  529. popInfoContext(p.config)
  530. template generateTypeInstance*(p: PContext, pt: TIdTable, arg: PNode,
  531. t: PType): untyped =
  532. generateTypeInstance(p, pt, arg.info, t)