semtypes.nim 70 KB

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