semtypes.nim 95 KB

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