semtypes.nim 87 KB

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