semtypes.nim 91 KB

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