seminst.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. let needsTypeDescSkipping = resulti.kind == tyTypeDesc and tfUnresolved in resulti.flags
  230. result[i] = replaceTypeVarsT(cl, resulti)
  231. if needsStaticSkipping:
  232. result[i] = result[i].skipTypes({tyStatic})
  233. if needsTypeDescSkipping:
  234. result[i] = result[i].skipTypes({tyTypeDesc})
  235. typeToFit = result[i]
  236. # ...otherwise, we use the instantiated type in `fitNode`
  237. if (typeToFit.kind != tyTypeDesc or typeToFit.base.kind != tyNone) and
  238. (typeToFit.kind != tyStatic):
  239. typeToFit = result[i]
  240. internalAssert c.config, originalParams[i].kind == nkSym
  241. let oldParam = originalParams[i].sym
  242. let param = copySym(oldParam, c.idgen)
  243. param.owner = prc
  244. param.typ = result[i]
  245. # The default value is instantiated and fitted against the final
  246. # concrete param type. We avoid calling `replaceTypeVarsN` on the
  247. # call head symbol, because this leads to infinite recursion.
  248. if oldParam.ast != nil:
  249. var def = oldParam.ast.copyTree
  250. if def.kind in nkCallKinds:
  251. for i in 1..<def.len:
  252. def[i] = replaceTypeVarsN(cl, def[i], 1)
  253. # allow symchoice since node will be fit later
  254. # although expectedType should cover it
  255. def = semExprWithType(c, def, {efAllowSymChoice}, typeToFit)
  256. if def.referencesAnotherParam(getCurrOwner(c)):
  257. def.flags.incl nfDefaultRefsParam
  258. var converted = indexTypesMatch(c, typeToFit, def.typ, def)
  259. if converted == nil:
  260. # The default value doesn't match the final instantiated type.
  261. # As an example of this, see:
  262. # https://github.com/nim-lang/Nim/issues/1201
  263. # We are replacing the default value with an error node in case
  264. # the user calls an explicit instantiation of the proc (this is
  265. # the only way the default value might be inserted).
  266. param.ast = errorNode(c, def)
  267. # we know the node is empty, we need the actual type for error message
  268. param.ast.typ = def.typ
  269. else:
  270. param.ast = fitNodePostMatch(c, typeToFit, converted)
  271. param.typ = result[i]
  272. result.n[i] = newSymNode(param)
  273. propagateToOwner(result, result[i])
  274. addDecl(c, param)
  275. resetIdTable(cl.symMap)
  276. resetIdTable(cl.localCache)
  277. cl.isReturnType = true
  278. result.setReturnType replaceTypeVarsT(cl, result.returnType)
  279. cl.isReturnType = false
  280. result.n[0] = originalParams[0].copyTree
  281. if result[0] != nil:
  282. propagateToOwner(result, result[0])
  283. eraseVoidParams(result)
  284. skipIntLiteralParams(result, c.idgen)
  285. prc.typ = result
  286. popInfoContext(c.config)
  287. proc fillMixinScope(c: PContext) =
  288. var p = c.p
  289. while p != nil:
  290. for bnd in p.localBindStmts:
  291. for n in bnd:
  292. addSym(c.currentScope, n.sym)
  293. p = p.next
  294. proc getLocalPassC(c: PContext, s: PSym): string =
  295. when defined(nimsuggest): return ""
  296. if s.ast == nil or s.ast.len == 0: return ""
  297. result = ""
  298. template extractPassc(p: PNode) =
  299. if p.kind == nkPragma and p[0][0].ident == c.cache.getIdent"localpassc":
  300. return p[0][1].strVal
  301. extractPassc(s.ast[0]) #it is set via appendToModule in pragmas (fast access)
  302. for n in s.ast:
  303. for p in n:
  304. extractPassc(p)
  305. proc generateInstance(c: PContext, fn: PSym, pt: TypeMapping,
  306. info: TLineInfo): PSym =
  307. ## Generates a new instance of a generic procedure.
  308. ## The `pt` parameter is a type-unsafe mapping table used to link generic
  309. ## parameters to their concrete types within the generic instance.
  310. # no need to instantiate generic templates/macros:
  311. internalAssert c.config, fn.kind notin {skMacro, skTemplate}
  312. # generates an instantiated proc
  313. if c.instCounter > 50:
  314. globalError(c.config, info, "generic instantiation too nested")
  315. inc c.instCounter
  316. defer: dec c.instCounter
  317. # careful! we copy the whole AST including the possibly nil body!
  318. var n = copyTree(fn.ast)
  319. # NOTE: for access of private fields within generics from a different module
  320. # we set the friend module:
  321. let producer = getModule(fn)
  322. c.friendModules.add(producer)
  323. let oldMatchedConcept = c.matchedConcept
  324. c.matchedConcept = nil
  325. let oldScope = c.currentScope
  326. while not isTopLevel(c): c.currentScope = c.currentScope.parent
  327. result = copySym(fn, c.idgen)
  328. incl(result.flags, sfFromGeneric)
  329. result.instantiatedFrom = fn
  330. if sfGlobal in result.flags and c.config.symbolFiles != disabledSf:
  331. let passc = getLocalPassC(c, producer)
  332. if passc != "": #pass the local compiler options to the consumer module too
  333. extccomp.addLocalCompileOption(c.config, passc, toFullPathConsiderDirty(c.config, c.module.info.fileIndex))
  334. result.owner = c.module
  335. else:
  336. result.owner = fn
  337. result.ast = n
  338. pushOwner(c, result)
  339. # mixin scope:
  340. openScope(c)
  341. fillMixinScope(c)
  342. openScope(c)
  343. let gp = n[genericParamsPos]
  344. if gp.kind != nkGenericParams:
  345. # bug #22137
  346. globalError(c.config, info, "generic instantiation too nested")
  347. n[namePos] = newSymNode(result)
  348. pushInfoContext(c.config, info, fn.detailedInfo)
  349. var entry = TInstantiation.new
  350. entry.sym = result
  351. # we need to compare both the generic types and the concrete types:
  352. # generic[void](), generic[int]()
  353. # see ttypeor.nim test.
  354. var i = 0
  355. newSeq(entry.concreteTypes, fn.typ.paramsLen+gp.len)
  356. # let param instantiation know we are in a concept for unresolved statics:
  357. c.matchedConcept = oldMatchedConcept
  358. for s in instantiateGenericParamList(c, gp, pt):
  359. addDecl(c, s)
  360. entry.concreteTypes[i] = s.typ
  361. inc i
  362. c.matchedConcept = nil
  363. pushProcCon(c, result)
  364. instantiateProcType(c, pt, result, info)
  365. for _, param in paramTypes(result.typ):
  366. entry.concreteTypes[i] = param
  367. inc i
  368. #echo "INSTAN ", fn.name.s, " ", typeToString(result.typ), " ", entry.concreteTypes.len
  369. if tfTriggersCompileTime in result.typ.flags:
  370. incl(result.flags, sfCompileTime)
  371. n[genericParamsPos] = c.graph.emptyNode
  372. var oldPrc = genericCacheGet(c.graph, fn, entry[], c.compilesContextId)
  373. if oldPrc == nil:
  374. # we MUST not add potentially wrong instantiations to the caching mechanism.
  375. # This means recursive instantiations behave differently when in
  376. # a ``compiles`` context but this is the lesser evil. See
  377. # bug #1055 (tevilcompiles).
  378. #if c.compilesContextId == 0:
  379. entry.compilesId = c.compilesContextId
  380. addToGenericProcCache(c, fn, entry)
  381. c.generics.add(makeInstPair(fn, entry))
  382. # bug #12985 bug #22913
  383. # TODO: use the context of the declaration of generic functions instead
  384. # TODO: consider fixing options as well
  385. let otherPragmas = c.optionStack[^1].otherPragmas
  386. c.optionStack[^1].otherPragmas = nil
  387. if n[pragmasPos].kind != nkEmpty:
  388. pragma(c, result, n[pragmasPos], allRoutinePragmas)
  389. if isNil(n[bodyPos]):
  390. n[bodyPos] = copyTree(getBody(c.graph, fn))
  391. instantiateBody(c, n, fn.typ.n, result, fn)
  392. c.optionStack[^1].otherPragmas = otherPragmas
  393. sideEffectsCheck(c, result)
  394. if result.magic notin {mSlice, mTypeOf}:
  395. # 'toOpenArray' is special and it is allowed to return 'openArray':
  396. paramsTypeCheck(c, result.typ)
  397. #echo "INSTAN ", fn.name.s, " ", typeToString(result.typ), " <-- NEW PROC!", " ", entry.concreteTypes.len
  398. else:
  399. #echo "INSTAN ", fn.name.s, " ", typeToString(result.typ), " <-- CACHED! ", typeToString(oldPrc.typ), " ", entry.concreteTypes.len
  400. result = oldPrc
  401. popProcCon(c)
  402. popInfoContext(c.config)
  403. closeScope(c) # close scope for parameters
  404. closeScope(c) # close scope for 'mixin' declarations
  405. popOwner(c)
  406. c.currentScope = oldScope
  407. discard c.friendModules.pop()
  408. c.matchedConcept = oldMatchedConcept
  409. if result.kind == skMethod: finishMethod(c, result)
  410. # inform IC of the generic
  411. #addGeneric(c.ic, result, entry.concreteTypes)