semtypinst.nim 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 replaceTypeVarsN(cl: var TReplTypeVars, n: PNode; start=0): PNode =
  169. if n == nil: return
  170. result = copyNode(n)
  171. if n.typ != nil:
  172. result.typ = replaceTypeVarsT(cl, n.typ)
  173. checkMetaInvariants(cl, result.typ)
  174. case n.kind
  175. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit:
  176. discard
  177. of nkOpenSymChoice, nkClosedSymChoice: result = n
  178. of nkSym:
  179. result.sym = replaceTypeVarsS(cl, n.sym)
  180. if result.sym.typ.kind == tyVoid:
  181. # don't add the 'void' field
  182. result = newNodeI(nkRecList, n.info)
  183. of nkRecWhen:
  184. var branch: PNode = nil # the branch to take
  185. for i in 0..<n.len:
  186. var it = n[i]
  187. if it == nil: illFormedAst(n, cl.c.config)
  188. case it.kind
  189. of nkElifBranch:
  190. checkSonsLen(it, 2, cl.c.config)
  191. var cond = prepareNode(cl, it[0])
  192. var e = cl.c.semConstExpr(cl.c, cond)
  193. if e.kind != nkIntLit:
  194. internalError(cl.c.config, e.info, "ReplaceTypeVarsN: when condition not a bool")
  195. if e.intVal != 0 and branch == nil: branch = it[1]
  196. of nkElse:
  197. checkSonsLen(it, 1, cl.c.config)
  198. if branch == nil: branch = it[0]
  199. else: illFormedAst(n, cl.c.config)
  200. if branch != nil:
  201. result = replaceTypeVarsN(cl, branch)
  202. else:
  203. result = newNodeI(nkRecList, n.info)
  204. of nkStaticExpr:
  205. var n = prepareNode(cl, n)
  206. n = reResolveCallsWithTypedescParams(cl, n)
  207. result = if cl.allowMetaTypes: n
  208. else: cl.c.semExpr(cl.c, n)
  209. if not cl.allowMetaTypes:
  210. assert result.kind notin nkCallKinds
  211. else:
  212. if n.len > 0:
  213. newSons(result, n.len)
  214. if start > 0:
  215. result[0] = n[0]
  216. for i in start..<n.len:
  217. result[i] = replaceTypeVarsN(cl, n[i])
  218. proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym =
  219. if s == nil: return nil
  220. # symbol is not our business:
  221. if cl.owner != nil and s.owner != cl.owner:
  222. return s
  223. # XXX: Bound symbols in default parameter expressions may reach here.
  224. # We cannot process them, because `sym.n` may point to a proc body with
  225. # cyclic references that will lead to an infinite recursion.
  226. # Perhaps we should not use a black-list here, but a whitelist instead
  227. # (e.g. skGenericParam and skType).
  228. # Note: `s.magic` may be `mType` in an example such as:
  229. # proc foo[T](a: T, b = myDefault(type(a)))
  230. if s.kind in routineKinds+{skLet, skConst, skVar} or s.magic != mNone:
  231. return s
  232. #result = PSym(idTableGet(cl.symMap, s))
  233. #if result == nil:
  234. #[
  235. We cannot naively check for symbol recursions, because otherwise
  236. object types A, B whould share their fields!
  237. import tables
  238. type
  239. Table[S, T] = object
  240. x: S
  241. y: T
  242. G[T] = object
  243. inodes: Table[int, T] # A
  244. rnodes: Table[T, int] # B
  245. var g: G[string]
  246. ]#
  247. result = copySym(s, nextSymId cl.c.idgen)
  248. incl(result.flags, sfFromGeneric)
  249. #idTablePut(cl.symMap, s, result)
  250. result.owner = s.owner
  251. result.typ = replaceTypeVarsT(cl, s.typ)
  252. if result.kind != skType:
  253. result.ast = replaceTypeVarsN(cl, s.ast)
  254. proc lookupTypeVar(cl: var TReplTypeVars, t: PType): PType =
  255. result = cl.typeMap.lookup(t)
  256. if result == nil:
  257. if cl.allowMetaTypes or tfRetType in t.flags: return
  258. localError(cl.c.config, t.sym.info, "cannot instantiate: '" & typeToString(t) & "'")
  259. result = errorType(cl.c)
  260. # In order to prevent endless recursions, we must remember
  261. # this bad lookup and replace it with errorType everywhere.
  262. # These code paths are only active in "nim check"
  263. cl.typeMap.put(t, result)
  264. elif result.kind == tyGenericParam and not cl.allowMetaTypes:
  265. internalError(cl.c.config, cl.info, "substitution with generic parameter")
  266. proc instCopyType*(cl: var TReplTypeVars, t: PType): PType =
  267. # XXX: relying on allowMetaTypes is a kludge
  268. if cl.allowMetaTypes:
  269. result = t.exactReplica
  270. else:
  271. result = copyType(t, nextTypeId(cl.c.idgen), t.owner)
  272. copyTypeProps(cl.c.graph, cl.c.idgen.module, result, t)
  273. #cl.typeMap.topLayer.idTablePut(result, t)
  274. if cl.allowMetaTypes: return
  275. result.flags.incl tfFromGeneric
  276. if not (t.kind in tyMetaTypes or
  277. (t.kind == tyStatic and t.n == nil)):
  278. result.flags.excl tfInstClearedFlags
  279. else:
  280. result.flags.excl tfHasAsgn
  281. when false:
  282. if newDestructors:
  283. result.assignment = nil
  284. result.destructor = nil
  285. result.sink = nil
  286. proc handleGenericInvocation(cl: var TReplTypeVars, t: PType): PType =
  287. # tyGenericInvocation[A, tyGenericInvocation[A, B]]
  288. # is difficult to handle:
  289. var body = t[0]
  290. if body.kind != tyGenericBody:
  291. internalError(cl.c.config, cl.info, "no generic body")
  292. var header = t
  293. # search for some instantiation here:
  294. if cl.allowMetaTypes:
  295. result = PType(idTableGet(cl.localCache, t))
  296. else:
  297. result = searchInstTypes(cl.c.graph, t)
  298. if result != nil and sameFlags(result, t):
  299. when defined(reportCacheHits):
  300. echo "Generic instantiation cached ", typeToString(result), " for ", typeToString(t)
  301. return
  302. for i in 1..<t.len:
  303. var x = t[i]
  304. if x.kind in {tyGenericParam}:
  305. x = lookupTypeVar(cl, x)
  306. if x != nil:
  307. if header == t: header = instCopyType(cl, t)
  308. header[i] = x
  309. propagateToOwner(header, x)
  310. else:
  311. propagateToOwner(header, x)
  312. if header != t:
  313. # search again after first pass:
  314. result = searchInstTypes(cl.c.graph, header)
  315. if result != nil and sameFlags(result, t):
  316. when defined(reportCacheHits):
  317. echo "Generic instantiation cached ", typeToString(result), " for ",
  318. typeToString(t), " header ", typeToString(header)
  319. return
  320. else:
  321. header = instCopyType(cl, t)
  322. result = newType(tyGenericInst, nextTypeId(cl.c.idgen), t[0].owner)
  323. result.flags = header.flags
  324. # be careful not to propagate unnecessary flags here (don't use rawAddSon)
  325. result.sons = @[header[0]]
  326. # ugh need another pass for deeply recursive generic types (e.g. PActor)
  327. # we need to add the candidate here, before it's fully instantiated for
  328. # recursive instantions:
  329. if not cl.allowMetaTypes:
  330. cacheTypeInst(cl.c, result)
  331. else:
  332. idTablePut(cl.localCache, t, result)
  333. let oldSkipTypedesc = cl.skipTypedesc
  334. cl.skipTypedesc = true
  335. cl.typeMap = newTypeMapLayer(cl)
  336. for i in 1..<t.len:
  337. var x = replaceTypeVarsT(cl):
  338. if header[i].kind == tyGenericInst:
  339. t[i]
  340. else:
  341. header[i]
  342. assert x.kind != tyGenericInvocation
  343. header[i] = x
  344. propagateToOwner(header, x)
  345. cl.typeMap.put(body[i-1], x)
  346. for i in 1..<t.len:
  347. # if one of the params is not concrete, we cannot do anything
  348. # but we already raised an error!
  349. rawAddSon(result, header[i], propagateHasAsgn = false)
  350. if body.kind == tyError:
  351. return
  352. let bbody = lastSon body
  353. var newbody = replaceTypeVarsT(cl, bbody)
  354. cl.skipTypedesc = oldSkipTypedesc
  355. newbody.flags = newbody.flags + (t.flags + body.flags - tfInstClearedFlags)
  356. result.flags = result.flags + newbody.flags - tfInstClearedFlags
  357. cl.typeMap = cl.typeMap.nextLayer
  358. # This is actually wrong: tgeneric_closure fails with this line:
  359. #newbody.callConv = body.callConv
  360. # This type may be a generic alias and we want to resolve it here.
  361. # One step is enough, because the recursive nature of
  362. # handleGenericInvocation will handle the alias-to-alias-to-alias case
  363. if newbody.isGenericAlias: newbody = newbody.skipGenericAlias
  364. rawAddSon(result, newbody)
  365. checkPartialConstructedType(cl.c.config, cl.info, newbody)
  366. if not cl.allowMetaTypes:
  367. let dc = cl.c.graph.getAttachedOp(newbody, attachedDeepCopy)
  368. if dc != nil and sfFromGeneric notin dc.flags:
  369. # 'deepCopy' needs to be instantiated for
  370. # generics *when the type is constructed*:
  371. cl.c.graph.setAttachedOp(cl.c.module.position, newbody, attachedDeepCopy,
  372. cl.c.instTypeBoundOp(cl.c, dc, result, cl.info, attachedDeepCopy, 1))
  373. if newbody.typeInst == nil:
  374. # doAssert newbody.typeInst == nil
  375. newbody.typeInst = result
  376. if tfRefsAnonObj in newbody.flags and newbody.kind != tyGenericInst:
  377. # can come here for tyGenericInst too, see tests/metatype/ttypeor.nim
  378. # need to look into this issue later
  379. assert newbody.kind in {tyRef, tyPtr}
  380. if newbody.lastSon.typeInst != nil:
  381. #internalError(cl.c.config, cl.info, "ref already has a 'typeInst' field")
  382. discard
  383. else:
  384. newbody.lastSon.typeInst = result
  385. # DESTROY: adding object|opt for opt[topttree.Tree]
  386. # sigmatch: Formal opt[=destroy.T] real opt[topttree.Tree]
  387. # adding myseq for myseq[system.int]
  388. # sigmatch: Formal myseq[=destroy.T] real myseq[system.int]
  389. #echo "DESTROY: adding ", typeToString(newbody), " for ", typeToString(result, preferDesc)
  390. let mm = skipTypes(bbody, abstractPtrs)
  391. if tfFromGeneric notin mm.flags:
  392. # bug #5479, prevent endless recursions here:
  393. incl mm.flags, tfFromGeneric
  394. for col, meth in methodsForGeneric(cl.c.graph, mm):
  395. # we instantiate the known methods belonging to that type, this causes
  396. # them to be registered and that's enough, so we 'discard' the result.
  397. discard cl.c.instTypeBoundOp(cl.c, meth, result, cl.info,
  398. attachedAsgn, col)
  399. excl mm.flags, tfFromGeneric
  400. proc eraseVoidParams*(t: PType) =
  401. # transform '(): void' into '()' because old parts of the compiler really
  402. # don't deal with '(): void':
  403. if t[0] != nil and t[0].kind == tyVoid:
  404. t[0] = nil
  405. for i in 1..<t.len:
  406. # don't touch any memory unless necessary
  407. if t[i].kind == tyVoid:
  408. var pos = i
  409. for j in i+1..<t.len:
  410. if t[j].kind != tyVoid:
  411. t[pos] = t[j]
  412. t.n[pos] = t.n[j]
  413. inc pos
  414. setLen t.sons, pos
  415. setLen t.n.sons, pos
  416. break
  417. proc skipIntLiteralParams*(t: PType; idgen: IdGenerator) =
  418. for i in 0..<t.len:
  419. let p = t[i]
  420. if p == nil: continue
  421. let skipped = p.skipIntLit(idgen)
  422. if skipped != p:
  423. t[i] = skipped
  424. if i > 0: t.n[i].sym.typ = skipped
  425. # when the typeof operator is used on a static input
  426. # param, the results gets infected with static as well:
  427. if t[0] != nil and t[0].kind == tyStatic:
  428. t[0] = t[0].base
  429. proc propagateFieldFlags(t: PType, n: PNode) =
  430. # This is meant for objects and tuples
  431. # The type must be fully instantiated!
  432. if n.isNil:
  433. return
  434. #internalAssert n.kind != nkRecWhen
  435. case n.kind
  436. of nkSym:
  437. propagateToOwner(t, n.sym.typ)
  438. of nkRecList, nkRecCase, nkOfBranch, nkElse:
  439. for son in n:
  440. propagateFieldFlags(t, son)
  441. else: discard
  442. proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType =
  443. template bailout =
  444. if (t.sym == nil) or (t.sym != nil and sfGeneratedType in t.sym.flags):
  445. # In the first case 't.sym' can be 'nil' if the type is a ref/ptr, see
  446. # issue https://github.com/nim-lang/Nim/issues/20416 for more details.
  447. # Fortunately for us this works for now because partial ref/ptr types are
  448. # not allowed in object construction, eg.
  449. # type
  450. # Container[T] = ...
  451. # O = object
  452. # val: ref Container
  453. #
  454. # In the second case only consider the recursion limit if the symbol is a
  455. # type with generic parameters that have not been explicitly supplied,
  456. # typechecking should terminate when generic parameters are explicitly
  457. # supplied.
  458. if cl.recursionLimit > 100:
  459. # bail out, see bug #2509. But note this caching is in general wrong,
  460. # look at this example where TwoVectors should not share the generic
  461. # instantiations (bug #3112):
  462. # type
  463. # Vector[N: static[int]] = array[N, float64]
  464. # TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb])
  465. result = PType(idTableGet(cl.localCache, t))
  466. if result != nil: return result
  467. inc cl.recursionLimit
  468. result = t
  469. if t == nil: return
  470. if t.kind in {tyStatic, tyGenericParam, tyConcept} + tyTypeClasses:
  471. let lookup = cl.typeMap.lookup(t)
  472. if lookup != nil: return lookup
  473. case t.kind
  474. of tyGenericInvocation:
  475. result = handleGenericInvocation(cl, t)
  476. if result.lastSon.kind == tyUserTypeClass:
  477. result.kind = tyUserTypeClassInst
  478. of tyGenericBody:
  479. localError(
  480. cl.c.config,
  481. cl.info,
  482. "cannot instantiate: '" &
  483. typeToString(t, preferDesc) &
  484. "'; Maybe generic arguments are missing?")
  485. result = errorType(cl.c)
  486. #result = replaceTypeVarsT(cl, lastSon(t))
  487. of tyFromExpr:
  488. if cl.allowMetaTypes: return
  489. # This assert is triggered when a tyFromExpr was created in a cyclic
  490. # way. You should break the cycle at the point of creation by introducing
  491. # a call such as: `n.typ = makeTypeFromExpr(c, n.copyTree)`
  492. # Otherwise, the cycle will be fatal for the prepareNode call below
  493. assert t.n.typ != t
  494. var n = prepareNode(cl, t.n)
  495. if n.kind != nkEmpty:
  496. n = cl.c.semConstExpr(cl.c, n)
  497. if n.typ.kind == tyTypeDesc:
  498. # XXX: sometimes, chained typedescs enter here.
  499. # It may be worth investigating why this is happening,
  500. # because it may cause other bugs elsewhere.
  501. result = n.typ.skipTypes({tyTypeDesc})
  502. # result = n.typ.base
  503. else:
  504. if n.typ.kind != tyStatic and n.kind != nkType:
  505. # XXX: In the future, semConstExpr should
  506. # return tyStatic values to let anyone make
  507. # use of this knowledge. The patching here
  508. # won't be necessary then.
  509. result = newTypeS(tyStatic, cl.c)
  510. result.sons = @[n.typ]
  511. result.n = n
  512. else:
  513. result = n.typ
  514. of tyInt, tyFloat:
  515. result = skipIntLit(t, cl.c.idgen)
  516. of tyTypeDesc:
  517. let lookup = cl.typeMap.lookup(t)
  518. if lookup != nil:
  519. result = lookup
  520. if result.kind != tyTypeDesc:
  521. result = makeTypeDesc(cl.c, result)
  522. elif tfUnresolved in t.flags or cl.skipTypedesc:
  523. result = result.base
  524. elif t[0].kind != tyNone:
  525. result = makeTypeDesc(cl.c, replaceTypeVarsT(cl, t[0]))
  526. of tyUserTypeClass, tyStatic:
  527. result = t
  528. of tyGenericInst, tyUserTypeClassInst:
  529. bailout()
  530. result = instCopyType(cl, t)
  531. idTablePut(cl.localCache, t, result)
  532. for i in 1..<result.len:
  533. result[i] = replaceTypeVarsT(cl, result[i])
  534. propagateToOwner(result, result.lastSon)
  535. else:
  536. if containsGenericType(t):
  537. #if not cl.allowMetaTypes:
  538. bailout()
  539. result = instCopyType(cl, t)
  540. result.size = -1 # needs to be recomputed
  541. #if not cl.allowMetaTypes:
  542. idTablePut(cl.localCache, t, result)
  543. for i in 0..<result.len:
  544. if result[i] != nil:
  545. if result[i].kind == tyGenericBody:
  546. localError(cl.c.config, if t.sym != nil: t.sym.info else: cl.info,
  547. "cannot instantiate '" &
  548. typeToString(result[i], preferDesc) &
  549. "' inside of type definition: '" &
  550. t.owner.name.s & "'; Maybe generic arguments are missing?")
  551. var r = replaceTypeVarsT(cl, result[i])
  552. if result.kind == tyObject:
  553. # carefully coded to not skip the precious tyGenericInst:
  554. let r2 = r.skipTypes({tyAlias, tySink, tyOwned})
  555. if r2.kind in {tyPtr, tyRef}:
  556. r = skipTypes(r2, {tyPtr, tyRef})
  557. result[i] = r
  558. if result.kind != tyArray or i != 0:
  559. propagateToOwner(result, r)
  560. # bug #4677: Do not instantiate effect lists
  561. result.n = replaceTypeVarsN(cl, result.n, ord(result.kind==tyProc))
  562. case result.kind
  563. of tyArray:
  564. let idx = result[0]
  565. internalAssert cl.c.config, idx.kind != tyStatic
  566. of tyObject, tyTuple:
  567. propagateFieldFlags(result, result.n)
  568. if result.kind == tyObject and cl.c.computeRequiresInit(cl.c, result):
  569. result.flags.incl tfRequiresInit
  570. of tyProc:
  571. eraseVoidParams(result)
  572. skipIntLiteralParams(result, cl.c.idgen)
  573. of tyRange:
  574. result[0] = result[0].skipTypes({tyStatic, tyDistinct})
  575. else: discard
  576. else:
  577. # If this type doesn't refer to a generic type we may still want to run it
  578. # trough replaceObjBranches in order to resolve any pending nkRecWhen nodes
  579. result = t
  580. # Slow path, we have some work to do
  581. if t.kind == tyRef and t.len > 0 and t[0].kind == tyObject and t[0].n != nil:
  582. discard replaceObjBranches(cl, t[0].n)
  583. elif result.n != nil and t.kind == tyObject:
  584. # Invalidate the type size as we may alter its structure
  585. result.size = -1
  586. result.n = replaceObjBranches(cl, result.n)
  587. proc initTypeVars*(p: PContext, typeMap: LayeredIdTable, info: TLineInfo;
  588. owner: PSym): TReplTypeVars =
  589. initIdTable(result.symMap)
  590. initIdTable(result.localCache)
  591. result.typeMap = typeMap
  592. result.info = info
  593. result.c = p
  594. result.owner = owner
  595. proc replaceTypesInBody*(p: PContext, pt: TIdTable, n: PNode;
  596. owner: PSym, allowMetaTypes = false): PNode =
  597. var typeMap = initLayeredTypeMap(pt)
  598. var cl = initTypeVars(p, typeMap, n.info, owner)
  599. cl.allowMetaTypes = allowMetaTypes
  600. pushInfoContext(p.config, n.info)
  601. result = replaceTypeVarsN(cl, n)
  602. popInfoContext(p.config)
  603. when false:
  604. # deadcode
  605. proc replaceTypesForLambda*(p: PContext, pt: TIdTable, n: PNode;
  606. original, new: PSym): PNode =
  607. var typeMap = initLayeredTypeMap(pt)
  608. var cl = initTypeVars(p, typeMap, n.info, original)
  609. idTablePut(cl.symMap, original, new)
  610. pushInfoContext(p.config, n.info)
  611. result = replaceTypeVarsN(cl, n)
  612. popInfoContext(p.config)
  613. proc recomputeFieldPositions*(t: PType; obj: PNode; currPosition: var int) =
  614. if t != nil and t.len > 0 and t[0] != nil:
  615. let b = skipTypes(t[0], skipPtrs)
  616. recomputeFieldPositions(b, b.n, currPosition)
  617. case obj.kind
  618. of nkRecList:
  619. for i in 0..<obj.len: recomputeFieldPositions(nil, obj[i], currPosition)
  620. of nkRecCase:
  621. recomputeFieldPositions(nil, obj[0], currPosition)
  622. for i in 1..<obj.len:
  623. recomputeFieldPositions(nil, lastSon(obj[i]), currPosition)
  624. of nkSym:
  625. obj.sym.position = currPosition
  626. inc currPosition
  627. else: discard "cannot happen"
  628. proc generateTypeInstance*(p: PContext, pt: TIdTable, info: TLineInfo,
  629. t: PType): PType =
  630. # Given `t` like Foo[T]
  631. # pt: Table with type mappings: T -> int
  632. # Desired result: Foo[int]
  633. # proc (x: T = 0); T -> int ----> proc (x: int = 0)
  634. var typeMap = initLayeredTypeMap(pt)
  635. var cl = initTypeVars(p, typeMap, info, nil)
  636. pushInfoContext(p.config, info)
  637. result = replaceTypeVarsT(cl, t)
  638. popInfoContext(p.config)
  639. let objType = result.skipTypes(abstractInst)
  640. if objType.kind == tyObject:
  641. var position = 0
  642. recomputeFieldPositions(objType, objType.n, position)
  643. proc prepareMetatypeForSigmatch*(p: PContext, pt: TIdTable, info: TLineInfo,
  644. t: PType): PType =
  645. var typeMap = initLayeredTypeMap(pt)
  646. var cl = initTypeVars(p, typeMap, info, nil)
  647. cl.allowMetaTypes = true
  648. pushInfoContext(p.config, info)
  649. result = replaceTypeVarsT(cl, t)
  650. popInfoContext(p.config)
  651. template generateTypeInstance*(p: PContext, pt: TIdTable, arg: PNode,
  652. t: PType): untyped =
  653. generateTypeInstance(p, pt, arg.info, t)