seminst.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements the instantiation of generic procs.
  10. # included from sem.nim
  11. proc addObjFieldsToLocalScope(c: PContext; n: PNode) =
  12. template rec(n) = addObjFieldsToLocalScope(c, n)
  13. case n.kind
  14. of nkRecList:
  15. for i in 0..<n.len:
  16. rec n[i]
  17. of nkRecCase:
  18. if n.len > 0: rec n[0]
  19. for i in 1..<n.len:
  20. if n[i].kind in {nkOfBranch, nkElse}: rec lastSon(n[i])
  21. of nkSym:
  22. let f = n.sym
  23. if f.kind == skField and fieldVisible(c, f):
  24. c.currentScope.symbols.strTableIncl(f, onConflictKeepOld=true)
  25. incl(f.flags, sfUsed)
  26. # it is not an error to shadow fields via parameters
  27. else: discard
  28. proc pushProcCon*(c: PContext; owner: PSym) =
  29. var x: PProcCon
  30. new(x)
  31. x.owner = owner
  32. x.next = c.p
  33. c.p = x
  34. const
  35. errCannotInstantiateX = "cannot instantiate: '$1'"
  36. iterator instantiateGenericParamList(c: PContext, n: PNode, pt: TIdTable): PSym =
  37. internalAssert c.config, n.kind == nkGenericParams
  38. for i, a in n.pairs:
  39. internalAssert c.config, a.kind == nkSym
  40. var q = a.sym
  41. if q.typ.kind in {tyTypeDesc, tyGenericParam, tyStatic, tyConcept}+tyTypeClasses:
  42. let symKind = if q.typ.kind == tyStatic: skConst else: skType
  43. var s = newSym(symKind, q.name, nextSymId(c.idgen), getCurrOwner(c), q.info)
  44. s.flags.incl {sfUsed, sfFromGeneric}
  45. var t = PType(idTableGet(pt, q.typ))
  46. if t == nil:
  47. if tfRetType in q.typ.flags:
  48. # keep the generic type and allow the return type to be bound
  49. # later by semAsgn in return type inference scenario
  50. t = q.typ
  51. else:
  52. if q.typ.kind != tyCompositeTypeClass:
  53. localError(c.config, a.info, errCannotInstantiateX % s.name.s)
  54. t = errorType(c)
  55. elif t.kind in {tyGenericParam, tyConcept}:
  56. localError(c.config, a.info, errCannotInstantiateX % q.name.s)
  57. t = errorType(c)
  58. elif t.kind == tyGenericInvocation:
  59. #t = instGenericContainer(c, a, t)
  60. t = generateTypeInstance(c, pt, a, t)
  61. #t = ReplaceTypeVarsT(cl, t)
  62. s.typ = t
  63. if t.kind == tyStatic: s.ast = t.n
  64. yield s
  65. proc sameInstantiation(a, b: TInstantiation): bool =
  66. if a.concreteTypes.len == b.concreteTypes.len:
  67. for i in 0..a.concreteTypes.high:
  68. if not compareTypes(a.concreteTypes[i], b.concreteTypes[i],
  69. flags = {ExactTypeDescValues,
  70. ExactGcSafety,
  71. PickyCAliases}): return
  72. result = true
  73. proc genericCacheGet(g: ModuleGraph; genericSym: PSym, entry: TInstantiation;
  74. id: CompilesId): PSym =
  75. for inst in procInstCacheItems(g, genericSym):
  76. if (inst.compilesId == 0 or inst.compilesId == id) and sameInstantiation(entry, inst[]):
  77. return inst.sym
  78. when false:
  79. proc `$`(x: PSym): string =
  80. result = x.name.s & " " & " id " & $x.id
  81. proc freshGenSyms(c: PContext; n: PNode, owner, orig: PSym, symMap: var TIdTable) =
  82. # we need to create a fresh set of gensym'ed symbols:
  83. #if n.kind == nkSym and sfGenSym in n.sym.flags:
  84. # if n.sym.owner != orig:
  85. # echo "symbol ", n.sym.name.s, " orig ", orig, " owner ", n.sym.owner
  86. if n.kind == nkSym and sfGenSym in n.sym.flags: # and
  87. # (n.sym.owner == orig or n.sym.owner.kind in {skPackage}):
  88. let s = n.sym
  89. var x = PSym(idTableGet(symMap, s))
  90. if x != nil:
  91. n.sym = x
  92. elif s.owner == nil or s.owner.kind == skPackage:
  93. #echo "copied this ", s.name.s
  94. x = copySym(s, nextSymId c.idgen)
  95. x.owner = owner
  96. idTablePut(symMap, s, x)
  97. n.sym = x
  98. else:
  99. for i in 0..<n.safeLen: freshGenSyms(c, n[i], owner, orig, symMap)
  100. proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind)
  101. proc instantiateBody(c: PContext, n, params: PNode, result, orig: PSym) =
  102. if n[bodyPos].kind != nkEmpty:
  103. let procParams = result.typ.n
  104. for i in 1..<procParams.len:
  105. addDecl(c, procParams[i].sym)
  106. maybeAddResult(c, result, result.ast)
  107. inc c.inGenericInst
  108. # add it here, so that recursive generic procs are possible:
  109. var b = n[bodyPos]
  110. var symMap: TIdTable
  111. initIdTable symMap
  112. if params != nil:
  113. for i in 1..<params.len:
  114. let param = params[i].sym
  115. if sfGenSym in param.flags:
  116. idTablePut(symMap, params[i].sym, result.typ.n[param.position+1].sym)
  117. freshGenSyms(c, b, result, orig, symMap)
  118. if sfBorrow notin orig.flags:
  119. # We do not want to generate a body for generic borrowed procs.
  120. # As body is a sym to the borrowed proc.
  121. b = semProcBody(c, b)
  122. result.ast[bodyPos] = hloBody(c, b)
  123. excl(result.flags, sfForward)
  124. trackProc(c, result, result.ast[bodyPos])
  125. dec c.inGenericInst
  126. proc fixupInstantiatedSymbols(c: PContext, s: PSym) =
  127. for i in 0..<c.generics.len:
  128. if c.generics[i].genericSym.id == s.id:
  129. var oldPrc = c.generics[i].inst.sym
  130. pushProcCon(c, oldPrc)
  131. pushOwner(c, oldPrc)
  132. pushInfoContext(c.config, oldPrc.info)
  133. openScope(c)
  134. var n = oldPrc.ast
  135. n[bodyPos] = copyTree(getBody(c.graph, s))
  136. instantiateBody(c, n, oldPrc.typ.n, oldPrc, s)
  137. closeScope(c)
  138. popInfoContext(c.config)
  139. popOwner(c)
  140. popProcCon(c)
  141. proc sideEffectsCheck(c: PContext, s: PSym) =
  142. when false:
  143. if {sfNoSideEffect, sfSideEffect} * s.flags ==
  144. {sfNoSideEffect, sfSideEffect}:
  145. localError(s.info, errXhasSideEffects, s.name.s)
  146. proc instGenericContainer(c: PContext, info: TLineInfo, header: PType,
  147. allowMetaTypes = false): PType =
  148. internalAssert c.config, header.kind == tyGenericInvocation
  149. var
  150. cl: TReplTypeVars
  151. initIdTable(cl.symMap)
  152. initIdTable(cl.localCache)
  153. cl.typeMap = LayeredIdTable()
  154. initIdTable(cl.typeMap.topLayer)
  155. cl.info = info
  156. cl.c = c
  157. cl.allowMetaTypes = allowMetaTypes
  158. # We must add all generic params in scope, because the generic body
  159. # may include tyFromExpr nodes depending on these generic params.
  160. # XXX: This looks quite similar to the code in matchUserTypeClass,
  161. # perhaps the code can be extracted in a shared function.
  162. openScope(c)
  163. let genericTyp = header.base
  164. for i in 0..<genericTyp.len - 1:
  165. let genParam = genericTyp[i]
  166. var param: PSym
  167. template paramSym(kind): untyped =
  168. newSym(kind, genParam.sym.name, nextSymId c.idgen, genericTyp.sym, genParam.sym.info)
  169. if genParam.kind == tyStatic:
  170. param = paramSym skConst
  171. param.ast = header[i+1].n
  172. param.typ = header[i+1]
  173. else:
  174. param = paramSym skType
  175. param.typ = makeTypeDesc(c, header[i+1])
  176. # this scope was not created by the user,
  177. # unused params shouldn't be reported.
  178. param.flags.incl sfUsed
  179. addDecl(c, param)
  180. result = replaceTypeVarsT(cl, header)
  181. closeScope(c)
  182. proc referencesAnotherParam(n: PNode, p: PSym): bool =
  183. if n.kind == nkSym:
  184. return n.sym.kind == skParam and n.sym.owner == p
  185. else:
  186. for i in 0..<n.safeLen:
  187. if referencesAnotherParam(n[i], p): return true
  188. return false
  189. proc instantiateProcType(c: PContext, pt: TIdTable,
  190. prc: PSym, info: TLineInfo) =
  191. # XXX: Instantiates a generic proc signature, while at the same
  192. # time adding the instantiated proc params into the current scope.
  193. # This is necessary, because the instantiation process may refer to
  194. # these params in situations like this:
  195. # proc foo[Container](a: Container, b: a.type.Item): typeof(b.x)
  196. #
  197. # Alas, doing this here is probably not enough, because another
  198. # proc signature could appear in the params:
  199. # proc foo[T](a: proc (x: T, b: typeof(x.y))
  200. #
  201. # The solution would be to move this logic into semtypinst, but
  202. # at this point semtypinst have to become part of sem, because it
  203. # will need to use openScope, addDecl, etc.
  204. #addDecl(c, prc)
  205. pushInfoContext(c.config, info)
  206. var typeMap = initLayeredTypeMap(pt)
  207. var cl = initTypeVars(c, typeMap, info, nil)
  208. var result = instCopyType(cl, prc.typ)
  209. let originalParams = result.n
  210. result.n = originalParams.shallowCopy
  211. for i in 1..<result.len:
  212. # twrong_field_caching requires these 'resetIdTable' calls:
  213. if i > 1:
  214. resetIdTable(cl.symMap)
  215. resetIdTable(cl.localCache)
  216. # take a note of the original type. If't a free type or static parameter
  217. # we'll need to keep it unbound for the `fitNode` operation below...
  218. var typeToFit = result[i]
  219. let needsStaticSkipping = result[i].kind == tyFromExpr
  220. result[i] = replaceTypeVarsT(cl, result[i])
  221. if needsStaticSkipping:
  222. result[i] = result[i].skipTypes({tyStatic})
  223. # ...otherwise, we use the instantiated type in `fitNode`
  224. if (typeToFit.kind != tyTypeDesc or typeToFit.base.kind != tyNone) and
  225. (typeToFit.kind != tyStatic):
  226. typeToFit = result[i]
  227. internalAssert c.config, originalParams[i].kind == nkSym
  228. let oldParam = originalParams[i].sym
  229. let param = copySym(oldParam, nextSymId c.idgen)
  230. param.owner = prc
  231. param.typ = result[i]
  232. # The default value is instantiated and fitted against the final
  233. # concrete param type. We avoid calling `replaceTypeVarsN` on the
  234. # call head symbol, because this leads to infinite recursion.
  235. if oldParam.ast != nil:
  236. var def = oldParam.ast.copyTree
  237. if def.kind == nkCall:
  238. for i in 1..<def.len:
  239. def[i] = replaceTypeVarsN(cl, def[i])
  240. def = semExprWithType(c, def)
  241. if def.referencesAnotherParam(getCurrOwner(c)):
  242. def.flags.incl nfDefaultRefsParam
  243. var converted = indexTypesMatch(c, typeToFit, def.typ, def)
  244. if converted == nil:
  245. # The default value doesn't match the final instantiated type.
  246. # As an example of this, see:
  247. # https://github.com/nim-lang/Nim/issues/1201
  248. # We are replacing the default value with an error node in case
  249. # the user calls an explicit instantiation of the proc (this is
  250. # the only way the default value might be inserted).
  251. param.ast = errorNode(c, def)
  252. else:
  253. param.ast = fitNodePostMatch(c, typeToFit, converted)
  254. param.typ = result[i]
  255. result.n[i] = newSymNode(param)
  256. propagateToOwner(result, result[i])
  257. addDecl(c, param)
  258. resetIdTable(cl.symMap)
  259. resetIdTable(cl.localCache)
  260. cl.isReturnType = true
  261. result[0] = replaceTypeVarsT(cl, result[0])
  262. cl.isReturnType = false
  263. result.n[0] = originalParams[0].copyTree
  264. if result[0] != nil:
  265. propagateToOwner(result, result[0])
  266. eraseVoidParams(result)
  267. skipIntLiteralParams(result, c.idgen)
  268. prc.typ = result
  269. popInfoContext(c.config)
  270. proc fillMixinScope(c: PContext) =
  271. var p = c.p
  272. while p != nil:
  273. for bnd in p.localBindStmts:
  274. for n in bnd:
  275. addSym(c.currentScope, n.sym)
  276. p = p.next
  277. proc generateInstance(c: PContext, fn: PSym, pt: TIdTable,
  278. info: TLineInfo): PSym {.nosinks.} =
  279. ## Generates a new instance of a generic procedure.
  280. ## The `pt` parameter is a type-unsafe mapping table used to link generic
  281. ## parameters to their concrete types within the generic instance.
  282. # no need to instantiate generic templates/macros:
  283. internalAssert c.config, fn.kind notin {skMacro, skTemplate}
  284. # generates an instantiated proc
  285. if c.instCounter > 50:
  286. globalError(c.config, info, "generic instantiation too nested")
  287. inc(c.instCounter)
  288. # careful! we copy the whole AST including the possibly nil body!
  289. var n = copyTree(fn.ast)
  290. # NOTE: for access of private fields within generics from a different module
  291. # we set the friend module:
  292. c.friendModules.add(getModule(fn))
  293. let oldMatchedConcept = c.matchedConcept
  294. c.matchedConcept = nil
  295. let oldScope = c.currentScope
  296. while not isTopLevel(c): c.currentScope = c.currentScope.parent
  297. result = copySym(fn, nextSymId c.idgen)
  298. incl(result.flags, sfFromGeneric)
  299. result.owner = fn
  300. result.ast = n
  301. pushOwner(c, result)
  302. # mixin scope:
  303. openScope(c)
  304. fillMixinScope(c)
  305. openScope(c)
  306. let gp = n[genericParamsPos]
  307. internalAssert c.config, gp.kind == nkGenericParams
  308. n[namePos] = newSymNode(result)
  309. pushInfoContext(c.config, info, fn.detailedInfo)
  310. var entry = TInstantiation.new
  311. entry.sym = result
  312. # we need to compare both the generic types and the concrete types:
  313. # generic[void](), generic[int]()
  314. # see ttypeor.nim test.
  315. var i = 0
  316. newSeq(entry.concreteTypes, fn.typ.len+gp.len-1)
  317. for s in instantiateGenericParamList(c, gp, pt):
  318. addDecl(c, s)
  319. entry.concreteTypes[i] = s.typ
  320. inc i
  321. pushProcCon(c, result)
  322. instantiateProcType(c, pt, result, info)
  323. for j in 1..<result.typ.len:
  324. entry.concreteTypes[i] = result.typ[j]
  325. inc i
  326. if tfTriggersCompileTime in result.typ.flags:
  327. incl(result.flags, sfCompileTime)
  328. n[genericParamsPos] = c.graph.emptyNode
  329. var oldPrc = genericCacheGet(c.graph, fn, entry[], c.compilesContextId)
  330. if oldPrc == nil:
  331. # we MUST not add potentially wrong instantiations to the caching mechanism.
  332. # This means recursive instantiations behave differently when in
  333. # a ``compiles`` context but this is the lesser evil. See
  334. # bug #1055 (tevilcompiles).
  335. #if c.compilesContextId == 0:
  336. entry.compilesId = c.compilesContextId
  337. addToGenericProcCache(c, fn, entry)
  338. c.generics.add(makeInstPair(fn, entry))
  339. if n[pragmasPos].kind != nkEmpty:
  340. pragma(c, result, n[pragmasPos], allRoutinePragmas)
  341. if isNil(n[bodyPos]):
  342. n[bodyPos] = copyTree(getBody(c.graph, fn))
  343. if c.inGenericContext == 0:
  344. instantiateBody(c, n, fn.typ.n, result, fn)
  345. sideEffectsCheck(c, result)
  346. if result.magic notin {mSlice, mTypeOf}:
  347. # 'toOpenArray' is special and it is allowed to return 'openArray':
  348. paramsTypeCheck(c, result.typ)
  349. else:
  350. result = oldPrc
  351. popProcCon(c)
  352. popInfoContext(c.config)
  353. closeScope(c) # close scope for parameters
  354. closeScope(c) # close scope for 'mixin' declarations
  355. popOwner(c)
  356. c.currentScope = oldScope
  357. discard c.friendModules.pop()
  358. dec(c.instCounter)
  359. c.matchedConcept = oldMatchedConcept
  360. if result.kind == skMethod: finishMethod(c, result)
  361. # inform IC of the generic
  362. #addGeneric(c.ic, result, entry.concreteTypes)