# # # The Nim Compiler # (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # # This module does the instantiation of generic types. import std / tables import ast, astalgo, msgs, types, magicsys, semdata, renderer, options, lineinfos, modulegraphs when defined(nimPreviewSlimSystem): import std/assertions const tfInstClearedFlags = {tfHasMeta, tfUnresolved} proc checkPartialConstructedType(conf: ConfigRef; info: TLineInfo, t: PType) = if t.kind in {tyVar, tyLent} and t.elementType.kind in {tyVar, tyLent}: localError(conf, info, "type 'var var' is not allowed") proc checkConstructedType*(conf: ConfigRef; info: TLineInfo, typ: PType) = var t = typ.skipTypes({tyDistinct}) if t.kind in tyTypeClasses: discard elif t.kind in {tyVar, tyLent} and t.elementType.kind in {tyVar, tyLent}: localError(conf, info, "type 'var var' is not allowed") elif computeSize(conf, t) == szIllegalRecursion or isTupleRecursive(t): localError(conf, info, "illegal recursion in type '" & typeToString(t) & "'") proc searchInstTypes*(g: ModuleGraph; key: PType): PType = result = nil let genericTyp = key[0] if not (genericTyp.kind == tyGenericBody and genericTyp.sym != nil): return for inst in typeInstCacheItems(g, genericTyp.sym): if inst.id == key.id: return inst if inst.kidsLen < key.kidsLen: # XXX: This happens for prematurely cached # types such as Channel[empty]. Why? # See the notes for PActor in handleGenericInvocation # if this is return the same type gets cached more than it needs to continue if not sameFlags(inst, key): continue block matchType: for j in FirstGenericParamAt.. 1 and # generic type instantiation: ((n[1].typ != nil and n[1].typ.kind == tyTypeDesc) or # generic proc instantiation: (n[1].kind == nkSym and n[1].sym.isGenericRoutineStrict)) if ignoreFirst: result.add(n[0]) else: result.add(prepareNode(cl, n[0])) if n.len > 1: if ignoreSecond: result.add(n[1]) else: result.add(prepareNode(cl, n[1])) for i in 2..= 2 result.add(prepareNode(cl, n[0])) result.add(n[1]) for i in 2.. 0: newSons(result, n.len) if start > 0: result[0] = n[0] for i in start.. 0: t.n[i].sym.typ = skipped # when the typeof operator is used on a static input # param, the results gets infected with static as well: if t.returnType != nil and t.returnType.kind == tyStatic: t.setReturnType t.returnType.skipModifier proc propagateFieldFlags(t: PType, n: PNode) = # This is meant for objects and tuples # The type must be fully instantiated! if n.isNil: return #internalAssert n.kind != nkRecWhen case n.kind of nkSym: propagateToOwner(t, n.sym.typ) of nkRecList, nkRecCase, nkOfBranch, nkElse: for son in n: propagateFieldFlags(t, son) else: discard proc replaceTypeVarsTAux(cl: var TReplTypeVars, t: PType): PType = template bailout = if (t.sym == nil) or (t.sym != nil and sfGeneratedType in t.sym.flags): # In the first case 't.sym' can be 'nil' if the type is a ref/ptr, see # issue https://github.com/nim-lang/Nim/issues/20416 for more details. # Fortunately for us this works for now because partial ref/ptr types are # not allowed in object construction, eg. # type # Container[T] = ... # O = object # val: ref Container # # In the second case only consider the recursion limit if the symbol is a # type with generic parameters that have not been explicitly supplied, # typechecking should terminate when generic parameters are explicitly # supplied. if cl.recursionLimit > 100: # bail out, see bug #2509. But note this caching is in general wrong, # look at this example where TwoVectors should not share the generic # instantiations (bug #3112): # type # Vector[N: static[int]] = array[N, float64] # TwoVectors[Na, Nb: static[int]] = (Vector[Na], Vector[Nb]) result = getOrDefault(cl.localCache, t.itemId) if result != nil: return result inc cl.recursionLimit result = t if t == nil: return const lookupMetas = {tyStatic, tyGenericParam, tyConcept} + tyTypeClasses - {tyAnything} if t.kind in lookupMetas or (t.kind == tyAnything and tfRetType notin t.flags): let lookup = cl.typeMap.lookup(t) if lookup != nil: return lookup case t.kind of tyGenericInvocation: result = handleGenericInvocation(cl, t) if result.last.kind == tyUserTypeClass: result.kind = tyUserTypeClassInst of tyGenericBody: if cl.allowMetaTypes: return localError( cl.c.config, cl.info, "cannot instantiate: '" & typeToString(t, preferDesc) & "'; Maybe generic arguments are missing?") result = errorType(cl.c) #result = replaceTypeVarsT(cl, lastSon(t)) of tyFromExpr: if cl.allowMetaTypes: return # This assert is triggered when a tyFromExpr was created in a cyclic # way. You should break the cycle at the point of creation by introducing # a call such as: `n.typ = makeTypeFromExpr(c, n.copyTree)` # Otherwise, the cycle will be fatal for the prepareNode call below assert t.n.typ != t var n = prepareNode(cl, t.n) if n.kind != nkEmpty: if tfNonConstExpr in t.flags: n = cl.c.semExprWithType(cl.c, n, flags = {efInTypeof}) else: n = cl.c.semConstExpr(cl.c, n) if n.typ.kind == tyTypeDesc: # XXX: sometimes, chained typedescs enter here. # It may be worth investigating why this is happening, # because it may cause other bugs elsewhere. result = n.typ.skipTypes({tyTypeDesc}) # result = n.typ.base elif tfNonConstExpr in t.flags: result = n.typ else: if n.typ.kind != tyStatic and n.kind != nkType: # XXX: In the future, semConstExpr should # return tyStatic values to let anyone make # use of this knowledge. The patching here # won't be necessary then. result = newTypeS(tyStatic, cl.c, son = n.typ) result.n = n else: result = n.typ of tyInt, tyFloat: result = skipIntLit(t, cl.c.idgen) of tyTypeDesc: let lookup = cl.typeMap.lookup(t) if lookup != nil: result = lookup if result.kind != tyTypeDesc: result = makeTypeDesc(cl.c, result) elif tfUnresolved in t.flags or cl.skipTypedesc: result = result.base elif t.elementType.kind != tyNone: result = makeTypeDesc(cl.c, replaceTypeVarsT(cl, t.elementType)) of tyUserTypeClass: result = t of tyStatic: if cl.c.matchedConcept != nil: # allow concepts to not instantiate statics for now # they can't always infer them return if not containsGenericType(t) and (t.n == nil or t.n.kind in nkLiterals): # no need to instantiate return bailout() result = instCopyType(cl, t) cl.localCache[t.itemId] = result for i in FirstGenericParamAt.. int # Desired result: Foo[int] # proc (x: T = 0); T -> int ----> proc (x: int = 0) var typeMap = initLayeredTypeMap(pt) var cl = initTypeVars(p, typeMap, info, nil) pushInfoContext(p.config, info) result = replaceTypeVarsT(cl, t) popInfoContext(p.config) let objType = result.skipTypes(abstractInst) if objType.kind == tyObject: var position = 0 recomputeFieldPositions(objType, objType.n, position) proc prepareMetatypeForSigmatch*(p: PContext, pt: TypeMapping, info: TLineInfo, t: PType): PType = var typeMap = initLayeredTypeMap(pt) var cl = initTypeVars(p, typeMap, info, nil) cl.allowMetaTypes = true pushInfoContext(p.config, info) result = replaceTypeVarsT(cl, t) popInfoContext(p.config) template generateTypeInstance*(p: PContext, pt: TypeMapping, arg: PNode, t: PType): untyped = generateTypeInstance(p, pt, arg.info, t)