semtypes.nim 87 KB

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