semtypes.nim 81 KB

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