semtypes.nim 92 KB

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