semtypinst.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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 std / tables
  11. import ast, astalgo, msgs, types, magicsys, semdata, renderer, options,
  12. lineinfos, modulegraphs
  13. when defined(nimPreviewSlimSystem):
  14. import std/assertions
  15. const tfInstClearedFlags = {tfHasMeta, tfUnresolved}
  16. proc checkPartialConstructedType(conf: ConfigRef; info: TLineInfo, t: PType) =
  17. if t.kind in {tyVar, tyLent} and t.elementType.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 t.kind in {tyVar, tyLent} and t.elementType.kind in {tyVar, tyLent}:
  23. localError(conf, info, "type 'var var' is not allowed")
  24. elif computeSize(conf, t) == szIllegalRecursion or isTupleRecursive(t):
  25. localError(conf, info, "illegal recursion in type '" & typeToString(t) & "'")
  26. proc searchInstTypes*(g: ModuleGraph; key: PType): PType =
  27. result = nil
  28. let genericTyp = key[0]
  29. if not (genericTyp.kind == tyGenericBody and
  30. genericTyp.sym != nil): return
  31. for inst in typeInstCacheItems(g, genericTyp.sym):
  32. if inst.id == key.id: return inst
  33. if inst.kidsLen < key.kidsLen:
  34. # XXX: This happens for prematurely cached
  35. # types such as Channel[empty]. Why?
  36. # See the notes for PActor in handleGenericInvocation
  37. # if this is return the same type gets cached more than it needs to
  38. continue
  39. if not sameFlags(inst, key):
  40. continue
  41. block matchType:
  42. for j in FirstGenericParamAt..<key.kidsLen:
  43. # XXX sameType is not really correct for nested generics?
  44. if not compareTypes(inst[j], key[j],
  45. flags = {ExactGenericParams, PickyCAliases}):
  46. break matchType
  47. return inst
  48. proc cacheTypeInst(c: PContext; inst: PType) =
  49. let gt = inst[0]
  50. let t = if gt.kind == tyGenericBody: gt.typeBodyImpl else: gt
  51. if t.kind in {tyStatic, tyError, tyGenericParam} + tyTypeClasses:
  52. return
  53. addToGenericCache(c, gt.sym, inst)
  54. type
  55. LayeredIdTable* {.acyclic.} = ref object
  56. topLayer*: TypeMapping
  57. nextLayer*: LayeredIdTable
  58. TReplTypeVars* = object
  59. c*: PContext
  60. typeMap*: LayeredIdTable # map PType to PType
  61. symMap*: SymMapping # map PSym to PSym
  62. localCache*: TypeMapping # local cache for remembering already replaced
  63. # types during instantiation of meta types
  64. # (they are not stored in the global cache)
  65. info*: TLineInfo
  66. allowMetaTypes*: bool # allow types such as seq[Number]
  67. # i.e. the result contains unresolved generics
  68. skipTypedesc*: bool # whether we should skip typeDescs
  69. isReturnType*: bool
  70. owner*: PSym # where this instantiation comes from
  71. recursionLimit: int
  72. proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType
  73. proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym, t: PType): PSym
  74. proc replaceTypeVarsN*(cl: var TReplTypeVars, n: PNode; start=0; expectedType: PType = nil): PNode
  75. proc initLayeredTypeMap*(pt: sink TypeMapping): LayeredIdTable =
  76. result = LayeredIdTable()
  77. result.topLayer = pt
  78. proc newTypeMapLayer*(cl: var TReplTypeVars): LayeredIdTable =
  79. result = LayeredIdTable(nextLayer: cl.typeMap, topLayer: initTable[ItemId, PType]())
  80. proc lookup(typeMap: LayeredIdTable, key: PType): PType =
  81. result = nil
  82. var tm = typeMap
  83. while tm != nil:
  84. result = getOrDefault(tm.topLayer, key.itemId)
  85. if result != nil: return
  86. tm = tm.nextLayer
  87. template put(typeMap: LayeredIdTable, key, value: PType) =
  88. typeMap.topLayer[key.itemId] = value
  89. template checkMetaInvariants(cl: TReplTypeVars, t: PType) = # noop code
  90. when false:
  91. if t != nil and tfHasMeta in t.flags and
  92. cl.allowMetaTypes == false:
  93. echo "UNEXPECTED META ", t.id, " ", instantiationInfo(-1)
  94. debug t
  95. writeStackTrace()
  96. proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType =
  97. result = replaceTypeVarsTAux(cl, t)
  98. checkMetaInvariants(cl, result)
  99. proc prepareNode(cl: var TReplTypeVars, n: PNode): PNode =
  100. let t = replaceTypeVarsT(cl, n.typ)
  101. if t != nil and t.kind == tyStatic and t.n != nil:
  102. return if tfUnresolved in t.flags: prepareNode(cl, t.n)
  103. else: t.n
  104. result = copyNode(n)
  105. result.typ = t
  106. if result.kind == nkSym:
  107. result.sym =
  108. if n.typ != nil and n.typ == n.sym.typ:
  109. replaceTypeVarsS(cl, n.sym, result.typ)
  110. else:
  111. replaceTypeVarsS(cl, n.sym, replaceTypeVarsT(cl, n.sym.typ))
  112. let isCall = result.kind in nkCallKinds
  113. for i in 0..<n.safeLen:
  114. # XXX HACK: ``f(a, b)``, avoid to instantiate `f`
  115. if isCall and i == 0: result.add(n[i])
  116. else: result.add(prepareNode(cl, n[i]))
  117. proc isTypeParam(n: PNode): bool =
  118. # XXX: generic params should use skGenericParam instead of skType
  119. return n.kind == nkSym and
  120. (n.sym.kind == skGenericParam or
  121. (n.sym.kind == skType and sfFromGeneric in n.sym.flags))
  122. when false: # old workaround
  123. proc reResolveCallsWithTypedescParams(cl: var TReplTypeVars, n: PNode): PNode =
  124. # This is needed for tuninstantiatedgenericcalls
  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[0] = newSymNode(n[0].sym.owner)
  138. return cl.c.semOverloadedCall(cl.c, n, n, {skProc, skFunc}, {})
  139. for i in 0..<n.safeLen:
  140. n[i] = reResolveCallsWithTypedescParams(cl, n[i])
  141. return n
  142. proc replaceObjBranches(cl: TReplTypeVars, n: PNode): PNode =
  143. result = n
  144. case n.kind
  145. of nkNone..nkNilLit:
  146. discard
  147. of nkRecWhen:
  148. var branch: PNode = nil # the branch to take
  149. for i in 0..<n.len:
  150. var it = n[i]
  151. if it == nil: illFormedAst(n, cl.c.config)
  152. case it.kind
  153. of nkElifBranch:
  154. checkSonsLen(it, 2, cl.c.config)
  155. var cond = it[0]
  156. var e = cl.c.semConstExpr(cl.c, cond)
  157. if e.kind != nkIntLit:
  158. internalError(cl.c.config, e.info, "ReplaceTypeVarsN: when condition not a bool")
  159. if e.intVal != 0 and branch == nil: branch = it[1]
  160. of nkElse:
  161. checkSonsLen(it, 1, cl.c.config)
  162. if branch == nil: branch = it[0]
  163. else: illFormedAst(n, cl.c.config)
  164. if branch != nil:
  165. result = replaceObjBranches(cl, branch)
  166. else:
  167. result = newNodeI(nkRecList, n.info)
  168. else:
  169. for i in 0..<n.len:
  170. n[i] = replaceObjBranches(cl, n[i])
  171. proc hasValuelessStatics(n: PNode): bool =
  172. # We should only attempt to call an expression that has no tyStatics
  173. # As those are unresolved generic parameters, which means in the following
  174. # The compiler attempts to do `T == 300` which errors since the typeclass `MyThing` lacks a parameter
  175. #[
  176. type MyThing[T: static int] = object
  177. when T == 300:
  178. a
  179. proc doThing(_: MyThing)
  180. ]#
  181. if n.safeLen == 0 and n.kind != nkEmpty: # Some empty nodes can get in here
  182. n.typ == nil or n.typ.kind == tyStatic
  183. else:
  184. for x in n:
  185. if hasValuelessStatics(x):
  186. return true
  187. false
  188. proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode; start=0; expectedType: PType = nil): PNode =
  189. if n == nil: return
  190. result = copyNode(n)
  191. if n.typ != nil:
  192. result.typ = replaceTypeVarsT(cl, n.typ)
  193. checkMetaInvariants(cl, result.typ)
  194. case n.kind
  195. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit:
  196. discard
  197. of nkOpenSymChoice, nkClosedSymChoice: result = n
  198. of nkSym:
  199. result.sym =
  200. if n.typ != nil and n.typ == n.sym.typ:
  201. replaceTypeVarsS(cl, n.sym, result.typ)
  202. else:
  203. replaceTypeVarsS(cl, n.sym, replaceTypeVarsT(cl, n.sym.typ))
  204. if result.sym.typ.kind == tyVoid:
  205. # don't add the 'void' field
  206. result = newNodeI(nkRecList, n.info)
  207. of nkRecWhen:
  208. var branch: PNode = nil # the branch to take
  209. for i in 0..<n.len:
  210. var it = n[i]
  211. if it == nil: illFormedAst(n, cl.c.config)
  212. case it.kind
  213. of nkElifBranch:
  214. checkSonsLen(it, 2, cl.c.config)
  215. var cond = prepareNode(cl, it[0])
  216. if not cond.hasValuelessStatics:
  217. var e = cl.c.semConstExpr(cl.c, cond)
  218. if e.kind != nkIntLit:
  219. internalError(cl.c.config, e.info, "ReplaceTypeVarsN: when condition not a bool")
  220. if e.intVal != 0 and branch == nil: branch = it[1]
  221. of nkElse:
  222. checkSonsLen(it, 1, cl.c.config)
  223. if branch == nil: branch = it[0]
  224. else: illFormedAst(n, cl.c.config)
  225. if branch != nil:
  226. result = replaceTypeVarsN(cl, branch)
  227. else:
  228. result = newNodeI(nkRecList, n.info)
  229. of nkStaticExpr:
  230. var n = prepareNode(cl, n)
  231. when false:
  232. n = reResolveCallsWithTypedescParams(cl, n)
  233. result = if cl.allowMetaTypes: n
  234. else: cl.c.semExpr(cl.c, n, {}, expectedType)
  235. if not cl.allowMetaTypes and expectedType != nil:
  236. assert result.kind notin nkCallKinds
  237. else:
  238. if n.len > 0:
  239. newSons(result, n.len)
  240. if start > 0:
  241. result[0] = n[0]
  242. for i in start..<n.len:
  243. result[i] = replaceTypeVarsN(cl, n[i])
  244. proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym, t: PType): PSym =
  245. if s == nil: return nil
  246. # symbol is not our business:
  247. if cl.owner != nil and s.owner != cl.owner:
  248. return s
  249. # XXX: Bound symbols in default parameter expressions may reach here.
  250. # We cannot process them, because `sym.n` may point to a proc body with
  251. # cyclic references that will lead to an infinite recursion.
  252. # Perhaps we should not use a black-list here, but a whitelist instead
  253. # (e.g. skGenericParam and skType).
  254. # Note: `s.magic` may be `mType` in an example such as:
  255. # proc foo[T](a: T, b = myDefault(type(a)))
  256. if s.kind in routineKinds+{skLet, skConst, skVar} or s.magic != mNone:
  257. return s
  258. #result = PSym(idTableGet(cl.symMap, s))
  259. #if result == nil:
  260. #[
  261. We cannot naively check for symbol recursions, because otherwise
  262. object types A, B whould share their fields!
  263. import tables
  264. type
  265. Table[S, T] = object
  266. x: S
  267. y: T
  268. G[T] = object
  269. inodes: Table[int, T] # A
  270. rnodes: Table[T, int] # B
  271. var g: G[string]
  272. ]#
  273. result = copySym(s, cl.c.idgen)
  274. incl(result.flags, sfFromGeneric)
  275. #idTablePut(cl.symMap, s, result)
  276. result.owner = s.owner
  277. result.typ = t
  278. if result.kind != skType:
  279. result.ast = replaceTypeVarsN(cl, s.ast)
  280. proc lookupTypeVar(cl: var TReplTypeVars, t: PType): PType =
  281. if tfRetType in t.flags and t.kind == tyAnything:
  282. # don't bind `auto` return type to a previous binding of `auto`
  283. return nil
  284. result = cl.typeMap.lookup(t)
  285. if result == nil:
  286. if cl.allowMetaTypes or tfRetType in t.flags: return
  287. localError(cl.c.config, t.sym.info, "cannot instantiate: '" & typeToString(t) & "'")
  288. result = errorType(cl.c)
  289. # In order to prevent endless recursions, we must remember
  290. # this bad lookup and replace it with errorType everywhere.
  291. # These code paths are only active in "nim check"
  292. cl.typeMap.put(t, result)
  293. elif result.kind == tyGenericParam and not cl.allowMetaTypes:
  294. internalError(cl.c.config, cl.info, "substitution with generic parameter")
  295. proc instCopyType*(cl: var TReplTypeVars, t: PType): PType =
  296. # XXX: relying on allowMetaTypes is a kludge
  297. if cl.allowMetaTypes:
  298. result = t.exactReplica
  299. else:
  300. result = copyType(t, cl.c.idgen, t.owner)
  301. copyTypeProps(cl.c.graph, cl.c.idgen.module, result, t)
  302. #cl.typeMap.topLayer.idTablePut(result, t)
  303. if cl.allowMetaTypes: return
  304. result.flags.incl tfFromGeneric
  305. if not (t.kind in tyMetaTypes or
  306. (t.kind == tyStatic and t.n == nil)):
  307. result.flags.excl tfInstClearedFlags
  308. else:
  309. result.flags.excl tfHasAsgn
  310. when false:
  311. if newDestructors:
  312. result.assignment = nil
  313. result.destructor = nil
  314. result.sink = nil
  315. proc handleGenericInvocation(cl: var TReplTypeVars, t: PType): PType =
  316. # tyGenericInvocation[A, tyGenericInvocation[A, B]]
  317. # is difficult to handle:
  318. var body = t.genericHead
  319. if body.kind != tyGenericBody:
  320. internalError(cl.c.config, cl.info, "no generic body")
  321. var header = t
  322. # search for some instantiation here:
  323. if cl.allowMetaTypes:
  324. result = getOrDefault(cl.localCache, t.itemId)
  325. else:
  326. result = searchInstTypes(cl.c.graph, t)
  327. if result != nil and sameFlags(result, t):
  328. when defined(reportCacheHits):
  329. echo "Generic instantiation cached ", typeToString(result), " for ", typeToString(t)
  330. return
  331. for i in FirstGenericParamAt..<t.kidsLen:
  332. var x = t[i]
  333. if x.kind in {tyGenericParam}:
  334. x = lookupTypeVar(cl, x)
  335. if x != nil:
  336. if header == t: header = instCopyType(cl, t)
  337. header[i] = x
  338. propagateToOwner(header, x)
  339. else:
  340. propagateToOwner(header, x)
  341. if header != t:
  342. # search again after first pass:
  343. result = searchInstTypes(cl.c.graph, header)
  344. if result != nil and sameFlags(result, t):
  345. when defined(reportCacheHits):
  346. echo "Generic instantiation cached ", typeToString(result), " for ",
  347. typeToString(t), " header ", typeToString(header)
  348. return
  349. else:
  350. header = instCopyType(cl, t)
  351. result = newType(tyGenericInst, cl.c.idgen, t.genericHead.owner, son = header.genericHead)
  352. result.flags = header.flags
  353. # be careful not to propagate unnecessary flags here (don't use rawAddSon)
  354. # ugh need another pass for deeply recursive generic types (e.g. PActor)
  355. # we need to add the candidate here, before it's fully instantiated for
  356. # recursive instantions:
  357. if not cl.allowMetaTypes:
  358. cacheTypeInst(cl.c, result)
  359. else:
  360. cl.localCache[t.itemId] = result
  361. let oldSkipTypedesc = cl.skipTypedesc
  362. cl.skipTypedesc = true
  363. cl.typeMap = newTypeMapLayer(cl)
  364. for i in FirstGenericParamAt..<t.kidsLen:
  365. var x = replaceTypeVarsT(cl):
  366. if header[i].kind == tyGenericInst:
  367. t[i]
  368. else:
  369. header[i]
  370. assert x.kind != tyGenericInvocation
  371. header[i] = x
  372. propagateToOwner(header, x)
  373. cl.typeMap.put(body[i-1], x)
  374. for i in FirstGenericParamAt..<t.kidsLen:
  375. # if one of the params is not concrete, we cannot do anything
  376. # but we already raised an error!
  377. rawAddSon(result, header[i], propagateHasAsgn = false)
  378. if body.kind == tyError:
  379. return
  380. let bbody = last body
  381. var newbody = replaceTypeVarsT(cl, bbody)
  382. cl.skipTypedesc = oldSkipTypedesc
  383. newbody.flags = newbody.flags + (t.flags + body.flags - tfInstClearedFlags)
  384. result.flags = result.flags + newbody.flags - tfInstClearedFlags
  385. cl.typeMap = cl.typeMap.nextLayer
  386. # This is actually wrong: tgeneric_closure fails with this line:
  387. #newbody.callConv = body.callConv
  388. # This type may be a generic alias and we want to resolve it here.
  389. # One step is enough, because the recursive nature of
  390. # handleGenericInvocation will handle the alias-to-alias-to-alias case
  391. if newbody.isGenericAlias: newbody = newbody.skipGenericAlias
  392. rawAddSon(result, newbody)
  393. checkPartialConstructedType(cl.c.config, cl.info, newbody)
  394. if not cl.allowMetaTypes:
  395. let dc = cl.c.graph.getAttachedOp(newbody, attachedDeepCopy)
  396. if dc != nil and sfFromGeneric notin dc.flags:
  397. # 'deepCopy' needs to be instantiated for
  398. # generics *when the type is constructed*:
  399. cl.c.graph.setAttachedOp(cl.c.module.position, newbody, attachedDeepCopy,
  400. cl.c.instTypeBoundOp(cl.c, dc, result, cl.info, attachedDeepCopy, 1))
  401. if newbody.typeInst == nil:
  402. # doAssert newbody.typeInst == nil
  403. newbody.typeInst = result
  404. if tfRefsAnonObj in newbody.flags and newbody.kind != tyGenericInst:
  405. # can come here for tyGenericInst too, see tests/metatype/ttypeor.nim
  406. # need to look into this issue later
  407. assert newbody.kind in {tyRef, tyPtr}
  408. if newbody.last.typeInst != nil:
  409. #internalError(cl.c.config, cl.info, "ref already has a 'typeInst' field")
  410. discard
  411. else:
  412. newbody.last.typeInst = result
  413. # DESTROY: adding object|opt for opt[topttree.Tree]
  414. # sigmatch: Formal opt[=destroy.T] real opt[topttree.Tree]
  415. # adding myseq for myseq[system.int]
  416. # sigmatch: Formal myseq[=destroy.T] real myseq[system.int]
  417. #echo "DESTROY: adding ", typeToString(newbody), " for ", typeToString(result, preferDesc)
  418. let mm = skipTypes(bbody, abstractPtrs)
  419. if tfFromGeneric notin mm.flags:
  420. # bug #5479, prevent endless recursions here:
  421. incl mm.flags, tfFromGeneric
  422. for col, meth in methodsForGeneric(cl.c.graph, mm):
  423. # we instantiate the known methods belonging to that type, this causes
  424. # them to be registered and that's enough, so we 'discard' the result.
  425. discard cl.c.instTypeBoundOp(cl.c, meth, result, cl.info,
  426. attachedAsgn, col)
  427. excl mm.flags, tfFromGeneric
  428. proc eraseVoidParams*(t: PType) =
  429. # transform '(): void' into '()' because old parts of the compiler really
  430. # don't deal with '(): void':
  431. if t.returnType != nil and t.returnType.kind == tyVoid:
  432. t.setReturnType nil
  433. for i in FirstParamAt..<t.signatureLen:
  434. # don't touch any memory unless necessary
  435. if t[i].kind == tyVoid:
  436. var pos = i
  437. for j in i+1..<t.signatureLen:
  438. if t[j].kind != tyVoid:
  439. t[pos] = t[j]
  440. t.n[pos] = t.n[j]
  441. inc pos
  442. newSons t, pos
  443. setLen t.n.sons, pos
  444. break
  445. proc skipIntLiteralParams*(t: PType; idgen: IdGenerator) =
  446. for i, p in t.ikids:
  447. if p == nil: continue
  448. let skipped = p.skipIntLit(idgen)
  449. if skipped != p:
  450. t[i] = skipped
  451. if i > 0: t.n[i].sym.typ = skipped
  452. # when the typeof operator is used on a static input
  453. # param, the results gets infected with static as well:
  454. if t.returnType != nil and t.returnType.kind == tyStatic:
  455. t.setReturnType t.returnType.skipModifier
  456. proc propagateFieldFlags(t: PType, n: PNode) =
  457. # This is meant for objects and tuples
  458. # The type must be fully instantiated!
  459. if n.isNil:
  460. return
  461. #internalAssert n.kind != nkRecWhen
  462. case n.kind
  463. of nkSym:
  464. propagateToOwner(t, n.sym.typ)
  465. of nkRecList, nkRecCase, nkOfBranch, nkElse:
  466. for son in n:
  467. propagateFieldFlags(t, son)
  468. else: discard
  469. proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
  470. template bailout =
  471. if (t.sym == nil) or (t.sym != nil and sfGeneratedType in t.sym.flags):
  472. # In the first case 't.sym' can be 'nil' if the type is a ref/ptr, see
  473. # issue https://github.com/nim-lang/Nim/issues/20416 for more details.
  474. # Fortunately for us this works for now because partial ref/ptr types are
  475. # not allowed in object construction, eg.
  476. # type
  477. # Container[T] = ...
  478. # O = object
  479. # val: ref Container
  480. #
  481. # In the second case only consider the recursion limit if the symbol is a
  482. # type with generic parameters that have not been explicitly supplied,
  483. # typechecking should terminate when generic parameters are explicitly
  484. # supplied.
  485. if cl.recursionLimit > 100:
  486. # bail out, see bug #2509. But note this caching is in general wrong,
  487. # look at this example where TwoVectors should not share the generic
  488. # instantiations (bug #3112):
  489. # type
  490. # Vector[N: static[int]] = array[N, float64]
  491. # TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb])
  492. result = getOrDefault(cl.localCache, t.itemId)
  493. if result != nil: return result
  494. inc cl.recursionLimit
  495. result = t
  496. if t == nil: return
  497. const lookupMetas = {tyStatic, tyGenericParam, tyConcept} + tyTypeClasses - {tyAnything}
  498. if t.kind in lookupMetas or
  499. (t.kind == tyAnything and tfRetType notin t.flags):
  500. let lookup = cl.typeMap.lookup(t)
  501. if lookup != nil: return lookup
  502. case t.kind
  503. of tyGenericInvocation:
  504. result = handleGenericInvocation(cl, t)
  505. if result.last.kind == tyUserTypeClass:
  506. result.kind = tyUserTypeClassInst
  507. of tyGenericBody:
  508. localError(
  509. cl.c.config,
  510. cl.info,
  511. "cannot instantiate: '" &
  512. typeToString(t, preferDesc) &
  513. "'; Maybe generic arguments are missing?")
  514. result = errorType(cl.c)
  515. #result = replaceTypeVarsT(cl, lastSon(t))
  516. of tyFromExpr:
  517. if cl.allowMetaTypes: return
  518. # This assert is triggered when a tyFromExpr was created in a cyclic
  519. # way. You should break the cycle at the point of creation by introducing
  520. # a call such as: `n.typ = makeTypeFromExpr(c, n.copyTree)`
  521. # Otherwise, the cycle will be fatal for the prepareNode call below
  522. assert t.n.typ != t
  523. var n = prepareNode(cl, t.n)
  524. if n.kind != nkEmpty:
  525. n = cl.c.semConstExpr(cl.c, n)
  526. if n.typ.kind == tyTypeDesc:
  527. # XXX: sometimes, chained typedescs enter here.
  528. # It may be worth investigating why this is happening,
  529. # because it may cause other bugs elsewhere.
  530. result = n.typ.skipTypes({tyTypeDesc})
  531. # result = n.typ.base
  532. else:
  533. if n.typ.kind != tyStatic and n.kind != nkType:
  534. # XXX: In the future, semConstExpr should
  535. # return tyStatic values to let anyone make
  536. # use of this knowledge. The patching here
  537. # won't be necessary then.
  538. result = newTypeS(tyStatic, cl.c, son = n.typ)
  539. result.n = n
  540. else:
  541. result = n.typ
  542. of tyInt, tyFloat:
  543. result = skipIntLit(t, cl.c.idgen)
  544. of tyTypeDesc:
  545. let lookup = cl.typeMap.lookup(t)
  546. if lookup != nil:
  547. result = lookup
  548. if result.kind != tyTypeDesc:
  549. result = makeTypeDesc(cl.c, result)
  550. elif tfUnresolved in t.flags or cl.skipTypedesc:
  551. result = result.base
  552. elif t.elementType.kind != tyNone:
  553. result = makeTypeDesc(cl.c, replaceTypeVarsT(cl, t.elementType))
  554. of tyUserTypeClass, tyStatic:
  555. result = t
  556. of tyGenericInst, tyUserTypeClassInst:
  557. bailout()
  558. result = instCopyType(cl, t)
  559. cl.localCache[t.itemId] = result
  560. for i in FirstGenericParamAt..<result.kidsLen:
  561. result[i] = replaceTypeVarsT(cl, result[i])
  562. propagateToOwner(result, result.last)
  563. else:
  564. if containsGenericType(t):
  565. #if not cl.allowMetaTypes:
  566. bailout()
  567. result = instCopyType(cl, t)
  568. result.size = -1 # needs to be recomputed
  569. #if not cl.allowMetaTypes:
  570. cl.localCache[t.itemId] = result
  571. for i, resulti in result.ikids:
  572. if resulti != nil:
  573. if resulti.kind == tyGenericBody:
  574. localError(cl.c.config, if t.sym != nil: t.sym.info else: cl.info,
  575. "cannot instantiate '" &
  576. typeToString(result[i], preferDesc) &
  577. "' inside of type definition: '" &
  578. t.owner.name.s & "'; Maybe generic arguments are missing?")
  579. var r = replaceTypeVarsT(cl, resulti)
  580. if result.kind == tyObject:
  581. # carefully coded to not skip the precious tyGenericInst:
  582. let r2 = r.skipTypes({tyAlias, tySink, tyOwned})
  583. if r2.kind in {tyPtr, tyRef}:
  584. r = skipTypes(r2, {tyPtr, tyRef})
  585. result[i] = r
  586. if result.kind != tyArray or i != 0:
  587. propagateToOwner(result, r)
  588. # bug #4677: Do not instantiate effect lists
  589. result.n = replaceTypeVarsN(cl, result.n, ord(result.kind==tyProc))
  590. case result.kind
  591. of tyArray:
  592. let idx = result.indexType
  593. internalAssert cl.c.config, idx.kind != tyStatic
  594. of tyObject, tyTuple:
  595. propagateFieldFlags(result, result.n)
  596. if result.kind == tyObject and cl.c.computeRequiresInit(cl.c, result):
  597. result.flags.incl tfRequiresInit
  598. of tyProc:
  599. eraseVoidParams(result)
  600. skipIntLiteralParams(result, cl.c.idgen)
  601. of tyRange:
  602. result.setIndexType result.indexType.skipTypes({tyStatic, tyDistinct})
  603. else: discard
  604. else:
  605. # If this type doesn't refer to a generic type we may still want to run it
  606. # trough replaceObjBranches in order to resolve any pending nkRecWhen nodes
  607. result = t
  608. # Slow path, we have some work to do
  609. if t.kind == tyRef and t.hasElementType and t.elementType.kind == tyObject and t.elementType.n != nil:
  610. discard replaceObjBranches(cl, t.elementType.n)
  611. elif result.n != nil and t.kind == tyObject:
  612. # Invalidate the type size as we may alter its structure
  613. result.size = -1
  614. result.n = replaceObjBranches(cl, result.n)
  615. proc initTypeVars*(p: PContext, typeMap: LayeredIdTable, info: TLineInfo;
  616. owner: PSym): TReplTypeVars =
  617. result = TReplTypeVars(symMap: initSymMapping(),
  618. localCache: initTypeMapping(), typeMap: typeMap,
  619. info: info, c: p, owner: owner)
  620. proc replaceTypesInBody*(p: PContext, pt: TypeMapping, n: PNode;
  621. owner: PSym, allowMetaTypes = false,
  622. fromStaticExpr = false, expectedType: PType = nil): PNode =
  623. var typeMap = initLayeredTypeMap(pt)
  624. var cl = initTypeVars(p, typeMap, n.info, owner)
  625. cl.allowMetaTypes = allowMetaTypes
  626. pushInfoContext(p.config, n.info)
  627. result = replaceTypeVarsN(cl, n, expectedType = expectedType)
  628. popInfoContext(p.config)
  629. when false:
  630. # deadcode
  631. proc replaceTypesForLambda*(p: PContext, pt: TIdTable, n: PNode;
  632. original, new: PSym): PNode =
  633. var typeMap = initLayeredTypeMap(pt)
  634. var cl = initTypeVars(p, typeMap, n.info, original)
  635. idTablePut(cl.symMap, original, new)
  636. pushInfoContext(p.config, n.info)
  637. result = replaceTypeVarsN(cl, n)
  638. popInfoContext(p.config)
  639. proc recomputeFieldPositions*(t: PType; obj: PNode; currPosition: var int) =
  640. if t != nil and t.baseClass != nil:
  641. let b = skipTypes(t.baseClass, skipPtrs)
  642. recomputeFieldPositions(b, b.n, currPosition)
  643. case obj.kind
  644. of nkRecList:
  645. for i in 0..<obj.len: recomputeFieldPositions(nil, obj[i], currPosition)
  646. of nkRecCase:
  647. recomputeFieldPositions(nil, obj[0], currPosition)
  648. for i in 1..<obj.len:
  649. recomputeFieldPositions(nil, lastSon(obj[i]), currPosition)
  650. of nkSym:
  651. obj.sym.position = currPosition
  652. inc currPosition
  653. else: discard "cannot happen"
  654. proc generateTypeInstance*(p: PContext, pt: TypeMapping, info: TLineInfo,
  655. t: PType): PType =
  656. # Given `t` like Foo[T]
  657. # pt: Table with type mappings: T -> int
  658. # Desired result: Foo[int]
  659. # proc (x: T = 0); T -> int ----> proc (x: int = 0)
  660. var typeMap = initLayeredTypeMap(pt)
  661. var cl = initTypeVars(p, typeMap, info, nil)
  662. pushInfoContext(p.config, info)
  663. result = replaceTypeVarsT(cl, t)
  664. popInfoContext(p.config)
  665. let objType = result.skipTypes(abstractInst)
  666. if objType.kind == tyObject:
  667. var position = 0
  668. recomputeFieldPositions(objType, objType.n, position)
  669. proc prepareMetatypeForSigmatch*(p: PContext, pt: TypeMapping, info: TLineInfo,
  670. t: PType): PType =
  671. var typeMap = initLayeredTypeMap(pt)
  672. var cl = initTypeVars(p, typeMap, info, nil)
  673. cl.allowMetaTypes = true
  674. pushInfoContext(p.config, info)
  675. result = replaceTypeVarsT(cl, t)
  676. popInfoContext(p.config)
  677. template generateTypeInstance*(p: PContext, pt: TypeMapping, arg: PNode,
  678. t: PType): untyped =
  679. generateTypeInstance(p, pt, arg.info, t)