semtypes.nim 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  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 does the semantic checking of type declarations
  10. # included from sem.nim
  11. const
  12. errStringOrIdentNodeExpected = "string or ident node expected"
  13. errStringLiteralExpected = "string literal expected"
  14. errIntLiteralExpected = "integer literal expected"
  15. errWrongNumberOfVariables = "wrong number of variables"
  16. errInvalidOrderInEnumX = "invalid order in enum '$1'"
  17. errOrdinalTypeExpected = "ordinal type expected"
  18. errSetTooBig = "set is too large"
  19. errBaseTypeMustBeOrdinal = "base type of a set must be an ordinal"
  20. errInheritanceOnlyWithNonFinalObjects = "inheritance only works with non-final objects"
  21. errXExpectsOneTypeParam = "'$1' expects one type parameter"
  22. errArrayExpectsTwoTypeParams = "array expects two type parameters"
  23. errInvalidVisibilityX = "invalid visibility: '$1'"
  24. errInitHereNotAllowed = "initialization not allowed here"
  25. errXCannotBeAssignedTo = "'$1' cannot be assigned to"
  26. errIteratorNotAllowed = "iterators can only be defined at the module's top level"
  27. errXNeedsReturnType = "$1 needs a return type"
  28. errNoReturnTypeDeclared = "no return type declared"
  29. errTIsNotAConcreteType = "'$1' is not a concrete type"
  30. errTypeExpected = "type expected"
  31. errXOnlyAtModuleScope = "'$1' is only allowed at top level"
  32. errDuplicateCaseLabel = "duplicate case label"
  33. errMacroBodyDependsOnGenericTypes = "the macro body cannot be compiled, " &
  34. "because the parameter '$1' has a generic type"
  35. errIllegalRecursionInTypeX = "illegal recursion in type '$1'"
  36. errNoGenericParamsAllowedForX = "no generic parameters allowed for $1"
  37. errInOutFlagNotExtern = "the '$1' modifier can be used only with imported types"
  38. proc newOrPrevType(kind: TTypeKind, prev: PType, c: PContext): PType =
  39. if prev == nil:
  40. result = newTypeS(kind, c)
  41. else:
  42. result = prev
  43. if result.kind == tyForward: result.kind = kind
  44. #if kind == tyError: result.flags.incl tfCheckedForDestructor
  45. proc newConstraint(c: PContext, k: TTypeKind): PType =
  46. result = newTypeS(tyBuiltInTypeClass, c)
  47. result.flags.incl tfCheckedForDestructor
  48. result.addSonSkipIntLit(newTypeS(k, c))
  49. proc semEnum(c: PContext, n: PNode, prev: PType): PType =
  50. if n.sonsLen == 0: return newConstraint(c, tyEnum)
  51. elif n.sonsLen == 1:
  52. # don't create an empty tyEnum; fixes #3052
  53. return errorType(c)
  54. var
  55. counter, x: BiggestInt
  56. e: PSym
  57. base: PType
  58. counter = 0
  59. base = nil
  60. result = newOrPrevType(tyEnum, prev, c)
  61. result.n = newNodeI(nkEnumTy, n.info)
  62. checkMinSonsLen(n, 1, c.config)
  63. if n.sons[0].kind != nkEmpty:
  64. base = semTypeNode(c, n.sons[0].sons[0], nil)
  65. if base.kind != tyEnum:
  66. localError(c.config, n.sons[0].info, "inheritance only works with an enum")
  67. counter = lastOrd(c.config, base) + 1
  68. rawAddSon(result, base)
  69. let isPure = result.sym != nil and sfPure in result.sym.flags
  70. var symbols: TStrTable
  71. if isPure: initStrTable(symbols)
  72. var hasNull = false
  73. for i in 1 ..< sonsLen(n):
  74. if n.sons[i].kind == nkEmpty: continue
  75. case n.sons[i].kind
  76. of nkEnumFieldDef:
  77. if n.sons[i].sons[0].kind == nkPragmaExpr:
  78. e = newSymS(skEnumField, n.sons[i].sons[0].sons[0], c)
  79. pragma(c, e, n.sons[i].sons[0].sons[1], enumFieldPragmas)
  80. else:
  81. e = newSymS(skEnumField, n.sons[i].sons[0], c)
  82. var v = semConstExpr(c, n.sons[i].sons[1])
  83. var strVal: PNode = nil
  84. case skipTypes(v.typ, abstractInst-{tyTypeDesc}).kind
  85. of tyTuple:
  86. if sonsLen(v) == 2:
  87. strVal = v.sons[1] # second tuple part is the string value
  88. if skipTypes(strVal.typ, abstractInst).kind in {tyString, tyCString}:
  89. if not isOrdinalType(v.sons[0].typ, allowEnumWithHoles=true):
  90. localError(c.config, v.sons[0].info, errOrdinalTypeExpected & "; given: " & typeToString(v.sons[0].typ, preferDesc))
  91. x = getOrdValue(v.sons[0]) # first tuple part is the ordinal
  92. else:
  93. localError(c.config, strVal.info, errStringLiteralExpected)
  94. else:
  95. localError(c.config, v.info, errWrongNumberOfVariables)
  96. of tyString, tyCString:
  97. strVal = v
  98. x = counter
  99. else:
  100. if not isOrdinalType(v.typ, allowEnumWithHoles=true):
  101. localError(c.config, v.info, errOrdinalTypeExpected & "; given: " & typeToString(v.typ, preferDesc))
  102. x = getOrdValue(v)
  103. if i != 1:
  104. if x != counter: incl(result.flags, tfEnumHasHoles)
  105. if x < counter:
  106. localError(c.config, n.sons[i].info, errInvalidOrderInEnumX % e.name.s)
  107. x = counter
  108. e.ast = strVal # might be nil
  109. counter = x
  110. of nkSym:
  111. e = n.sons[i].sym
  112. of nkIdent, nkAccQuoted:
  113. e = newSymS(skEnumField, n.sons[i], c)
  114. of nkPragmaExpr:
  115. e = newSymS(skEnumField, n.sons[i].sons[0], c)
  116. pragma(c, e, n.sons[i].sons[1], enumFieldPragmas)
  117. else:
  118. illFormedAst(n[i], c.config)
  119. e.typ = result
  120. e.position = int(counter)
  121. if e.position == 0: hasNull = true
  122. if result.sym != nil and sfExported in result.sym.flags:
  123. incl(e.flags, sfUsed)
  124. incl(e.flags, sfExported)
  125. if not isPure: strTableAdd(c.module.tab, e)
  126. addSon(result.n, newSymNode(e))
  127. styleCheckDef(c.config, e)
  128. onDef(e.info, e)
  129. if sfGenSym notin e.flags:
  130. if not isPure: addDecl(c, e)
  131. else: importPureEnumField(c, e)
  132. if isPure and (let conflict = strTableInclReportConflict(symbols, e); conflict != nil):
  133. wrongRedefinition(c, e.info, e.name.s, conflict.info)
  134. inc(counter)
  135. if tfNotNil in e.typ.flags and not hasNull: incl(result.flags, tfNeedsInit)
  136. proc semSet(c: PContext, n: PNode, prev: PType): PType =
  137. result = newOrPrevType(tySet, prev, c)
  138. if sonsLen(n) == 2 and n.sons[1].kind != nkEmpty:
  139. var base = semTypeNode(c, n.sons[1], nil)
  140. addSonSkipIntLit(result, base)
  141. if base.kind in {tyGenericInst, tyAlias, tySink}: base = lastSon(base)
  142. if base.kind != tyGenericParam:
  143. if not isOrdinalType(base, allowEnumWithHoles = true):
  144. localError(c.config, n.info, errOrdinalTypeExpected)
  145. elif lengthOrd(c.config, base) > MaxSetElements:
  146. localError(c.config, n.info, errSetTooBig)
  147. else:
  148. localError(c.config, n.info, errXExpectsOneTypeParam % "set")
  149. addSonSkipIntLit(result, errorType(c))
  150. proc semContainerArg(c: PContext; n: PNode, kindStr: string; result: PType) =
  151. if sonsLen(n) == 2:
  152. var base = semTypeNode(c, n.sons[1], nil)
  153. if base.kind == tyVoid:
  154. localError(c.config, n.info, errTIsNotAConcreteType % typeToString(base))
  155. addSonSkipIntLit(result, base)
  156. else:
  157. localError(c.config, n.info, errXExpectsOneTypeParam % kindStr)
  158. addSonSkipIntLit(result, errorType(c))
  159. proc semContainer(c: PContext, n: PNode, kind: TTypeKind, kindStr: string,
  160. prev: PType): PType =
  161. result = newOrPrevType(kind, prev, c)
  162. semContainerArg(c, n, kindStr, result)
  163. proc semVarargs(c: PContext, n: PNode, prev: PType): PType =
  164. result = newOrPrevType(tyVarargs, prev, c)
  165. if sonsLen(n) == 2 or sonsLen(n) == 3:
  166. var base = semTypeNode(c, n.sons[1], nil)
  167. addSonSkipIntLit(result, base)
  168. if sonsLen(n) == 3:
  169. result.n = newIdentNode(considerQuotedIdent(c, n.sons[2]), n.sons[2].info)
  170. else:
  171. localError(c.config, n.info, errXExpectsOneTypeParam % "varargs")
  172. addSonSkipIntLit(result, errorType(c))
  173. proc semVarType(c: PContext, n: PNode, prev: PType): PType =
  174. if sonsLen(n) == 1:
  175. result = newOrPrevType(tyVar, prev, c)
  176. var base = semTypeNode(c, n.sons[0], nil).skipTypes({tyTypeDesc})
  177. if base.kind == tyVar:
  178. localError(c.config, n.info, "type 'var var' is not allowed")
  179. base = base.sons[0]
  180. addSonSkipIntLit(result, base)
  181. else:
  182. result = newConstraint(c, tyVar)
  183. proc semDistinct(c: PContext, n: PNode, prev: PType): PType =
  184. if n.len == 0: return newConstraint(c, tyDistinct)
  185. result = newOrPrevType(tyDistinct, prev, c)
  186. addSonSkipIntLit(result, semTypeNode(c, n.sons[0], nil))
  187. if n.len > 1: result.n = n[1]
  188. proc semRangeAux(c: PContext, n: PNode, prev: PType): PType =
  189. assert isRange(n)
  190. checkSonsLen(n, 3, c.config)
  191. result = newOrPrevType(tyRange, prev, c)
  192. result.n = newNodeI(nkRange, n.info)
  193. # always create a 'valid' range type, but overwrite it later
  194. # because 'semExprWithType' can raise an exception. See bug #6895.
  195. addSonSkipIntLit(result, errorType(c))
  196. if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty):
  197. localError(c.config, n.info, "range is empty")
  198. var range: array[2, PNode]
  199. range[0] = semExprWithType(c, n[1], {efDetermineType})
  200. range[1] = semExprWithType(c, n[2], {efDetermineType})
  201. var rangeT: array[2, PType]
  202. for i in 0..1:
  203. rangeT[i] = range[i].typ.skipTypes({tyStatic}).skipIntLit
  204. let hasUnknownTypes = c.inGenericContext > 0 and
  205. rangeT[0].kind == tyFromExpr or rangeT[1].kind == tyFromExpr
  206. if not hasUnknownTypes:
  207. if not sameType(rangeT[0].skipTypes({tyRange}), rangeT[1].skipTypes({tyRange})):
  208. localError(c.config, n.info, "type mismatch")
  209. elif not rangeT[0].isOrdinalType and rangeT[0].kind notin tyFloat..tyFloat128 or
  210. rangeT[0].kind == tyBool:
  211. localError(c.config, n.info, "ordinal or float type expected")
  212. elif enumHasHoles(rangeT[0]):
  213. localError(c.config, n.info, "enum '$1' has holes" % typeToString(rangeT[0]))
  214. for i in 0..1:
  215. if hasUnresolvedArgs(c, range[i]):
  216. result.n.addSon makeStaticExpr(c, range[i])
  217. result.flags.incl tfUnresolved
  218. else:
  219. result.n.addSon semConstExpr(c, range[i])
  220. if weakLeValue(result.n[0], result.n[1]) == impNo:
  221. localError(c.config, n.info, "range is empty")
  222. result[0] = rangeT[0]
  223. proc semRange(c: PContext, n: PNode, prev: PType): PType =
  224. result = nil
  225. if sonsLen(n) == 2:
  226. if isRange(n[1]):
  227. result = semRangeAux(c, n[1], prev)
  228. let n = result.n
  229. if n.sons[0].kind in {nkCharLit..nkUInt64Lit} and n.sons[0].intVal > 0:
  230. incl(result.flags, tfNeedsInit)
  231. elif n.sons[1].kind in {nkCharLit..nkUInt64Lit} and n.sons[1].intVal < 0:
  232. incl(result.flags, tfNeedsInit)
  233. elif n.sons[0].kind in {nkFloatLit..nkFloat64Lit} and
  234. n.sons[0].floatVal > 0.0:
  235. incl(result.flags, tfNeedsInit)
  236. elif n.sons[1].kind in {nkFloatLit..nkFloat64Lit} and
  237. n.sons[1].floatVal < 0.0:
  238. incl(result.flags, tfNeedsInit)
  239. else:
  240. if n[1].kind == nkInfix and considerQuotedIdent(c, n[1][0]).s == "..<":
  241. localError(c.config, n[0].info, "range types need to be constructed with '..', '..<' is not supported")
  242. else:
  243. localError(c.config, n.sons[0].info, "expected range")
  244. result = newOrPrevType(tyError, prev, c)
  245. else:
  246. localError(c.config, n.info, errXExpectsOneTypeParam % "range")
  247. result = newOrPrevType(tyError, prev, c)
  248. proc semArrayIndex(c: PContext, n: PNode): PType =
  249. if isRange(n):
  250. result = semRangeAux(c, n, nil)
  251. else:
  252. let e = semExprWithType(c, n, {efDetermineType})
  253. if e.typ.kind == tyFromExpr:
  254. result = makeRangeWithStaticExpr(c, e.typ.n)
  255. elif e.kind in {nkIntLit..nkUInt64Lit}:
  256. if e.intVal < 0:
  257. localError(c.config, n[1].info,
  258. "Array length can't be negative, but was " & $e.intVal)
  259. result = makeRangeType(c, 0, e.intVal-1, n.info, e.typ)
  260. elif e.kind == nkSym and e.typ.kind == tyStatic:
  261. if e.sym.ast != nil:
  262. return semArrayIndex(c, e.sym.ast)
  263. if not isOrdinalType(e.typ.lastSon):
  264. let info = if n.safeLen > 1: n[1].info else: n.info
  265. localError(c.config, info, errOrdinalTypeExpected)
  266. result = makeRangeWithStaticExpr(c, e)
  267. if c.inGenericContext > 0: result.flags.incl tfUnresolved
  268. elif e.kind in (nkCallKinds + {nkBracketExpr}) and hasUnresolvedArgs(c, e):
  269. if not isOrdinalType(e.typ):
  270. localError(c.config, n[1].info, errOrdinalTypeExpected)
  271. # This is an int returning call, depending on an
  272. # yet unknown generic param (see tgenericshardcases).
  273. # We are going to construct a range type that will be
  274. # properly filled-out in semtypinst (see how tyStaticExpr
  275. # is handled there).
  276. result = makeRangeWithStaticExpr(c, e)
  277. elif e.kind == nkIdent:
  278. result = e.typ.skipTypes({tyTypeDesc})
  279. else:
  280. let x = semConstExpr(c, e)
  281. if x.kind in {nkIntLit..nkUInt64Lit}:
  282. result = makeRangeType(c, 0, x.intVal-1, n.info,
  283. x.typ.skipTypes({tyTypeDesc}))
  284. else:
  285. result = x.typ.skipTypes({tyTypeDesc})
  286. #localError(c.config, n[1].info, errConstExprExpected)
  287. proc semArray(c: PContext, n: PNode, prev: PType): PType =
  288. var base: PType
  289. if sonsLen(n) == 3:
  290. # 3 = length(array indx base)
  291. let indx = semArrayIndex(c, n[1])
  292. var indxB = indx
  293. if indxB.kind in {tyGenericInst, tyAlias, tySink}: indxB = lastSon(indxB)
  294. if indxB.kind notin {tyGenericParam, tyStatic, tyFromExpr}:
  295. if indxB.skipTypes({tyRange}).kind in {tyUInt, tyUInt64}:
  296. discard
  297. elif not isOrdinalType(indxB):
  298. localError(c.config, n.sons[1].info, errOrdinalTypeExpected)
  299. elif enumHasHoles(indxB):
  300. localError(c.config, n.sons[1].info, "enum '$1' has holes" %
  301. typeToString(indxB.skipTypes({tyRange})))
  302. base = semTypeNode(c, n.sons[2], nil)
  303. # ensure we only construct a tyArray when there was no error (bug #3048):
  304. result = newOrPrevType(tyArray, prev, c)
  305. # bug #6682: Do not propagate initialization requirements etc for the
  306. # index type:
  307. rawAddSonNoPropagationOfTypeFlags(result, indx)
  308. addSonSkipIntLit(result, base)
  309. else:
  310. localError(c.config, n.info, errArrayExpectsTwoTypeParams)
  311. result = newOrPrevType(tyError, prev, c)
  312. proc semOrdinal(c: PContext, n: PNode, prev: PType): PType =
  313. result = newOrPrevType(tyOrdinal, prev, c)
  314. if sonsLen(n) == 2:
  315. var base = semTypeNode(c, n.sons[1], nil)
  316. if base.kind != tyGenericParam:
  317. if not isOrdinalType(base):
  318. localError(c.config, n.sons[1].info, errOrdinalTypeExpected)
  319. addSonSkipIntLit(result, base)
  320. else:
  321. localError(c.config, n.info, errXExpectsOneTypeParam % "ordinal")
  322. result = newOrPrevType(tyError, prev, c)
  323. proc semTypeIdent(c: PContext, n: PNode): PSym =
  324. if n.kind == nkSym:
  325. result = getGenSym(c, n.sym)
  326. else:
  327. result = pickSym(c, n, {skType, skGenericParam, skParam})
  328. if result.isNil:
  329. result = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared})
  330. if result != nil:
  331. markUsed(c.config, n.info, result, c.graph.usageSym)
  332. onUse(n.info, result)
  333. if result.kind == skParam and result.typ.kind == tyTypeDesc:
  334. # This is a typedesc param. is it already bound?
  335. # it's not bound when it's used multiple times in the
  336. # proc signature for example
  337. if c.inGenericInst > 0:
  338. let bound = result.typ.sons[0].sym
  339. if bound != nil: return bound
  340. return result
  341. if result.typ.sym == nil:
  342. localError(c.config, n.info, errTypeExpected)
  343. return errorSym(c, n)
  344. result = result.typ.sym.copySym
  345. result.typ = exactReplica(result.typ)
  346. result.typ.flags.incl tfUnresolved
  347. if result.kind == skGenericParam:
  348. if result.typ.kind == tyGenericParam and result.typ.len == 0 and
  349. tfWildcard in result.typ.flags:
  350. # collapse the wild-card param to a type
  351. result.kind = skType
  352. result.typ.flags.excl tfWildcard
  353. return
  354. else:
  355. localError(c.config, n.info, errTypeExpected)
  356. return errorSym(c, n)
  357. if result.kind != skType and result.magic notin {mStatic, mType, mTypeOf}:
  358. # this implements the wanted ``var v: V, x: V`` feature ...
  359. var ov: TOverloadIter
  360. var amb = initOverloadIter(ov, c, n)
  361. while amb != nil and amb.kind != skType:
  362. amb = nextOverloadIter(ov, c, n)
  363. if amb != nil: result = amb
  364. else:
  365. if result.kind != skError: localError(c.config, n.info, errTypeExpected)
  366. return errorSym(c, n)
  367. if result.typ.kind != tyGenericParam:
  368. # XXX get rid of this hack!
  369. var oldInfo = n.info
  370. when defined(useNodeIds):
  371. let oldId = n.id
  372. reset(n[])
  373. when defined(useNodeIds):
  374. n.id = oldId
  375. n.kind = nkSym
  376. n.sym = result
  377. n.info = oldInfo
  378. n.typ = result.typ
  379. else:
  380. localError(c.config, n.info, "identifier expected")
  381. result = errorSym(c, n)
  382. proc semAnonTuple(c: PContext, n: PNode, prev: PType): PType =
  383. if sonsLen(n) == 0:
  384. localError(c.config, n.info, errTypeExpected)
  385. result = newOrPrevType(tyTuple, prev, c)
  386. for it in n:
  387. addSonSkipIntLit(result, semTypeNode(c, it, nil))
  388. proc semTuple(c: PContext, n: PNode, prev: PType): PType =
  389. var typ: PType
  390. result = newOrPrevType(tyTuple, prev, c)
  391. result.n = newNodeI(nkRecList, n.info)
  392. var check = initIntSet()
  393. var counter = 0
  394. for i in ord(n.kind == nkBracketExpr) ..< sonsLen(n):
  395. var a = n.sons[i]
  396. if (a.kind != nkIdentDefs): illFormedAst(a, c.config)
  397. checkMinSonsLen(a, 3, c.config)
  398. var length = sonsLen(a)
  399. if a.sons[length - 2].kind != nkEmpty:
  400. typ = semTypeNode(c, a.sons[length - 2], nil)
  401. else:
  402. localError(c.config, a.info, errTypeExpected)
  403. typ = errorType(c)
  404. if a.sons[length - 1].kind != nkEmpty:
  405. localError(c.config, a.sons[length - 1].info, errInitHereNotAllowed)
  406. for j in 0 .. length - 3:
  407. var field = newSymG(skField, a.sons[j], c)
  408. field.typ = typ
  409. field.position = counter
  410. inc(counter)
  411. if containsOrIncl(check, field.name.id):
  412. localError(c.config, a.sons[j].info, "attempt to redefine: '" & field.name.s & "'")
  413. else:
  414. addSon(result.n, newSymNode(field))
  415. addSonSkipIntLit(result, typ)
  416. styleCheckDef(c.config, a.sons[j].info, field)
  417. onDef(field.info, field)
  418. if result.n.len == 0: result.n = nil
  419. if isTupleRecursive(result):
  420. localError(c.config, n.info, errIllegalRecursionInTypeX % typeToString(result))
  421. proc semIdentVis(c: PContext, kind: TSymKind, n: PNode,
  422. allowed: TSymFlags): PSym =
  423. # identifier with visibility
  424. if n.kind == nkPostfix:
  425. if sonsLen(n) == 2:
  426. # for gensym'ed identifiers the identifier may already have been
  427. # transformed to a symbol and we need to use that here:
  428. result = newSymG(kind, n.sons[1], c)
  429. var v = considerQuotedIdent(c, n.sons[0])
  430. if sfExported in allowed and v.id == ord(wStar):
  431. incl(result.flags, sfExported)
  432. else:
  433. if not (sfExported in allowed):
  434. localError(c.config, n.sons[0].info, errXOnlyAtModuleScope % "export")
  435. else:
  436. localError(c.config, n.sons[0].info, errInvalidVisibilityX % renderTree(n[0]))
  437. else:
  438. illFormedAst(n, c.config)
  439. else:
  440. result = newSymG(kind, n, c)
  441. proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
  442. allowed: TSymFlags): PSym =
  443. if n.kind == nkPragmaExpr:
  444. checkSonsLen(n, 2, c.config)
  445. result = semIdentVis(c, kind, n.sons[0], allowed)
  446. case kind
  447. of skType:
  448. # process pragmas later, because result.typ has not been set yet
  449. discard
  450. of skField: pragma(c, result, n.sons[1], fieldPragmas)
  451. of skVar: pragma(c, result, n.sons[1], varPragmas)
  452. of skLet: pragma(c, result, n.sons[1], letPragmas)
  453. of skConst: pragma(c, result, n.sons[1], constPragmas)
  454. else: discard
  455. else:
  456. result = semIdentVis(c, kind, n, allowed)
  457. proc checkForOverlap(c: PContext, t: PNode, currentEx, branchIndex: int) =
  458. let ex = t[branchIndex][currentEx].skipConv
  459. for i in 1 .. branchIndex:
  460. for j in 0 .. sonsLen(t.sons[i]) - 2:
  461. if i == branchIndex and j == currentEx: break
  462. if overlap(t.sons[i].sons[j].skipConv, ex):
  463. localError(c.config, ex.info, errDuplicateCaseLabel)
  464. proc semBranchRange(c: PContext, t, a, b: PNode, covered: var BiggestInt): PNode =
  465. checkMinSonsLen(t, 1, c.config)
  466. let ac = semConstExpr(c, a)
  467. let bc = semConstExpr(c, b)
  468. let at = fitNode(c, t.sons[0].typ, ac, ac.info).skipConvTakeType
  469. let bt = fitNode(c, t.sons[0].typ, bc, bc.info).skipConvTakeType
  470. result = newNodeI(nkRange, a.info)
  471. result.add(at)
  472. result.add(bt)
  473. if emptyRange(ac, bc): localError(c.config, b.info, "range is empty")
  474. else: covered = covered + getOrdValue(bc) - getOrdValue(ac) + 1
  475. proc semCaseBranchRange(c: PContext, t, b: PNode,
  476. covered: var BiggestInt): PNode =
  477. checkSonsLen(b, 3, c.config)
  478. result = semBranchRange(c, t, b.sons[1], b.sons[2], covered)
  479. proc semCaseBranchSetElem(c: PContext, t, b: PNode,
  480. covered: var BiggestInt): PNode =
  481. if isRange(b):
  482. checkSonsLen(b, 3, c.config)
  483. result = semBranchRange(c, t, b.sons[1], b.sons[2], covered)
  484. elif b.kind == nkRange:
  485. checkSonsLen(b, 2, c.config)
  486. result = semBranchRange(c, t, b.sons[0], b.sons[1], covered)
  487. else:
  488. result = fitNode(c, t.sons[0].typ, b, b.info)
  489. inc(covered)
  490. proc semCaseBranch(c: PContext, t, branch: PNode, branchIndex: int,
  491. covered: var BiggestInt) =
  492. let lastIndex = sonsLen(branch) - 2
  493. for i in 0..lastIndex:
  494. var b = branch.sons[i]
  495. if b.kind == nkRange:
  496. branch.sons[i] = b
  497. elif isRange(b):
  498. branch.sons[i] = semCaseBranchRange(c, t, b, covered)
  499. else:
  500. # constant sets and arrays are allowed:
  501. var r = semConstExpr(c, b)
  502. if r.kind in {nkCurly, nkBracket} and len(r) == 0 and sonsLen(branch)==2:
  503. # discarding ``{}`` and ``[]`` branches silently
  504. delSon(branch, 0)
  505. return
  506. elif r.kind notin {nkCurly, nkBracket} or len(r) == 0:
  507. checkMinSonsLen(t, 1, c.config)
  508. var tmp = fitNode(c, t.sons[0].typ, r, r.info)
  509. # the call to fitNode may introduce a call to a converter
  510. if tmp.kind in {nkHiddenCallConv}: tmp = semConstExpr(c, tmp)
  511. branch.sons[i] = skipConv(tmp)
  512. inc(covered)
  513. else:
  514. if r.kind == nkCurly:
  515. r = deduplicate(c.config, r)
  516. # first element is special and will overwrite: branch.sons[i]:
  517. branch.sons[i] = semCaseBranchSetElem(c, t, r[0], covered)
  518. # other elements have to be added to ``branch``
  519. for j in 1 ..< r.len:
  520. branch.add(semCaseBranchSetElem(c, t, r[j], covered))
  521. # caution! last son of branch must be the actions to execute:
  522. swap(branch.sons[^2], branch.sons[^1])
  523. checkForOverlap(c, t, i, branchIndex)
  524. # Elements added above needs to be checked for overlaps.
  525. for i in lastIndex.succ..(sonsLen(branch) - 2):
  526. checkForOverlap(c, t, i, branchIndex)
  527. proc toCover(c: PContext, t: PType): BiggestInt =
  528. let t2 = skipTypes(t, abstractVarRange-{tyTypeDesc})
  529. if t2.kind == tyEnum and enumHasHoles(t2):
  530. result = sonsLen(t2.n)
  531. else:
  532. result = lengthOrd(c.config, skipTypes(t, abstractVar-{tyTypeDesc}))
  533. proc semRecordNodeAux(c: PContext, n: PNode, check: var IntSet, pos: var int,
  534. father: PNode, rectype: PType, hasCaseFields = false)
  535. proc formatMissingEnums(n: PNode): string =
  536. var coveredCases = initIntSet()
  537. for i in 1 ..< n.len:
  538. let ofBranch = n[i]
  539. for j in 0 ..< ofBranch.len - 1:
  540. let child = ofBranch[j]
  541. if child.kind == nkIntLit:
  542. coveredCases.incl(child.intVal.int)
  543. elif child.kind == nkRange:
  544. for k in child[0].intVal.int .. child[1].intVal.int:
  545. coveredCases.incl k
  546. for child in n[0].typ.n.sons:
  547. if child.sym.position notin coveredCases:
  548. if result.len > 0:
  549. result.add ", "
  550. result.add child.sym.name.s
  551. proc semRecordCase(c: PContext, n: PNode, check: var IntSet, pos: var int,
  552. father: PNode, rectype: PType) =
  553. var a = copyNode(n)
  554. checkMinSonsLen(n, 2, c.config)
  555. semRecordNodeAux(c, n.sons[0], check, pos, a, rectype, hasCaseFields = true)
  556. if a.sons[0].kind != nkSym:
  557. internalError(c.config, "semRecordCase: discriminant is no symbol")
  558. return
  559. incl(a.sons[0].sym.flags, sfDiscriminant)
  560. var covered: BiggestInt = 0
  561. var chckCovered = false
  562. var typ = skipTypes(a.sons[0].typ, abstractVar-{tyTypeDesc})
  563. const shouldChckCovered = {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32, tyBool}
  564. case typ.kind
  565. of shouldChckCovered:
  566. chckCovered = true
  567. of tyFloat..tyFloat128, tyString, tyError:
  568. discard
  569. of tyRange:
  570. if skipTypes(typ.sons[0], abstractInst).kind in shouldChckCovered:
  571. chckCovered = true
  572. of tyForward:
  573. errorUndeclaredIdentifier(c, n.sons[0].info, typ.sym.name.s)
  574. elif not isOrdinalType(typ):
  575. localError(c.config, n.sons[0].info, "selector must be of an ordinal type, float or string")
  576. for i in 1 ..< sonsLen(n):
  577. var b = copyTree(n.sons[i])
  578. addSon(a, b)
  579. case n.sons[i].kind
  580. of nkOfBranch:
  581. checkMinSonsLen(b, 2, c.config)
  582. semCaseBranch(c, a, b, i, covered)
  583. of nkElse:
  584. checkSonsLen(b, 1, c.config)
  585. if chckCovered and covered == toCover(c, a.sons[0].typ):
  586. localError(c.config, b.info, "invalid else, all cases are already covered")
  587. chckCovered = false
  588. else: illFormedAst(n, c.config)
  589. delSon(b, sonsLen(b) - 1)
  590. semRecordNodeAux(c, lastSon(n.sons[i]), check, pos, b, rectype, hasCaseFields = true)
  591. if chckCovered and covered != toCover(c, a.sons[0].typ):
  592. if a.sons[0].typ.kind == tyEnum:
  593. localError(c.config, a.info, "not all cases are covered; missing: {$1}" %
  594. formatMissingEnums(a))
  595. else:
  596. localError(c.config, a.info, "not all cases are covered")
  597. addSon(father, a)
  598. proc semRecordNodeAux(c: PContext, n: PNode, check: var IntSet, pos: var int,
  599. father: PNode, rectype: PType, hasCaseFields = false) =
  600. if n == nil: return
  601. case n.kind
  602. of nkRecWhen:
  603. var branch: PNode = nil # the branch to take
  604. for i in 0 ..< sonsLen(n):
  605. var it = n.sons[i]
  606. if it == nil: illFormedAst(n, c.config)
  607. var idx = 1
  608. case it.kind
  609. of nkElifBranch:
  610. checkSonsLen(it, 2, c.config)
  611. if c.inGenericContext == 0:
  612. var e = semConstBoolExpr(c, it.sons[0])
  613. if e.kind != nkIntLit: internalError(c.config, e.info, "semRecordNodeAux")
  614. elif e.intVal != 0 and branch == nil: branch = it.sons[1]
  615. else:
  616. it.sons[0] = forceBool(c, semExprWithType(c, it.sons[0]))
  617. of nkElse:
  618. checkSonsLen(it, 1, c.config)
  619. if branch == nil: branch = it.sons[0]
  620. idx = 0
  621. else: illFormedAst(n, c.config)
  622. if c.inGenericContext > 0:
  623. # use a new check intset here for each branch:
  624. var newCheck: IntSet
  625. assign(newCheck, check)
  626. var newPos = pos
  627. var newf = newNodeI(nkRecList, n.info)
  628. semRecordNodeAux(c, it.sons[idx], newCheck, newPos, newf, rectype)
  629. it.sons[idx] = if newf.len == 1: newf[0] else: newf
  630. if c.inGenericContext > 0:
  631. addSon(father, n)
  632. elif branch != nil:
  633. semRecordNodeAux(c, branch, check, pos, father, rectype)
  634. of nkRecCase:
  635. semRecordCase(c, n, check, pos, father, rectype)
  636. of nkNilLit:
  637. if father.kind != nkRecList: addSon(father, newNodeI(nkRecList, n.info))
  638. of nkRecList:
  639. # attempt to keep the nesting at a sane level:
  640. var a = if father.kind == nkRecList: father else: copyNode(n)
  641. for i in 0 ..< sonsLen(n):
  642. semRecordNodeAux(c, n.sons[i], check, pos, a, rectype)
  643. if a != father: addSon(father, a)
  644. of nkIdentDefs:
  645. checkMinSonsLen(n, 3, c.config)
  646. var length = sonsLen(n)
  647. var a: PNode
  648. if father.kind != nkRecList and length>=4: a = newNodeI(nkRecList, n.info)
  649. else: a = newNodeI(nkEmpty, n.info)
  650. if n.sons[length-1].kind != nkEmpty:
  651. localError(c.config, n.sons[length-1].info, errInitHereNotAllowed)
  652. var typ: PType
  653. if n.sons[length-2].kind == nkEmpty:
  654. localError(c.config, n.info, errTypeExpected)
  655. typ = errorType(c)
  656. else:
  657. typ = semTypeNode(c, n.sons[length-2], nil)
  658. propagateToOwner(rectype, typ)
  659. var fieldOwner = if c.inGenericContext > 0: c.getCurrOwner
  660. else: rectype.sym
  661. for i in 0 .. sonsLen(n)-3:
  662. var f = semIdentWithPragma(c, skField, n.sons[i], {sfExported})
  663. suggestSym(c.config, n.sons[i].info, f, c.graph.usageSym)
  664. f.typ = typ
  665. f.position = pos
  666. if fieldOwner != nil and
  667. {sfImportc, sfExportc} * fieldOwner.flags != {} and
  668. not hasCaseFields and f.loc.r == nil:
  669. f.loc.r = rope(f.name.s)
  670. f.flags = f.flags + ({sfImportc, sfExportc} * fieldOwner.flags)
  671. inc(pos)
  672. if containsOrIncl(check, f.name.id):
  673. localError(c.config, n.sons[i].info, "attempt to redefine: '" & f.name.s & "'")
  674. if a.kind == nkEmpty: addSon(father, newSymNode(f))
  675. else: addSon(a, newSymNode(f))
  676. styleCheckDef(c.config, f)
  677. onDef(f.info, f)
  678. if a.kind != nkEmpty: addSon(father, a)
  679. of nkSym:
  680. # This branch only valid during generic object
  681. # inherited from generic/partial specialized parent second check.
  682. # There is no branch validity check here
  683. if containsOrIncl(check, n.sym.name.id):
  684. localError(c.config, n.info, "attempt to redefine: '" & n.sym.name.s & "'")
  685. addSon(father, n)
  686. of nkEmpty: discard
  687. else: illFormedAst(n, c.config)
  688. proc addInheritedFieldsAux(c: PContext, check: var IntSet, pos: var int,
  689. n: PNode) =
  690. case n.kind
  691. of nkRecCase:
  692. if (n.sons[0].kind != nkSym): internalError(c.config, n.info, "addInheritedFieldsAux")
  693. addInheritedFieldsAux(c, check, pos, n.sons[0])
  694. for i in 1 ..< sonsLen(n):
  695. case n.sons[i].kind
  696. of nkOfBranch, nkElse:
  697. addInheritedFieldsAux(c, check, pos, lastSon(n.sons[i]))
  698. else: internalError(c.config, n.info, "addInheritedFieldsAux(record case branch)")
  699. of nkRecList, nkRecWhen, nkElifBranch, nkElse:
  700. for i in 0 ..< sonsLen(n):
  701. addInheritedFieldsAux(c, check, pos, n.sons[i])
  702. of nkSym:
  703. incl(check, n.sym.name.id)
  704. inc(pos)
  705. else: internalError(c.config, n.info, "addInheritedFieldsAux()")
  706. proc skipGenericInvocation(t: PType): PType {.inline.} =
  707. result = t
  708. if result.kind == tyGenericInvocation:
  709. result = result.sons[0]
  710. while result.kind in {tyGenericInst, tyGenericBody, tyRef, tyPtr, tyAlias, tySink, tyOwned}:
  711. result = lastSon(result)
  712. proc addInheritedFields(c: PContext, check: var IntSet, pos: var int,
  713. obj: PType) =
  714. assert obj.kind == tyObject
  715. if (sonsLen(obj) > 0) and (obj.sons[0] != nil):
  716. addInheritedFields(c, check, pos, obj.sons[0].skipGenericInvocation)
  717. addInheritedFieldsAux(c, check, pos, obj.n)
  718. proc semObjectNode(c: PContext, n: PNode, prev: PType; isInheritable: bool): PType =
  719. if n.sonsLen == 0:
  720. return newConstraint(c, tyObject)
  721. var check = initIntSet()
  722. var pos = 0
  723. var base, realBase: PType = nil
  724. # n.sons[0] contains the pragmas (if any). We process these later...
  725. checkSonsLen(n, 3, c.config)
  726. if n.sons[1].kind != nkEmpty:
  727. realBase = semTypeNode(c, n.sons[1].sons[0], nil)
  728. base = skipTypesOrNil(realBase, skipPtrs)
  729. if base.isNil:
  730. localError(c.config, n.info, "cannot inherit from a type that is not an object type")
  731. else:
  732. var concreteBase = skipGenericInvocation(base)
  733. if concreteBase.kind in {tyObject, tyGenericParam,
  734. tyGenericInvocation} and tfFinal notin concreteBase.flags:
  735. # we only check fields duplication of object inherited from
  736. # concrete object. If inheriting from generic object or partial
  737. # specialized object, there will be second check after instantiation
  738. # located in semGeneric.
  739. if concreteBase.kind == tyObject:
  740. addInheritedFields(c, check, pos, concreteBase)
  741. else:
  742. if concreteBase.kind != tyError:
  743. localError(c.config, n.sons[1].info, "inheritance only works with non-final objects; " &
  744. "to enable inheritance write '" & typeToString(realBase) & " of RootObj'")
  745. base = nil
  746. realBase = nil
  747. if n.kind != nkObjectTy: internalError(c.config, n.info, "semObjectNode")
  748. result = newOrPrevType(tyObject, prev, c)
  749. rawAddSon(result, realBase)
  750. if realBase == nil and isInheritable:
  751. result.flags.incl tfInheritable
  752. if result.n.isNil:
  753. result.n = newNodeI(nkRecList, n.info)
  754. else:
  755. # partial object so add things to the check
  756. addInheritedFields(c, check, pos, result)
  757. semRecordNodeAux(c, n.sons[2], check, pos, result.n, result)
  758. if n.sons[0].kind != nkEmpty:
  759. # dummy symbol for `pragma`:
  760. var s = newSymS(skType, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  761. s.typ = result
  762. pragma(c, s, n.sons[0], typePragmas)
  763. if base == nil and tfInheritable notin result.flags:
  764. incl(result.flags, tfFinal)
  765. proc semAnyRef(c: PContext; n: PNode; kind: TTypeKind; prev: PType): PType =
  766. if n.len < 1:
  767. result = newConstraint(c, kind)
  768. else:
  769. let isCall = int ord(n.kind in nkCallKinds+{nkBracketExpr})
  770. let n = if n[0].kind == nkBracket: n[0] else: n
  771. checkMinSonsLen(n, 1, c.config)
  772. let body = n.lastSon
  773. var t = if prev != nil and body.kind == nkObjectTy and tfInheritable in prev.flags:
  774. semObjectNode(c, body, nil, isInheritable=true)
  775. else:
  776. semTypeNode(c, body, nil)
  777. if t.kind == tyTypeDesc and tfUnresolved notin t.flags:
  778. t = t.base
  779. if t.kind == tyVoid:
  780. const kindToStr: array[tyPtr..tyRef, string] = ["ptr", "ref"]
  781. localError(c.config, n.info, "type '$1 void' is not allowed" % kindToStr[kind])
  782. result = newOrPrevType(kind, prev, c)
  783. var isNilable = false
  784. # check every except the last is an object:
  785. for i in isCall .. n.len-2:
  786. let ni = n[i]
  787. if ni.kind == nkNilLit:
  788. isNilable = true
  789. else:
  790. let region = semTypeNode(c, ni, nil)
  791. if region.skipTypes({tyGenericInst, tyAlias, tySink}).kind notin {
  792. tyError, tyObject}:
  793. message c.config, n[i].info, errGenerated, "region needs to be an object type"
  794. else:
  795. message(c.config, n.info, warnDeprecated, "region for pointer types is deprecated")
  796. addSonSkipIntLit(result, region)
  797. addSonSkipIntLit(result, t)
  798. if tfPartial in result.flags:
  799. if result.lastSon.kind == tyObject: incl(result.lastSon.flags, tfPartial)
  800. #if not isNilable: result.flags.incl tfNotNil
  801. proc findEnforcedStaticType(t: PType): PType =
  802. # This handles types such as `static[T] and Foo`,
  803. # which are subset of `static[T]`, hence they could
  804. # be treated in the same way
  805. if t == nil: return nil
  806. if t.kind == tyStatic: return t
  807. if t.kind == tyAnd:
  808. for s in t.sons:
  809. let t = findEnforcedStaticType(s)
  810. if t != nil: return t
  811. proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind) =
  812. if kind == skMacro:
  813. let staticType = findEnforcedStaticType(param.typ)
  814. if staticType != nil:
  815. var a = copySym(param)
  816. a.typ = staticType.base
  817. addDecl(c, a)
  818. #elif param.typ != nil and param.typ.kind == tyTypeDesc:
  819. # addDecl(c, param)
  820. else:
  821. # within a macro, every param has the type NimNode!
  822. let nn = getSysSym(c.graph, param.info, "NimNode")
  823. var a = copySym(param)
  824. a.typ = nn.typ
  825. addDecl(c, a)
  826. else:
  827. if sfGenSym in param.flags:
  828. # bug #XXX, fix the gensym'ed parameters owner:
  829. if param.owner == nil:
  830. param.owner = getCurrOwner(c)
  831. else: addDecl(c, param)
  832. template shouldHaveMeta(t) =
  833. internalAssert c.config, tfHasMeta in t.flags
  834. # result.lastSon.flags.incl tfHasMeta
  835. proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode,
  836. paramType: PType, paramName: string,
  837. info: TLineInfo, anon = false): PType =
  838. if paramType == nil: return # (e.g. proc return type)
  839. proc addImplicitGenericImpl(c: PContext; typeClass: PType, typId: PIdent): PType =
  840. if genericParams == nil:
  841. # This happens with anonymous proc types appearing in signatures
  842. # XXX: we need to lift these earlier
  843. return
  844. let finalTypId = if typId != nil: typId
  845. else: getIdent(c.cache, paramName & ":type")
  846. # is this a bindOnce type class already present in the param list?
  847. for i in 0 ..< genericParams.len:
  848. if genericParams.sons[i].sym.name.id == finalTypId.id:
  849. return genericParams.sons[i].typ
  850. let owner = if typeClass.sym != nil: typeClass.sym
  851. else: getCurrOwner(c)
  852. var s = newSym(skType, finalTypId, owner, info)
  853. if sfExplain in owner.flags: s.flags.incl sfExplain
  854. if typId == nil: s.flags.incl(sfAnon)
  855. s.linkTo(typeClass)
  856. typeClass.flags.incl tfImplicitTypeParam
  857. s.position = genericParams.len
  858. genericParams.addSon(newSymNode(s))
  859. result = typeClass
  860. addDecl(c, s)
  861. # XXX: There are codegen errors if this is turned into a nested proc
  862. template liftingWalk(typ: PType, anonFlag = false): untyped =
  863. liftParamType(c, procKind, genericParams, typ, paramName, info, anonFlag)
  864. #proc liftingWalk(paramType: PType, anon = false): PType =
  865. var paramTypId = if not anon and paramType.sym != nil: paramType.sym.name
  866. else: nil
  867. template maybeLift(typ: PType): untyped =
  868. let lifted = liftingWalk(typ)
  869. (if lifted != nil: lifted else: typ)
  870. template addImplicitGeneric(e): untyped =
  871. addImplicitGenericImpl(c, e, paramTypId)
  872. case paramType.kind:
  873. of tyAnything:
  874. result = addImplicitGenericImpl(c, newTypeS(tyGenericParam, c), nil)
  875. of tyStatic:
  876. if paramType.base.kind != tyNone and paramType.n != nil:
  877. # this is a concrete static value
  878. return
  879. if tfUnresolved in paramType.flags: return # already lifted
  880. let base = paramType.base.maybeLift
  881. if base.isMetaType and procKind == skMacro:
  882. localError(c.config, info, errMacroBodyDependsOnGenericTypes % paramName)
  883. result = addImplicitGeneric(c.newTypeWithSons(tyStatic, @[base]))
  884. if result != nil: result.flags.incl({tfHasStatic, tfUnresolved})
  885. of tyTypeDesc:
  886. if tfUnresolved notin paramType.flags:
  887. # naked typedescs are not bindOnce types
  888. if paramType.base.kind == tyNone and paramTypId != nil and
  889. (paramTypId.id == getIdent(c.cache, "typedesc").id or
  890. paramTypId.id == getIdent(c.cache, "type").id):
  891. # XXX Why doesn't this check for tyTypeDesc instead?
  892. paramTypId = nil
  893. let t = c.newTypeWithSons(tyTypeDesc, @[paramType.base])
  894. incl t.flags, tfCheckedForDestructor
  895. result = addImplicitGeneric(t)
  896. of tyDistinct:
  897. if paramType.sonsLen == 1:
  898. # disable the bindOnce behavior for the type class
  899. result = liftingWalk(paramType.base, true)
  900. of tyAlias, tyOwned:
  901. result = liftingWalk(paramType.base)
  902. of tySequence, tySet, tyArray, tyOpenArray,
  903. tyVar, tyLent, tyPtr, tyRef, tyProc:
  904. # XXX: this is a bit strange, but proc(s: seq)
  905. # produces tySequence(tyGenericParam, tyNone).
  906. # This also seems to be true when creating aliases
  907. # like: type myseq = distinct seq.
  908. # Maybe there is another better place to associate
  909. # the seq type class with the seq identifier.
  910. if paramType.kind == tySequence and paramType.lastSon.kind == tyNone:
  911. let typ = c.newTypeWithSons(tyBuiltInTypeClass,
  912. @[newTypeS(paramType.kind, c)])
  913. result = addImplicitGeneric(typ)
  914. else:
  915. for i in 0 ..< paramType.len:
  916. if paramType.sons[i] == paramType:
  917. globalError(c.config, info, errIllegalRecursionInTypeX % typeToString(paramType))
  918. var lifted = liftingWalk(paramType.sons[i])
  919. if lifted != nil:
  920. paramType.sons[i] = lifted
  921. result = paramType
  922. of tyGenericBody:
  923. result = newTypeS(tyGenericInvocation, c)
  924. result.rawAddSon(paramType)
  925. for i in 0 .. paramType.sonsLen - 2:
  926. if paramType.sons[i].kind == tyStatic:
  927. var staticCopy = paramType.sons[i].exactReplica
  928. staticCopy.flags.incl tfInferrableStatic
  929. result.rawAddSon staticCopy
  930. else:
  931. result.rawAddSon newTypeS(tyAnything, c)
  932. if paramType.lastSon.kind == tyUserTypeClass:
  933. result.kind = tyUserTypeClassInst
  934. result.rawAddSon paramType.lastSon
  935. return addImplicitGeneric(result)
  936. let x = instGenericContainer(c, paramType.sym.info, result,
  937. allowMetaTypes = true)
  938. result = newTypeWithSons(c, tyCompositeTypeClass, @[paramType, x])
  939. #result = newTypeS(tyCompositeTypeClass, c)
  940. #for i in 0..<x.len: result.rawAddSon(x.sons[i])
  941. result = addImplicitGeneric(result)
  942. of tyGenericInst:
  943. if paramType.lastSon.kind == tyUserTypeClass:
  944. var cp = copyType(paramType, getCurrOwner(c), false)
  945. cp.kind = tyUserTypeClassInst
  946. return addImplicitGeneric(cp)
  947. for i in 1 .. paramType.len-2:
  948. var lifted = liftingWalk(paramType.sons[i])
  949. if lifted != nil:
  950. paramType.sons[i] = lifted
  951. result = paramType
  952. result.lastSon.shouldHaveMeta
  953. let liftBody = liftingWalk(paramType.lastSon, true)
  954. if liftBody != nil:
  955. result = liftBody
  956. result.flags.incl tfHasMeta
  957. #result.shouldHaveMeta
  958. of tyGenericInvocation:
  959. for i in 1 ..< paramType.len:
  960. let lifted = liftingWalk(paramType.sons[i])
  961. if lifted != nil: paramType.sons[i] = lifted
  962. let body = paramType.base
  963. if body.kind in {tyForward, tyError}:
  964. # this may happen for proc type appearing in a type section
  965. # before one of its param types
  966. return
  967. if body.lastSon.kind == tyUserTypeClass:
  968. let expanded = instGenericContainer(c, info, paramType,
  969. allowMetaTypes = true)
  970. result = liftingWalk(expanded, true)
  971. of tyUserTypeClasses, tyBuiltInTypeClass, tyCompositeTypeClass,
  972. tyAnd, tyOr, tyNot:
  973. result = addImplicitGeneric(copyType(paramType, getCurrOwner(c), false))
  974. of tyGenericParam:
  975. markUsed(c.config, paramType.sym.info, paramType.sym, c.graph.usageSym)
  976. onUse(paramType.sym.info, paramType.sym)
  977. if tfWildcard in paramType.flags:
  978. paramType.flags.excl tfWildcard
  979. paramType.sym.kind = skType
  980. else: discard
  981. # result = liftingWalk(paramType)
  982. proc semParamType(c: PContext, n: PNode, constraint: var PNode): PType =
  983. if n.kind == nkCurlyExpr:
  984. result = semTypeNode(c, n.sons[0], nil)
  985. constraint = semNodeKindConstraints(n, c.config, 1)
  986. elif n.kind == nkCall and
  987. n[0].kind in {nkIdent, nkSym, nkOpenSymChoice, nkClosedSymChoice} and
  988. considerQuotedIdent(c, n[0]).s == "{}":
  989. result = semTypeNode(c, n[1], nil)
  990. constraint = semNodeKindConstraints(n, c.config, 2)
  991. else:
  992. result = semTypeNode(c, n, nil)
  993. proc newProcType(c: PContext; info: TLineInfo; prev: PType = nil): PType =
  994. result = newOrPrevType(tyProc, prev, c)
  995. result.callConv = lastOptionEntry(c).defaultCC
  996. result.n = newNodeI(nkFormalParams, info)
  997. rawAddSon(result, nil) # return type
  998. # result.n[0] used to be `nkType`, but now it's `nkEffectList` because
  999. # the effects are now stored in there too ... this is a bit hacky, but as
  1000. # usual we desperately try to save memory:
  1001. addSon(result.n, newNodeI(nkEffectList, info))
  1002. proc semProcTypeNode(c: PContext, n, genericParams: PNode,
  1003. prev: PType, kind: TSymKind; isType=false): PType =
  1004. # for historical reasons (code grows) this is invoked for parameter
  1005. # lists too and then 'isType' is false.
  1006. checkMinSonsLen(n, 1, c.config)
  1007. result = newProcType(c, n.info, prev)
  1008. var check = initIntSet()
  1009. var counter = 0
  1010. for i in 1 ..< n.len:
  1011. var a = n.sons[i]
  1012. if a.kind != nkIdentDefs:
  1013. # for some generic instantiations the passed ':env' parameter
  1014. # for closures has already been produced (see bug #898). We simply
  1015. # skip this parameter here. It'll then be re-generated in another LL
  1016. # pass over this instantiation:
  1017. if a.kind == nkSym and sfFromGeneric in a.sym.flags: continue
  1018. illFormedAst(a, c.config)
  1019. checkMinSonsLen(a, 3, c.config)
  1020. var
  1021. typ: PType = nil
  1022. def: PNode = nil
  1023. constraint: PNode = nil
  1024. length = sonsLen(a)
  1025. hasType = a.sons[length-2].kind != nkEmpty
  1026. hasDefault = a.sons[length-1].kind != nkEmpty
  1027. if hasType:
  1028. typ = semParamType(c, a.sons[length-2], constraint)
  1029. var owner = getCurrOwner(c).owner
  1030. # TODO: Disallow typed/untyped in procs in the compiler/stdlib
  1031. if (owner.kind != skModule or owner.owner.name.s != "stdlib") and
  1032. kind == skProc and (typ.kind == tyTyped or typ.kind == tyUntyped):
  1033. localError(c.config, a.sons[length-2].info, "'" & typ.sym.name.s & "' is only allowed in templates and macros")
  1034. if hasDefault:
  1035. def = a[^1]
  1036. block determineType:
  1037. if genericParams != nil and genericParams.len > 0:
  1038. def = semGenericStmt(c, def)
  1039. if hasUnresolvedArgs(c, def):
  1040. def.typ = makeTypeFromExpr(c, def.copyTree)
  1041. break determineType
  1042. def = semExprWithType(c, def, {efDetermineType})
  1043. if def.referencesAnotherParam(getCurrOwner(c)):
  1044. def.flags.incl nfDefaultRefsParam
  1045. if typ == nil:
  1046. typ = def.typ
  1047. if isEmptyContainer(typ):
  1048. localError(c.config, a.info, "cannot infer the type of parameter '" & a[0].ident.s & "'")
  1049. if typ.kind == tyTypeDesc:
  1050. # consider a proc such as:
  1051. # proc takesType(T = int)
  1052. # a naive analysis may conclude that the proc type is type[int]
  1053. # which will prevent other types from matching - clearly a very
  1054. # surprising behavior. We must instead fix the expected type of
  1055. # the proc to be the unbound typedesc type:
  1056. typ = newTypeWithSons(c, tyTypeDesc, @[newTypeS(tyNone, c)])
  1057. typ.flags.incl tfCheckedForDestructor
  1058. else:
  1059. # if def.typ != nil and def.typ.kind != tyNone:
  1060. # example code that triggers it:
  1061. # proc sort[T](cmp: proc(a, b: T): int = cmp)
  1062. if not containsGenericType(typ):
  1063. # check type compatibility between def.typ and typ:
  1064. def = fitNode(c, typ, def, def.info)
  1065. elif typ.kind == tyStatic:
  1066. def = semConstExpr(c, def)
  1067. def = fitNode(c, typ, def, def.info)
  1068. if not hasType and not hasDefault:
  1069. if isType: localError(c.config, a.info, "':' expected")
  1070. if kind in {skTemplate, skMacro}:
  1071. typ = newTypeS(tyUntyped, c)
  1072. elif skipTypes(typ, {tyGenericInst, tyAlias, tySink}).kind == tyVoid:
  1073. continue
  1074. for j in 0 .. length-3:
  1075. var arg = newSymG(skParam, a.sons[j], c)
  1076. if not hasType and not hasDefault and kind notin {skTemplate, skMacro}:
  1077. let param = strTableGet(c.signatures, arg.name)
  1078. if param != nil: typ = param.typ
  1079. else:
  1080. localError(c.config, a.info, "typeless parameters are obsolete")
  1081. typ = errorType(c)
  1082. let lifted = liftParamType(c, kind, genericParams, typ,
  1083. arg.name.s, arg.info)
  1084. let finalType = if lifted != nil: lifted else: typ.skipIntLit
  1085. arg.typ = finalType
  1086. arg.position = counter
  1087. arg.constraint = constraint
  1088. inc(counter)
  1089. if def != nil and def.kind != nkEmpty:
  1090. arg.ast = copyTree(def)
  1091. if containsOrIncl(check, arg.name.id):
  1092. localError(c.config, a.sons[j].info, "attempt to redefine: '" & arg.name.s & "'")
  1093. addSon(result.n, newSymNode(arg))
  1094. rawAddSon(result, finalType)
  1095. addParamOrResult(c, arg, kind)
  1096. styleCheckDef(c.config, a.sons[j].info, arg)
  1097. onDef(a[j].info, arg)
  1098. var r: PType
  1099. if n.sons[0].kind != nkEmpty:
  1100. r = semTypeNode(c, n.sons[0], nil)
  1101. if r != nil and kind in {skMacro, skTemplate} and r.kind == tyTyped:
  1102. # XXX: To implement the propesed change in the warning, just
  1103. # delete this entire if block. The rest is (at least at time of
  1104. # writing this comment) already implemented.
  1105. let info = n.sons[0].info
  1106. const msg = "`typed` will change its meaning in future versions of Nim. " &
  1107. "`void` or no return type declaration at all has the same " &
  1108. "meaning as the current meaning of `typed` as return type " &
  1109. "declaration."
  1110. message(c.config, info, warnDeprecated, msg)
  1111. r = nil
  1112. if r != nil:
  1113. # turn explicit 'void' return type into 'nil' because the rest of the
  1114. # compiler only checks for 'nil':
  1115. if skipTypes(r, {tyGenericInst, tyAlias, tySink}).kind != tyVoid:
  1116. if kind notin {skMacro, skTemplate} and r.kind in {tyTyped, tyUntyped}:
  1117. localError(c.config, n.sons[0].info, "return type '" & typeToString(r) &
  1118. "' is only valid for macros and templates")
  1119. # 'auto' as a return type does not imply a generic:
  1120. elif r.kind == tyAnything:
  1121. # 'p(): auto' and 'p(): expr' are equivalent, but the rest of the
  1122. # compiler is hardly aware of 'auto':
  1123. r = newTypeS(tyUntyped, c)
  1124. else:
  1125. if r.sym == nil or sfAnon notin r.sym.flags:
  1126. let lifted = liftParamType(c, kind, genericParams, r, "result",
  1127. n.sons[0].info)
  1128. if lifted != nil:
  1129. r = lifted
  1130. #if r.kind != tyGenericParam:
  1131. #echo "came here for ", typeToString(r)
  1132. r.flags.incl tfRetType
  1133. r = skipIntLit(r)
  1134. if kind == skIterator:
  1135. # see tchainediterators
  1136. # in cases like iterator foo(it: iterator): type(it)
  1137. # we don't need to change the return type to iter[T]
  1138. result.flags.incl tfIterator
  1139. # XXX Would be nice if we could get rid of this
  1140. result.sons[0] = r
  1141. let oldFlags = result.flags
  1142. propagateToOwner(result, r)
  1143. if oldFlags != result.flags:
  1144. # XXX This rather hacky way keeps 'tflatmap' compiling:
  1145. if tfHasMeta notin oldFlags:
  1146. result.flags.excl tfHasMeta
  1147. result.n.typ = r
  1148. if genericParams != nil and genericParams.len > 0:
  1149. for n in genericParams:
  1150. if {sfUsed, sfAnon} * n.sym.flags == {}:
  1151. result.flags.incl tfUnresolved
  1152. if tfWildcard in n.sym.typ.flags:
  1153. n.sym.kind = skType
  1154. n.sym.typ.flags.excl tfWildcard
  1155. proc semStmtListType(c: PContext, n: PNode, prev: PType): PType =
  1156. checkMinSonsLen(n, 1, c.config)
  1157. var length = sonsLen(n)
  1158. for i in 0 .. length - 2:
  1159. n.sons[i] = semStmt(c, n.sons[i], {})
  1160. if length > 0:
  1161. result = semTypeNode(c, n.sons[length - 1], prev)
  1162. n.typ = result
  1163. n.sons[length - 1].typ = result
  1164. else:
  1165. result = nil
  1166. proc semBlockType(c: PContext, n: PNode, prev: PType): PType =
  1167. inc(c.p.nestedBlockCounter)
  1168. checkSonsLen(n, 2, c.config)
  1169. openScope(c)
  1170. if n.sons[0].kind notin {nkEmpty, nkSym}:
  1171. addDecl(c, newSymS(skLabel, n.sons[0], c))
  1172. result = semStmtListType(c, n.sons[1], prev)
  1173. n.sons[1].typ = result
  1174. n.typ = result
  1175. closeScope(c)
  1176. dec(c.p.nestedBlockCounter)
  1177. proc semGenericParamInInvocation(c: PContext, n: PNode): PType =
  1178. result = semTypeNode(c, n, nil)
  1179. n.typ = makeTypeDesc(c, result)
  1180. proc semObjectTypeForInheritedGenericInst(c: PContext, n: PNode, t: PType) =
  1181. var
  1182. check = initIntSet()
  1183. pos = 0
  1184. let
  1185. realBase = t.sons[0]
  1186. base = skipTypesOrNil(realBase, skipPtrs)
  1187. if base.isNil:
  1188. localError(c.config, n.info, errIllegalRecursionInTypeX % "object")
  1189. else:
  1190. let concreteBase = skipGenericInvocation(base)
  1191. if concreteBase.kind == tyObject and tfFinal notin concreteBase.flags:
  1192. addInheritedFields(c, check, pos, concreteBase)
  1193. else:
  1194. if concreteBase.kind != tyError:
  1195. localError(c.config, n.info, errInheritanceOnlyWithNonFinalObjects)
  1196. var newf = newNodeI(nkRecList, n.info)
  1197. semRecordNodeAux(c, t.n, check, pos, newf, t)
  1198. proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType =
  1199. if s.typ == nil:
  1200. localError(c.config, n.info, "cannot instantiate the '$1' $2" %
  1201. [s.name.s, ($s.kind).substr(2).toLowerAscii])
  1202. return newOrPrevType(tyError, prev, c)
  1203. var t = s.typ
  1204. if t.kind == tyCompositeTypeClass and t.base.kind == tyGenericBody:
  1205. t = t.base
  1206. result = newOrPrevType(tyGenericInvocation, prev, c)
  1207. addSonSkipIntLit(result, t)
  1208. template addToResult(typ) =
  1209. if typ.isNil:
  1210. internalAssert c.config, false
  1211. rawAddSon(result, typ)
  1212. else: addSonSkipIntLit(result, typ)
  1213. if t.kind == tyForward:
  1214. for i in 1 ..< sonsLen(n):
  1215. var elem = semGenericParamInInvocation(c, n.sons[i])
  1216. addToResult(elem)
  1217. return
  1218. elif t.kind != tyGenericBody:
  1219. # we likely got code of the form TypeA[TypeB] where TypeA is
  1220. # not generic.
  1221. localError(c.config, n.info, errNoGenericParamsAllowedForX % s.name.s)
  1222. return newOrPrevType(tyError, prev, c)
  1223. else:
  1224. var m = newCandidate(c, t)
  1225. m.isNoCall = true
  1226. matches(c, n, copyTree(n), m)
  1227. if m.state != csMatch:
  1228. let err = "cannot instantiate " & typeToString(t) & "\n" &
  1229. "got: <" & describeArgs(c, n) & ">\n" &
  1230. "but expected: <" & describeArgs(c, t.n, 0) & ">"
  1231. localError(c.config, n.info, errGenerated, err)
  1232. return newOrPrevType(tyError, prev, c)
  1233. var isConcrete = true
  1234. for i in 1 ..< m.call.len:
  1235. var typ = m.call[i].typ
  1236. if typ.kind == tyTypeDesc and typ.sons[0].kind == tyNone:
  1237. isConcrete = false
  1238. addToResult(typ)
  1239. else:
  1240. typ = typ.skipTypes({tyTypeDesc})
  1241. if containsGenericType(typ): isConcrete = false
  1242. addToResult(typ)
  1243. if isConcrete:
  1244. if s.ast == nil and s.typ.kind != tyCompositeTypeClass:
  1245. # XXX: What kind of error is this? is it still relevant?
  1246. localError(c.config, n.info, errCannotInstantiateX % s.name.s)
  1247. result = newOrPrevType(tyError, prev, c)
  1248. else:
  1249. result = instGenericContainer(c, n.info, result,
  1250. allowMetaTypes = false)
  1251. # special check for generic object with
  1252. # generic/partial specialized parent
  1253. let tx = result.skipTypes(abstractPtrs, 50)
  1254. if tx.isNil or isTupleRecursive(tx):
  1255. localError(c.config, n.info, "illegal recursion in type '$1'" % typeToString(result[0]))
  1256. return errorType(c)
  1257. if tx != result and tx.kind == tyObject and tx.sons[0] != nil:
  1258. semObjectTypeForInheritedGenericInst(c, n, tx)
  1259. proc maybeAliasType(c: PContext; typeExpr, prev: PType): PType =
  1260. if typeExpr.kind in {tyObject, tyEnum, tyDistinct, tyForward} and prev != nil:
  1261. result = newTypeS(tyAlias, c)
  1262. result.rawAddSon typeExpr
  1263. result.sym = prev.sym
  1264. assignType(prev, result)
  1265. proc fixupTypeOf(c: PContext, prev: PType, typExpr: PNode) =
  1266. if prev != nil:
  1267. let result = newTypeS(tyAlias, c)
  1268. result.rawAddSon typExpr.typ
  1269. result.sym = prev.sym
  1270. assignType(prev, result)
  1271. proc semTypeExpr(c: PContext, n: PNode; prev: PType): PType =
  1272. var n = semExprWithType(c, n, {efDetermineType})
  1273. if n.typ.kind == tyTypeDesc:
  1274. result = n.typ.base
  1275. # fix types constructed by macros/template:
  1276. if prev != nil and prev.sym != nil:
  1277. if result.sym.isNil:
  1278. # Behold! you're witnessing enormous power yielded
  1279. # by macros. Only macros can summon unnamed types
  1280. # and cast spell upon AST. Here we need to give
  1281. # it a name taken from left hand side's node
  1282. result.sym = prev.sym
  1283. result.sym.typ = result
  1284. else:
  1285. # Less powerful routine like template do not have
  1286. # the ability to produce unnamed types. But still
  1287. # it has wild power to push a type a bit too far.
  1288. # So we need to hold it back using alias and prevent
  1289. # unnecessary new type creation
  1290. let alias = maybeAliasType(c, result, prev)
  1291. if alias != nil: result = alias
  1292. else:
  1293. localError(c.config, n.info, "expected type, but got: " & n.renderTree)
  1294. result = errorType(c)
  1295. proc freshType(res, prev: PType): PType {.inline.} =
  1296. if prev.isNil:
  1297. result = copyType(res, res.owner, keepId=false)
  1298. else:
  1299. result = res
  1300. template modifierTypeKindOfNode(n: PNode): TTypeKind =
  1301. case n.kind
  1302. of nkVarTy: tyVar
  1303. of nkRefTy: tyRef
  1304. of nkPtrTy: tyPtr
  1305. of nkStaticTy: tyStatic
  1306. of nkTypeOfExpr: tyTypeDesc
  1307. else: tyNone
  1308. proc semTypeClass(c: PContext, n: PNode, prev: PType): PType =
  1309. # if n.sonsLen == 0: return newConstraint(c, tyTypeClass)
  1310. let
  1311. pragmas = n[1]
  1312. inherited = n[2]
  1313. result = newOrPrevType(tyUserTypeClass, prev, c)
  1314. result.flags.incl tfCheckedForDestructor
  1315. var owner = getCurrOwner(c)
  1316. var candidateTypeSlot = newTypeWithSons(owner, tyAlias, @[c.errorType])
  1317. result.sons = @[candidateTypeSlot]
  1318. result.n = n
  1319. if inherited.kind != nkEmpty:
  1320. for n in inherited.sons:
  1321. let typ = semTypeNode(c, n, nil)
  1322. result.sons.add(typ)
  1323. openScope(c)
  1324. for param in n[0]:
  1325. var
  1326. dummyName: PNode
  1327. dummyType: PType
  1328. let modifier = param.modifierTypeKindOfNode
  1329. if modifier != tyNone:
  1330. dummyName = param[0]
  1331. dummyType = c.makeTypeWithModifier(modifier, candidateTypeSlot)
  1332. if modifier == tyTypeDesc:
  1333. dummyType.flags.incl tfConceptMatchedTypeSym
  1334. dummyType.flags.incl tfCheckedForDestructor
  1335. else:
  1336. dummyName = param
  1337. dummyType = candidateTypeSlot
  1338. # this can be true for 'nim check' on incomplete concepts,
  1339. # see bug #8230
  1340. if dummyName.kind == nkEmpty: continue
  1341. internalAssert c.config, dummyName.kind == nkIdent
  1342. var dummyParam = newSym(if modifier == tyTypeDesc: skType else: skVar,
  1343. dummyName.ident, owner, param.info)
  1344. dummyParam.typ = dummyType
  1345. incl dummyParam.flags, sfUsed
  1346. addDecl(c, dummyParam)
  1347. result.n[3] = semConceptBody(c, n[3])
  1348. closeScope(c)
  1349. proc semProcTypeWithScope(c: PContext, n: PNode,
  1350. prev: PType, kind: TSymKind): PType =
  1351. checkSonsLen(n, 2, c.config)
  1352. openScope(c)
  1353. result = semProcTypeNode(c, n.sons[0], nil, prev, kind, isType=true)
  1354. # start with 'ccClosure', but of course pragmas can overwrite this:
  1355. result.callConv = ccClosure
  1356. # dummy symbol for `pragma`:
  1357. var s = newSymS(kind, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  1358. s.typ = result
  1359. if n.sons[1].kind != nkEmpty and n.sons[1].len > 0:
  1360. pragma(c, s, n.sons[1], procTypePragmas)
  1361. when useEffectSystem: setEffectsForProcType(c.graph, result, n.sons[1])
  1362. closeScope(c)
  1363. proc symFromExpectedTypeNode(c: PContext, n: PNode): PSym =
  1364. if n.kind == nkType:
  1365. result = symFromType(c, n.typ, n.info)
  1366. else:
  1367. localError(c.config, n.info, errTypeExpected)
  1368. result = errorSym(c, n)
  1369. proc semStaticType(c: PContext, childNode: PNode, prev: PType): PType =
  1370. result = newOrPrevType(tyStatic, prev, c)
  1371. var base = semTypeNode(c, childNode, nil).skipTypes({tyTypeDesc, tyAlias})
  1372. result.rawAddSon(base)
  1373. result.flags.incl tfHasStatic
  1374. proc semTypeof(c: PContext; n: PNode; prev: PType): PType =
  1375. openScope(c)
  1376. let t = semExprWithType(c, n, {efInTypeof})
  1377. closeScope(c)
  1378. fixupTypeOf(c, prev, t)
  1379. result = t.typ
  1380. proc semTypeof2(c: PContext; n: PNode; prev: PType): PType =
  1381. openScope(c)
  1382. var m = BiggestInt 1 # typeOfIter
  1383. if n.len == 3:
  1384. let mode = semConstExpr(c, n[2])
  1385. if mode.kind != nkIntLit:
  1386. localError(c.config, n.info, "typeof: cannot evaluate 'mode' parameter at compile-time")
  1387. else:
  1388. m = mode.intVal
  1389. let t = semExprWithType(c, n[1], if m == 1: {efInTypeof} else: {})
  1390. closeScope(c)
  1391. fixupTypeOf(c, prev, t)
  1392. result = t.typ
  1393. proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
  1394. result = nil
  1395. inc c.inTypeContext
  1396. if c.config.cmd == cmdIdeTools: suggestExpr(c, n)
  1397. case n.kind
  1398. of nkEmpty: result = n.typ
  1399. of nkTypeOfExpr:
  1400. # for ``type(countup(1,3))``, see ``tests/ttoseq``.
  1401. checkSonsLen(n, 1, c.config)
  1402. result = semTypeof(c, n.sons[0], prev)
  1403. if result.kind == tyTypeDesc: result.flags.incl tfExplicit
  1404. of nkPar:
  1405. if sonsLen(n) == 1: result = semTypeNode(c, n.sons[0], prev)
  1406. else:
  1407. result = semAnonTuple(c, n, prev)
  1408. of nkTupleConstr: result = semAnonTuple(c, n, prev)
  1409. of nkCallKinds:
  1410. let x = n[0]
  1411. let ident = case x.kind
  1412. of nkIdent: x.ident
  1413. of nkSym: x.sym.name
  1414. of nkClosedSymChoice, nkOpenSymChoice: x[0].sym.name
  1415. else: nil
  1416. if ident != nil and ident.s == "[]":
  1417. let b = newNodeI(nkBracketExpr, n.info)
  1418. for i in 1..<n.len: b.add(n[i])
  1419. result = semTypeNode(c, b, prev)
  1420. elif ident != nil and ident.id == ord(wDotDot):
  1421. result = semRangeAux(c, n, prev)
  1422. elif n[0].kind == nkNilLit and n.len == 2:
  1423. result = semTypeNode(c, n.sons[1], prev)
  1424. if result.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).kind in NilableTypes+GenericTypes:
  1425. if tfNotNil in result.flags:
  1426. result = freshType(result, prev)
  1427. result.flags.excl(tfNotNil)
  1428. else:
  1429. localError(c.config, n.info, errGenerated, "invalid type")
  1430. elif n[0].kind notin nkIdentKinds:
  1431. result = semTypeExpr(c, n, prev)
  1432. else:
  1433. let op = considerQuotedIdent(c, n.sons[0])
  1434. if op.id in {ord(wAnd), ord(wOr)} or op.s == "|":
  1435. checkSonsLen(n, 3, c.config)
  1436. var
  1437. t1 = semTypeNode(c, n.sons[1], nil)
  1438. t2 = semTypeNode(c, n.sons[2], nil)
  1439. if t1 == nil:
  1440. localError(c.config, n.sons[1].info, errTypeExpected)
  1441. result = newOrPrevType(tyError, prev, c)
  1442. elif t2 == nil:
  1443. localError(c.config, n.sons[2].info, errTypeExpected)
  1444. result = newOrPrevType(tyError, prev, c)
  1445. else:
  1446. result = if op.id == ord(wAnd): makeAndType(c, t1, t2)
  1447. else: makeOrType(c, t1, t2)
  1448. elif op.id == ord(wNot):
  1449. case n.len
  1450. of 3:
  1451. result = semTypeNode(c, n.sons[1], prev)
  1452. if result.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).kind in NilableTypes+GenericTypes+{tyForward} and
  1453. n.sons[2].kind == nkNilLit:
  1454. result = freshType(result, prev)
  1455. result.flags.incl(tfNotNil)
  1456. if notnil notin c.features:
  1457. localError(c.config, n.info, "enable the 'not nil' annotation with {.experimental: \"notnil\".}")
  1458. else:
  1459. localError(c.config, n.info, errGenerated, "invalid type")
  1460. of 2:
  1461. let negated = semTypeNode(c, n.sons[1], prev)
  1462. result = makeNotType(c, negated)
  1463. else:
  1464. localError(c.config, n.info, errGenerated, "invalid type")
  1465. elif op.id == ord(wPtr):
  1466. result = semAnyRef(c, n, tyPtr, prev)
  1467. elif op.id == ord(wRef):
  1468. result = semAnyRef(c, n, tyRef, prev)
  1469. elif op.id == ord(wType):
  1470. checkSonsLen(n, 2, c.config)
  1471. result = semTypeof(c, n[1], prev)
  1472. elif op.s == "typeof" and n[0].kind == nkSym and n[0].sym.magic == mTypeof:
  1473. result = semTypeOf2(c, n, prev)
  1474. else:
  1475. if c.inGenericContext > 0 and n.kind == nkCall:
  1476. result = makeTypeFromExpr(c, n.copyTree)
  1477. else:
  1478. result = semTypeExpr(c, n, prev)
  1479. of nkWhenStmt:
  1480. var whenResult = semWhen(c, n, false)
  1481. if whenResult.kind == nkStmtList: whenResult.kind = nkStmtListType
  1482. result = semTypeNode(c, whenResult, prev)
  1483. of nkBracketExpr:
  1484. checkMinSonsLen(n, 2, c.config)
  1485. var head = n.sons[0]
  1486. var s = if head.kind notin nkCallKinds: semTypeIdent(c, head)
  1487. else: symFromExpectedTypeNode(c, semExpr(c, head))
  1488. case s.magic
  1489. of mArray: result = semArray(c, n, prev)
  1490. of mOpenArray: result = semContainer(c, n, tyOpenArray, "openarray", prev)
  1491. of mUncheckedArray: result = semContainer(c, n, tyUncheckedArray, "UncheckedArray", prev)
  1492. of mRange: result = semRange(c, n, prev)
  1493. of mSet: result = semSet(c, n, prev)
  1494. of mOrdinal: result = semOrdinal(c, n, prev)
  1495. of mSeq:
  1496. if c.config.selectedGc == gcDestructors and optNimV2 notin c.config.globalOptions:
  1497. let s = c.graph.sysTypes[tySequence]
  1498. assert s != nil
  1499. assert prev == nil
  1500. result = copyType(s, s.owner, keepId=false)
  1501. # Remove the 'T' parameter from tySequence:
  1502. result.sons.setLen 0
  1503. result.n = nil
  1504. result.flags = {tfHasAsgn}
  1505. semContainerArg(c, n, "seq", result)
  1506. if result.len > 0:
  1507. var base = result[0]
  1508. if base.kind in {tyGenericInst, tyAlias, tySink}: base = lastSon(base)
  1509. if not containsGenericType(base):
  1510. # base.kind != tyGenericParam:
  1511. c.typesWithOps.add((result, result))
  1512. else:
  1513. result = semContainer(c, n, tySequence, "seq", prev)
  1514. if c.config.selectedGc == gcDestructors:
  1515. incl result.flags, tfHasAsgn
  1516. of mOpt: result = semContainer(c, n, tyOpt, "opt", prev)
  1517. of mVarargs: result = semVarargs(c, n, prev)
  1518. of mTypeDesc, mType, mTypeOf:
  1519. result = makeTypeDesc(c, semTypeNode(c, n[1], nil))
  1520. result.flags.incl tfExplicit
  1521. of mStatic:
  1522. result = semStaticType(c, n[1], prev)
  1523. of mExpr:
  1524. result = semTypeNode(c, n.sons[0], nil)
  1525. if result != nil:
  1526. result = copyType(result, getCurrOwner(c), false)
  1527. for i in 1 ..< n.len:
  1528. result.rawAddSon(semTypeNode(c, n.sons[i], nil))
  1529. of mDistinct:
  1530. result = newOrPrevType(tyDistinct, prev, c)
  1531. addSonSkipIntLit(result, semTypeNode(c, n[1], nil))
  1532. of mVar:
  1533. result = newOrPrevType(tyVar, prev, c)
  1534. var base = semTypeNode(c, n.sons[1], nil)
  1535. if base.kind in {tyVar, tyLent}:
  1536. localError(c.config, n.info, "type 'var var' is not allowed")
  1537. base = base.sons[0]
  1538. addSonSkipIntLit(result, base)
  1539. of mRef: result = semAnyRef(c, n, tyRef, prev)
  1540. of mPtr: result = semAnyRef(c, n, tyPtr, prev)
  1541. of mTuple: result = semTuple(c, n, prev)
  1542. else: result = semGeneric(c, n, s, prev)
  1543. of nkDotExpr:
  1544. let typeExpr = semExpr(c, n)
  1545. if typeExpr.typ.isNil:
  1546. localError(c.config, n.info, "object constructor needs an object type;" &
  1547. " for named arguments use '=' instead of ':'")
  1548. result = errorType(c)
  1549. elif typeExpr.typ.kind == tyFromExpr:
  1550. result = typeExpr.typ
  1551. elif typeExpr.typ.kind != tyTypeDesc:
  1552. localError(c.config, n.info, errTypeExpected)
  1553. result = errorType(c)
  1554. else:
  1555. result = typeExpr.typ.base
  1556. if result.isMetaType and
  1557. result.kind != tyUserTypeClass:
  1558. # the dot expression may refer to a concept type in
  1559. # a different module. allow a normal alias then.
  1560. let preprocessed = semGenericStmt(c, n)
  1561. result = makeTypeFromExpr(c, preprocessed.copyTree)
  1562. else:
  1563. let alias = maybeAliasType(c, result, prev)
  1564. if alias != nil: result = alias
  1565. of nkIdent, nkAccQuoted:
  1566. var s = semTypeIdent(c, n)
  1567. if s.typ == nil:
  1568. if s.kind != skError: localError(c.config, n.info, errTypeExpected)
  1569. result = newOrPrevType(tyError, prev, c)
  1570. elif s.kind == skParam and s.typ.kind == tyTypeDesc:
  1571. internalAssert c.config, s.typ.base.kind != tyNone and prev == nil
  1572. result = s.typ.base
  1573. elif prev == nil:
  1574. result = s.typ
  1575. else:
  1576. let alias = maybeAliasType(c, s.typ, prev)
  1577. if alias != nil:
  1578. result = alias
  1579. else:
  1580. assignType(prev, s.typ)
  1581. # bugfix: keep the fresh id for aliases to integral types:
  1582. if s.typ.kind notin {tyBool, tyChar, tyInt..tyInt64, tyFloat..tyFloat128,
  1583. tyUInt..tyUInt64}:
  1584. prev.id = s.typ.id
  1585. result = prev
  1586. of nkSym:
  1587. let s = getGenSym(c, n.sym)
  1588. if s.typ != nil and (s.kind == skType or s.typ.kind == tyTypeDesc):
  1589. var t =
  1590. if s.kind == skType:
  1591. s.typ
  1592. else:
  1593. internalAssert c.config, s.typ.base.kind != tyNone and prev == nil
  1594. s.typ.base
  1595. let alias = maybeAliasType(c, t, prev)
  1596. if alias != nil:
  1597. result = alias
  1598. elif prev == nil:
  1599. result = t
  1600. else:
  1601. assignType(prev, t)
  1602. result = prev
  1603. markUsed(c.config, n.info, n.sym, c.graph.usageSym)
  1604. onUse(n.info, n.sym)
  1605. else:
  1606. if s.kind != skError: localError(c.config, n.info, errTypeExpected)
  1607. result = newOrPrevType(tyError, prev, c)
  1608. of nkObjectTy: result = semObjectNode(c, n, prev, isInheritable=false)
  1609. of nkTupleTy: result = semTuple(c, n, prev)
  1610. of nkTupleClassTy: result = newConstraint(c, tyTuple)
  1611. of nkTypeClassTy: result = semTypeClass(c, n, prev)
  1612. of nkRefTy: result = semAnyRef(c, n, tyRef, prev)
  1613. of nkPtrTy: result = semAnyRef(c, n, tyPtr, prev)
  1614. of nkVarTy: result = semVarType(c, n, prev)
  1615. of nkDistinctTy: result = semDistinct(c, n, prev)
  1616. of nkStaticTy: result = semStaticType(c, n[0], prev)
  1617. of nkIteratorTy:
  1618. if n.sonsLen == 0:
  1619. result = newTypeS(tyBuiltInTypeClass, c)
  1620. let child = newTypeS(tyProc, c)
  1621. child.flags.incl tfIterator
  1622. result.addSonSkipIntLit(child)
  1623. else:
  1624. result = semProcTypeWithScope(c, n, prev, skIterator)
  1625. result.flags.incl(tfIterator)
  1626. if n.lastSon.kind == nkPragma and hasPragma(n.lastSon, wInline):
  1627. result.callConv = ccInline
  1628. else:
  1629. result.callConv = ccClosure
  1630. of nkProcTy:
  1631. if n.sonsLen == 0:
  1632. result = newConstraint(c, tyProc)
  1633. else:
  1634. result = semProcTypeWithScope(c, n, prev, skProc)
  1635. of nkEnumTy: result = semEnum(c, n, prev)
  1636. of nkType: result = n.typ
  1637. of nkStmtListType: result = semStmtListType(c, n, prev)
  1638. of nkBlockType: result = semBlockType(c, n, prev)
  1639. else:
  1640. localError(c.config, n.info, errTypeExpected)
  1641. result = newOrPrevType(tyError, prev, c)
  1642. n.typ = result
  1643. dec c.inTypeContext
  1644. if false: # c.inTypeContext == 0:
  1645. #if $n == "var seq[StackTraceEntry]":
  1646. # echo "begin ", n
  1647. instAllTypeBoundOp(c, n.info)
  1648. proc setMagicType(conf: ConfigRef; m: PSym, kind: TTypeKind, size: int) =
  1649. # source : https://en.wikipedia.org/wiki/Data_structure_alignment#x86
  1650. m.typ.kind = kind
  1651. m.typ.size = size
  1652. # this usually works for most basic types
  1653. # Assuming that since ARM, ARM64 don't support unaligned access
  1654. # data is aligned to type size
  1655. m.typ.align = size.int16
  1656. # FIXME: proper support for clongdouble should be added.
  1657. # long double size can be 8, 10, 12, 16 bytes depending on platform & compiler
  1658. if conf.target.targetCPU == cpuI386 and size == 8:
  1659. #on Linux/BSD i386, double are aligned to 4bytes (except with -malign-double)
  1660. if kind in {tyFloat64, tyFloat} and
  1661. conf.target.targetOS in {osLinux, osAndroid, osNetbsd, osFreebsd, osOpenbsd, osDragonfly}:
  1662. m.typ.align = 4
  1663. # on i386, all known compiler, 64bits ints are aligned to 4bytes (except with -malign-double)
  1664. elif kind in {tyInt, tyUInt, tyInt64, tyUInt64}:
  1665. m.typ.align = 4
  1666. else:
  1667. discard
  1668. proc setMagicIntegral(conf: ConfigRef; m: PSym, kind: TTypeKind, size: int) =
  1669. setMagicType(conf, m, kind, size)
  1670. incl m.typ.flags, tfCheckedForDestructor
  1671. proc processMagicType(c: PContext, m: PSym) =
  1672. case m.magic
  1673. of mInt: setMagicIntegral(c.config, m, tyInt, c.config.target.intSize)
  1674. of mInt8: setMagicIntegral(c.config, m, tyInt8, 1)
  1675. of mInt16: setMagicIntegral(c.config, m, tyInt16, 2)
  1676. of mInt32: setMagicIntegral(c.config, m, tyInt32, 4)
  1677. of mInt64: setMagicIntegral(c.config, m, tyInt64, 8)
  1678. of mUInt: setMagicIntegral(c.config, m, tyUInt, c.config.target.intSize)
  1679. of mUInt8: setMagicIntegral(c.config, m, tyUInt8, 1)
  1680. of mUInt16: setMagicIntegral(c.config, m, tyUInt16, 2)
  1681. of mUInt32: setMagicIntegral(c.config, m, tyUInt32, 4)
  1682. of mUInt64: setMagicIntegral(c.config, m, tyUInt64, 8)
  1683. of mFloat: setMagicIntegral(c.config, m, tyFloat, c.config.target.floatSize)
  1684. of mFloat32: setMagicIntegral(c.config, m, tyFloat32, 4)
  1685. of mFloat64: setMagicIntegral(c.config, m, tyFloat64, 8)
  1686. of mFloat128: setMagicIntegral(c.config, m, tyFloat128, 16)
  1687. of mBool: setMagicIntegral(c.config, m, tyBool, 1)
  1688. of mChar: setMagicIntegral(c.config, m, tyChar, 1)
  1689. of mString:
  1690. setMagicType(c.config, m, tyString, szUncomputedSize)
  1691. rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
  1692. if c.config.selectedGc == gcDestructors:
  1693. incl m.typ.flags, tfHasAsgn
  1694. of mCstring:
  1695. setMagicIntegral(c.config, m, tyCString, c.config.target.ptrSize)
  1696. rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
  1697. of mPointer: setMagicIntegral(c.config, m, tyPointer, c.config.target.ptrSize)
  1698. of mEmptySet:
  1699. setMagicIntegral(c.config, m, tySet, 1)
  1700. rawAddSon(m.typ, newTypeS(tyEmpty, c))
  1701. of mIntSetBaseType: setMagicIntegral(c.config, m, tyRange, c.config.target.intSize)
  1702. of mNil: setMagicType(c.config, m, tyNil, c.config.target.ptrSize)
  1703. of mExpr:
  1704. if m.name.s == "auto":
  1705. setMagicIntegral(c.config, m, tyAnything, 0)
  1706. else:
  1707. setMagicIntegral(c.config, m, tyUntyped, 0)
  1708. of mStmt:
  1709. setMagicIntegral(c.config, m, tyTyped, 0)
  1710. of mTypeDesc, mType:
  1711. setMagicIntegral(c.config, m, tyTypeDesc, 0)
  1712. rawAddSon(m.typ, newTypeS(tyNone, c))
  1713. of mStatic:
  1714. setMagicType(c.config, m, tyStatic, 0)
  1715. rawAddSon(m.typ, newTypeS(tyNone, c))
  1716. of mVoidType:
  1717. setMagicIntegral(c.config, m, tyVoid, 0)
  1718. of mArray:
  1719. setMagicType(c.config, m, tyArray, szUncomputedSize)
  1720. of mOpenArray:
  1721. setMagicType(c.config, m, tyOpenArray, szUncomputedSize)
  1722. of mVarargs:
  1723. setMagicType(c.config, m, tyVarargs, szUncomputedSize)
  1724. of mRange:
  1725. setMagicIntegral(c.config, m, tyRange, szUncomputedSize)
  1726. rawAddSon(m.typ, newTypeS(tyNone, c))
  1727. of mSet:
  1728. setMagicIntegral(c.config, m, tySet, szUncomputedSize)
  1729. of mUncheckedArray:
  1730. setMagicIntegral(c.config, m, tyUncheckedArray, szUncomputedSize)
  1731. of mSeq:
  1732. setMagicType(c.config, m, tySequence, szUncomputedSize)
  1733. if c.config.selectedGc == gcDestructors:
  1734. incl m.typ.flags, tfHasAsgn
  1735. assert c.graph.sysTypes[tySequence] == nil
  1736. c.graph.sysTypes[tySequence] = m.typ
  1737. of mOpt:
  1738. setMagicType(c.config, m, tyOpt, szUncomputedSize)
  1739. of mOrdinal:
  1740. setMagicIntegral(c.config, m, tyOrdinal, szUncomputedSize)
  1741. rawAddSon(m.typ, newTypeS(tyNone, c))
  1742. of mPNimrodNode:
  1743. incl m.typ.flags, tfTriggersCompileTime
  1744. incl m.typ.flags, tfCheckedForDestructor
  1745. of mException: discard
  1746. of mBuiltinType:
  1747. case m.name.s
  1748. of "lent": setMagicType(c.config, m, tyLent, c.config.target.ptrSize)
  1749. of "sink": setMagicType(c.config, m, tySink, szUncomputedSize)
  1750. of "owned":
  1751. setMagicType(c.config, m, tyOwned, c.config.target.ptrSize)
  1752. incl m.typ.flags, tfHasOwned
  1753. else: localError(c.config, m.info, errTypeExpected)
  1754. else: localError(c.config, m.info, errTypeExpected)
  1755. proc semGenericConstraints(c: PContext, x: PType): PType =
  1756. result = newTypeWithSons(c, tyGenericParam, @[x])
  1757. proc semGenericParamList(c: PContext, n: PNode, father: PType = nil): PNode =
  1758. result = copyNode(n)
  1759. if n.kind != nkGenericParams:
  1760. illFormedAst(n, c.config)
  1761. return
  1762. for i in 0 ..< sonsLen(n):
  1763. var a = n.sons[i]
  1764. if a.kind != nkIdentDefs: illFormedAst(n, c.config)
  1765. let L = a.len
  1766. var def = a[^1]
  1767. let constraint = a[^2]
  1768. var typ: PType
  1769. if constraint.kind != nkEmpty:
  1770. typ = semTypeNode(c, constraint, nil)
  1771. if typ.kind != tyStatic or typ.len == 0:
  1772. if typ.kind == tyTypeDesc:
  1773. if typ.sons[0].kind == tyNone:
  1774. typ = newTypeWithSons(c, tyTypeDesc, @[newTypeS(tyNone, c)])
  1775. incl typ.flags, tfCheckedForDestructor
  1776. else:
  1777. typ = semGenericConstraints(c, typ)
  1778. if def.kind != nkEmpty:
  1779. def = semConstExpr(c, def)
  1780. if typ == nil:
  1781. if def.typ.kind != tyTypeDesc:
  1782. typ = newTypeWithSons(c, tyStatic, @[def.typ])
  1783. else:
  1784. # the following line fixes ``TV2*[T:SomeNumber=TR] = array[0..1, T]``
  1785. # from manyloc/named_argument_bug/triengine:
  1786. def.typ = def.typ.skipTypes({tyTypeDesc})
  1787. if not containsGenericType(def.typ):
  1788. def = fitNode(c, typ, def, def.info)
  1789. if typ == nil:
  1790. typ = newTypeS(tyGenericParam, c)
  1791. if father == nil: typ.flags.incl tfWildcard
  1792. typ.flags.incl tfGenericTypeParam
  1793. for j in 0 .. L-3:
  1794. let finalType = if j == 0: typ
  1795. else: copyType(typ, typ.owner, false)
  1796. # it's important the we create an unique
  1797. # type for each generic param. the index
  1798. # of the parameter will be stored in the
  1799. # attached symbol.
  1800. var paramName = a.sons[j]
  1801. var covarianceFlag = tfUnresolved
  1802. if paramName.safeLen == 2:
  1803. if not nimEnableCovariance or paramName[0].ident.s == "in":
  1804. if father == nil or sfImportc notin father.sym.flags:
  1805. localError(c.config, paramName.info, errInOutFlagNotExtern % $paramName[0])
  1806. covarianceFlag = if paramName[0].ident.s == "in": tfContravariant
  1807. else: tfCovariant
  1808. if father != nil: father.flags.incl tfCovariant
  1809. paramName = paramName[1]
  1810. var s = if finalType.kind == tyStatic or tfWildcard in typ.flags:
  1811. newSymG(skGenericParam, paramName, c).linkTo(finalType)
  1812. else:
  1813. newSymG(skType, paramName, c).linkTo(finalType)
  1814. if covarianceFlag != tfUnresolved: s.typ.flags.incl(covarianceFlag)
  1815. if def.kind != nkEmpty: s.ast = def
  1816. if father != nil: addSonSkipIntLit(father, s.typ)
  1817. s.position = result.len
  1818. addSon(result, newSymNode(s))
  1819. if sfGenSym notin s.flags: addDecl(c, s)