semtypinst.nim 28 KB

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