types.nim 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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, tyOpenArray, tyVarargs}
  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. result = ""
  414. let prefer = getPrefer(prefer)
  415. let t = typ
  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 == ccNimCall and tfExplicitCallConv notin t.flags: "" 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, tyLent:
  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, tyLent:
  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. while a.kind == tyUserTypeClass and tfResolved in a.flags:
  982. a = skipTypes(a[^1], {tyGenericInst, tyAlias})
  983. var b = skipTypes(y, {tyGenericInst, tyAlias})
  984. while b.kind == tyUserTypeClass and tfResolved in b.flags:
  985. b = skipTypes(b[^1], {tyGenericInst, tyAlias})
  986. assert(a != nil)
  987. assert(b != nil)
  988. if a.kind != b.kind:
  989. case c.cmp
  990. of dcEq: return false
  991. of dcEqIgnoreDistinct:
  992. while a.kind == tyDistinct: a = a[0]
  993. while b.kind == tyDistinct: b = b[0]
  994. if a.kind != b.kind: return false
  995. of dcEqOrDistinctOf:
  996. while a.kind == tyDistinct: a = a[0]
  997. if a.kind != b.kind: return false
  998. # this is required by tunique_type but makes no sense really:
  999. if x.kind == tyGenericInst and IgnoreTupleFields notin c.flags:
  1000. let
  1001. lhs = x.skipGenericAlias
  1002. rhs = y.skipGenericAlias
  1003. if rhs.kind != tyGenericInst or lhs.base != rhs.base:
  1004. return false
  1005. for i in 1..<lhs.len - 1:
  1006. let ff = rhs[i]
  1007. let aa = lhs[i]
  1008. if not sameTypeAux(ff, aa, c): return false
  1009. return true
  1010. case a.kind
  1011. of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString,
  1012. tyInt..tyUInt64, tyTyped, tyUntyped, tyVoid:
  1013. result = sameFlags(a, b)
  1014. of tyStatic, tyFromExpr:
  1015. result = exprStructuralEquivalent(a.n, b.n) and sameFlags(a, b)
  1016. if result and a.len == b.len and a.len == 1:
  1017. cycleCheck()
  1018. result = sameTypeAux(a[0], b[0], c)
  1019. of tyObject:
  1020. ifFastObjectTypeCheckFailed(a, b):
  1021. cycleCheck()
  1022. result = sameObjectStructures(a, b, c) and sameFlags(a, b)
  1023. of tyDistinct:
  1024. cycleCheck()
  1025. if c.cmp == dcEq:
  1026. if sameFlags(a, b):
  1027. ifFastObjectTypeCheckFailed(a, b):
  1028. result = sameTypeAux(a[0], b[0], c)
  1029. else:
  1030. result = sameTypeAux(a[0], b[0], c) and sameFlags(a, b)
  1031. of tyEnum, tyForward:
  1032. # XXX generic enums do not make much sense, but require structural checking
  1033. result = a.id == b.id and sameFlags(a, b)
  1034. of tyError:
  1035. result = b.kind == tyError
  1036. of tyTuple:
  1037. cycleCheck()
  1038. result = sameTuple(a, b, c) and sameFlags(a, b)
  1039. of tyTypeDesc:
  1040. if c.cmp == dcEqIgnoreDistinct: result = false
  1041. elif ExactTypeDescValues in c.flags:
  1042. cycleCheck()
  1043. result = sameChildrenAux(x, y, c) and sameFlags(a, b)
  1044. else:
  1045. result = sameFlags(a, b)
  1046. of tyGenericParam:
  1047. result = sameChildrenAux(a, b, c) and sameFlags(a, b)
  1048. if result and {ExactGenericParams, ExactTypeDescValues} * c.flags != {}:
  1049. result = a.sym.position == b.sym.position
  1050. of tyBuiltInTypeClass:
  1051. assert a.len == 1
  1052. assert a[0].len == 0
  1053. assert b.len == 1
  1054. assert b[0].len == 0
  1055. result = a[0].kind == b[0].kind
  1056. of tyGenericInvocation, tyGenericBody, tySequence, tyOpenArray, tySet, tyRef,
  1057. tyPtr, tyVar, tyLent, tySink, tyUncheckedArray, tyArray, tyProc, tyVarargs,
  1058. tyOrdinal, tyCompositeTypeClass, tyUserTypeClass, tyUserTypeClassInst,
  1059. tyAnd, tyOr, tyNot, tyAnything, tyOwned:
  1060. cycleCheck()
  1061. if a.kind == tyUserTypeClass and a.n != nil: return a.n == b.n
  1062. result = sameChildrenAux(a, b, c)
  1063. if result:
  1064. if IgnoreTupleFields in c.flags:
  1065. result = a.flags * {tfVarIsPtr} == b.flags * {tfVarIsPtr}
  1066. else:
  1067. result = sameFlags(a, b)
  1068. if result and ExactGcSafety in c.flags:
  1069. result = a.flags * {tfThread} == b.flags * {tfThread}
  1070. if result and a.kind == tyProc:
  1071. result = ((IgnoreCC in c.flags) or a.callConv == b.callConv) and
  1072. ((ExactConstraints notin c.flags) or sameConstraints(a.n, b.n))
  1073. of tyRange:
  1074. cycleCheck()
  1075. result = sameTypeOrNilAux(a[0], b[0], c) and
  1076. sameValue(a.n[0], b.n[0]) and
  1077. sameValue(a.n[1], b.n[1])
  1078. of tyGenericInst, tyAlias, tyInferred:
  1079. cycleCheck()
  1080. result = sameTypeAux(a.lastSon, b.lastSon, c)
  1081. of tyNone: result = false
  1082. of tyOptDeprecated: doAssert false
  1083. proc sameBackendType*(x, y: PType): bool =
  1084. var c = initSameTypeClosure()
  1085. c.flags.incl IgnoreTupleFields
  1086. c.cmp = dcEqIgnoreDistinct
  1087. result = sameTypeAux(x, y, c)
  1088. proc compareTypes*(x, y: PType,
  1089. cmp: TDistinctCompare = dcEq,
  1090. flags: TTypeCmpFlags = {}): bool =
  1091. ## compares two type for equality (modulo type distinction)
  1092. var c = initSameTypeClosure()
  1093. c.cmp = cmp
  1094. c.flags = flags
  1095. if x == y: result = true
  1096. elif x.isNil or y.isNil: result = false
  1097. else: result = sameTypeAux(x, y, c)
  1098. proc inheritanceDiff*(a, b: PType): int =
  1099. # | returns: 0 iff `a` == `b`
  1100. # | returns: -x iff `a` is the x'th direct superclass of `b`
  1101. # | returns: +x iff `a` is the x'th direct subclass of `b`
  1102. # | returns: `maxint` iff `a` and `b` are not compatible at all
  1103. if a == b or a.kind == tyError or b.kind == tyError: return 0
  1104. assert a.kind in {tyObject} + skipPtrs
  1105. assert b.kind in {tyObject} + skipPtrs
  1106. var x = a
  1107. result = 0
  1108. while x != nil:
  1109. x = skipTypes(x, skipPtrs)
  1110. if sameObjectTypes(x, b): return
  1111. x = x[0]
  1112. dec(result)
  1113. var y = b
  1114. result = 0
  1115. while y != nil:
  1116. y = skipTypes(y, skipPtrs)
  1117. if sameObjectTypes(y, a): return
  1118. y = y[0]
  1119. inc(result)
  1120. result = high(int)
  1121. proc commonSuperclass*(a, b: PType): PType =
  1122. # quick check: are they the same?
  1123. if sameObjectTypes(a, b): return a
  1124. # simple algorithm: we store all ancestors of 'a' in a ID-set and walk 'b'
  1125. # up until the ID is found:
  1126. assert a.kind == tyObject
  1127. assert b.kind == tyObject
  1128. var x = a
  1129. var ancestors = initIntSet()
  1130. while x != nil:
  1131. x = skipTypes(x, skipPtrs)
  1132. ancestors.incl(x.id)
  1133. x = x[0]
  1134. var y = b
  1135. while y != nil:
  1136. var t = y # bug #7818, save type before skip
  1137. y = skipTypes(y, skipPtrs)
  1138. if ancestors.contains(y.id):
  1139. # bug #7818, defer the previous skipTypes
  1140. if t.kind != tyGenericInst: t = y
  1141. return t
  1142. y = y[0]
  1143. proc matchType*(a: PType, pattern: openArray[tuple[k:TTypeKind, i:int]],
  1144. last: TTypeKind): bool =
  1145. var a = a
  1146. for k, i in pattern.items:
  1147. if a.kind != k: return false
  1148. if i >= a.len or a[i] == nil: return false
  1149. a = a[i]
  1150. result = a.kind == last
  1151. include sizealignoffsetimpl
  1152. proc computeSize*(conf: ConfigRef; typ: PType): BiggestInt =
  1153. computeSizeAlign(conf, typ)
  1154. result = typ.size
  1155. proc getReturnType*(s: PSym): PType =
  1156. # Obtains the return type of a iterator/proc/macro/template
  1157. assert s.kind in skProcKinds
  1158. result = s.typ[0]
  1159. proc getAlign*(conf: ConfigRef; typ: PType): BiggestInt =
  1160. computeSizeAlign(conf, typ)
  1161. result = typ.align
  1162. proc getSize*(conf: ConfigRef; typ: PType): BiggestInt =
  1163. computeSizeAlign(conf, typ)
  1164. result = typ.size
  1165. proc containsGenericTypeIter(t: PType, closure: RootRef): bool =
  1166. case t.kind
  1167. of tyStatic:
  1168. return t.n == nil
  1169. of tyTypeDesc:
  1170. if t.base.kind == tyNone: return true
  1171. if containsGenericTypeIter(t.base, closure): return true
  1172. return false
  1173. of GenericTypes + tyTypeClasses + {tyFromExpr}:
  1174. return true
  1175. else:
  1176. return false
  1177. proc containsGenericType*(t: PType): bool =
  1178. result = iterOverType(t, containsGenericTypeIter, nil)
  1179. proc baseOfDistinct*(t: PType): PType =
  1180. if t.kind == tyDistinct:
  1181. result = t[0]
  1182. else:
  1183. result = copyType(t, t.owner, false)
  1184. var parent: PType = nil
  1185. var it = result
  1186. while it.kind in {tyPtr, tyRef, tyOwned}:
  1187. parent = it
  1188. it = it.lastSon
  1189. if it.kind == tyDistinct and parent != nil:
  1190. parent[0] = it[0]
  1191. proc safeInheritanceDiff*(a, b: PType): int =
  1192. # same as inheritanceDiff but checks for tyError:
  1193. if a.kind == tyError or b.kind == tyError:
  1194. result = -1
  1195. else:
  1196. result = inheritanceDiff(a.skipTypes(skipPtrs), b.skipTypes(skipPtrs))
  1197. proc compatibleEffectsAux(se, re: PNode): bool =
  1198. if re.isNil: return false
  1199. for r in items(re):
  1200. block search:
  1201. for s in items(se):
  1202. if safeInheritanceDiff(r.typ, s.typ) <= 0:
  1203. break search
  1204. return false
  1205. result = true
  1206. type
  1207. EffectsCompat* = enum
  1208. efCompat
  1209. efRaisesDiffer
  1210. efRaisesUnknown
  1211. efTagsDiffer
  1212. efTagsUnknown
  1213. efLockLevelsDiffer
  1214. proc compatibleEffects*(formal, actual: PType): EffectsCompat =
  1215. # for proc type compatibility checking:
  1216. assert formal.kind == tyProc and actual.kind == tyProc
  1217. if formal.n[0].kind != nkEffectList or
  1218. actual.n[0].kind != nkEffectList:
  1219. return efTagsUnknown
  1220. var spec = formal.n[0]
  1221. if spec.len != 0:
  1222. var real = actual.n[0]
  1223. let se = spec[exceptionEffects]
  1224. # if 'se.kind == nkArgList' it is no formal type really, but a
  1225. # computed effect and as such no spec:
  1226. # 'r.msgHandler = if isNil(msgHandler): defaultMsgHandler else: msgHandler'
  1227. if not isNil(se) and se.kind != nkArgList:
  1228. # spec requires some exception or tag, but we don't know anything:
  1229. if real.len == 0: return efRaisesUnknown
  1230. let res = compatibleEffectsAux(se, real[exceptionEffects])
  1231. if not res: return efRaisesDiffer
  1232. let st = spec[tagEffects]
  1233. if not isNil(st) and st.kind != nkArgList:
  1234. # spec requires some exception or tag, but we don't know anything:
  1235. if real.len == 0: return efTagsUnknown
  1236. let res = compatibleEffectsAux(st, real[tagEffects])
  1237. if not res: return efTagsDiffer
  1238. if formal.lockLevel.ord < 0 or
  1239. actual.lockLevel.ord <= formal.lockLevel.ord:
  1240. result = efCompat
  1241. else:
  1242. result = efLockLevelsDiffer
  1243. proc isCompileTimeOnly*(t: PType): bool {.inline.} =
  1244. result = t.kind in {tyTypeDesc, tyStatic}
  1245. proc containsCompileTimeOnly*(t: PType): bool =
  1246. if isCompileTimeOnly(t): return true
  1247. for i in 0..<t.len:
  1248. if t[i] != nil and isCompileTimeOnly(t[i]):
  1249. return true
  1250. return false
  1251. proc safeSkipTypes*(t: PType, kinds: TTypeKinds): PType =
  1252. ## same as 'skipTypes' but with a simple cycle detector.
  1253. result = t
  1254. var seen = initIntSet()
  1255. while result.kind in kinds and not containsOrIncl(seen, result.id):
  1256. result = lastSon(result)
  1257. type
  1258. OrdinalType* = enum
  1259. NoneLike, IntLike, FloatLike
  1260. proc classify*(t: PType): OrdinalType =
  1261. ## for convenient type checking:
  1262. if t == nil:
  1263. result = NoneLike
  1264. else:
  1265. case skipTypes(t, abstractVarRange).kind
  1266. of tyFloat..tyFloat128: result = FloatLike
  1267. of tyInt..tyInt64, tyUInt..tyUInt64, tyBool, tyChar, tyEnum:
  1268. result = IntLike
  1269. else: result = NoneLike
  1270. proc skipConv*(n: PNode): PNode =
  1271. result = n
  1272. case n.kind
  1273. of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
  1274. # only skip the conversion if it doesn't lose too important information
  1275. # (see bug #1334)
  1276. if n[0].typ.classify == n.typ.classify:
  1277. result = n[0]
  1278. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  1279. if n[1].typ.classify == n.typ.classify:
  1280. result = n[1]
  1281. else: discard
  1282. proc skipHidden*(n: PNode): PNode =
  1283. result = n
  1284. while true:
  1285. case result.kind
  1286. of nkHiddenStdConv, nkHiddenSubConv:
  1287. if result[1].typ.classify == result.typ.classify:
  1288. result = result[1]
  1289. else: break
  1290. of nkHiddenDeref, nkHiddenAddr:
  1291. result = result[0]
  1292. else: break
  1293. proc skipConvTakeType*(n: PNode): PNode =
  1294. result = n.skipConv
  1295. result.typ = n.typ
  1296. proc isEmptyContainer*(t: PType): bool =
  1297. case t.kind
  1298. of tyUntyped, tyNil: result = true
  1299. of tyArray: result = t[1].kind == tyEmpty
  1300. of tySet, tySequence, tyOpenArray, tyVarargs:
  1301. result = t[0].kind == tyEmpty
  1302. of tyGenericInst, tyAlias, tySink: result = isEmptyContainer(t.lastSon)
  1303. else: result = false
  1304. proc takeType*(formal, arg: PType): PType =
  1305. # param: openArray[string] = []
  1306. # [] is an array constructor of length 0 of type string!
  1307. if arg.kind == tyNil:
  1308. # and not (formal.kind == tyProc and formal.callConv == ccClosure):
  1309. result = formal
  1310. elif formal.kind in {tyOpenArray, tyVarargs, tySequence} and
  1311. arg.isEmptyContainer:
  1312. let a = copyType(arg.skipTypes({tyGenericInst, tyAlias}), arg.owner, keepId=false)
  1313. a[ord(arg.kind == tyArray)] = formal[0]
  1314. result = a
  1315. elif formal.kind in {tyTuple, tySet} and arg.kind == formal.kind:
  1316. result = formal
  1317. else:
  1318. result = arg
  1319. proc skipHiddenSubConv*(n: PNode): PNode =
  1320. if n.kind == nkHiddenSubConv:
  1321. # param: openArray[string] = []
  1322. # [] is an array constructor of length 0 of type string!
  1323. let formal = n.typ
  1324. result = n[1]
  1325. let arg = result.typ
  1326. let dest = takeType(formal, arg)
  1327. if dest == arg and formal.kind != tyUntyped:
  1328. #echo n.info, " came here for ", formal.typeToString
  1329. result = n
  1330. else:
  1331. result = copyTree(result)
  1332. result.typ = dest
  1333. else:
  1334. result = n
  1335. proc typeMismatch*(conf: ConfigRef; info: TLineInfo, formal, actual: PType) =
  1336. if formal.kind != tyError and actual.kind != tyError:
  1337. let named = typeToString(formal)
  1338. let desc = typeToString(formal, preferDesc)
  1339. let x = if named == desc: named else: named & " = " & desc
  1340. var msg = "type mismatch: got <" &
  1341. typeToString(actual) & "> " &
  1342. "but expected '" & x & "'"
  1343. if formal.kind == tyProc and actual.kind == tyProc:
  1344. case compatibleEffects(formal, actual)
  1345. of efCompat: discard
  1346. of efRaisesDiffer:
  1347. msg.add "\n.raise effects differ"
  1348. of efRaisesUnknown:
  1349. msg.add "\n.raise effect is 'can raise any'"
  1350. of efTagsDiffer:
  1351. msg.add "\n.tag effects differ"
  1352. of efTagsUnknown:
  1353. msg.add "\n.tag effect is 'any tag allowed'"
  1354. of efLockLevelsDiffer:
  1355. msg.add "\nlock levels differ"
  1356. localError(conf, info, msg)
  1357. proc isTupleRecursive(t: PType, cycleDetector: var IntSet): bool =
  1358. if t == nil:
  1359. return false
  1360. if cycleDetector.containsOrIncl(t.id):
  1361. return true
  1362. case t.kind
  1363. of tyTuple:
  1364. var cycleDetectorCopy: IntSet
  1365. for i in 0..<t.len:
  1366. assign(cycleDetectorCopy, cycleDetector)
  1367. if isTupleRecursive(t[i], cycleDetectorCopy):
  1368. return true
  1369. of tyAlias, tyRef, tyPtr, tyGenericInst, tyVar, tyLent, tySink,
  1370. tyArray, tyUncheckedArray, tySequence, tyDistinct:
  1371. return isTupleRecursive(t.lastSon, cycleDetector)
  1372. else:
  1373. return false
  1374. proc isTupleRecursive*(t: PType): bool =
  1375. var cycleDetector = initIntSet()
  1376. isTupleRecursive(t, cycleDetector)
  1377. proc isException*(t: PType): bool =
  1378. # check if `y` is object type and it inherits from Exception
  1379. assert(t != nil)
  1380. var t = t.skipTypes(abstractInst)
  1381. while t.kind == tyObject:
  1382. if t.sym != nil and t.sym.magic == mException: return true
  1383. if t[0] == nil: break
  1384. t = skipTypes(t[0], abstractPtrs)
  1385. return false
  1386. proc isDefectException*(t: PType): bool =
  1387. var t = t.skipTypes(abstractPtrs)
  1388. while t.kind == tyObject:
  1389. if t.sym != nil and t.sym.owner != nil and
  1390. sfSystemModule in t.sym.owner.flags and
  1391. t.sym.name.s == "Defect":
  1392. return true
  1393. if t[0] == nil: break
  1394. t = skipTypes(t[0], abstractPtrs)
  1395. return false
  1396. proc isSinkTypeForParam*(t: PType): bool =
  1397. # a parameter like 'seq[owned T]' must not be used only once, but its
  1398. # elements must, so we detect this case here:
  1399. result = t.skipTypes({tyGenericInst, tyAlias}).kind in {tySink, tyOwned}
  1400. when false:
  1401. if isSinkType(t):
  1402. if t.skipTypes({tyGenericInst, tyAlias}).kind in {tyArray, tyVarargs, tyOpenArray, tySequence}:
  1403. result = false
  1404. else:
  1405. result = true