semtypes.nim 93 KB

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