semtypes.nim 87 KB

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