semtypes.nim 71 KB

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