semtypes.nim 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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 or prev.kind == tyGenericBody:
  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 a = copyTree(n)
  724. var branch: PNode = nil # the branch to take
  725. for i in 0..<a.len:
  726. var it = a[i]
  727. if it == nil: illFormedAst(n, c.config)
  728. var idx = 1
  729. case it.kind
  730. of nkElifBranch:
  731. checkSonsLen(it, 2, c.config)
  732. if c.inGenericContext == 0:
  733. var e = semConstBoolExpr(c, it[0])
  734. if e.kind != nkIntLit: discard "don't report followup error"
  735. elif e.intVal != 0 and branch == nil: branch = it[1]
  736. else:
  737. it[0] = forceBool(c, semExprWithType(c, it[0]))
  738. of nkElse:
  739. checkSonsLen(it, 1, c.config)
  740. if branch == nil: branch = it[0]
  741. idx = 0
  742. else: illFormedAst(n, c.config)
  743. if c.inGenericContext > 0:
  744. # use a new check intset here for each branch:
  745. var newCheck: IntSet
  746. assign(newCheck, check)
  747. var newPos = pos
  748. var newf = newNodeI(nkRecList, n.info)
  749. semRecordNodeAux(c, it[idx], newCheck, newPos, newf, rectype, hasCaseFields)
  750. it[idx] = if newf.len == 1: newf[0] else: newf
  751. if c.inGenericContext > 0:
  752. father.add a
  753. elif branch != nil:
  754. semRecordNodeAux(c, branch, check, pos, father, rectype, hasCaseFields)
  755. elif father.kind in {nkElse, nkOfBranch}:
  756. father.add newNodeI(nkRecList, n.info)
  757. of nkRecCase:
  758. semRecordCase(c, n, check, pos, father, rectype)
  759. of nkNilLit:
  760. if father.kind != nkRecList: father.add newNodeI(nkRecList, n.info)
  761. of nkRecList:
  762. # attempt to keep the nesting at a sane level:
  763. var a = if father.kind == nkRecList: father else: copyNode(n)
  764. for i in 0..<n.len:
  765. semRecordNodeAux(c, n[i], check, pos, a, rectype, hasCaseFields)
  766. if a != father: father.add a
  767. of nkIdentDefs:
  768. checkMinSonsLen(n, 3, c.config)
  769. var a: PNode
  770. if father.kind != nkRecList and n.len >= 4: a = newNodeI(nkRecList, n.info)
  771. else: a = newNodeI(nkEmpty, n.info)
  772. var typ: PType
  773. var hasDefaultField = n[^1].kind != nkEmpty
  774. if hasDefaultField:
  775. typ = fitDefaultNode(c, n)
  776. propagateToOwner(rectype, typ)
  777. elif n[^2].kind == nkEmpty:
  778. localError(c.config, n.info, errTypeExpected)
  779. typ = errorType(c)
  780. else:
  781. typ = semTypeNode(c, n[^2], nil)
  782. if c.graph.config.isDefined("nimPreviewRangeDefault") and typ.skipTypes(abstractInst).kind == tyRange:
  783. n[^1] = newIntNode(nkIntLit, firstOrd(c.config, typ))
  784. n[^1].typ = typ
  785. hasDefaultField = true
  786. propagateToOwner(rectype, typ)
  787. var fieldOwner = if c.inGenericContext > 0: c.getCurrOwner
  788. else: rectype.sym
  789. for i in 0..<n.len-2:
  790. var f = semIdentWithPragma(c, skField, n[i], {sfExported})
  791. let info = if n[i].kind == nkPostfix:
  792. n[i][1].info
  793. else:
  794. n[i].info
  795. suggestSym(c.graph, info, f, c.graph.usageSym)
  796. f.typ = typ
  797. f.position = pos
  798. f.options = c.config.options
  799. if fieldOwner != nil and
  800. {sfImportc, sfExportc} * fieldOwner.flags != {} and
  801. not hasCaseFields and f.loc.r == "":
  802. f.loc.r = rope(f.name.s)
  803. f.flags.incl {sfImportc, sfExportc} * fieldOwner.flags
  804. inc(pos)
  805. if containsOrIncl(check, f.name.id):
  806. localError(c.config, info, "attempt to redefine: '" & f.name.s & "'")
  807. let fSym = newSymNode(f)
  808. if hasDefaultField:
  809. fSym.sym.ast = n[^1]
  810. fSym.sym.ast.flags.incl nfUseDefaultField
  811. if a.kind == nkEmpty: father.add fSym
  812. else: a.add fSym
  813. styleCheckDef(c, f)
  814. onDef(f.info, f)
  815. if a.kind != nkEmpty: father.add a
  816. of nkSym:
  817. # This branch only valid during generic object
  818. # inherited from generic/partial specialized parent second check.
  819. # There is no branch validity check here
  820. if containsOrIncl(check, n.sym.name.id):
  821. localError(c.config, n.info, "attempt to redefine: '" & n.sym.name.s & "'")
  822. father.add n
  823. of nkEmpty:
  824. if father.kind in {nkElse, nkOfBranch}:
  825. father.add n
  826. else: illFormedAst(n, c.config)
  827. proc addInheritedFieldsAux(c: PContext, check: var IntSet, pos: var int,
  828. n: PNode) =
  829. case n.kind
  830. of nkRecCase:
  831. if (n[0].kind != nkSym): internalError(c.config, n.info, "addInheritedFieldsAux")
  832. addInheritedFieldsAux(c, check, pos, n[0])
  833. for i in 1..<n.len:
  834. case n[i].kind
  835. of nkOfBranch, nkElse:
  836. addInheritedFieldsAux(c, check, pos, lastSon(n[i]))
  837. else: internalError(c.config, n.info, "addInheritedFieldsAux(record case branch)")
  838. of nkRecList, nkRecWhen, nkElifBranch, nkElse:
  839. for i in int(n.kind == nkElifBranch)..<n.len:
  840. addInheritedFieldsAux(c, check, pos, n[i])
  841. of nkSym:
  842. incl(check, n.sym.name.id)
  843. inc(pos)
  844. else: internalError(c.config, n.info, "addInheritedFieldsAux()")
  845. proc skipGenericInvocation(t: PType): PType {.inline.} =
  846. result = t
  847. if result.kind == tyGenericInvocation:
  848. result = result[0]
  849. while result.kind in {tyGenericInst, tyGenericBody, tyRef, tyPtr, tyAlias, tySink, tyOwned}:
  850. result = lastSon(result)
  851. proc addInheritedFields(c: PContext, check: var IntSet, pos: var int,
  852. obj: PType) =
  853. assert obj.kind == tyObject
  854. if (obj.len > 0) and (obj[0] != nil):
  855. addInheritedFields(c, check, pos, obj[0].skipGenericInvocation)
  856. addInheritedFieldsAux(c, check, pos, obj.n)
  857. proc semObjectNode(c: PContext, n: PNode, prev: PType; flags: TTypeFlags): PType =
  858. if n.len == 0:
  859. return newConstraint(c, tyObject)
  860. var check = initIntSet()
  861. var pos = 0
  862. var base, realBase: PType = nil
  863. # n[0] contains the pragmas (if any). We process these later...
  864. checkSonsLen(n, 3, c.config)
  865. if n[1].kind != nkEmpty:
  866. realBase = semTypeNode(c, n[1][0], nil)
  867. base = skipTypesOrNil(realBase, skipPtrs)
  868. if base.isNil:
  869. localError(c.config, n.info, "cannot inherit from a type that is not an object type")
  870. else:
  871. var concreteBase = skipGenericInvocation(base)
  872. if concreteBase.kind in {tyObject, tyGenericParam,
  873. tyGenericInvocation} and tfFinal notin concreteBase.flags:
  874. # we only check fields duplication of object inherited from
  875. # concrete object. If inheriting from generic object or partial
  876. # specialized object, there will be second check after instantiation
  877. # located in semGeneric.
  878. if concreteBase.kind == tyObject:
  879. if concreteBase.sym != nil and concreteBase.sym.magic == mException and
  880. sfSystemModule notin c.module.flags:
  881. message(c.config, n.info, warnInheritFromException, "")
  882. addInheritedFields(c, check, pos, concreteBase)
  883. else:
  884. if concreteBase.kind != tyError:
  885. localError(c.config, n[1].info, "inheritance only works with non-final objects; " &
  886. "for " & typeToString(realBase) & " to be inheritable it must be " &
  887. "'object of RootObj' instead of 'object'")
  888. base = nil
  889. realBase = nil
  890. if n.kind != nkObjectTy: internalError(c.config, n.info, "semObjectNode")
  891. result = newOrPrevType(tyObject, prev, c)
  892. rawAddSon(result, realBase)
  893. if realBase == nil and tfInheritable in flags:
  894. result.flags.incl tfInheritable
  895. if tfAcyclic in flags: result.flags.incl tfAcyclic
  896. if result.n.isNil:
  897. result.n = newNodeI(nkRecList, n.info)
  898. else:
  899. # partial object so add things to the check
  900. addInheritedFields(c, check, pos, result)
  901. semRecordNodeAux(c, n[2], check, pos, result.n, result)
  902. if n[0].kind != nkEmpty:
  903. # dummy symbol for `pragma`:
  904. var s = newSymS(skType, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  905. s.typ = result
  906. pragma(c, s, n[0], typePragmas)
  907. if base == nil and tfInheritable notin result.flags:
  908. incl(result.flags, tfFinal)
  909. if c.inGenericContext == 0 and computeRequiresInit(c, result):
  910. result.flags.incl tfRequiresInit
  911. proc semAnyRef(c: PContext; n: PNode; kind: TTypeKind; prev: PType): PType =
  912. if n.len < 1:
  913. result = newConstraint(c, kind)
  914. else:
  915. let isCall = int ord(n.kind in nkCallKinds+{nkBracketExpr})
  916. let n = if n[0].kind == nkBracket: n[0] else: n
  917. checkMinSonsLen(n, 1, c.config)
  918. let body = n.lastSon
  919. var t = if prev != nil and prev.kind != tyGenericBody and body.kind == nkObjectTy:
  920. semObjectNode(c, body, nil, prev.flags)
  921. else:
  922. semTypeNode(c, body, nil)
  923. if t.kind == tyTypeDesc and tfUnresolved notin t.flags:
  924. t = t.base
  925. if t.kind == tyVoid:
  926. localError(c.config, n.info, "type '$1 void' is not allowed" % kind.toHumanStr)
  927. result = newOrPrevType(kind, prev, c)
  928. var isNilable = false
  929. var wrapperKind = tyNone
  930. # check every except the last is an object:
  931. for i in isCall..<n.len-1:
  932. let ni = n[i]
  933. # echo "semAnyRef ", "n: ", n, "i: ", i, "ni: ", ni
  934. if ni.kind == nkNilLit:
  935. isNilable = true
  936. else:
  937. let region = semTypeNode(c, ni, nil)
  938. if region.kind in {tyOwned, tySink}:
  939. wrapperKind = region.kind
  940. elif region.skipTypes({tyGenericInst, tyAlias, tySink}).kind notin {
  941. tyError, tyObject}:
  942. message c.config, n[i].info, errGenerated, "region needs to be an object type"
  943. addSonSkipIntLit(result, region, c.idgen)
  944. else:
  945. message(c.config, n.info, warnDeprecated, "region for pointer types is deprecated")
  946. addSonSkipIntLit(result, region, c.idgen)
  947. addSonSkipIntLit(result, t, c.idgen)
  948. if tfPartial in result.flags:
  949. if result.lastSon.kind == tyObject: incl(result.lastSon.flags, tfPartial)
  950. # if not isNilable: result.flags.incl tfNotNil
  951. case wrapperKind
  952. of tyOwned:
  953. if optOwnedRefs in c.config.globalOptions:
  954. let t = newTypeS(tyOwned, c)
  955. t.flags.incl tfHasOwned
  956. t.rawAddSonNoPropagationOfTypeFlags result
  957. result = t
  958. of tySink:
  959. let t = newTypeS(tySink, c)
  960. t.rawAddSonNoPropagationOfTypeFlags result
  961. result = t
  962. else: discard
  963. if result.kind == tyRef and c.config.selectedGC in {gcArc, gcOrc}:
  964. result.flags.incl tfHasAsgn
  965. proc findEnforcedStaticType(t: PType): PType =
  966. # This handles types such as `static[T] and Foo`,
  967. # which are subset of `static[T]`, hence they could
  968. # be treated in the same way
  969. if t == nil: return nil
  970. if t.kind == tyStatic: return t
  971. if t.kind == tyAnd:
  972. for s in t.sons:
  973. let t = findEnforcedStaticType(s)
  974. if t != nil: return t
  975. proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind) =
  976. if kind == skMacro:
  977. let staticType = findEnforcedStaticType(param.typ)
  978. if staticType != nil:
  979. var a = copySym(param, nextSymId c.idgen)
  980. a.typ = staticType.base
  981. addDecl(c, a)
  982. #elif param.typ != nil and param.typ.kind == tyTypeDesc:
  983. # addDecl(c, param)
  984. else:
  985. # within a macro, every param has the type NimNode!
  986. let nn = getSysSym(c.graph, param.info, "NimNode")
  987. var a = copySym(param, nextSymId c.idgen)
  988. a.typ = nn.typ
  989. addDecl(c, a)
  990. else:
  991. if sfGenSym in param.flags:
  992. # bug #XXX, fix the gensym'ed parameters owner:
  993. if param.owner == nil:
  994. param.owner = getCurrOwner(c)
  995. else: addDecl(c, param)
  996. template shouldHaveMeta(t) =
  997. internalAssert c.config, tfHasMeta in t.flags
  998. # result.lastSon.flags.incl tfHasMeta
  999. proc addImplicitGeneric(c: PContext; typeClass: PType, typId: PIdent;
  1000. info: TLineInfo; genericParams: PNode;
  1001. paramName: string): PType =
  1002. if genericParams == nil:
  1003. # This happens with anonymous proc types appearing in signatures
  1004. # XXX: we need to lift these earlier
  1005. return
  1006. let finalTypId = if typId != nil: typId
  1007. else: getIdent(c.cache, paramName & ":type")
  1008. # is this a bindOnce type class already present in the param list?
  1009. for i in 0..<genericParams.len:
  1010. if genericParams[i].sym.name.id == finalTypId.id:
  1011. return genericParams[i].typ
  1012. let owner = if typeClass.sym != nil: typeClass.sym
  1013. else: getCurrOwner(c)
  1014. var s = newSym(skType, finalTypId, nextSymId c.idgen, owner, info)
  1015. if sfExplain in owner.flags: s.flags.incl sfExplain
  1016. if typId == nil: s.flags.incl(sfAnon)
  1017. s.linkTo(typeClass)
  1018. typeClass.flags.incl tfImplicitTypeParam
  1019. s.position = genericParams.len
  1020. genericParams.add newSymNode(s)
  1021. result = typeClass
  1022. addDecl(c, s)
  1023. proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode,
  1024. paramType: PType, paramName: string,
  1025. info: TLineInfo, anon = false): PType =
  1026. if paramType == nil: return # (e.g. proc return type)
  1027. template recurse(typ: PType, anonFlag = false): untyped =
  1028. liftParamType(c, procKind, genericParams, typ, paramName, info, anonFlag)
  1029. var paramTypId = if not anon and paramType.sym != nil: paramType.sym.name
  1030. else: nil
  1031. case paramType.kind
  1032. of tyAnything:
  1033. result = addImplicitGeneric(c, newTypeS(tyGenericParam, c), nil, info, genericParams, paramName)
  1034. of tyStatic:
  1035. if paramType.base.kind != tyNone and paramType.n != nil:
  1036. # this is a concrete static value
  1037. return
  1038. if tfUnresolved in paramType.flags: return # already lifted
  1039. let lifted = recurse(paramType.base)
  1040. let base = (if lifted != nil: lifted else: paramType.base)
  1041. if base.isMetaType and procKind == skMacro:
  1042. localError(c.config, info, errMacroBodyDependsOnGenericTypes % paramName)
  1043. result = addImplicitGeneric(c, c.newTypeWithSons(tyStatic, @[base]),
  1044. paramTypId, info, genericParams, paramName)
  1045. if result != nil: result.flags.incl({tfHasStatic, tfUnresolved})
  1046. of tyTypeDesc:
  1047. if tfUnresolved notin paramType.flags:
  1048. # naked typedescs are not bindOnce types
  1049. if paramType.base.kind == tyNone and paramTypId != nil and
  1050. (paramTypId.id == getIdent(c.cache, "typedesc").id or
  1051. paramTypId.id == getIdent(c.cache, "type").id):
  1052. # XXX Why doesn't this check for tyTypeDesc instead?
  1053. paramTypId = nil
  1054. let t = c.newTypeWithSons(tyTypeDesc, @[paramType.base])
  1055. incl t.flags, tfCheckedForDestructor
  1056. result = addImplicitGeneric(c, t, paramTypId, info, genericParams, paramName)
  1057. of tyDistinct:
  1058. if paramType.len == 1:
  1059. # disable the bindOnce behavior for the type class
  1060. result = recurse(paramType.base, true)
  1061. of tyTuple:
  1062. for i in 0..<paramType.len:
  1063. let t = recurse(paramType[i])
  1064. if t != nil:
  1065. paramType[i] = t
  1066. result = paramType
  1067. of tyAlias, tyOwned, tySink:
  1068. result = recurse(paramType.base)
  1069. of tySequence, tySet, tyArray, tyOpenArray,
  1070. tyVar, tyLent, tyPtr, tyRef, tyProc:
  1071. # XXX: this is a bit strange, but proc(s: seq)
  1072. # produces tySequence(tyGenericParam, tyNone).
  1073. # This also seems to be true when creating aliases
  1074. # like: type myseq = distinct seq.
  1075. # Maybe there is another better place to associate
  1076. # the seq type class with the seq identifier.
  1077. if paramType.kind == tySequence and paramType.lastSon.kind == tyNone:
  1078. let typ = c.newTypeWithSons(tyBuiltInTypeClass,
  1079. @[newTypeS(paramType.kind, c)])
  1080. result = addImplicitGeneric(c, typ, paramTypId, info, genericParams, paramName)
  1081. else:
  1082. for i in 0..<paramType.len:
  1083. if paramType[i] == paramType:
  1084. globalError(c.config, info, errIllegalRecursionInTypeX % typeToString(paramType))
  1085. var lifted = recurse(paramType[i])
  1086. if lifted != nil:
  1087. paramType[i] = lifted
  1088. result = paramType
  1089. of tyGenericBody:
  1090. result = newTypeS(tyGenericInvocation, c)
  1091. result.rawAddSon(paramType)
  1092. for i in 0..<paramType.len - 1:
  1093. if paramType[i].kind == tyStatic:
  1094. var staticCopy = paramType[i].exactReplica
  1095. staticCopy.flags.incl tfInferrableStatic
  1096. result.rawAddSon staticCopy
  1097. else:
  1098. result.rawAddSon newTypeS(tyAnything, c)
  1099. if paramType.lastSon.kind == tyUserTypeClass:
  1100. result.kind = tyUserTypeClassInst
  1101. result.rawAddSon paramType.lastSon
  1102. return addImplicitGeneric(c, result, paramTypId, info, genericParams, paramName)
  1103. let x = instGenericContainer(c, paramType.sym.info, result,
  1104. allowMetaTypes = true)
  1105. result = newTypeWithSons(c, tyCompositeTypeClass, @[paramType, x])
  1106. #result = newTypeS(tyCompositeTypeClass, c)
  1107. #for i in 0..<x.len: result.rawAddSon(x[i])
  1108. result = addImplicitGeneric(c, result, paramTypId, info, genericParams, paramName)
  1109. of tyGenericInst:
  1110. if paramType.lastSon.kind == tyUserTypeClass:
  1111. var cp = copyType(paramType, nextTypeId c.idgen, getCurrOwner(c))
  1112. copyTypeProps(c.graph, c.idgen.module, cp, paramType)
  1113. cp.kind = tyUserTypeClassInst
  1114. return addImplicitGeneric(c, cp, paramTypId, info, genericParams, paramName)
  1115. for i in 1..<paramType.len-1:
  1116. var lifted = recurse(paramType[i])
  1117. if lifted != nil:
  1118. paramType[i] = lifted
  1119. result = paramType
  1120. result.lastSon.shouldHaveMeta
  1121. let liftBody = recurse(paramType.lastSon, true)
  1122. if liftBody != nil:
  1123. result = liftBody
  1124. result.flags.incl tfHasMeta
  1125. #result.shouldHaveMeta
  1126. of tyGenericInvocation:
  1127. for i in 1..<paramType.len:
  1128. #if paramType[i].kind != tyTypeDesc:
  1129. let lifted = recurse(paramType[i])
  1130. if lifted != nil: paramType[i] = lifted
  1131. let body = paramType.base
  1132. if body.kind in {tyForward, tyError}:
  1133. # this may happen for proc type appearing in a type section
  1134. # before one of its param types
  1135. return
  1136. if body.lastSon.kind == tyUserTypeClass:
  1137. let expanded = instGenericContainer(c, info, paramType,
  1138. allowMetaTypes = true)
  1139. result = recurse(expanded, true)
  1140. of tyUserTypeClasses, tyBuiltInTypeClass, tyCompositeTypeClass,
  1141. tyAnd, tyOr, tyNot, tyConcept:
  1142. result = addImplicitGeneric(c,
  1143. copyType(paramType, nextTypeId c.idgen, getCurrOwner(c)), paramTypId,
  1144. info, genericParams, paramName)
  1145. of tyGenericParam:
  1146. markUsed(c, paramType.sym.info, paramType.sym)
  1147. onUse(paramType.sym.info, paramType.sym)
  1148. if tfWildcard in paramType.flags:
  1149. paramType.flags.excl tfWildcard
  1150. paramType.sym.transitionGenericParamToType()
  1151. else: discard
  1152. proc semParamType(c: PContext, n: PNode, constraint: var PNode): PType =
  1153. ## Semchecks the type of parameters.
  1154. if n.kind == nkCurlyExpr:
  1155. result = semTypeNode(c, n[0], nil)
  1156. constraint = semNodeKindConstraints(n, c.config, 1)
  1157. elif n.kind == nkCall and
  1158. n[0].kind in {nkIdent, nkSym, nkOpenSymChoice, nkClosedSymChoice} and
  1159. considerQuotedIdent(c, n[0]).s == "{}":
  1160. result = semTypeNode(c, n[1], nil)
  1161. constraint = semNodeKindConstraints(n, c.config, 2)
  1162. else:
  1163. result = semTypeNode(c, n, nil)
  1164. proc newProcType(c: PContext; info: TLineInfo; prev: PType = nil): PType =
  1165. result = newOrPrevType(tyProc, prev, c)
  1166. result.callConv = lastOptionEntry(c).defaultCC
  1167. result.n = newNodeI(nkFormalParams, info)
  1168. rawAddSon(result, nil) # return type
  1169. # result.n[0] used to be `nkType`, but now it's `nkEffectList` because
  1170. # the effects are now stored in there too ... this is a bit hacky, but as
  1171. # usual we desperately try to save memory:
  1172. result.n.add newNodeI(nkEffectList, info)
  1173. proc isMagic(sym: PSym): bool =
  1174. if sym.ast == nil: return false
  1175. let nPragmas = sym.ast[pragmasPos]
  1176. return hasPragma(nPragmas, wMagic)
  1177. proc semProcTypeNode(c: PContext, n, genericParams: PNode,
  1178. prev: PType, kind: TSymKind; isType=false): PType =
  1179. # for historical reasons (code grows) this is invoked for parameter
  1180. # lists too and then 'isType' is false.
  1181. checkMinSonsLen(n, 1, c.config)
  1182. result = newProcType(c, n.info, prev)
  1183. var check = initIntSet()
  1184. var counter = 0
  1185. for i in 1..<n.len:
  1186. var a = n[i]
  1187. if a.kind != nkIdentDefs:
  1188. # for some generic instantiations the passed ':env' parameter
  1189. # for closures has already been produced (see bug #898). We simply
  1190. # skip this parameter here. It'll then be re-generated in another LL
  1191. # pass over this instantiation:
  1192. if a.kind == nkSym and sfFromGeneric in a.sym.flags: continue
  1193. illFormedAst(a, c.config)
  1194. checkMinSonsLen(a, 3, c.config)
  1195. var
  1196. typ: PType = nil
  1197. def: PNode = nil
  1198. constraint: PNode = nil
  1199. hasType = a[^2].kind != nkEmpty
  1200. hasDefault = a[^1].kind != nkEmpty
  1201. if hasType:
  1202. typ = semParamType(c, a[^2], constraint)
  1203. # TODO: Disallow typed/untyped in procs in the compiler/stdlib
  1204. if kind in {skProc, skFunc} and (typ.kind == tyTyped or typ.kind == tyUntyped):
  1205. if not isMagic(getCurrOwner(c)):
  1206. localError(c.config, a[^2].info, "'" & typ.sym.name.s & "' is only allowed in templates and macros or magic procs")
  1207. if hasDefault:
  1208. def = a[^1]
  1209. block determineType:
  1210. if genericParams != nil and genericParams.len > 0:
  1211. def = semGenericStmt(c, def)
  1212. if hasUnresolvedArgs(c, def):
  1213. def.typ = makeTypeFromExpr(c, def.copyTree)
  1214. break determineType
  1215. def = semExprWithType(c, def, {efDetermineType})
  1216. if def.referencesAnotherParam(getCurrOwner(c)):
  1217. def.flags.incl nfDefaultRefsParam
  1218. if typ == nil:
  1219. typ = def.typ
  1220. if isEmptyContainer(typ):
  1221. localError(c.config, a.info, "cannot infer the type of parameter '" & $a[0] & "'")
  1222. if typ.kind == tyTypeDesc:
  1223. # consider a proc such as:
  1224. # proc takesType(T = int)
  1225. # a naive analysis may conclude that the proc type is type[int]
  1226. # which will prevent other types from matching - clearly a very
  1227. # surprising behavior. We must instead fix the expected type of
  1228. # the proc to be the unbound typedesc type:
  1229. typ = newTypeWithSons(c, tyTypeDesc, @[newTypeS(tyNone, c)])
  1230. typ.flags.incl tfCheckedForDestructor
  1231. else:
  1232. # if def.typ != nil and def.typ.kind != tyNone:
  1233. # example code that triggers it:
  1234. # proc sort[T](cmp: proc(a, b: T): int = cmp)
  1235. if not containsGenericType(typ):
  1236. # check type compatibility between def.typ and typ:
  1237. def = fitNode(c, typ, def, def.info)
  1238. elif typ.kind == tyStatic:
  1239. def = semConstExpr(c, def)
  1240. def = fitNode(c, typ, def, def.info)
  1241. if not hasType and not hasDefault:
  1242. if isType: localError(c.config, a.info, "':' expected")
  1243. if kind in {skTemplate, skMacro}:
  1244. typ = newTypeS(tyUntyped, c)
  1245. elif skipTypes(typ, {tyGenericInst, tyAlias, tySink}).kind == tyVoid:
  1246. continue
  1247. for j in 0..<a.len-2:
  1248. var arg = newSymG(skParam, if a[j].kind == nkPragmaExpr: a[j][0] else: a[j], c)
  1249. if a[j].kind == nkPragmaExpr:
  1250. pragma(c, arg, a[j][1], paramPragmas)
  1251. if not hasType and not hasDefault and kind notin {skTemplate, skMacro}:
  1252. let param = strTableGet(c.signatures, arg.name)
  1253. if param != nil: typ = param.typ
  1254. else:
  1255. localError(c.config, a.info, "parameter '$1' requires a type" % arg.name.s)
  1256. typ = errorType(c)
  1257. let lifted = liftParamType(c, kind, genericParams, typ,
  1258. arg.name.s, arg.info)
  1259. let finalType = if lifted != nil: lifted else: typ.skipIntLit(c.idgen)
  1260. arg.typ = finalType
  1261. arg.position = counter
  1262. arg.constraint = constraint
  1263. inc(counter)
  1264. if def != nil and def.kind != nkEmpty:
  1265. arg.ast = copyTree(def)
  1266. if containsOrIncl(check, arg.name.id):
  1267. localError(c.config, a[j].info, "attempt to redefine: '" & arg.name.s & "'")
  1268. result.n.add newSymNode(arg)
  1269. rawAddSon(result, finalType)
  1270. addParamOrResult(c, arg, kind)
  1271. styleCheckDef(c, a[j].info, arg)
  1272. onDef(a[j].info, arg)
  1273. if {optNimV1Emulation, optNimV12Emulation} * c.config.globalOptions == {}:
  1274. a[j] = newSymNode(arg)
  1275. var r: PType
  1276. if n[0].kind != nkEmpty:
  1277. r = semTypeNode(c, n[0], nil)
  1278. if r != nil and kind in {skMacro, skTemplate} and r.kind == tyTyped:
  1279. # XXX: To implement the proposed change in the warning, just
  1280. # delete this entire if block. The rest is (at least at time of
  1281. # writing this comment) already implemented.
  1282. let info = n[0].info
  1283. const msg = "`typed` will change its meaning in future versions of Nim. " &
  1284. "`void` or no return type declaration at all has the same " &
  1285. "meaning as the current meaning of `typed` as return type " &
  1286. "declaration."
  1287. message(c.config, info, warnDeprecated, msg)
  1288. r = nil
  1289. if r != nil:
  1290. # turn explicit 'void' return type into 'nil' because the rest of the
  1291. # compiler only checks for 'nil':
  1292. if skipTypes(r, {tyGenericInst, tyAlias, tySink}).kind != tyVoid:
  1293. if kind notin {skMacro, skTemplate} and r.kind in {tyTyped, tyUntyped}:
  1294. localError(c.config, n[0].info, "return type '" & typeToString(r) &
  1295. "' is only valid for macros and templates")
  1296. # 'auto' as a return type does not imply a generic:
  1297. elif r.kind == tyAnything:
  1298. discard
  1299. elif r.kind == tyStatic:
  1300. # type allowed should forbid this type
  1301. discard
  1302. else:
  1303. if r.sym == nil or sfAnon notin r.sym.flags:
  1304. let lifted = liftParamType(c, kind, genericParams, r, "result",
  1305. n[0].info)
  1306. if lifted != nil:
  1307. r = lifted
  1308. #if r.kind != tyGenericParam:
  1309. #echo "came here for ", typeToString(r)
  1310. r.flags.incl tfRetType
  1311. r = skipIntLit(r, c.idgen)
  1312. if kind == skIterator:
  1313. # see tchainediterators
  1314. # in cases like iterator foo(it: iterator): typeof(it)
  1315. # we don't need to change the return type to iter[T]
  1316. result.flags.incl tfIterator
  1317. # XXX Would be nice if we could get rid of this
  1318. result[0] = r
  1319. let oldFlags = result.flags
  1320. propagateToOwner(result, r)
  1321. if oldFlags != result.flags:
  1322. # XXX This rather hacky way keeps 'tflatmap' compiling:
  1323. if tfHasMeta notin oldFlags:
  1324. result.flags.excl tfHasMeta
  1325. result.n.typ = r
  1326. if genericParams != nil and genericParams.len > 0:
  1327. for n in genericParams:
  1328. if {sfUsed, sfAnon} * n.sym.flags == {}:
  1329. result.flags.incl tfUnresolved
  1330. if tfWildcard in n.sym.typ.flags:
  1331. n.sym.transitionGenericParamToType()
  1332. n.sym.typ.flags.excl tfWildcard
  1333. proc semStmtListType(c: PContext, n: PNode, prev: PType): PType =
  1334. checkMinSonsLen(n, 1, c.config)
  1335. for i in 0..<n.len - 1:
  1336. n[i] = semStmt(c, n[i], {})
  1337. if n.len > 0:
  1338. result = semTypeNode(c, n[^1], prev)
  1339. n.typ = result
  1340. n[^1].typ = result
  1341. else:
  1342. result = nil
  1343. proc semBlockType(c: PContext, n: PNode, prev: PType): PType =
  1344. inc(c.p.nestedBlockCounter)
  1345. let oldBreakInLoop = c.p.breakInLoop
  1346. c.p.breakInLoop = false
  1347. checkSonsLen(n, 2, c.config)
  1348. openScope(c)
  1349. if n[0].kind notin {nkEmpty, nkSym}:
  1350. addDecl(c, newSymS(skLabel, n[0], c))
  1351. result = semStmtListType(c, n[1], prev)
  1352. n[1].typ = result
  1353. n.typ = result
  1354. closeScope(c)
  1355. c.p.breakInLoop = oldBreakInLoop
  1356. dec(c.p.nestedBlockCounter)
  1357. proc semGenericParamInInvocation(c: PContext, n: PNode): PType =
  1358. result = semTypeNode(c, n, nil)
  1359. n.typ = makeTypeDesc(c, result)
  1360. proc semObjectTypeForInheritedGenericInst(c: PContext, n: PNode, t: PType) =
  1361. var
  1362. check = initIntSet()
  1363. pos = 0
  1364. let
  1365. realBase = t[0]
  1366. base = skipTypesOrNil(realBase, skipPtrs)
  1367. if base.isNil:
  1368. localError(c.config, n.info, errIllegalRecursionInTypeX % "object")
  1369. else:
  1370. let concreteBase = skipGenericInvocation(base)
  1371. if concreteBase.kind == tyObject and tfFinal notin concreteBase.flags:
  1372. addInheritedFields(c, check, pos, concreteBase)
  1373. else:
  1374. if concreteBase.kind != tyError:
  1375. localError(c.config, n.info, errInheritanceOnlyWithNonFinalObjects)
  1376. var newf = newNodeI(nkRecList, n.info)
  1377. semRecordNodeAux(c, t.n, check, pos, newf, t)
  1378. proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType =
  1379. if s.typ == nil:
  1380. localError(c.config, n.info, "cannot instantiate the '$1' $2" %
  1381. [s.name.s, s.kind.toHumanStr])
  1382. return newOrPrevType(tyError, prev, c)
  1383. var t = s.typ.skipTypes({tyAlias})
  1384. if t.kind == tyCompositeTypeClass and t.base.kind == tyGenericBody:
  1385. t = t.base
  1386. result = newOrPrevType(tyGenericInvocation, prev, c)
  1387. addSonSkipIntLit(result, t, c.idgen)
  1388. template addToResult(typ) =
  1389. if typ.isNil:
  1390. internalAssert c.config, false
  1391. rawAddSon(result, typ)
  1392. else: addSonSkipIntLit(result, typ, c.idgen)
  1393. if t.kind == tyForward:
  1394. for i in 1..<n.len:
  1395. var elem = semGenericParamInInvocation(c, n[i])
  1396. addToResult(elem)
  1397. return
  1398. elif t.kind != tyGenericBody:
  1399. # we likely got code of the form TypeA[TypeB] where TypeA is
  1400. # not generic.
  1401. localError(c.config, n.info, errNoGenericParamsAllowedForX % s.name.s)
  1402. return newOrPrevType(tyError, prev, c)
  1403. else:
  1404. var m = newCandidate(c, t)
  1405. m.isNoCall = true
  1406. matches(c, n, copyTree(n), m)
  1407. if m.state != csMatch:
  1408. var err = "cannot instantiate "
  1409. err.addTypeHeader(c.config, t)
  1410. err.add "\ngot: <$1>\nbut expected: <$2>" % [describeArgs(c, n), describeArgs(c, t.n, 0)]
  1411. localError(c.config, n.info, errGenerated, err)
  1412. return newOrPrevType(tyError, prev, c)
  1413. var isConcrete = true
  1414. for i in 1..<m.call.len:
  1415. var typ = m.call[i].typ
  1416. # is this a 'typedesc' *parameter*? If so, use the typedesc type,
  1417. # unstripped.
  1418. if m.call[i].kind == nkSym and m.call[i].sym.kind == skParam and
  1419. typ.kind == tyTypeDesc and containsGenericType(typ):
  1420. isConcrete = false
  1421. addToResult(typ)
  1422. else:
  1423. typ = typ.skipTypes({tyTypeDesc})
  1424. if containsGenericType(typ): isConcrete = false
  1425. addToResult(typ)
  1426. if isConcrete:
  1427. if s.ast == nil and s.typ.kind != tyCompositeTypeClass:
  1428. # XXX: What kind of error is this? is it still relevant?
  1429. localError(c.config, n.info, errCannotInstantiateX % s.name.s)
  1430. result = newOrPrevType(tyError, prev, c)
  1431. else:
  1432. result = instGenericContainer(c, n.info, result,
  1433. allowMetaTypes = false)
  1434. # special check for generic object with
  1435. # generic/partial specialized parent
  1436. let tx = result.skipTypes(abstractPtrs, 50)
  1437. if tx.isNil or isTupleRecursive(tx):
  1438. localError(c.config, n.info, "illegal recursion in type '$1'" % typeToString(result[0]))
  1439. return errorType(c)
  1440. if tx != result and tx.kind == tyObject:
  1441. if tx[0] != nil:
  1442. semObjectTypeForInheritedGenericInst(c, n, tx)
  1443. var position = 0
  1444. recomputeFieldPositions(tx, tx.n, position)
  1445. proc maybeAliasType(c: PContext; typeExpr, prev: PType): PType =
  1446. if typeExpr.kind in {tyObject, tyEnum, tyDistinct, tyForward, tyGenericBody} and prev != nil:
  1447. result = newTypeS(tyAlias, c)
  1448. result.rawAddSon typeExpr
  1449. result.sym = prev.sym
  1450. if prev.kind != tyGenericBody:
  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. if prev.kind != tyGenericBody:
  1458. assignType(prev, result)
  1459. proc semTypeExpr(c: PContext, n: PNode; prev: PType): PType =
  1460. var n = semExprWithType(c, n, {efDetermineType})
  1461. if n.typ.kind == tyTypeDesc:
  1462. result = n.typ.base
  1463. # fix types constructed by macros/template:
  1464. if prev != nil and prev.kind != tyGenericBody and prev.sym != nil:
  1465. if result.sym.isNil:
  1466. # Behold! you're witnessing enormous power yielded
  1467. # by macros. Only macros can summon unnamed types
  1468. # and cast spell upon AST. Here we need to give
  1469. # it a name taken from left hand side's node
  1470. result.sym = prev.sym
  1471. result.sym.typ = result
  1472. else:
  1473. # Less powerful routine like template do not have
  1474. # the ability to produce unnamed types. But still
  1475. # it has wild power to push a type a bit too far.
  1476. # So we need to hold it back using alias and prevent
  1477. # unnecessary new type creation
  1478. let alias = maybeAliasType(c, result, prev)
  1479. if alias != nil: result = alias
  1480. else:
  1481. localError(c.config, n.info, "expected type, but got: " & n.renderTree)
  1482. result = errorType(c)
  1483. proc freshType(c: PContext; res, prev: PType): PType {.inline.} =
  1484. if prev.isNil or prev.kind == tyGenericBody:
  1485. result = copyType(res, nextTypeId c.idgen, res.owner)
  1486. copyTypeProps(c.graph, c.idgen.module, result, res)
  1487. else:
  1488. result = res
  1489. template modifierTypeKindOfNode(n: PNode): TTypeKind =
  1490. case n.kind
  1491. of nkVarTy: tyVar
  1492. of nkRefTy: tyRef
  1493. of nkPtrTy: tyPtr
  1494. of nkStaticTy: tyStatic
  1495. of nkTypeOfExpr: tyTypeDesc
  1496. else: tyNone
  1497. proc semTypeClass(c: PContext, n: PNode, prev: PType): PType =
  1498. # if n.len == 0: return newConstraint(c, tyTypeClass)
  1499. if isNewStyleConcept(n):
  1500. result = newOrPrevType(tyConcept, prev, c)
  1501. result.flags.incl tfCheckedForDestructor
  1502. result.n = semConceptDeclaration(c, n)
  1503. return result
  1504. let
  1505. pragmas = n[1]
  1506. inherited = n[2]
  1507. result = newOrPrevType(tyUserTypeClass, prev, c)
  1508. result.flags.incl tfCheckedForDestructor
  1509. var owner = getCurrOwner(c)
  1510. var candidateTypeSlot = newTypeWithSons(owner, tyAlias, @[c.errorType], c.idgen)
  1511. result.sons = @[candidateTypeSlot]
  1512. result.n = n
  1513. if inherited.kind != nkEmpty:
  1514. for n in inherited.sons:
  1515. let typ = semTypeNode(c, n, nil)
  1516. result.add(typ)
  1517. openScope(c)
  1518. for param in n[0]:
  1519. var
  1520. dummyName: PNode
  1521. dummyType: PType
  1522. let modifier = param.modifierTypeKindOfNode
  1523. if modifier != tyNone:
  1524. dummyName = param[0]
  1525. dummyType = c.makeTypeWithModifier(modifier, candidateTypeSlot)
  1526. # if modifier == tyRef:
  1527. # dummyType.flags.incl tfNotNil
  1528. if modifier == tyTypeDesc:
  1529. dummyType.flags.incl tfConceptMatchedTypeSym
  1530. dummyType.flags.incl tfCheckedForDestructor
  1531. else:
  1532. dummyName = param
  1533. dummyType = candidateTypeSlot
  1534. # this can be true for 'nim check' on incomplete concepts,
  1535. # see bug #8230
  1536. if dummyName.kind == nkEmpty: continue
  1537. internalAssert c.config, dummyName.kind == nkIdent
  1538. var dummyParam = newSym(if modifier == tyTypeDesc: skType else: skVar,
  1539. dummyName.ident, nextSymId c.idgen, owner, param.info)
  1540. dummyParam.typ = dummyType
  1541. incl dummyParam.flags, sfUsed
  1542. addDecl(c, dummyParam)
  1543. result.n[3] = semConceptBody(c, n[3])
  1544. closeScope(c)
  1545. proc applyTypeSectionPragmas(c: PContext; pragmas, operand: PNode): PNode =
  1546. for p in pragmas:
  1547. let key = if p.kind in nkPragmaCallKinds and p.len >= 1: p[0] else: p
  1548. if p.kind == nkEmpty or whichPragma(p) != wInvalid:
  1549. discard "builtin pragma"
  1550. else:
  1551. let ident = considerQuotedIdent(c, key)
  1552. if strTableGet(c.userPragmas, ident) != nil:
  1553. discard "User-defined pragma"
  1554. else:
  1555. var amb = false
  1556. let sym = searchInScopes(c, ident, amb)
  1557. # XXX: What to do here if amb is true?
  1558. if sym != nil and sfCustomPragma in sym.flags:
  1559. discard "Custom user pragma"
  1560. else:
  1561. # we transform ``(arg1, arg2: T) {.m, rest.}`` into ``m((arg1, arg2: T) {.rest.})`` and
  1562. # let the semantic checker deal with it:
  1563. var x = newNodeI(nkCall, key.info)
  1564. x.add(key)
  1565. if p.kind in nkPragmaCallKinds and p.len > 1:
  1566. # pass pragma arguments to the macro too:
  1567. for i in 1 ..< p.len:
  1568. x.add(p[i])
  1569. # Also pass the node the pragma has been applied to
  1570. x.add(operand.copyTreeWithoutNode(p))
  1571. # recursion assures that this works for multiple macro annotations too:
  1572. var r = semOverloadedCall(c, x, x, {skMacro, skTemplate}, {efNoUndeclared})
  1573. if r != nil:
  1574. doAssert r[0].kind == nkSym
  1575. let m = r[0].sym
  1576. case m.kind
  1577. of skMacro: return semMacroExpr(c, r, r, m, {efNoSemCheck})
  1578. of skTemplate: return semTemplateExpr(c, r, m, {efNoSemCheck})
  1579. else: doAssert(false, "cannot happen")
  1580. proc semProcTypeWithScope(c: PContext, n: PNode,
  1581. prev: PType, kind: TSymKind): PType =
  1582. checkSonsLen(n, 2, c.config)
  1583. if n[1].kind != nkEmpty and n[1].len > 0:
  1584. let macroEval = applyTypeSectionPragmas(c, n[1], n)
  1585. if macroEval != nil:
  1586. return semTypeNode(c, macroEval, prev)
  1587. openScope(c)
  1588. result = semProcTypeNode(c, n[0], nil, prev, kind, isType=true)
  1589. # start with 'ccClosure', but of course pragmas can overwrite this:
  1590. result.callConv = ccClosure
  1591. # dummy symbol for `pragma`:
  1592. var s = newSymS(kind, newIdentNode(getIdent(c.cache, "dummy"), n.info), c)
  1593. s.typ = result
  1594. if n[1].kind != nkEmpty and n[1].len > 0:
  1595. pragma(c, s, n[1], procTypePragmas)
  1596. when useEffectSystem: setEffectsForProcType(c.graph, result, n[1])
  1597. elif c.optionStack.len > 0 and optNimV1Emulation notin c.config.globalOptions:
  1598. # we construct a fake 'nkProcDef' for the 'mergePragmas' inside 'implicitPragmas'...
  1599. s.ast = newTree(nkProcDef, newNodeI(nkEmpty, n.info), newNodeI(nkEmpty, n.info),
  1600. newNodeI(nkEmpty, n.info), newNodeI(nkEmpty, n.info), newNodeI(nkEmpty, n.info))
  1601. implicitPragmas(c, s, n.info, {wTags, wRaises})
  1602. when useEffectSystem: setEffectsForProcType(c.graph, result, s.ast[pragmasPos])
  1603. closeScope(c)
  1604. proc symFromExpectedTypeNode(c: PContext, n: PNode): PSym =
  1605. if n.kind == nkType:
  1606. result = symFromType(c, n.typ, n.info)
  1607. else:
  1608. localError(c.config, n.info, errTypeExpected)
  1609. result = errorSym(c, n)
  1610. proc semStaticType(c: PContext, childNode: PNode, prev: PType): PType =
  1611. result = newOrPrevType(tyStatic, prev, c)
  1612. var base = semTypeNode(c, childNode, nil).skipTypes({tyTypeDesc, tyAlias})
  1613. result.rawAddSon(base)
  1614. result.flags.incl tfHasStatic
  1615. proc semTypeOf(c: PContext; n: PNode; prev: PType): PType =
  1616. openScope(c)
  1617. let t = semExprWithType(c, n, {efInTypeof})
  1618. closeScope(c)
  1619. fixupTypeOf(c, prev, t)
  1620. result = t.typ
  1621. proc semTypeOf2(c: PContext; n: PNode; prev: PType): PType =
  1622. openScope(c)
  1623. var m = BiggestInt 1 # typeOfIter
  1624. if n.len == 3:
  1625. let mode = semConstExpr(c, n[2])
  1626. if mode.kind != nkIntLit:
  1627. localError(c.config, n.info, "typeof: cannot evaluate 'mode' parameter at compile-time")
  1628. else:
  1629. m = mode.intVal
  1630. let t = semExprWithType(c, n[1], if m == 1: {efInTypeof} else: {})
  1631. closeScope(c)
  1632. fixupTypeOf(c, prev, t)
  1633. result = t.typ
  1634. proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
  1635. result = nil
  1636. inc c.inTypeContext
  1637. if c.config.cmd == cmdIdeTools: suggestExpr(c, n)
  1638. case n.kind
  1639. of nkEmpty: result = n.typ
  1640. of nkTypeOfExpr:
  1641. # for ``typeof(countup(1,3))``, see ``tests/ttoseq``.
  1642. checkSonsLen(n, 1, c.config)
  1643. result = semTypeOf(c, n[0], prev)
  1644. if result.kind == tyTypeDesc: result.flags.incl tfExplicit
  1645. of nkPar:
  1646. if n.len == 1: result = semTypeNode(c, n[0], prev)
  1647. else:
  1648. result = semAnonTuple(c, n, prev)
  1649. of nkTupleConstr: result = semAnonTuple(c, n, prev)
  1650. of nkCallKinds:
  1651. let x = n[0]
  1652. let ident = case x.kind
  1653. of nkIdent: x.ident
  1654. of nkSym: x.sym.name
  1655. of nkClosedSymChoice, nkOpenSymChoice: x[0].sym.name
  1656. else: nil
  1657. if ident != nil and ident.s == "[]":
  1658. let b = newNodeI(nkBracketExpr, n.info)
  1659. for i in 1..<n.len: b.add(n[i])
  1660. result = semTypeNode(c, b, prev)
  1661. elif ident != nil and ident.id == ord(wDotDot):
  1662. result = semRangeAux(c, n, prev)
  1663. elif n[0].kind == nkNilLit and n.len == 2:
  1664. result = semTypeNode(c, n[1], prev)
  1665. if result.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).kind in NilableTypes+GenericTypes:
  1666. if tfNotNil in result.flags:
  1667. result = freshType(c, result, prev)
  1668. result.flags.excl(tfNotNil)
  1669. else:
  1670. localError(c.config, n.info, errGenerated, "invalid type")
  1671. elif n[0].kind notin nkIdentKinds:
  1672. result = semTypeExpr(c, n, prev)
  1673. else:
  1674. let op = considerQuotedIdent(c, n[0])
  1675. if op.id in {ord(wAnd), ord(wOr)} or op.s == "|":
  1676. checkSonsLen(n, 3, c.config)
  1677. var
  1678. t1 = semTypeNode(c, n[1], nil)
  1679. t2 = semTypeNode(c, n[2], nil)
  1680. if t1 == nil:
  1681. localError(c.config, n[1].info, errTypeExpected)
  1682. result = newOrPrevType(tyError, prev, c)
  1683. elif t2 == nil:
  1684. localError(c.config, n[2].info, errTypeExpected)
  1685. result = newOrPrevType(tyError, prev, c)
  1686. else:
  1687. result = if op.id == ord(wAnd): makeAndType(c, t1, t2)
  1688. else: makeOrType(c, t1, t2)
  1689. elif op.id == ord(wNot):
  1690. case n.len
  1691. of 3:
  1692. result = semTypeNode(c, n[1], prev)
  1693. if result.kind == tyTypeDesc and tfUnresolved notin result.flags:
  1694. result = result.base
  1695. if n[2].kind != nkNilLit:
  1696. localError(c.config, n.info,
  1697. "Invalid syntax. When used with a type, 'not' can be followed only by 'nil'")
  1698. if notnil notin c.features and strictNotNil notin c.features:
  1699. localError(c.config, n.info,
  1700. "enable the 'not nil' annotation with {.experimental: \"notnil\".} or " &
  1701. " the `strict not nil` annotation with {.experimental: \"strictNotNil\".} " &
  1702. " the \"notnil\" one is going to be deprecated, so please use \"strictNotNil\"")
  1703. let resolvedType = result.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned})
  1704. case resolvedType.kind
  1705. of tyGenericParam, tyTypeDesc, tyFromExpr:
  1706. # XXX: This is a really inappropraite hack, but it solves
  1707. # https://github.com/nim-lang/Nim/issues/4907 for now.
  1708. #
  1709. # A proper solution is to introduce a new type kind such
  1710. # as `tyNotNil[tyRef[SomeGenericParam]]`. This will allow
  1711. # semtypinst to replace the generic param correctly in
  1712. # situations like the following:
  1713. #
  1714. # type Foo[T] = object
  1715. # bar: ref T not nil
  1716. # baz: ref T
  1717. #
  1718. # The root of the problem is that `T` here must have a specific
  1719. # ID that is bound to a concrete type during instantiation.
  1720. # The use of `freshType` below breaks this. Another hack would
  1721. # be to reuse the same ID for the not nil type, but this will
  1722. # fail if the `T` parameter is referenced multiple times as in
  1723. # the example above.
  1724. #
  1725. # I suggest revisiting this once the language decides on whether
  1726. # `not nil` should be the default. We can then map nilable refs
  1727. # to other types such as `Option[T]`.
  1728. result = makeTypeFromExpr(c, newTree(nkStmtListType, n.copyTree))
  1729. of NilableTypes + {tyGenericInvocation, tyForward}:
  1730. result = freshType(c, result, prev)
  1731. result.flags.incl(tfNotNil)
  1732. else:
  1733. localError(c.config, n.info, errGenerated, "invalid type")
  1734. of 2:
  1735. let negated = semTypeNode(c, n[1], prev)
  1736. result = makeNotType(c, negated)
  1737. else:
  1738. localError(c.config, n.info, errGenerated, "invalid type")
  1739. elif op.id == ord(wPtr):
  1740. result = semAnyRef(c, n, tyPtr, prev)
  1741. elif op.id == ord(wRef):
  1742. result = semAnyRef(c, n, tyRef, prev)
  1743. elif op.id == ord(wType):
  1744. checkSonsLen(n, 2, c.config)
  1745. result = semTypeOf(c, n[1], prev)
  1746. elif op.s == "typeof" and n[0].kind == nkSym and n[0].sym.magic == mTypeOf:
  1747. result = semTypeOf2(c, n, prev)
  1748. elif op.s == "owned" and optOwnedRefs notin c.config.globalOptions and n.len == 2:
  1749. result = semTypeExpr(c, n[1], prev)
  1750. else:
  1751. if c.inGenericContext > 0 and n.kind == nkCall:
  1752. result = makeTypeFromExpr(c, n.copyTree)
  1753. else:
  1754. result = semTypeExpr(c, n, prev)
  1755. of nkWhenStmt:
  1756. var whenResult = semWhen(c, n, false)
  1757. if whenResult.kind == nkStmtList: whenResult.transitionSonsKind(nkStmtListType)
  1758. result = semTypeNode(c, whenResult, prev)
  1759. of nkBracketExpr:
  1760. checkMinSonsLen(n, 2, c.config)
  1761. var head = n[0]
  1762. var s = if head.kind notin nkCallKinds: semTypeIdent(c, head)
  1763. else: symFromExpectedTypeNode(c, semExpr(c, head))
  1764. case s.magic
  1765. of mArray: result = semArray(c, n, prev)
  1766. of mOpenArray: result = semContainer(c, n, tyOpenArray, "openarray", prev)
  1767. of mUncheckedArray: result = semContainer(c, n, tyUncheckedArray, "UncheckedArray", prev)
  1768. of mRange: result = semRange(c, n, prev)
  1769. of mSet: result = semSet(c, n, prev)
  1770. of mOrdinal: result = semOrdinal(c, n, prev)
  1771. of mIterableType: result = semIterableType(c, n, prev)
  1772. of mSeq:
  1773. result = semContainer(c, n, tySequence, "seq", prev)
  1774. if optSeqDestructors in c.config.globalOptions:
  1775. incl result.flags, tfHasAsgn
  1776. of mVarargs: result = semVarargs(c, n, prev)
  1777. of mTypeDesc, mType, mTypeOf:
  1778. result = makeTypeDesc(c, semTypeNode(c, n[1], nil))
  1779. result.flags.incl tfExplicit
  1780. of mStatic:
  1781. result = semStaticType(c, n[1], prev)
  1782. of mExpr:
  1783. result = semTypeNode(c, n[0], nil)
  1784. if result != nil:
  1785. let old = result
  1786. result = copyType(result, nextTypeId c.idgen, getCurrOwner(c))
  1787. copyTypeProps(c.graph, c.idgen.module, result, old)
  1788. for i in 1..<n.len:
  1789. result.rawAddSon(semTypeNode(c, n[i], nil))
  1790. of mDistinct:
  1791. result = newOrPrevType(tyDistinct, prev, c)
  1792. addSonSkipIntLit(result, semTypeNode(c, n[1], nil), c.idgen)
  1793. of mVar:
  1794. result = newOrPrevType(tyVar, prev, c)
  1795. var base = semTypeNode(c, n[1], nil)
  1796. if base.kind in {tyVar, tyLent}:
  1797. localError(c.config, n.info, "type 'var var' is not allowed")
  1798. base = base[0]
  1799. addSonSkipIntLit(result, base, c.idgen)
  1800. of mRef: result = semAnyRef(c, n, tyRef, prev)
  1801. of mPtr: result = semAnyRef(c, n, tyPtr, prev)
  1802. of mTuple: result = semTuple(c, n, prev)
  1803. else: result = semGeneric(c, n, s, prev)
  1804. of nkDotExpr:
  1805. let typeExpr = semExpr(c, n)
  1806. if typeExpr.typ.isNil:
  1807. localError(c.config, n.info, "object constructor needs an object type;" &
  1808. " for named arguments use '=' instead of ':'")
  1809. result = errorType(c)
  1810. elif typeExpr.typ.kind == tyFromExpr:
  1811. result = typeExpr.typ
  1812. elif typeExpr.typ.kind != tyTypeDesc:
  1813. localError(c.config, n.info, errTypeExpected)
  1814. result = errorType(c)
  1815. else:
  1816. result = typeExpr.typ.base
  1817. if result.isMetaType and
  1818. result.kind != tyUserTypeClass:
  1819. # the dot expression may refer to a concept type in
  1820. # a different module. allow a normal alias then.
  1821. let preprocessed = semGenericStmt(c, n)
  1822. result = makeTypeFromExpr(c, preprocessed.copyTree)
  1823. else:
  1824. let alias = maybeAliasType(c, result, prev)
  1825. if alias != nil: result = alias
  1826. of nkIdent, nkAccQuoted:
  1827. var s = semTypeIdent(c, n)
  1828. if s.typ == nil:
  1829. if s.kind != skError: localError(c.config, n.info, errTypeExpected)
  1830. result = newOrPrevType(tyError, prev, c)
  1831. elif s.kind == skParam and s.typ.kind == tyTypeDesc:
  1832. internalAssert c.config, s.typ.base.kind != tyNone and prev == nil
  1833. result = s.typ.base
  1834. elif prev == nil:
  1835. result = s.typ
  1836. else:
  1837. let alias = maybeAliasType(c, s.typ, prev)
  1838. if alias != nil:
  1839. result = alias
  1840. elif prev.kind == tyGenericBody:
  1841. result = s.typ
  1842. else:
  1843. assignType(prev, s.typ)
  1844. # bugfix: keep the fresh id for aliases to integral types:
  1845. if s.typ.kind notin {tyBool, tyChar, tyInt..tyInt64, tyFloat..tyFloat128,
  1846. tyUInt..tyUInt64}:
  1847. prev.itemId = s.typ.itemId
  1848. result = prev
  1849. of nkSym:
  1850. let s = getGenSym(c, n.sym)
  1851. if s.typ != nil and (s.kind == skType or s.typ.kind == tyTypeDesc):
  1852. var t =
  1853. if s.kind == skType:
  1854. s.typ
  1855. else:
  1856. internalAssert c.config, s.typ.base.kind != tyNone and prev == nil
  1857. s.typ.base
  1858. let alias = maybeAliasType(c, t, prev)
  1859. if alias != nil:
  1860. result = alias
  1861. elif prev == nil or prev.kind == tyGenericBody:
  1862. result = t
  1863. else:
  1864. assignType(prev, t)
  1865. result = prev
  1866. markUsed(c, n.info, n.sym)
  1867. onUse(n.info, n.sym)
  1868. else:
  1869. if s.kind != skError:
  1870. if s.typ == nil:
  1871. localError(c.config, n.info, "type expected, but symbol '$1' has no type." % [s.name.s])
  1872. else:
  1873. localError(c.config, n.info, "type expected, but got symbol '$1' of kind '$2'" %
  1874. [s.name.s, s.kind.toHumanStr])
  1875. result = newOrPrevType(tyError, prev, c)
  1876. of nkObjectTy: result = semObjectNode(c, n, prev, {})
  1877. of nkTupleTy: result = semTuple(c, n, prev)
  1878. of nkTupleClassTy: result = newConstraint(c, tyTuple)
  1879. of nkTypeClassTy: result = semTypeClass(c, n, prev)
  1880. of nkRefTy: result = semAnyRef(c, n, tyRef, prev)
  1881. of nkPtrTy: result = semAnyRef(c, n, tyPtr, prev)
  1882. of nkVarTy: result = semVarOutType(c, n, prev, {})
  1883. of nkOutTy: result = semVarOutType(c, n, prev, {tfIsOutParam})
  1884. of nkDistinctTy: result = semDistinct(c, n, prev)
  1885. of nkStaticTy: result = semStaticType(c, n[0], prev)
  1886. of nkIteratorTy:
  1887. if n.len == 0:
  1888. result = newTypeS(tyBuiltInTypeClass, c)
  1889. let child = newTypeS(tyProc, c)
  1890. child.flags.incl tfIterator
  1891. result.addSonSkipIntLit(child, c.idgen)
  1892. else:
  1893. result = semProcTypeWithScope(c, n, prev, skIterator)
  1894. if result.kind == tyProc:
  1895. result.flags.incl(tfIterator)
  1896. if n.lastSon.kind == nkPragma and hasPragma(n.lastSon, wInline):
  1897. result.callConv = ccInline
  1898. else:
  1899. result.callConv = ccClosure
  1900. of nkProcTy:
  1901. if n.len == 0:
  1902. result = newConstraint(c, tyProc)
  1903. else:
  1904. result = semProcTypeWithScope(c, n, prev, skProc)
  1905. of nkEnumTy: result = semEnum(c, n, prev)
  1906. of nkType: result = n.typ
  1907. of nkStmtListType: result = semStmtListType(c, n, prev)
  1908. of nkBlockType: result = semBlockType(c, n, prev)
  1909. else:
  1910. result = semTypeExpr(c, n, prev)
  1911. when false:
  1912. localError(c.config, n.info, "type expected, but got: " & renderTree(n))
  1913. result = newOrPrevType(tyError, prev, c)
  1914. n.typ = result
  1915. dec c.inTypeContext
  1916. proc setMagicType(conf: ConfigRef; m: PSym, kind: TTypeKind, size: int) =
  1917. # source : https://en.wikipedia.org/wiki/Data_structure_alignment#x86
  1918. m.typ.kind = kind
  1919. m.typ.size = size
  1920. # this usually works for most basic types
  1921. # Assuming that since ARM, ARM64 don't support unaligned access
  1922. # data is aligned to type size
  1923. m.typ.align = size.int16
  1924. # FIXME: proper support for clongdouble should be added.
  1925. # long double size can be 8, 10, 12, 16 bytes depending on platform & compiler
  1926. if kind in {tyFloat64, tyFloat, tyInt, tyUInt, tyInt64, tyUInt64} and size == 8:
  1927. m.typ.align = int16(conf.floatInt64Align)
  1928. proc setMagicIntegral(conf: ConfigRef; m: PSym, kind: TTypeKind, size: int) =
  1929. setMagicType(conf, m, kind, size)
  1930. incl m.typ.flags, tfCheckedForDestructor
  1931. proc processMagicType(c: PContext, m: PSym) =
  1932. case m.magic
  1933. of mInt: setMagicIntegral(c.config, m, tyInt, c.config.target.intSize)
  1934. of mInt8: setMagicIntegral(c.config, m, tyInt8, 1)
  1935. of mInt16: setMagicIntegral(c.config, m, tyInt16, 2)
  1936. of mInt32: setMagicIntegral(c.config, m, tyInt32, 4)
  1937. of mInt64: setMagicIntegral(c.config, m, tyInt64, 8)
  1938. of mUInt: setMagicIntegral(c.config, m, tyUInt, c.config.target.intSize)
  1939. of mUInt8: setMagicIntegral(c.config, m, tyUInt8, 1)
  1940. of mUInt16: setMagicIntegral(c.config, m, tyUInt16, 2)
  1941. of mUInt32: setMagicIntegral(c.config, m, tyUInt32, 4)
  1942. of mUInt64: setMagicIntegral(c.config, m, tyUInt64, 8)
  1943. of mFloat: setMagicIntegral(c.config, m, tyFloat, c.config.target.floatSize)
  1944. of mFloat32: setMagicIntegral(c.config, m, tyFloat32, 4)
  1945. of mFloat64: setMagicIntegral(c.config, m, tyFloat64, 8)
  1946. of mFloat128: setMagicIntegral(c.config, m, tyFloat128, 16)
  1947. of mBool: setMagicIntegral(c.config, m, tyBool, 1)
  1948. of mChar: setMagicIntegral(c.config, m, tyChar, 1)
  1949. of mString:
  1950. setMagicType(c.config, m, tyString, szUncomputedSize)
  1951. rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
  1952. if optSeqDestructors in c.config.globalOptions:
  1953. incl m.typ.flags, tfHasAsgn
  1954. of mCstring:
  1955. setMagicIntegral(c.config, m, tyCstring, c.config.target.ptrSize)
  1956. rawAddSon(m.typ, getSysType(c.graph, m.info, tyChar))
  1957. of mPointer: setMagicIntegral(c.config, m, tyPointer, c.config.target.ptrSize)
  1958. of mNil: setMagicType(c.config, m, tyNil, c.config.target.ptrSize)
  1959. of mExpr:
  1960. if m.name.s == "auto":
  1961. setMagicIntegral(c.config, m, tyAnything, 0)
  1962. else:
  1963. setMagicIntegral(c.config, m, tyUntyped, 0)
  1964. of mStmt:
  1965. setMagicIntegral(c.config, m, tyTyped, 0)
  1966. of mTypeDesc, mType:
  1967. setMagicIntegral(c.config, m, tyTypeDesc, 0)
  1968. rawAddSon(m.typ, newTypeS(tyNone, c))
  1969. of mStatic:
  1970. setMagicType(c.config, m, tyStatic, 0)
  1971. rawAddSon(m.typ, newTypeS(tyNone, c))
  1972. of mVoidType:
  1973. setMagicIntegral(c.config, m, tyVoid, 0)
  1974. of mArray:
  1975. setMagicType(c.config, m, tyArray, szUncomputedSize)
  1976. of mOpenArray:
  1977. setMagicType(c.config, m, tyOpenArray, szUncomputedSize)
  1978. of mVarargs:
  1979. setMagicType(c.config, m, tyVarargs, szUncomputedSize)
  1980. of mRange:
  1981. setMagicIntegral(c.config, m, tyRange, szUncomputedSize)
  1982. rawAddSon(m.typ, newTypeS(tyNone, c))
  1983. of mSet:
  1984. setMagicIntegral(c.config, m, tySet, szUncomputedSize)
  1985. of mUncheckedArray:
  1986. setMagicIntegral(c.config, m, tyUncheckedArray, szUncomputedSize)
  1987. of mSeq:
  1988. setMagicType(c.config, m, tySequence, szUncomputedSize)
  1989. if optSeqDestructors in c.config.globalOptions:
  1990. incl m.typ.flags, tfHasAsgn
  1991. if defined(nimsuggest) or c.config.cmd == cmdCheck: # bug #18985
  1992. discard
  1993. else:
  1994. assert c.graph.sysTypes[tySequence] == nil
  1995. c.graph.sysTypes[tySequence] = m.typ
  1996. of mOrdinal:
  1997. setMagicIntegral(c.config, m, tyOrdinal, szUncomputedSize)
  1998. rawAddSon(m.typ, newTypeS(tyNone, c))
  1999. of mIterableType:
  2000. setMagicIntegral(c.config, m, tyIterable, 0)
  2001. rawAddSon(m.typ, newTypeS(tyNone, c))
  2002. of mPNimrodNode:
  2003. incl m.typ.flags, tfTriggersCompileTime
  2004. incl m.typ.flags, tfCheckedForDestructor
  2005. of mException: discard
  2006. of mBuiltinType:
  2007. case m.name.s
  2008. of "lent": setMagicType(c.config, m, tyLent, c.config.target.ptrSize)
  2009. of "sink": setMagicType(c.config, m, tySink, szUncomputedSize)
  2010. of "owned":
  2011. setMagicType(c.config, m, tyOwned, c.config.target.ptrSize)
  2012. incl m.typ.flags, tfHasOwned
  2013. else: localError(c.config, m.info, errTypeExpected)
  2014. else: localError(c.config, m.info, errTypeExpected)
  2015. proc semGenericConstraints(c: PContext, x: PType): PType =
  2016. result = newTypeWithSons(c, tyGenericParam, @[x])
  2017. proc semGenericParamList(c: PContext, n: PNode, father: PType = nil): PNode =
  2018. template addSym(result: PNode, s: PSym): untyped =
  2019. if father != nil: addSonSkipIntLit(father, s.typ, c.idgen)
  2020. if sfGenSym notin s.flags: addDecl(c, s)
  2021. result.add newSymNode(s)
  2022. result = copyNode(n)
  2023. if n.kind != nkGenericParams:
  2024. illFormedAst(n, c.config)
  2025. return
  2026. for i in 0..<n.len:
  2027. var a = n[i]
  2028. case a.kind
  2029. of nkSym: result.addSym(a.sym)
  2030. of nkIdentDefs:
  2031. var def = a[^1]
  2032. let constraint = a[^2]
  2033. var typ: PType
  2034. if constraint.kind != nkEmpty:
  2035. typ = semTypeNode(c, constraint, nil)
  2036. if typ.kind != tyStatic or typ.len == 0:
  2037. if typ.kind == tyTypeDesc:
  2038. if typ[0].kind == tyNone:
  2039. typ = newTypeWithSons(c, tyTypeDesc, @[newTypeS(tyNone, c)])
  2040. incl typ.flags, tfCheckedForDestructor
  2041. else:
  2042. typ = semGenericConstraints(c, typ)
  2043. if def.kind != nkEmpty:
  2044. def = semConstExpr(c, def)
  2045. if typ == nil:
  2046. if def.typ.kind != tyTypeDesc:
  2047. typ = newTypeWithSons(c, tyStatic, @[def.typ])
  2048. else:
  2049. # the following line fixes ``TV2*[T:SomeNumber=TR] = array[0..1, T]``
  2050. # from manyloc/named_argument_bug/triengine:
  2051. def.typ = def.typ.skipTypes({tyTypeDesc})
  2052. if not containsGenericType(def.typ):
  2053. def = fitNode(c, typ, def, def.info)
  2054. if typ == nil:
  2055. typ = newTypeS(tyGenericParam, c)
  2056. if father == nil: typ.flags.incl tfWildcard
  2057. typ.flags.incl tfGenericTypeParam
  2058. for j in 0..<a.len-2:
  2059. var finalType: PType
  2060. if j == 0:
  2061. finalType = typ
  2062. else:
  2063. finalType = copyType(typ, nextTypeId c.idgen, typ.owner)
  2064. copyTypeProps(c.graph, c.idgen.module, finalType, typ)
  2065. # it's important the we create an unique
  2066. # type for each generic param. the index
  2067. # of the parameter will be stored in the
  2068. # attached symbol.
  2069. var paramName = a[j]
  2070. var covarianceFlag = tfUnresolved
  2071. if paramName.safeLen == 2:
  2072. if not nimEnableCovariance or paramName[0].ident.s == "in":
  2073. if father == nil or sfImportc notin father.sym.flags:
  2074. localError(c.config, paramName.info, errInOutFlagNotExtern % $paramName[0])
  2075. covarianceFlag = if paramName[0].ident.s == "in": tfContravariant
  2076. else: tfCovariant
  2077. if father != nil: father.flags.incl tfCovariant
  2078. paramName = paramName[1]
  2079. var s = if finalType.kind == tyStatic or tfWildcard in typ.flags:
  2080. newSymG(skGenericParam, paramName, c).linkTo(finalType)
  2081. else:
  2082. newSymG(skType, paramName, c).linkTo(finalType)
  2083. if covarianceFlag != tfUnresolved: s.typ.flags.incl(covarianceFlag)
  2084. if def.kind != nkEmpty: s.ast = def
  2085. s.position = result.len
  2086. result.addSym(s)
  2087. else:
  2088. illFormedAst(n, c.config)