seminst.nim 15 KB

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