semtypes.nim 95 KB

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