seminst.nim 15 KB

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