semtypes.nim 75 KB

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