types.nim 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # this module contains routines for accessing and iterating over types
  10. import
  11. intsets, ast, astalgo, trees, msgs, strutils, platform, renderer, options,
  12. lineinfos, int128
  13. type
  14. TPreferedDesc* = enum
  15. preferName, # default
  16. preferDesc, # probably should become what preferResolved is
  17. preferExported,
  18. preferModuleInfo, # fully qualified
  19. preferGenericArg,
  20. preferTypeName,
  21. preferResolved, # fully resolved symbols
  22. preferMixed,
  23. # most useful, shows: symbol + resolved symbols if it differs, eg:
  24. # tuple[a: MyInt{int}, b: float]
  25. proc typeToString*(typ: PType; prefer: TPreferedDesc = preferName): string
  26. template `$`*(typ: PType): string = typeToString(typ)
  27. proc base*(t: PType): PType =
  28. result = t[0]
  29. # ------------------- type iterator: ----------------------------------------
  30. type
  31. TTypeIter* = proc (t: PType, closure: RootRef): bool {.nimcall.} # true if iteration should stop
  32. TTypeMutator* = proc (t: PType, closure: RootRef): PType {.nimcall.} # copy t and mutate it
  33. TTypePredicate* = proc (t: PType): bool {.nimcall.}
  34. proc iterOverType*(t: PType, iter: TTypeIter, closure: RootRef): bool
  35. # Returns result of `iter`.
  36. proc mutateType*(t: PType, iter: TTypeMutator, closure: RootRef): PType
  37. # Returns result of `iter`.
  38. type
  39. TParamsEquality* = enum # they are equal, but their
  40. # identifiers or their return
  41. # type differ (i.e. they cannot be
  42. # overloaded)
  43. # this used to provide better error messages
  44. paramsNotEqual, # parameters are not equal
  45. paramsEqual, # parameters are equal
  46. paramsIncompatible
  47. proc equalParams*(a, b: PNode): TParamsEquality
  48. # returns whether the parameter lists of the procs a, b are exactly the same
  49. const
  50. # TODO: Remove tyTypeDesc from each abstractX and (where necessary)
  51. # replace with typedescX
  52. abstractPtrs* = {tyVar, tyPtr, tyRef, tyGenericInst, tyDistinct, tyOrdinal,
  53. tyTypeDesc, tyAlias, tyInferred, tySink, tyLent, tyOwned}
  54. abstractVar* = {tyVar, tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc,
  55. tyAlias, tyInferred, tySink, tyLent, tyOwned}
  56. abstractRange* = {tyGenericInst, tyRange, tyDistinct, tyOrdinal, tyTypeDesc,
  57. tyAlias, tyInferred, tySink, tyOwned}
  58. # see also ast.abstractVarRange
  59. abstractInst* = {tyGenericInst, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias,
  60. tyInferred, tySink, tyOwned}
  61. abstractInstOwned* = abstractInst + {tyOwned}
  62. skipPtrs* = {tyVar, tyPtr, tyRef, tyGenericInst, tyTypeDesc, tyAlias,
  63. tyInferred, tySink, tyLent, tyOwned}
  64. # typedescX is used if we're sure tyTypeDesc should be included (or skipped)
  65. typedescPtrs* = abstractPtrs + {tyTypeDesc}
  66. typedescInst* = abstractInst + {tyTypeDesc, tyOwned}
  67. proc invalidGenericInst*(f: PType): bool =
  68. result = f.kind == tyGenericInst and lastSon(f) == nil
  69. proc isPureObject*(typ: PType): bool =
  70. var t = typ
  71. while t.kind == tyObject and t[0] != nil:
  72. t = t[0].skipTypes(skipPtrs)
  73. result = t.sym != nil and sfPure in t.sym.flags
  74. proc isUnsigned*(t: PType): bool =
  75. t.skipTypes(abstractInst).kind in {tyChar, tyUInt..tyUInt64}
  76. proc getOrdValue*(n: PNode; onError = high(Int128)): Int128 =
  77. var k = n.kind
  78. if n.typ != nil and n.typ.skipTypes(abstractInst).kind in {tyChar, tyUInt..tyUInt64}:
  79. k = nkUIntLit
  80. case k
  81. of nkCharLit, nkUIntLit..nkUInt64Lit:
  82. # XXX: enable this assert
  83. #assert n.typ == nil or isUnsigned(n.typ), $n.typ
  84. toInt128(cast[uint64](n.intVal))
  85. of nkIntLit..nkInt64Lit:
  86. # XXX: enable this assert
  87. #assert n.typ == nil or not isUnsigned(n.typ), $n.typ.kind
  88. toInt128(n.intVal)
  89. of nkNilLit:
  90. int128.Zero
  91. of nkHiddenStdConv: getOrdValue(n[1], onError)
  92. else:
  93. # XXX: The idea behind the introduction of int128 was to finally
  94. # have all calculations numerically far away from any
  95. # overflows. This command just introduces such overflows and
  96. # should therefore really be revisited.
  97. onError
  98. proc getFloatValue*(n: PNode): BiggestFloat =
  99. case n.kind
  100. of nkFloatLiterals: n.floatVal
  101. of nkHiddenStdConv: getFloatValue(n[1])
  102. else: NaN
  103. proc isIntLit*(t: PType): bool {.inline.} =
  104. result = t.kind == tyInt and t.n != nil and t.n.kind == nkIntLit
  105. proc isFloatLit*(t: PType): bool {.inline.} =
  106. result = t.kind == tyFloat and t.n != nil and t.n.kind == nkFloatLit
  107. proc addDeclaredLoc(result: var string, conf: ConfigRef; sym: PSym) =
  108. result.add " [declared in " & conf$sym.info & "]"
  109. proc addTypeHeader*(result: var string, conf: ConfigRef; typ: PType; prefer: TPreferedDesc = preferMixed; getDeclarationPath = true) =
  110. result.add typeToString(typ, prefer)
  111. if getDeclarationPath: result.addDeclaredLoc(conf, typ.sym)
  112. proc getProcHeader*(conf: ConfigRef; sym: PSym; prefer: TPreferedDesc = preferName; getDeclarationPath = true): string =
  113. assert sym != nil
  114. # consider using `skipGenericOwner` to avoid fun2.fun2 when fun2 is generic
  115. result = sym.owner.name.s & '.' & sym.name.s
  116. if sym.kind in routineKinds:
  117. result.add '('
  118. var n = sym.typ.n
  119. for i in 1..<n.len:
  120. let p = n[i]
  121. if p.kind == nkSym:
  122. result.add(p.sym.name.s)
  123. result.add(": ")
  124. result.add(typeToString(p.sym.typ, prefer))
  125. if i != n.len-1: result.add(", ")
  126. else:
  127. result.add renderTree(p)
  128. result.add(')')
  129. if n[0].typ != nil:
  130. result.add(": " & typeToString(n[0].typ, prefer))
  131. if getDeclarationPath: result.addDeclaredLoc(conf, sym)
  132. proc elemType*(t: PType): PType =
  133. assert(t != nil)
  134. case t.kind
  135. of tyGenericInst, tyDistinct, tyAlias, tySink: result = elemType(lastSon(t))
  136. of tyArray: result = t[1]
  137. of tyError: result = t
  138. else: result = t.lastSon
  139. assert(result != nil)
  140. proc enumHasHoles*(t: PType): bool =
  141. var b = t.skipTypes({tyRange, tyGenericInst, tyAlias, tySink})
  142. result = b.kind == tyEnum and tfEnumHasHoles in b.flags
  143. proc isOrdinalType*(t: PType, allowEnumWithHoles: bool = false): bool =
  144. assert(t != nil)
  145. const
  146. baseKinds = {tyChar, tyInt..tyInt64, tyUInt..tyUInt64, tyBool, tyEnum}
  147. parentKinds = {tyRange, tyOrdinal, tyGenericInst, tyAlias, tySink, tyDistinct}
  148. result = (t.kind in baseKinds and (not t.enumHasHoles or allowEnumWithHoles)) or
  149. (t.kind in parentKinds and isOrdinalType(t.lastSon, allowEnumWithHoles))
  150. proc iterOverTypeAux(marker: var IntSet, t: PType, iter: TTypeIter,
  151. closure: RootRef): bool
  152. proc iterOverNode(marker: var IntSet, n: PNode, iter: TTypeIter,
  153. closure: RootRef): bool =
  154. if n != nil:
  155. case n.kind
  156. of nkNone..nkNilLit:
  157. # a leaf
  158. result = iterOverTypeAux(marker, n.typ, iter, closure)
  159. else:
  160. for i in 0..<n.len:
  161. result = iterOverNode(marker, n[i], iter, closure)
  162. if result: return
  163. proc iterOverTypeAux(marker: var IntSet, t: PType, iter: TTypeIter,
  164. closure: RootRef): bool =
  165. result = false
  166. if t == nil: return
  167. result = iter(t, closure)
  168. if result: return
  169. if not containsOrIncl(marker, t.id):
  170. case t.kind
  171. of tyGenericInst, tyGenericBody, tyAlias, tySink, tyInferred:
  172. result = iterOverTypeAux(marker, lastSon(t), iter, closure)
  173. else:
  174. for i in 0..<t.len:
  175. result = iterOverTypeAux(marker, t[i], iter, closure)
  176. if result: return
  177. if t.n != nil and t.kind != tyProc: result = iterOverNode(marker, t.n, iter, closure)
  178. proc iterOverType(t: PType, iter: TTypeIter, closure: RootRef): bool =
  179. var marker = initIntSet()
  180. result = iterOverTypeAux(marker, t, iter, closure)
  181. proc searchTypeForAux(t: PType, predicate: TTypePredicate,
  182. marker: var IntSet): bool
  183. proc searchTypeNodeForAux(n: PNode, p: TTypePredicate,
  184. marker: var IntSet): bool =
  185. result = false
  186. case n.kind
  187. of nkRecList:
  188. for i in 0..<n.len:
  189. result = searchTypeNodeForAux(n[i], p, marker)
  190. if result: return
  191. of nkRecCase:
  192. assert(n[0].kind == nkSym)
  193. result = searchTypeNodeForAux(n[0], p, marker)
  194. if result: return
  195. for i in 1..<n.len:
  196. case n[i].kind
  197. of nkOfBranch, nkElse:
  198. result = searchTypeNodeForAux(lastSon(n[i]), p, marker)
  199. if result: return
  200. else: discard
  201. of nkSym:
  202. result = searchTypeForAux(n.sym.typ, p, marker)
  203. else: discard
  204. proc searchTypeForAux(t: PType, predicate: TTypePredicate,
  205. marker: var IntSet): bool =
  206. # iterates over VALUE types!
  207. result = false
  208. if t == nil: return
  209. if containsOrIncl(marker, t.id): return
  210. result = predicate(t)
  211. if result: return
  212. case t.kind
  213. of tyObject:
  214. if t[0] != nil:
  215. result = searchTypeForAux(t[0].skipTypes(skipPtrs), predicate, marker)
  216. if not result: result = searchTypeNodeForAux(t.n, predicate, marker)
  217. of tyGenericInst, tyDistinct, tyAlias, tySink:
  218. result = searchTypeForAux(lastSon(t), predicate, marker)
  219. of tyArray, tySet, tyTuple:
  220. for i in 0..<t.len:
  221. result = searchTypeForAux(t[i], predicate, marker)
  222. if result: return
  223. else:
  224. discard
  225. proc searchTypeFor*(t: PType, predicate: TTypePredicate): bool =
  226. var marker = initIntSet()
  227. result = searchTypeForAux(t, predicate, marker)
  228. proc isObjectPredicate(t: PType): bool =
  229. result = t.kind == tyObject
  230. proc containsObject*(t: PType): bool =
  231. result = searchTypeFor(t, isObjectPredicate)
  232. proc isObjectWithTypeFieldPredicate(t: PType): bool =
  233. result = t.kind == tyObject and t[0] == nil and
  234. not (t.sym != nil and {sfPure, sfInfixCall} * t.sym.flags != {}) and
  235. tfFinal notin t.flags
  236. type
  237. TTypeFieldResult* = enum
  238. frNone, # type has no object type field
  239. frHeader, # type has an object type field only in the header
  240. frEmbedded # type has an object type field somewhere embedded
  241. proc analyseObjectWithTypeFieldAux(t: PType,
  242. marker: var IntSet): TTypeFieldResult =
  243. var res: TTypeFieldResult
  244. result = frNone
  245. if t == nil: return
  246. case t.kind
  247. of tyObject:
  248. if t.n != nil:
  249. if searchTypeNodeForAux(t.n, isObjectWithTypeFieldPredicate, marker):
  250. return frEmbedded
  251. for i in 0..<t.len:
  252. var x = t[i]
  253. if x != nil: x = x.skipTypes(skipPtrs)
  254. res = analyseObjectWithTypeFieldAux(x, marker)
  255. if res == frEmbedded:
  256. return frEmbedded
  257. if res == frHeader: result = frHeader
  258. if result == frNone:
  259. if isObjectWithTypeFieldPredicate(t): result = frHeader
  260. of tyGenericInst, tyDistinct, tyAlias, tySink:
  261. result = analyseObjectWithTypeFieldAux(lastSon(t), marker)
  262. of tyArray, tyTuple:
  263. for i in 0..<t.len:
  264. res = analyseObjectWithTypeFieldAux(t[i], marker)
  265. if res != frNone:
  266. return frEmbedded
  267. else:
  268. discard
  269. proc analyseObjectWithTypeField*(t: PType): TTypeFieldResult =
  270. # this does a complex analysis whether a call to ``objectInit`` needs to be
  271. # made or initializing of the type field suffices or if there is no type field
  272. # at all in this type.
  273. var marker = initIntSet()
  274. result = analyseObjectWithTypeFieldAux(t, marker)
  275. proc isGCRef(t: PType): bool =
  276. result = t.kind in GcTypeKinds or
  277. (t.kind == tyProc and t.callConv == ccClosure)
  278. if result and t.kind in {tyString, tySequence} and tfHasAsgn in t.flags:
  279. result = false
  280. proc containsGarbageCollectedRef*(typ: PType): bool =
  281. # returns true if typ contains a reference, sequence or string (all the
  282. # things that are garbage-collected)
  283. result = searchTypeFor(typ, isGCRef)
  284. proc isTyRef(t: PType): bool =
  285. result = t.kind == tyRef or (t.kind == tyProc and t.callConv == ccClosure)
  286. proc containsTyRef*(typ: PType): bool =
  287. # returns true if typ contains a 'ref'
  288. result = searchTypeFor(typ, isTyRef)
  289. proc isHiddenPointer(t: PType): bool =
  290. result = t.kind in {tyString, tySequence}
  291. proc containsHiddenPointer*(typ: PType): bool =
  292. # returns true if typ contains a string, table or sequence (all the things
  293. # that need to be copied deeply)
  294. result = searchTypeFor(typ, isHiddenPointer)
  295. proc canFormAcycleAux(marker: var IntSet, typ: PType, startId: int): bool
  296. proc canFormAcycleNode(marker: var IntSet, n: PNode, startId: int): bool =
  297. result = false
  298. if n != nil:
  299. result = canFormAcycleAux(marker, n.typ, startId)
  300. if not result:
  301. case n.kind
  302. of nkNone..nkNilLit:
  303. discard
  304. else:
  305. for i in 0..<n.len:
  306. result = canFormAcycleNode(marker, n[i], startId)
  307. if result: return
  308. proc canFormAcycleAux(marker: var IntSet, typ: PType, startId: int): bool =
  309. result = false
  310. if typ == nil: return
  311. if tfAcyclic in typ.flags: return
  312. var t = skipTypes(typ, abstractInst+{tyOwned}-{tyTypeDesc})
  313. if tfAcyclic in t.flags: return
  314. case t.kind
  315. of tyTuple, tyObject, tyRef, tySequence, tyArray, tyOpenArray, tyVarargs:
  316. if not containsOrIncl(marker, t.id):
  317. for i in 0..<t.len:
  318. result = canFormAcycleAux(marker, t[i], startId)
  319. if result: return
  320. if t.n != nil: result = canFormAcycleNode(marker, t.n, startId)
  321. else:
  322. result = t.id == startId
  323. # Inheritance can introduce cyclic types, however this is not relevant
  324. # as the type that is passed to 'new' is statically known!
  325. # er but we use it also for the write barrier ...
  326. if t.kind == tyObject and tfFinal notin t.flags:
  327. # damn inheritance may introduce cycles:
  328. result = true
  329. of tyProc: result = typ.callConv == ccClosure
  330. else: discard
  331. proc isFinal*(t: PType): bool =
  332. let t = t.skipTypes(abstractInst)
  333. result = t.kind != tyObject or tfFinal in t.flags or isPureObject(t)
  334. proc canFormAcycle*(typ: PType): bool =
  335. var marker = initIntSet()
  336. result = canFormAcycleAux(marker, typ, typ.id)
  337. proc mutateTypeAux(marker: var IntSet, t: PType, iter: TTypeMutator,
  338. closure: RootRef): PType
  339. proc mutateNode(marker: var IntSet, n: PNode, iter: TTypeMutator,
  340. closure: RootRef): PNode =
  341. result = nil
  342. if n != nil:
  343. result = copyNode(n)
  344. result.typ = mutateTypeAux(marker, n.typ, iter, closure)
  345. case n.kind
  346. of nkNone..nkNilLit:
  347. # a leaf
  348. discard
  349. else:
  350. for i in 0..<n.len:
  351. result.add mutateNode(marker, n[i], iter, closure)
  352. proc mutateTypeAux(marker: var IntSet, t: PType, iter: TTypeMutator,
  353. closure: RootRef): PType =
  354. result = nil
  355. if t == nil: return
  356. result = iter(t, closure)
  357. if not containsOrIncl(marker, t.id):
  358. for i in 0..<t.len:
  359. result[i] = mutateTypeAux(marker, result[i], iter, closure)
  360. if t.n != nil: result.n = mutateNode(marker, t.n, iter, closure)
  361. assert(result != nil)
  362. proc mutateType(t: PType, iter: TTypeMutator, closure: RootRef): PType =
  363. var marker = initIntSet()
  364. result = mutateTypeAux(marker, t, iter, closure)
  365. proc valueToString(a: PNode): string =
  366. case a.kind
  367. of nkCharLit..nkUInt64Lit: result = $a.intVal
  368. of nkFloatLit..nkFloat128Lit: result = $a.floatVal
  369. of nkStrLit..nkTripleStrLit: result = a.strVal
  370. else: result = "<invalid value>"
  371. proc rangeToStr(n: PNode): string =
  372. assert(n.kind == nkRange)
  373. result = valueToString(n[0]) & ".." & valueToString(n[1])
  374. const
  375. typeToStr: array[TTypeKind, string] = ["None", "bool", "char", "empty",
  376. "Alias", "typeof(nil)", "untyped", "typed", "typeDesc",
  377. "GenericInvocation", "GenericBody", "GenericInst", "GenericParam",
  378. "distinct $1", "enum", "ordinal[$1]", "array[$1, $2]", "object", "tuple",
  379. "set[$1]", "range[$1]", "ptr ", "ref ", "var ", "seq[$1]", "proc",
  380. "pointer", "OpenArray[$1]", "string", "cstring", "Forward",
  381. "int", "int8", "int16", "int32", "int64",
  382. "float", "float32", "float64", "float128",
  383. "uint", "uint8", "uint16", "uint32", "uint64",
  384. "owned", "sink",
  385. "lent ", "varargs[$1]", "UncheckedArray[$1]", "Error Type",
  386. "BuiltInTypeClass", "UserTypeClass",
  387. "UserTypeClassInst", "CompositeTypeClass", "inferred",
  388. "and", "or", "not", "any", "static", "TypeFromExpr", "out ",
  389. "void"]
  390. const preferToResolveSymbols = {preferName, preferTypeName, preferModuleInfo,
  391. preferGenericArg, preferResolved, preferMixed}
  392. template bindConcreteTypeToUserTypeClass*(tc, concrete: PType) =
  393. tc.add concrete
  394. tc.flags.incl tfResolved
  395. # TODO: It would be a good idea to kill the special state of a resolved
  396. # concept by switching to tyAlias within the instantiated procs.
  397. # Currently, tyAlias is always skipped with lastSon, which means that
  398. # we can store information about the matched concept in another position.
  399. # Then builtInFieldAccess can be modified to properly read the derived
  400. # consts and types stored within the concept.
  401. template isResolvedUserTypeClass*(t: PType): bool =
  402. tfResolved in t.flags
  403. proc addTypeFlags(name: var string, typ: PType) {.inline.} =
  404. if tfNotNil in typ.flags: name.add(" not nil")
  405. proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string =
  406. let preferToplevel = prefer
  407. proc getPrefer(prefer: TPreferedDesc): TPreferedDesc =
  408. if preferToplevel in {preferResolved, preferMixed}:
  409. preferToplevel # sticky option
  410. else:
  411. prefer
  412. proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string =
  413. let prefer = getPrefer(prefer)
  414. let t = typ
  415. result = ""
  416. if t == nil: return
  417. if prefer in preferToResolveSymbols and t.sym != nil and
  418. sfAnon notin t.sym.flags and t.kind != tySequence:
  419. if t.kind == tyInt and isIntLit(t):
  420. result = t.sym.name.s & " literal(" & $t.n.intVal & ")"
  421. elif t.kind == tyAlias and t[0].kind != tyAlias:
  422. result = typeToString(t[0])
  423. elif prefer in {preferResolved, preferMixed}:
  424. case t.kind
  425. of IntegralTypes + {tyFloat..tyFloat128} + {tyString, tyCString}:
  426. result = typeToStr[t.kind]
  427. of tyGenericBody:
  428. result = typeToString(t.lastSon)
  429. of tyCompositeTypeClass:
  430. # avoids showing `A[any]` in `proc fun(a: A)` with `A = object[T]`
  431. result = typeToString(t.lastSon.lastSon)
  432. else:
  433. result = t.sym.name.s
  434. if prefer == preferMixed and result != t.sym.name.s:
  435. result = t.sym.name.s & "{" & result & "}"
  436. elif prefer in {preferName, preferTypeName} or t.sym.owner.isNil:
  437. # note: should probably be: {preferName, preferTypeName, preferGenericArg}
  438. result = t.sym.name.s
  439. if t.kind == tyGenericParam and t.len > 0:
  440. result.add ": "
  441. var first = true
  442. for son in t.sons:
  443. if not first: result.add " or "
  444. result.add son.typeToString
  445. first = false
  446. else:
  447. result = t.sym.owner.name.s & '.' & t.sym.name.s
  448. result.addTypeFlags(t)
  449. return
  450. case t.kind
  451. of tyInt:
  452. if not isIntLit(t) or prefer == preferExported:
  453. result = typeToStr[t.kind]
  454. else:
  455. if prefer == preferGenericArg:
  456. result = $t.n.intVal
  457. else:
  458. result = "int literal(" & $t.n.intVal & ")"
  459. of tyGenericInst, tyGenericInvocation:
  460. result = typeToString(t[0]) & '['
  461. for i in 1..<t.len-ord(t.kind != tyGenericInvocation):
  462. if i > 1: result.add(", ")
  463. result.add(typeToString(t[i], preferGenericArg))
  464. result.add(']')
  465. of tyGenericBody:
  466. result = typeToString(t.lastSon) & '['
  467. for i in 0..<t.len-1:
  468. if i > 0: result.add(", ")
  469. result.add(typeToString(t[i], preferTypeName))
  470. result.add(']')
  471. of tyTypeDesc:
  472. if t[0].kind == tyNone: result = "typedesc"
  473. else: result = "type " & typeToString(t[0])
  474. of tyStatic:
  475. if prefer == preferGenericArg and t.n != nil:
  476. result = t.n.renderTree
  477. else:
  478. result = "static[" & (if t.len > 0: typeToString(t[0]) else: "") & "]"
  479. if t.n != nil: result.add "(" & renderTree(t.n) & ")"
  480. of tyUserTypeClass:
  481. if t.sym != nil and t.sym.owner != nil:
  482. if t.isResolvedUserTypeClass: return typeToString(t.lastSon)
  483. return t.sym.owner.name.s
  484. else:
  485. result = "<invalid tyUserTypeClass>"
  486. of tyBuiltInTypeClass:
  487. result = case t.base.kind:
  488. of tyVar: "var"
  489. of tyRef: "ref"
  490. of tyPtr: "ptr"
  491. of tySequence: "seq"
  492. of tyArray: "array"
  493. of tySet: "set"
  494. of tyRange: "range"
  495. of tyDistinct: "distinct"
  496. of tyProc: "proc"
  497. of tyObject: "object"
  498. of tyTuple: "tuple"
  499. of tyOpenArray: "openArray"
  500. else: typeToStr[t.base.kind]
  501. of tyInferred:
  502. let concrete = t.previouslyInferred
  503. if concrete != nil: result = typeToString(concrete)
  504. else: result = "inferred[" & typeToString(t.base) & "]"
  505. of tyUserTypeClassInst:
  506. let body = t.base
  507. result = body.sym.name.s & "["
  508. for i in 1..<t.len - 1:
  509. if i > 1: result.add(", ")
  510. result.add(typeToString(t[i]))
  511. result.add "]"
  512. of tyAnd:
  513. for i, son in t.sons:
  514. result.add(typeToString(son))
  515. if i < t.sons.high:
  516. result.add(" and ")
  517. of tyOr:
  518. for i, son in t.sons:
  519. result.add(typeToString(son))
  520. if i < t.sons.high:
  521. result.add(" or ")
  522. of tyNot:
  523. result = "not " & typeToString(t[0])
  524. of tyUntyped:
  525. #internalAssert t.len == 0
  526. result = "untyped"
  527. of tyFromExpr:
  528. if t.n == nil:
  529. result = "unknown"
  530. else:
  531. result = "typeof(" & renderTree(t.n) & ")"
  532. of tyArray:
  533. result = "array"
  534. if t.len > 0:
  535. if t[0].kind == tyRange:
  536. result &= "[" & rangeToStr(t[0].n) & ", " &
  537. typeToString(t[1]) & ']'
  538. else:
  539. result &= "[" & typeToString(t[0]) & ", " &
  540. typeToString(t[1]) & ']'
  541. of tyUncheckedArray:
  542. result = "UncheckedArray"
  543. if t.len > 0:
  544. result &= "[" & typeToString(t[0]) & ']'
  545. of tySequence:
  546. if t.sym != nil and prefer != preferResolved:
  547. result = t.sym.name.s
  548. else:
  549. result = "seq"
  550. if t.len > 0:
  551. result &= "[" & typeToString(t[0]) & ']'
  552. of tyOrdinal:
  553. result = "ordinal"
  554. if t.len > 0:
  555. result &= "[" & typeToString(t[0]) & ']'
  556. of tySet:
  557. result = "set"
  558. if t.len > 0:
  559. result &= "[" & typeToString(t[0]) & ']'
  560. of tyOpenArray:
  561. result = "openArray"
  562. if t.len > 0:
  563. result &= "[" & typeToString(t[0]) & ']'
  564. of tyDistinct:
  565. result = "distinct " & typeToString(t[0],
  566. if prefer == preferModuleInfo: preferModuleInfo else: preferTypeName)
  567. of tyTuple:
  568. # we iterate over t.sons here, because t.n may be nil
  569. if t.n != nil:
  570. result = "tuple["
  571. assert(t.n.len == t.len)
  572. for i in 0..<t.n.len:
  573. assert(t.n[i].kind == nkSym)
  574. result.add(t.n[i].sym.name.s & ": " & typeToString(t[i]))
  575. if i < t.n.len - 1: result.add(", ")
  576. result.add(']')
  577. elif t.len == 0:
  578. result = "tuple[]"
  579. else:
  580. result = "("
  581. for i in 0..<t.len:
  582. result.add(typeToString(t[i]))
  583. if i < t.len - 1: result.add(", ")
  584. elif t.len == 1: result.add(",")
  585. result.add(')')
  586. of tyPtr, tyRef, tyVar, tyLent:
  587. result = typeToStr[t.kind]
  588. if t.len >= 2:
  589. setLen(result, result.len-1)
  590. result.add '['
  591. for i in 0..<t.len:
  592. result.add(typeToString(t[i]))
  593. if i < t.len - 1: result.add(", ")
  594. result.add ']'
  595. else:
  596. result.add typeToString(t[0])
  597. of tyRange:
  598. result = "range "
  599. if t.n != nil and t.n.kind == nkRange:
  600. result.add rangeToStr(t.n)
  601. if prefer != preferExported:
  602. result.add("(" & typeToString(t[0]) & ")")
  603. of tyProc:
  604. result = if tfIterator in t.flags: "iterator "
  605. elif t.owner != nil:
  606. case t.owner.kind
  607. of skTemplate: "template "
  608. of skMacro: "macro "
  609. of skConverter: "converter "
  610. else: "proc "
  611. else:
  612. "proc "
  613. if tfUnresolved in t.flags: result.add "[*missing parameters*]"
  614. result.add "("
  615. for i in 1..<t.len:
  616. if t.n != nil and i < t.n.len and t.n[i].kind == nkSym:
  617. result.add(t.n[i].sym.name.s)
  618. result.add(": ")
  619. result.add(typeToString(t[i]))
  620. if i < t.len - 1: result.add(", ")
  621. result.add(')')
  622. if t.len > 0 and t[0] != nil: result.add(": " & typeToString(t[0]))
  623. var prag = if t.callConv == ccDefault: "" else: CallingConvToStr[t.callConv]
  624. if tfNoSideEffect in t.flags:
  625. addSep(prag)
  626. prag.add("noSideEffect")
  627. if tfThread in t.flags:
  628. addSep(prag)
  629. prag.add("gcsafe")
  630. if t.lockLevel.ord != UnspecifiedLockLevel.ord:
  631. addSep(prag)
  632. prag.add("locks: " & $t.lockLevel)
  633. if prag.len != 0: result.add("{." & prag & ".}")
  634. of tyVarargs:
  635. result = typeToStr[t.kind] % typeToString(t[0])
  636. of tySink:
  637. result = "sink " & typeToString(t[0])
  638. of tyOwned:
  639. result = "owned " & typeToString(t[0])
  640. else:
  641. result = typeToStr[t.kind]
  642. result.addTypeFlags(t)
  643. result = typeToString(typ, prefer)
  644. proc firstOrd*(conf: ConfigRef; t: PType): Int128 =
  645. case t.kind
  646. of tyBool, tyChar, tySequence, tyOpenArray, tyString, tyVarargs, tyProxy:
  647. result = Zero
  648. of tySet, tyVar: result = firstOrd(conf, t[0])
  649. of tyArray: result = firstOrd(conf, t[0])
  650. of tyRange:
  651. assert(t.n != nil) # range directly given:
  652. assert(t.n.kind == nkRange)
  653. result = getOrdValue(t.n[0])
  654. of tyInt:
  655. if conf != nil and conf.target.intSize == 4:
  656. result = toInt128(-2147483648)
  657. else:
  658. result = toInt128(0x8000000000000000'i64)
  659. of tyInt8: result = toInt128(-128)
  660. of tyInt16: result = toInt128(-32768)
  661. of tyInt32: result = toInt128(-2147483648)
  662. of tyInt64: result = toInt128(0x8000000000000000'i64)
  663. of tyUInt..tyUInt64: result = Zero
  664. of tyEnum:
  665. # if basetype <> nil then return firstOrd of basetype
  666. if t.len > 0 and t[0] != nil:
  667. result = firstOrd(conf, t[0])
  668. else:
  669. assert(t.n[0].kind == nkSym)
  670. result = toInt128(t.n[0].sym.position)
  671. of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink,
  672. tyStatic, tyInferred, tyUserTypeClasses:
  673. result = firstOrd(conf, lastSon(t))
  674. of tyOrdinal:
  675. if t.len > 0: result = firstOrd(conf, lastSon(t))
  676. else: internalError(conf, "invalid kind for firstOrd(" & $t.kind & ')')
  677. of tyUncheckedArray, tyCString:
  678. result = Zero
  679. else:
  680. internalError(conf, "invalid kind for firstOrd(" & $t.kind & ')')
  681. result = Zero
  682. proc firstFloat*(t: PType): BiggestFloat =
  683. case t.kind
  684. of tyFloat..tyFloat128: -Inf
  685. of tyRange:
  686. assert(t.n != nil) # range directly given:
  687. assert(t.n.kind == nkRange)
  688. getFloatValue(t.n[0])
  689. of tyVar: firstFloat(t[0])
  690. of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink,
  691. tyStatic, tyInferred, tyUserTypeClasses:
  692. firstFloat(lastSon(t))
  693. else:
  694. internalError(newPartialConfigRef(), "invalid kind for firstFloat(" & $t.kind & ')')
  695. NaN
  696. proc lastOrd*(conf: ConfigRef; t: PType): Int128 =
  697. case t.kind
  698. of tyBool: result = toInt128(1'u)
  699. of tyChar: result = toInt128(255'u)
  700. of tySet, tyVar: result = lastOrd(conf, t[0])
  701. of tyArray: result = lastOrd(conf, t[0])
  702. of tyRange:
  703. assert(t.n != nil) # range directly given:
  704. assert(t.n.kind == nkRange)
  705. result = getOrdValue(t.n[1])
  706. of tyInt:
  707. if conf != nil and conf.target.intSize == 4: result = toInt128(0x7FFFFFFF)
  708. else: result = toInt128(0x7FFFFFFFFFFFFFFF'u64)
  709. of tyInt8: result = toInt128(0x0000007F)
  710. of tyInt16: result = toInt128(0x00007FFF)
  711. of tyInt32: result = toInt128(0x7FFFFFFF)
  712. of tyInt64: result = toInt128(0x7FFFFFFFFFFFFFFF'u64)
  713. of tyUInt:
  714. if conf != nil and conf.target.intSize == 4:
  715. result = toInt128(0xFFFFFFFF)
  716. else:
  717. result = toInt128(0xFFFFFFFFFFFFFFFF'u64)
  718. of tyUInt8: result = toInt128(0xFF)
  719. of tyUInt16: result = toInt128(0xFFFF)
  720. of tyUInt32: result = toInt128(0xFFFFFFFF)
  721. of tyUInt64:
  722. result = toInt128(0xFFFFFFFFFFFFFFFF'u64)
  723. of tyEnum:
  724. assert(t.n[^1].kind == nkSym)
  725. result = toInt128(t.n[^1].sym.position)
  726. of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink,
  727. tyStatic, tyInferred, tyUserTypeClasses:
  728. result = lastOrd(conf, lastSon(t))
  729. of tyProxy: result = Zero
  730. of tyOrdinal:
  731. if t.len > 0: result = lastOrd(conf, lastSon(t))
  732. else: internalError(conf, "invalid kind for lastOrd(" & $t.kind & ')')
  733. of tyUncheckedArray:
  734. result = Zero
  735. else:
  736. internalError(conf, "invalid kind for lastOrd(" & $t.kind & ')')
  737. result = Zero
  738. proc lastFloat*(t: PType): BiggestFloat =
  739. case t.kind
  740. of tyFloat..tyFloat128: Inf
  741. of tyVar: lastFloat(t[0])
  742. of tyRange:
  743. assert(t.n != nil) # range directly given:
  744. assert(t.n.kind == nkRange)
  745. getFloatValue(t.n[1])
  746. of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink,
  747. tyStatic, tyInferred, tyUserTypeClasses:
  748. lastFloat(lastSon(t))
  749. else:
  750. internalError(newPartialConfigRef(), "invalid kind for lastFloat(" & $t.kind & ')')
  751. NaN
  752. proc floatRangeCheck*(x: BiggestFloat, t: PType): bool =
  753. case t.kind
  754. # This needs to be special cased since NaN is never
  755. # part of firstFloat(t)..lastFloat(t)
  756. of tyFloat..tyFloat128:
  757. true
  758. of tyRange:
  759. x in firstFloat(t)..lastFloat(t)
  760. of tyVar:
  761. floatRangeCheck(x, t[0])
  762. of tyGenericInst, tyDistinct, tyTypeDesc, tyAlias, tySink,
  763. tyStatic, tyInferred, tyUserTypeClasses:
  764. floatRangeCheck(x, lastSon(t))
  765. else:
  766. internalError(newPartialConfigRef(), "invalid kind for floatRangeCheck:" & $t.kind)
  767. false
  768. proc lengthOrd*(conf: ConfigRef; t: PType): Int128 =
  769. if t.skipTypes(tyUserTypeClasses).kind == tyDistinct:
  770. result = lengthOrd(conf, t[0])
  771. else:
  772. let last = lastOrd(conf, t)
  773. let first = firstOrd(conf, t)
  774. result = last - first + One
  775. # -------------- type equality -----------------------------------------------
  776. type
  777. TDistinctCompare* = enum ## how distinct types are to be compared
  778. dcEq, ## a and b should be the same type
  779. dcEqIgnoreDistinct, ## compare symmetrically: (distinct a) == b, a == b
  780. ## or a == (distinct b)
  781. dcEqOrDistinctOf ## a equals b or a is distinct of b
  782. TTypeCmpFlag* = enum
  783. IgnoreTupleFields ## NOTE: Only set this flag for backends!
  784. IgnoreCC
  785. ExactTypeDescValues
  786. ExactGenericParams
  787. ExactConstraints
  788. ExactGcSafety
  789. AllowCommonBase
  790. TTypeCmpFlags* = set[TTypeCmpFlag]
  791. TSameTypeClosure = object
  792. cmp: TDistinctCompare
  793. recCheck: int
  794. flags: TTypeCmpFlags
  795. s: seq[tuple[a,b: int]] # seq for a set as it's hopefully faster
  796. # (few elements expected)
  797. proc initSameTypeClosure: TSameTypeClosure =
  798. # we do the initialization lazily for performance (avoids memory allocations)
  799. discard
  800. proc containsOrIncl(c: var TSameTypeClosure, a, b: PType): bool =
  801. result = c.s.len > 0 and c.s.contains((a.id, b.id))
  802. if not result:
  803. when not defined(nimNoNilSeqs):
  804. if isNil(c.s): c.s = @[]
  805. c.s.add((a.id, b.id))
  806. proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool
  807. proc sameTypeOrNilAux(a, b: PType, c: var TSameTypeClosure): bool =
  808. if a == b:
  809. result = true
  810. else:
  811. if a == nil or b == nil: result = false
  812. else: result = sameTypeAux(a, b, c)
  813. proc sameType*(a, b: PType, flags: TTypeCmpFlags = {}): bool =
  814. var c = initSameTypeClosure()
  815. c.flags = flags
  816. result = sameTypeAux(a, b, c)
  817. proc sameTypeOrNil*(a, b: PType, flags: TTypeCmpFlags = {}): bool =
  818. if a == b:
  819. result = true
  820. else:
  821. if a == nil or b == nil: result = false
  822. else: result = sameType(a, b, flags)
  823. proc equalParam(a, b: PSym): TParamsEquality =
  824. if sameTypeOrNil(a.typ, b.typ, {ExactTypeDescValues}) and
  825. exprStructuralEquivalent(a.constraint, b.constraint):
  826. if a.ast == b.ast:
  827. result = paramsEqual
  828. elif a.ast != nil and b.ast != nil:
  829. if exprStructuralEquivalent(a.ast, b.ast): result = paramsEqual
  830. else: result = paramsIncompatible
  831. elif a.ast != nil:
  832. result = paramsEqual
  833. elif b.ast != nil:
  834. result = paramsIncompatible
  835. else:
  836. result = paramsNotEqual
  837. proc sameConstraints(a, b: PNode): bool =
  838. if isNil(a) and isNil(b): return true
  839. if a.len != b.len: return false
  840. for i in 1..<a.len:
  841. if not exprStructuralEquivalent(a[i].sym.constraint,
  842. b[i].sym.constraint):
  843. return false
  844. return true
  845. proc equalParams(a, b: PNode): TParamsEquality =
  846. result = paramsEqual
  847. if a.len != b.len:
  848. result = paramsNotEqual
  849. else:
  850. for i in 1..<a.len:
  851. var m = a[i].sym
  852. var n = b[i].sym
  853. assert((m.kind == skParam) and (n.kind == skParam))
  854. case equalParam(m, n)
  855. of paramsNotEqual:
  856. return paramsNotEqual
  857. of paramsEqual:
  858. discard
  859. of paramsIncompatible:
  860. result = paramsIncompatible
  861. if (m.name.id != n.name.id):
  862. # BUGFIX
  863. return paramsNotEqual # paramsIncompatible;
  864. # continue traversal! If not equal, we can return immediately; else
  865. # it stays incompatible
  866. if not sameTypeOrNil(a.typ, b.typ, {ExactTypeDescValues}):
  867. if (a.typ == nil) or (b.typ == nil):
  868. result = paramsNotEqual # one proc has a result, the other not is OK
  869. else:
  870. result = paramsIncompatible # overloading by different
  871. # result types does not work
  872. proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool =
  873. # two tuples are equivalent iff the names, types and positions are the same;
  874. # however, both types may not have any field names (t.n may be nil) which
  875. # complicates the matter a bit.
  876. if a.len == b.len:
  877. result = true
  878. for i in 0..<a.len:
  879. var x = a[i]
  880. var y = b[i]
  881. if IgnoreTupleFields in c.flags:
  882. x = skipTypes(x, {tyRange, tyGenericInst, tyAlias})
  883. y = skipTypes(y, {tyRange, tyGenericInst, tyAlias})
  884. result = sameTypeAux(x, y, c)
  885. if not result: return
  886. if a.n != nil and b.n != nil and IgnoreTupleFields notin c.flags:
  887. for i in 0..<a.n.len:
  888. # check field names:
  889. if a.n[i].kind == nkSym and b.n[i].kind == nkSym:
  890. var x = a.n[i].sym
  891. var y = b.n[i].sym
  892. result = x.name.id == y.name.id
  893. if not result: break
  894. else:
  895. return false
  896. elif a.n != b.n and (a.n == nil or b.n == nil) and IgnoreTupleFields notin c.flags:
  897. result = false
  898. template ifFastObjectTypeCheckFailed(a, b: PType, body: untyped) =
  899. if tfFromGeneric notin a.flags + b.flags:
  900. # fast case: id comparison suffices:
  901. result = a.id == b.id
  902. else:
  903. # expensive structural equality test; however due to the way generic and
  904. # objects work, if one of the types does **not** contain tfFromGeneric,
  905. # they cannot be equal. The check ``a.sym.id == b.sym.id`` checks
  906. # for the same origin and is essential because we don't want "pure"
  907. # structural type equivalence:
  908. #
  909. # type
  910. # TA[T] = object
  911. # TB[T] = object
  912. # --> TA[int] != TB[int]
  913. if tfFromGeneric in a.flags * b.flags and a.sym.id == b.sym.id:
  914. # ok, we need the expensive structural check
  915. body
  916. proc sameObjectTypes*(a, b: PType): bool =
  917. # specialized for efficiency (sigmatch uses it)
  918. ifFastObjectTypeCheckFailed(a, b):
  919. var c = initSameTypeClosure()
  920. result = sameTypeAux(a, b, c)
  921. proc sameDistinctTypes*(a, b: PType): bool {.inline.} =
  922. result = sameObjectTypes(a, b)
  923. proc sameEnumTypes*(a, b: PType): bool {.inline.} =
  924. result = a.id == b.id
  925. proc sameObjectTree(a, b: PNode, c: var TSameTypeClosure): bool =
  926. if a == b:
  927. result = true
  928. elif a != nil and b != nil and a.kind == b.kind:
  929. var x = a.typ
  930. var y = b.typ
  931. if IgnoreTupleFields in c.flags:
  932. if x != nil: x = skipTypes(x, {tyRange, tyGenericInst, tyAlias})
  933. if y != nil: y = skipTypes(y, {tyRange, tyGenericInst, tyAlias})
  934. if sameTypeOrNilAux(x, y, c):
  935. case a.kind
  936. of nkSym:
  937. # same symbol as string is enough:
  938. result = a.sym.name.id == b.sym.name.id
  939. of nkIdent: result = a.ident.id == b.ident.id
  940. of nkCharLit..nkInt64Lit: result = a.intVal == b.intVal
  941. of nkFloatLit..nkFloat64Lit: result = a.floatVal == b.floatVal
  942. of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal
  943. of nkEmpty, nkNilLit, nkType: result = true
  944. else:
  945. if a.len == b.len:
  946. for i in 0..<a.len:
  947. if not sameObjectTree(a[i], b[i], c): return
  948. result = true
  949. proc sameObjectStructures(a, b: PType, c: var TSameTypeClosure): bool =
  950. # check base types:
  951. if a.len != b.len: return
  952. for i in 0..<a.len:
  953. if not sameTypeOrNilAux(a[i], b[i], c): return
  954. if not sameObjectTree(a.n, b.n, c): return
  955. result = true
  956. proc sameChildrenAux(a, b: PType, c: var TSameTypeClosure): bool =
  957. if a.len != b.len: return false
  958. result = true
  959. for i in 0..<a.len:
  960. result = sameTypeOrNilAux(a[i], b[i], c)
  961. if not result: return
  962. proc isGenericAlias*(t: PType): bool =
  963. return t.kind == tyGenericInst and t.lastSon.kind == tyGenericInst
  964. proc skipGenericAlias*(t: PType): PType =
  965. return if t.isGenericAlias: t.lastSon else: t
  966. proc sameFlags*(a, b: PType): bool {.inline.} =
  967. result = eqTypeFlags*a.flags == eqTypeFlags*b.flags
  968. proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool =
  969. template cycleCheck() =
  970. # believe it or not, the direct check for ``containsOrIncl(c, a, b)``
  971. # increases bootstrapping time from 2.4s to 3.3s on my laptop! So we cheat
  972. # again: Since the recursion check is only to not get caught in an endless
  973. # recursion, we use a counter and only if it's value is over some
  974. # threshold we perform the expensive exact cycle check:
  975. if c.recCheck < 3:
  976. inc c.recCheck
  977. else:
  978. if containsOrIncl(c, a, b): return true
  979. if x == y: return true
  980. var a = skipTypes(x, {tyGenericInst, tyAlias})
  981. var b = skipTypes(y, {tyGenericInst, tyAlias})
  982. assert(a != nil)
  983. assert(b != nil)
  984. if a.kind != b.kind:
  985. case c.cmp
  986. of dcEq: return false
  987. of dcEqIgnoreDistinct:
  988. while a.kind == tyDistinct: a = a[0]
  989. while b.kind == tyDistinct: b = b[0]
  990. if a.kind != b.kind: return false
  991. of dcEqOrDistinctOf:
  992. while a.kind == tyDistinct: a = a[0]
  993. if a.kind != b.kind: return false
  994. # this is required by tunique_type but makes no sense really:
  995. if x.kind == tyGenericInst and IgnoreTupleFields notin c.flags:
  996. let
  997. lhs = x.skipGenericAlias
  998. rhs = y.skipGenericAlias
  999. if rhs.kind != tyGenericInst or lhs.base != rhs.base:
  1000. return false
  1001. for i in 1..<lhs.len - 1:
  1002. let ff = rhs[i]
  1003. let aa = lhs[i]
  1004. if not sameTypeAux(ff, aa, c): return false
  1005. return true
  1006. case a.kind
  1007. of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString,
  1008. tyInt..tyUInt64, tyTyped, tyUntyped, tyVoid:
  1009. result = sameFlags(a, b)
  1010. of tyStatic, tyFromExpr:
  1011. result = exprStructuralEquivalent(a.n, b.n) and sameFlags(a, b)
  1012. if result and a.len == b.len and a.len == 1:
  1013. cycleCheck()
  1014. result = sameTypeAux(a[0], b[0], c)
  1015. of tyObject:
  1016. ifFastObjectTypeCheckFailed(a, b):
  1017. cycleCheck()
  1018. result = sameObjectStructures(a, b, c) and sameFlags(a, b)
  1019. of tyDistinct:
  1020. cycleCheck()
  1021. if c.cmp == dcEq:
  1022. if sameFlags(a, b):
  1023. ifFastObjectTypeCheckFailed(a, b):
  1024. result = sameTypeAux(a[0], b[0], c)
  1025. else:
  1026. result = sameTypeAux(a[0], b[0], c) and sameFlags(a, b)
  1027. of tyEnum, tyForward:
  1028. # XXX generic enums do not make much sense, but require structural checking
  1029. result = a.id == b.id and sameFlags(a, b)
  1030. of tyError:
  1031. result = b.kind == tyError
  1032. of tyTuple:
  1033. cycleCheck()
  1034. result = sameTuple(a, b, c) and sameFlags(a, b)
  1035. of tyTypeDesc:
  1036. if c.cmp == dcEqIgnoreDistinct: result = false
  1037. elif ExactTypeDescValues in c.flags:
  1038. cycleCheck()
  1039. result = sameChildrenAux(x, y, c) and sameFlags(a, b)
  1040. else:
  1041. result = sameFlags(a, b)
  1042. of tyGenericParam:
  1043. result = sameChildrenAux(a, b, c) and sameFlags(a, b)
  1044. if result and {ExactGenericParams, ExactTypeDescValues} * c.flags != {}:
  1045. result = a.sym.position == b.sym.position
  1046. of tyBuiltInTypeClass:
  1047. assert a.len == 1
  1048. assert a[0].len == 0
  1049. assert b.len == 1
  1050. assert b[0].len == 0
  1051. result = a[0].kind == b[0].kind
  1052. of tyGenericInvocation, tyGenericBody, tySequence, tyOpenArray, tySet, tyRef,
  1053. tyPtr, tyVar, tyLent, tySink, tyUncheckedArray, tyArray, tyProc, tyVarargs,
  1054. tyOrdinal, tyCompositeTypeClass, tyUserTypeClass, tyUserTypeClassInst,
  1055. tyAnd, tyOr, tyNot, tyAnything, tyOwned:
  1056. cycleCheck()
  1057. if a.kind == tyUserTypeClass and a.n != nil: return a.n == b.n
  1058. result = sameChildrenAux(a, b, c)
  1059. if result:
  1060. if IgnoreTupleFields in c.flags:
  1061. result = a.flags * {tfVarIsPtr} == b.flags * {tfVarIsPtr}
  1062. else:
  1063. result = sameFlags(a, b)
  1064. if result and ExactGcSafety in c.flags:
  1065. result = a.flags * {tfThread} == b.flags * {tfThread}
  1066. if result and a.kind == tyProc:
  1067. result = ((IgnoreCC in c.flags) or a.callConv == b.callConv) and
  1068. ((ExactConstraints notin c.flags) or sameConstraints(a.n, b.n))
  1069. of tyRange:
  1070. cycleCheck()
  1071. result = sameTypeOrNilAux(a[0], b[0], c) and
  1072. sameValue(a.n[0], b.n[0]) and
  1073. sameValue(a.n[1], b.n[1])
  1074. of tyGenericInst, tyAlias, tyInferred:
  1075. cycleCheck()
  1076. result = sameTypeAux(a.lastSon, b.lastSon, c)
  1077. of tyNone: result = false
  1078. of tyOptDeprecated: doAssert false
  1079. proc sameBackendType*(x, y: PType): bool =
  1080. var c = initSameTypeClosure()
  1081. c.flags.incl IgnoreTupleFields
  1082. c.cmp = dcEqIgnoreDistinct
  1083. result = sameTypeAux(x, y, c)
  1084. proc compareTypes*(x, y: PType,
  1085. cmp: TDistinctCompare = dcEq,
  1086. flags: TTypeCmpFlags = {}): bool =
  1087. ## compares two type for equality (modulo type distinction)
  1088. var c = initSameTypeClosure()
  1089. c.cmp = cmp
  1090. c.flags = flags
  1091. if x == y: result = true
  1092. elif x.isNil or y.isNil: result = false
  1093. else: result = sameTypeAux(x, y, c)
  1094. proc inheritanceDiff*(a, b: PType): int =
  1095. # | returns: 0 iff `a` == `b`
  1096. # | returns: -x iff `a` is the x'th direct superclass of `b`
  1097. # | returns: +x iff `a` is the x'th direct subclass of `b`
  1098. # | returns: `maxint` iff `a` and `b` are not compatible at all
  1099. if a == b or a.kind == tyError or b.kind == tyError: return 0
  1100. assert a.kind in {tyObject} + skipPtrs
  1101. assert b.kind in {tyObject} + skipPtrs
  1102. var x = a
  1103. result = 0
  1104. while x != nil:
  1105. x = skipTypes(x, skipPtrs)
  1106. if sameObjectTypes(x, b): return
  1107. x = x[0]
  1108. dec(result)
  1109. var y = b
  1110. result = 0
  1111. while y != nil:
  1112. y = skipTypes(y, skipPtrs)
  1113. if sameObjectTypes(y, a): return
  1114. y = y[0]
  1115. inc(result)
  1116. result = high(int)
  1117. proc commonSuperclass*(a, b: PType): PType =
  1118. # quick check: are they the same?
  1119. if sameObjectTypes(a, b): return a
  1120. # simple algorithm: we store all ancestors of 'a' in a ID-set and walk 'b'
  1121. # up until the ID is found:
  1122. assert a.kind == tyObject
  1123. assert b.kind == tyObject
  1124. var x = a
  1125. var ancestors = initIntSet()
  1126. while x != nil:
  1127. x = skipTypes(x, skipPtrs)
  1128. ancestors.incl(x.id)
  1129. x = x[0]
  1130. var y = b
  1131. while y != nil:
  1132. var t = y # bug #7818, save type before skip
  1133. y = skipTypes(y, skipPtrs)
  1134. if ancestors.contains(y.id):
  1135. # bug #7818, defer the previous skipTypes
  1136. if t.kind != tyGenericInst: t = y
  1137. return t
  1138. y = y[0]
  1139. type
  1140. TTypeAllowedFlag* = enum
  1141. taField,
  1142. taHeap,
  1143. taConcept,
  1144. taIsOpenArray,
  1145. taNoUntyped
  1146. taIsTemplateOrMacro
  1147. taProcContextIsNotMacro
  1148. TTypeAllowedFlags* = set[TTypeAllowedFlag]
  1149. proc typeAllowedAux(marker: var IntSet, typ: PType, kind: TSymKind,
  1150. flags: TTypeAllowedFlags = {}): PType
  1151. proc typeAllowedNode(marker: var IntSet, n: PNode, kind: TSymKind,
  1152. flags: TTypeAllowedFlags = {}): PType =
  1153. if n != nil:
  1154. result = typeAllowedAux(marker, n.typ, kind, flags)
  1155. if result == nil:
  1156. case n.kind
  1157. of nkNone..nkNilLit:
  1158. discard
  1159. else:
  1160. #if n.kind == nkRecCase and kind in {skProc, skFunc, skConst}:
  1161. # return n[0].typ
  1162. for i in 0..<n.len:
  1163. let it = n[i]
  1164. result = typeAllowedNode(marker, it, kind, flags)
  1165. if result != nil: break
  1166. proc matchType*(a: PType, pattern: openArray[tuple[k:TTypeKind, i:int]],
  1167. last: TTypeKind): bool =
  1168. var a = a
  1169. for k, i in pattern.items:
  1170. if a.kind != k: return false
  1171. if i >= a.len or a[i] == nil: return false
  1172. a = a[i]
  1173. result = a.kind == last
  1174. proc typeAllowedAux(marker: var IntSet, typ: PType, kind: TSymKind,
  1175. flags: TTypeAllowedFlags = {}): PType =
  1176. assert(kind in {skVar, skLet, skConst, skProc, skFunc, skParam, skResult})
  1177. # if we have already checked the type, return true, because we stop the
  1178. # evaluation if something is wrong:
  1179. result = nil
  1180. if typ == nil: return nil
  1181. if containsOrIncl(marker, typ.id): return nil
  1182. var t = skipTypes(typ, abstractInst-{tyTypeDesc})
  1183. case t.kind
  1184. of tyVar, tyLent:
  1185. if kind in {skProc, skFunc, skConst}:
  1186. result = t
  1187. elif t.kind == tyLent and kind != skResult:
  1188. result = t
  1189. else:
  1190. var t2 = skipTypes(t[0], abstractInst-{tyTypeDesc})
  1191. case t2.kind
  1192. of tyVar, tyLent:
  1193. if taHeap notin flags: result = t2 # ``var var`` is illegal on the heap
  1194. of tyOpenArray:
  1195. if kind != skParam or taIsOpenArray in flags: result = t
  1196. else: result = typeAllowedAux(marker, t2[0], kind, flags+{taIsOpenArray})
  1197. of tyUncheckedArray:
  1198. if kind != skParam: result = t
  1199. else: result = typeAllowedAux(marker, t2[0], kind, flags)
  1200. else:
  1201. if kind notin {skParam, skResult}: result = t
  1202. else: result = typeAllowedAux(marker, t2, kind, flags)
  1203. of tyProc:
  1204. if kind in {skVar, skLet, skConst} and taIsTemplateOrMacro in flags:
  1205. result = t
  1206. else:
  1207. if isInlineIterator(typ) and kind in {skVar, skLet, skConst, skParam, skResult}:
  1208. # only closure iterators may be assigned to anything.
  1209. result = t
  1210. let f = if kind in {skProc, skFunc}: flags+{taNoUntyped} else: flags
  1211. for i in 1..<t.len:
  1212. if result != nil: break
  1213. result = typeAllowedAux(marker, t[i], skParam, f-{taIsOpenArray})
  1214. if result.isNil and t[0] != nil:
  1215. result = typeAllowedAux(marker, t[0], skResult, flags)
  1216. of tyTypeDesc:
  1217. if kind in {skVar, skLet, skConst} and taProcContextIsNotMacro in flags:
  1218. result = t
  1219. else:
  1220. # XXX: This is still a horrible idea...
  1221. result = nil
  1222. of tyUntyped, tyTyped:
  1223. if kind notin {skParam, skResult} or taNoUntyped in flags: result = t
  1224. of tyStatic:
  1225. if kind notin {skParam}: result = t
  1226. of tyVoid:
  1227. if taField notin flags: result = t
  1228. of tyTypeClasses:
  1229. if tfGenericTypeParam in t.flags or taConcept in flags: #or taField notin flags:
  1230. discard
  1231. elif t.isResolvedUserTypeClass:
  1232. result = typeAllowedAux(marker, t.lastSon, kind, flags)
  1233. elif kind notin {skParam, skResult}:
  1234. result = t
  1235. of tyGenericBody, tyGenericParam, tyGenericInvocation,
  1236. tyNone, tyForward, tyFromExpr:
  1237. result = t
  1238. of tyNil:
  1239. if kind != skConst and kind != skParam: result = t
  1240. of tyString, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCString, tyPointer:
  1241. result = nil
  1242. of tyOrdinal:
  1243. if kind != skParam: result = t
  1244. of tyGenericInst, tyDistinct, tyAlias, tyInferred:
  1245. result = typeAllowedAux(marker, lastSon(t), kind, flags)
  1246. of tyRange:
  1247. if skipTypes(t[0], abstractInst-{tyTypeDesc}).kind notin
  1248. {tyChar, tyEnum, tyInt..tyFloat128, tyInt..tyUInt64}: result = t
  1249. of tyOpenArray, tyVarargs, tySink:
  1250. # you cannot nest openArrays/sinks/etc.
  1251. if kind != skParam or taIsOpenArray in flags:
  1252. result = t
  1253. else:
  1254. result = typeAllowedAux(marker, t[0], kind, flags+{taIsOpenArray})
  1255. of tyUncheckedArray:
  1256. if kind != skParam and taHeap notin flags:
  1257. result = t
  1258. else:
  1259. result = typeAllowedAux(marker, lastSon(t), kind, flags-{taHeap})
  1260. of tySequence:
  1261. if t[0].kind != tyEmpty:
  1262. result = typeAllowedAux(marker, t[0], kind, flags+{taHeap})
  1263. elif kind in {skVar, skLet}:
  1264. result = t[0]
  1265. of tyArray:
  1266. if t[1].kind == tyTypeDesc:
  1267. result = t[1]
  1268. elif t[1].kind != tyEmpty:
  1269. result = typeAllowedAux(marker, t[1], kind, flags)
  1270. elif kind in {skVar, skLet}:
  1271. result = t[1]
  1272. of tyRef:
  1273. if kind == skConst: result = t
  1274. else: result = typeAllowedAux(marker, t.lastSon, kind, flags+{taHeap})
  1275. of tyPtr:
  1276. result = typeAllowedAux(marker, t.lastSon, kind, flags+{taHeap})
  1277. of tySet:
  1278. for i in 0..<t.len:
  1279. result = typeAllowedAux(marker, t[i], kind, flags)
  1280. if result != nil: break
  1281. of tyObject, tyTuple:
  1282. if kind in {skProc, skFunc, skConst} and
  1283. t.kind == tyObject and t[0] != nil:
  1284. result = t
  1285. else:
  1286. let flags = flags+{taField}
  1287. for i in 0..<t.len:
  1288. result = typeAllowedAux(marker, t[i], kind, flags)
  1289. if result != nil: break
  1290. if result.isNil and t.n != nil:
  1291. result = typeAllowedNode(marker, t.n, kind, flags)
  1292. of tyEmpty:
  1293. if kind in {skVar, skLet}: result = t
  1294. of tyProxy:
  1295. # for now same as error node; we say it's a valid type as it should
  1296. # prevent cascading errors:
  1297. result = nil
  1298. of tyOwned:
  1299. if t.len == 1 and t[0].skipTypes(abstractInst).kind in {tyRef, tyPtr, tyProc}:
  1300. result = typeAllowedAux(marker, t.lastSon, kind, flags+{taHeap})
  1301. else:
  1302. result = t
  1303. of tyOptDeprecated: doAssert false
  1304. proc typeAllowed*(t: PType, kind: TSymKind; flags: TTypeAllowedFlags = {}): PType =
  1305. # returns 'nil' on success and otherwise the part of the type that is
  1306. # wrong!
  1307. var marker = initIntSet()
  1308. result = typeAllowedAux(marker, t, kind, flags)
  1309. include sizealignoffsetimpl
  1310. proc computeSize*(conf: ConfigRef; typ: PType): BiggestInt =
  1311. computeSizeAlign(conf, typ)
  1312. result = typ.size
  1313. proc getReturnType*(s: PSym): PType =
  1314. # Obtains the return type of a iterator/proc/macro/template
  1315. assert s.kind in skProcKinds
  1316. result = s.typ[0]
  1317. proc getAlign*(conf: ConfigRef; typ: PType): BiggestInt =
  1318. computeSizeAlign(conf, typ)
  1319. result = typ.align
  1320. proc getSize*(conf: ConfigRef; typ: PType): BiggestInt =
  1321. computeSizeAlign(conf, typ)
  1322. result = typ.size
  1323. proc containsGenericTypeIter(t: PType, closure: RootRef): bool =
  1324. case t.kind
  1325. of tyStatic:
  1326. return t.n == nil
  1327. of tyTypeDesc:
  1328. if t.base.kind == tyNone: return true
  1329. if containsGenericTypeIter(t.base, closure): return true
  1330. return false
  1331. of GenericTypes + tyTypeClasses + {tyFromExpr}:
  1332. return true
  1333. else:
  1334. return false
  1335. proc containsGenericType*(t: PType): bool =
  1336. result = iterOverType(t, containsGenericTypeIter, nil)
  1337. proc baseOfDistinct*(t: PType): PType =
  1338. if t.kind == tyDistinct:
  1339. result = t[0]
  1340. else:
  1341. result = copyType(t, t.owner, false)
  1342. var parent: PType = nil
  1343. var it = result
  1344. while it.kind in {tyPtr, tyRef, tyOwned}:
  1345. parent = it
  1346. it = it.lastSon
  1347. if it.kind == tyDistinct and parent != nil:
  1348. parent[0] = it[0]
  1349. proc safeInheritanceDiff*(a, b: PType): int =
  1350. # same as inheritanceDiff but checks for tyError:
  1351. if a.kind == tyError or b.kind == tyError:
  1352. result = -1
  1353. else:
  1354. result = inheritanceDiff(a.skipTypes(skipPtrs), b.skipTypes(skipPtrs))
  1355. proc compatibleEffectsAux(se, re: PNode): bool =
  1356. if re.isNil: return false
  1357. for r in items(re):
  1358. block search:
  1359. for s in items(se):
  1360. if safeInheritanceDiff(r.typ, s.typ) <= 0:
  1361. break search
  1362. return false
  1363. result = true
  1364. type
  1365. EffectsCompat* = enum
  1366. efCompat
  1367. efRaisesDiffer
  1368. efRaisesUnknown
  1369. efTagsDiffer
  1370. efTagsUnknown
  1371. efLockLevelsDiffer
  1372. proc compatibleEffects*(formal, actual: PType): EffectsCompat =
  1373. # for proc type compatibility checking:
  1374. assert formal.kind == tyProc and actual.kind == tyProc
  1375. if formal.n[0].kind != nkEffectList or
  1376. actual.n[0].kind != nkEffectList:
  1377. return efTagsUnknown
  1378. var spec = formal.n[0]
  1379. if spec.len != 0:
  1380. var real = actual.n[0]
  1381. let se = spec[exceptionEffects]
  1382. # if 'se.kind == nkArgList' it is no formal type really, but a
  1383. # computed effect and as such no spec:
  1384. # 'r.msgHandler = if isNil(msgHandler): defaultMsgHandler else: msgHandler'
  1385. if not isNil(se) and se.kind != nkArgList:
  1386. # spec requires some exception or tag, but we don't know anything:
  1387. if real.len == 0: return efRaisesUnknown
  1388. let res = compatibleEffectsAux(se, real[exceptionEffects])
  1389. if not res: return efRaisesDiffer
  1390. let st = spec[tagEffects]
  1391. if not isNil(st) and st.kind != nkArgList:
  1392. # spec requires some exception or tag, but we don't know anything:
  1393. if real.len == 0: return efTagsUnknown
  1394. let res = compatibleEffectsAux(st, real[tagEffects])
  1395. if not res: return efTagsDiffer
  1396. if formal.lockLevel.ord < 0 or
  1397. actual.lockLevel.ord <= formal.lockLevel.ord:
  1398. result = efCompat
  1399. else:
  1400. result = efLockLevelsDiffer
  1401. proc isCompileTimeOnly*(t: PType): bool {.inline.} =
  1402. result = t.kind in {tyTypeDesc, tyStatic}
  1403. proc containsCompileTimeOnly*(t: PType): bool =
  1404. if isCompileTimeOnly(t): return true
  1405. for i in 0..<t.len:
  1406. if t[i] != nil and isCompileTimeOnly(t[i]):
  1407. return true
  1408. return false
  1409. proc safeSkipTypes*(t: PType, kinds: TTypeKinds): PType =
  1410. ## same as 'skipTypes' but with a simple cycle detector.
  1411. result = t
  1412. var seen = initIntSet()
  1413. while result.kind in kinds and not containsOrIncl(seen, result.id):
  1414. result = lastSon(result)
  1415. type
  1416. OrdinalType* = enum
  1417. NoneLike, IntLike, FloatLike
  1418. proc classify*(t: PType): OrdinalType =
  1419. ## for convenient type checking:
  1420. if t == nil:
  1421. result = NoneLike
  1422. else:
  1423. case skipTypes(t, abstractVarRange).kind
  1424. of tyFloat..tyFloat128: result = FloatLike
  1425. of tyInt..tyInt64, tyUInt..tyUInt64, tyBool, tyChar, tyEnum:
  1426. result = IntLike
  1427. else: result = NoneLike
  1428. proc skipConv*(n: PNode): PNode =
  1429. result = n
  1430. case n.kind
  1431. of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
  1432. # only skip the conversion if it doesn't lose too important information
  1433. # (see bug #1334)
  1434. if n[0].typ.classify == n.typ.classify:
  1435. result = n[0]
  1436. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  1437. if n[1].typ.classify == n.typ.classify:
  1438. result = n[1]
  1439. else: discard
  1440. proc skipHidden*(n: PNode): PNode =
  1441. result = n
  1442. while true:
  1443. case result.kind
  1444. of nkHiddenStdConv, nkHiddenSubConv:
  1445. if result[1].typ.classify == result.typ.classify:
  1446. result = result[1]
  1447. else: break
  1448. of nkHiddenDeref, nkHiddenAddr:
  1449. result = result[0]
  1450. else: break
  1451. proc skipConvTakeType*(n: PNode): PNode =
  1452. result = n.skipConv
  1453. result.typ = n.typ
  1454. proc isEmptyContainer*(t: PType): bool =
  1455. case t.kind
  1456. of tyUntyped, tyNil: result = true
  1457. of tyArray: result = t[1].kind == tyEmpty
  1458. of tySet, tySequence, tyOpenArray, tyVarargs:
  1459. result = t[0].kind == tyEmpty
  1460. of tyGenericInst, tyAlias, tySink: result = isEmptyContainer(t.lastSon)
  1461. else: result = false
  1462. proc takeType*(formal, arg: PType): PType =
  1463. # param: openArray[string] = []
  1464. # [] is an array constructor of length 0 of type string!
  1465. if arg.kind == tyNil:
  1466. # and not (formal.kind == tyProc and formal.callConv == ccClosure):
  1467. result = formal
  1468. elif formal.kind in {tyOpenArray, tyVarargs, tySequence} and
  1469. arg.isEmptyContainer:
  1470. let a = copyType(arg.skipTypes({tyGenericInst, tyAlias}), arg.owner, keepId=false)
  1471. a[ord(arg.kind == tyArray)] = formal[0]
  1472. result = a
  1473. elif formal.kind in {tyTuple, tySet} and arg.kind == formal.kind:
  1474. result = formal
  1475. else:
  1476. result = arg
  1477. proc skipHiddenSubConv*(n: PNode): PNode =
  1478. if n.kind == nkHiddenSubConv:
  1479. # param: openArray[string] = []
  1480. # [] is an array constructor of length 0 of type string!
  1481. let formal = n.typ
  1482. result = n[1]
  1483. let arg = result.typ
  1484. let dest = takeType(formal, arg)
  1485. if dest == arg and formal.kind != tyUntyped:
  1486. #echo n.info, " came here for ", formal.typeToString
  1487. result = n
  1488. else:
  1489. result = copyTree(result)
  1490. result.typ = dest
  1491. else:
  1492. result = n
  1493. proc typeMismatch*(conf: ConfigRef; info: TLineInfo, formal, actual: PType) =
  1494. if formal.kind != tyError and actual.kind != tyError:
  1495. let named = typeToString(formal)
  1496. let desc = typeToString(formal, preferDesc)
  1497. let x = if named == desc: named else: named & " = " & desc
  1498. var msg = "type mismatch: got <" &
  1499. typeToString(actual) & "> " &
  1500. "but expected '" & x & "'"
  1501. if formal.kind == tyProc and actual.kind == tyProc:
  1502. case compatibleEffects(formal, actual)
  1503. of efCompat: discard
  1504. of efRaisesDiffer:
  1505. msg.add "\n.raise effects differ"
  1506. of efRaisesUnknown:
  1507. msg.add "\n.raise effect is 'can raise any'"
  1508. of efTagsDiffer:
  1509. msg.add "\n.tag effects differ"
  1510. of efTagsUnknown:
  1511. msg.add "\n.tag effect is 'any tag allowed'"
  1512. of efLockLevelsDiffer:
  1513. msg.add "\nlock levels differ"
  1514. localError(conf, info, msg)
  1515. proc isTupleRecursive(t: PType, cycleDetector: var IntSet): bool =
  1516. if t == nil:
  1517. return false
  1518. if cycleDetector.containsOrIncl(t.id):
  1519. return true
  1520. case t.kind
  1521. of tyTuple:
  1522. var cycleDetectorCopy: IntSet
  1523. for i in 0..<t.len:
  1524. assign(cycleDetectorCopy, cycleDetector)
  1525. if isTupleRecursive(t[i], cycleDetectorCopy):
  1526. return true
  1527. of tyAlias, tyRef, tyPtr, tyGenericInst, tyVar, tyLent, tySink,
  1528. tyArray, tyUncheckedArray, tySequence, tyDistinct:
  1529. return isTupleRecursive(t.lastSon, cycleDetector)
  1530. else:
  1531. return false
  1532. proc isTupleRecursive*(t: PType): bool =
  1533. var cycleDetector = initIntSet()
  1534. isTupleRecursive(t, cycleDetector)
  1535. proc isException*(t: PType): bool =
  1536. # check if `y` is object type and it inherits from Exception
  1537. assert(t != nil)
  1538. var t = t.skipTypes(abstractInst)
  1539. while t.kind == tyObject:
  1540. if t.sym != nil and t.sym.magic == mException: return true
  1541. if t[0] == nil: break
  1542. t = skipTypes(t[0], abstractPtrs)
  1543. return false
  1544. proc isDefectException*(t: PType): bool =
  1545. var t = t.skipTypes(abstractPtrs)
  1546. while t.kind == tyObject:
  1547. if t.sym != nil and t.sym.owner != nil and
  1548. sfSystemModule in t.sym.owner.flags and
  1549. t.sym.name.s == "Defect":
  1550. return true
  1551. if t[0] == nil: break
  1552. t = skipTypes(t[0], abstractPtrs)
  1553. return false
  1554. proc isSinkTypeForParam*(t: PType): bool =
  1555. # a parameter like 'seq[owned T]' must not be used only once, but its
  1556. # elements must, so we detect this case here:
  1557. result = t.skipTypes({tyGenericInst, tyAlias}).kind in {tySink, tyOwned}
  1558. when false:
  1559. if isSinkType(t):
  1560. if t.skipTypes({tyGenericInst, tyAlias}).kind in {tyArray, tyVarargs, tyOpenArray, tySequence}:
  1561. result = false
  1562. else:
  1563. result = true