semtypes.nim 93 KB

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