types.nim 59 KB

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