semtypes.nim 86 KB

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