seminst.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 a in n.items:
  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. let resultType = # todo probably refactor it into a function
  122. if result.kind == skMacro:
  123. sysTypeFromName(c.graph, n.info, "NimNode")
  124. elif not isInlineIterator(result.typ):
  125. result.typ[0]
  126. else:
  127. nil
  128. b = semProcBody(c, b, resultType)
  129. result.ast[bodyPos] = hloBody(c, b)
  130. excl(result.flags, sfForward)
  131. trackProc(c, result, result.ast[bodyPos])
  132. dec c.inGenericInst
  133. proc fixupInstantiatedSymbols(c: PContext, s: PSym) =
  134. for i in 0..<c.generics.len:
  135. if c.generics[i].genericSym.id == s.id:
  136. var oldPrc = c.generics[i].inst.sym
  137. pushProcCon(c, oldPrc)
  138. pushOwner(c, oldPrc)
  139. pushInfoContext(c.config, oldPrc.info)
  140. openScope(c)
  141. var n = oldPrc.ast
  142. n[bodyPos] = copyTree(getBody(c.graph, s))
  143. instantiateBody(c, n, oldPrc.typ.n, oldPrc, s)
  144. closeScope(c)
  145. popInfoContext(c.config)
  146. popOwner(c)
  147. popProcCon(c)
  148. proc sideEffectsCheck(c: PContext, s: PSym) =
  149. when false:
  150. if {sfNoSideEffect, sfSideEffect} * s.flags ==
  151. {sfNoSideEffect, sfSideEffect}:
  152. localError(s.info, errXhasSideEffects, s.name.s)
  153. proc instGenericContainer(c: PContext, info: TLineInfo, header: PType,
  154. allowMetaTypes = false): PType =
  155. internalAssert c.config, header.kind == tyGenericInvocation
  156. var
  157. cl: TReplTypeVars
  158. initIdTable(cl.symMap)
  159. initIdTable(cl.localCache)
  160. cl.typeMap = LayeredIdTable()
  161. initIdTable(cl.typeMap.topLayer)
  162. cl.info = info
  163. cl.c = c
  164. cl.allowMetaTypes = allowMetaTypes
  165. # We must add all generic params in scope, because the generic body
  166. # may include tyFromExpr nodes depending on these generic params.
  167. # XXX: This looks quite similar to the code in matchUserTypeClass,
  168. # perhaps the code can be extracted in a shared function.
  169. openScope(c)
  170. let genericTyp = header.base
  171. for i in 0..<genericTyp.len - 1:
  172. let genParam = genericTyp[i]
  173. var param: PSym
  174. template paramSym(kind): untyped =
  175. newSym(kind, genParam.sym.name, nextSymId c.idgen, genericTyp.sym, genParam.sym.info)
  176. if genParam.kind == tyStatic:
  177. param = paramSym skConst
  178. param.ast = header[i+1].n
  179. param.typ = header[i+1]
  180. else:
  181. param = paramSym skType
  182. param.typ = makeTypeDesc(c, header[i+1])
  183. # this scope was not created by the user,
  184. # unused params shouldn't be reported.
  185. param.flags.incl sfUsed
  186. addDecl(c, param)
  187. result = replaceTypeVarsT(cl, header)
  188. closeScope(c)
  189. proc referencesAnotherParam(n: PNode, p: PSym): bool =
  190. if n.kind == nkSym:
  191. return n.sym.kind == skParam and n.sym.owner == p
  192. else:
  193. for i in 0..<n.safeLen:
  194. if referencesAnotherParam(n[i], p): return true
  195. return false
  196. proc instantiateProcType(c: PContext, pt: TIdTable,
  197. prc: PSym, info: TLineInfo) =
  198. # XXX: Instantiates a generic proc signature, while at the same
  199. # time adding the instantiated proc params into the current scope.
  200. # This is necessary, because the instantiation process may refer to
  201. # these params in situations like this:
  202. # proc foo[Container](a: Container, b: a.type.Item): typeof(b.x)
  203. #
  204. # Alas, doing this here is probably not enough, because another
  205. # proc signature could appear in the params:
  206. # proc foo[T](a: proc (x: T, b: typeof(x.y))
  207. #
  208. # The solution would be to move this logic into semtypinst, but
  209. # at this point semtypinst have to become part of sem, because it
  210. # will need to use openScope, addDecl, etc.
  211. #addDecl(c, prc)
  212. pushInfoContext(c.config, info)
  213. var typeMap = initLayeredTypeMap(pt)
  214. var cl = initTypeVars(c, typeMap, info, nil)
  215. var result = instCopyType(cl, prc.typ)
  216. let originalParams = result.n
  217. result.n = originalParams.shallowCopy
  218. for i in 1..<result.len:
  219. # twrong_field_caching requires these 'resetIdTable' calls:
  220. if i > 1:
  221. resetIdTable(cl.symMap)
  222. resetIdTable(cl.localCache)
  223. # take a note of the original type. If't a free type or static parameter
  224. # we'll need to keep it unbound for the `fitNode` operation below...
  225. var typeToFit = result[i]
  226. let needsStaticSkipping = result[i].kind == tyFromExpr
  227. result[i] = replaceTypeVarsT(cl, result[i])
  228. if needsStaticSkipping:
  229. result[i] = result[i].skipTypes({tyStatic})
  230. # ...otherwise, we use the instantiated type in `fitNode`
  231. if (typeToFit.kind != tyTypeDesc or typeToFit.base.kind != tyNone) and
  232. (typeToFit.kind != tyStatic):
  233. typeToFit = result[i]
  234. internalAssert c.config, originalParams[i].kind == nkSym
  235. let oldParam = originalParams[i].sym
  236. let param = copySym(oldParam, nextSymId c.idgen)
  237. param.owner = prc
  238. param.typ = result[i]
  239. # The default value is instantiated and fitted against the final
  240. # concrete param type. We avoid calling `replaceTypeVarsN` on the
  241. # call head symbol, because this leads to infinite recursion.
  242. if oldParam.ast != nil:
  243. var def = oldParam.ast.copyTree
  244. if def.kind == nkCall:
  245. for i in 1..<def.len:
  246. def[i] = replaceTypeVarsN(cl, def[i])
  247. def = semExprWithType(c, def)
  248. if def.referencesAnotherParam(getCurrOwner(c)):
  249. def.flags.incl nfDefaultRefsParam
  250. var converted = indexTypesMatch(c, typeToFit, def.typ, def)
  251. if converted == nil:
  252. # The default value doesn't match the final instantiated type.
  253. # As an example of this, see:
  254. # https://github.com/nim-lang/Nim/issues/1201
  255. # We are replacing the default value with an error node in case
  256. # the user calls an explicit instantiation of the proc (this is
  257. # the only way the default value might be inserted).
  258. param.ast = errorNode(c, def)
  259. else:
  260. param.ast = fitNodePostMatch(c, typeToFit, converted)
  261. param.typ = result[i]
  262. result.n[i] = newSymNode(param)
  263. propagateToOwner(result, result[i])
  264. addDecl(c, param)
  265. resetIdTable(cl.symMap)
  266. resetIdTable(cl.localCache)
  267. cl.isReturnType = true
  268. result[0] = replaceTypeVarsT(cl, result[0])
  269. cl.isReturnType = false
  270. result.n[0] = originalParams[0].copyTree
  271. if result[0] != nil:
  272. propagateToOwner(result, result[0])
  273. eraseVoidParams(result)
  274. skipIntLiteralParams(result, c.idgen)
  275. prc.typ = result
  276. popInfoContext(c.config)
  277. proc fillMixinScope(c: PContext) =
  278. var p = c.p
  279. while p != nil:
  280. for bnd in p.localBindStmts:
  281. for n in bnd:
  282. addSym(c.currentScope, n.sym)
  283. p = p.next
  284. proc generateInstance(c: PContext, fn: PSym, pt: TIdTable,
  285. info: TLineInfo): PSym =
  286. ## Generates a new instance of a generic procedure.
  287. ## The `pt` parameter is a type-unsafe mapping table used to link generic
  288. ## parameters to their concrete types within the generic instance.
  289. # no need to instantiate generic templates/macros:
  290. internalAssert c.config, fn.kind notin {skMacro, skTemplate}
  291. # generates an instantiated proc
  292. if c.instCounter > 50:
  293. globalError(c.config, info, "generic instantiation too nested")
  294. inc(c.instCounter)
  295. # careful! we copy the whole AST including the possibly nil body!
  296. var n = copyTree(fn.ast)
  297. # NOTE: for access of private fields within generics from a different module
  298. # we set the friend module:
  299. c.friendModules.add(getModule(fn))
  300. let oldMatchedConcept = c.matchedConcept
  301. c.matchedConcept = nil
  302. let oldScope = c.currentScope
  303. while not isTopLevel(c): c.currentScope = c.currentScope.parent
  304. result = copySym(fn, nextSymId c.idgen)
  305. incl(result.flags, sfFromGeneric)
  306. result.owner = fn
  307. result.ast = n
  308. pushOwner(c, result)
  309. # mixin scope:
  310. openScope(c)
  311. fillMixinScope(c)
  312. openScope(c)
  313. let gp = n[genericParamsPos]
  314. internalAssert c.config, gp.kind == nkGenericParams
  315. n[namePos] = newSymNode(result)
  316. pushInfoContext(c.config, info, fn.detailedInfo)
  317. var entry = TInstantiation.new
  318. entry.sym = result
  319. # we need to compare both the generic types and the concrete types:
  320. # generic[void](), generic[int]()
  321. # see ttypeor.nim test.
  322. var i = 0
  323. newSeq(entry.concreteTypes, fn.typ.len+gp.len-1)
  324. for s in instantiateGenericParamList(c, gp, pt):
  325. addDecl(c, s)
  326. entry.concreteTypes[i] = s.typ
  327. inc i
  328. pushProcCon(c, result)
  329. instantiateProcType(c, pt, result, info)
  330. for j in 1..<result.typ.len:
  331. entry.concreteTypes[i] = result.typ[j]
  332. inc i
  333. if tfTriggersCompileTime in result.typ.flags:
  334. incl(result.flags, sfCompileTime)
  335. n[genericParamsPos] = c.graph.emptyNode
  336. var oldPrc = genericCacheGet(c.graph, fn, entry[], c.compilesContextId)
  337. if oldPrc == nil:
  338. # we MUST not add potentially wrong instantiations to the caching mechanism.
  339. # This means recursive instantiations behave differently when in
  340. # a ``compiles`` context but this is the lesser evil. See
  341. # bug #1055 (tevilcompiles).
  342. #if c.compilesContextId == 0:
  343. entry.compilesId = c.compilesContextId
  344. addToGenericProcCache(c, fn, entry)
  345. c.generics.add(makeInstPair(fn, entry))
  346. if n[pragmasPos].kind != nkEmpty:
  347. pragma(c, result, n[pragmasPos], allRoutinePragmas)
  348. if isNil(n[bodyPos]):
  349. n[bodyPos] = copyTree(getBody(c.graph, fn))
  350. if c.inGenericContext == 0:
  351. instantiateBody(c, n, fn.typ.n, result, fn)
  352. sideEffectsCheck(c, result)
  353. if result.magic notin {mSlice, mTypeOf}:
  354. # 'toOpenArray' is special and it is allowed to return 'openArray':
  355. paramsTypeCheck(c, result.typ)
  356. else:
  357. result = oldPrc
  358. popProcCon(c)
  359. popInfoContext(c.config)
  360. closeScope(c) # close scope for parameters
  361. closeScope(c) # close scope for 'mixin' declarations
  362. popOwner(c)
  363. c.currentScope = oldScope
  364. discard c.friendModules.pop()
  365. dec(c.instCounter)
  366. c.matchedConcept = oldMatchedConcept
  367. if result.kind == skMethod: finishMethod(c, result)
  368. # inform IC of the generic
  369. #addGeneric(c.ic, result, entry.concreteTypes)