seminst.nim 16 KB

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