semtypes.nim 93 KB

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