types.nim 63 KB

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