seminst.nim 16 KB

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