types.nim 59 KB

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