semtypes.nim 61 KB

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