semtypes.nim 82 KB

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