semtypinst.nim 28 KB

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