semtypes.nim 86 KB

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