semtypinst.nim 26 KB

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