sigmatch.nim 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725
  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 implements the signature matching for resolving
  10. ## the call to overloaded procs, generic procs and operators.
  11. import
  12. intsets, ast, astalgo, semdata, types, msgs, renderer, lookups, semtypinst,
  13. magicsys, idents, lexer, options, parampatterns, strutils, trees,
  14. linter, lineinfos, lowerings, modulegraphs
  15. type
  16. MismatchKind* = enum
  17. kUnknown, kAlreadyGiven, kUnknownNamedParam, kTypeMismatch, kVarNeeded,
  18. kMissingParam, kExtraArg, kPositionalAlreadyGiven
  19. MismatchInfo* = object
  20. kind*: MismatchKind # reason for mismatch
  21. arg*: int # position of provided arguments that mismatches
  22. formal*: PSym # parameter that mismatches against provided argument
  23. # its position can differ from `arg` because of varargs
  24. TCandidateState* = enum
  25. csEmpty, csMatch, csNoMatch
  26. CandidateError* = object
  27. sym*: PSym
  28. firstMismatch*: MismatchInfo
  29. diagnostics*: seq[string]
  30. enabled*: bool
  31. CandidateErrors* = seq[CandidateError]
  32. TCandidate* = object
  33. c*: PContext
  34. exactMatches*: int # also misused to prefer iters over procs
  35. genericMatches: int # also misused to prefer constraints
  36. subtypeMatches: int
  37. intConvMatches: int # conversions to int are not as expensive
  38. convMatches: int
  39. state*: TCandidateState
  40. callee*: PType # may not be nil!
  41. calleeSym*: PSym # may be nil
  42. calleeScope*: int # scope depth:
  43. # is this a top-level symbol or a nested proc?
  44. call*: PNode # modified call
  45. bindings*: TIdTable # maps types to types
  46. magic*: TMagic # magic of operation
  47. baseTypeMatch: bool # needed for conversions from T to openarray[T]
  48. # for example
  49. fauxMatch*: TTypeKind # the match was successful only due to the use
  50. # of error or wildcard (unknown) types.
  51. # this is used to prevent instantiations.
  52. genericConverter*: bool # true if a generic converter needs to
  53. # be instantiated
  54. coerceDistincts*: bool # this is an explicit coercion that can strip away
  55. # a distrinct type
  56. typedescMatched*: bool
  57. isNoCall*: bool # misused for generic type instantiations C[T]
  58. inferredTypes: seq[PType] # inferred types during the current signature
  59. # matching. they will be reset if the matching
  60. # is not successful. may replace the bindings
  61. # table in the future.
  62. diagnostics*: seq[string] # \
  63. # when diagnosticsEnabled, the matching process
  64. # will collect extra diagnostics that will be
  65. # displayed to the user.
  66. # triggered when overload resolution fails
  67. # or when the explain pragma is used. may be
  68. # triggered with an idetools command in the
  69. # future.
  70. inheritancePenalty: int # to prefer closest father object type
  71. firstMismatch*: MismatchInfo # mismatch info for better error messages
  72. diagnosticsEnabled*: bool
  73. TTypeRelFlag* = enum
  74. trDontBind
  75. trNoCovariance
  76. TTypeRelFlags* = set[TTypeRelFlag]
  77. TTypeRelation* = enum # order is important!
  78. isNone, isConvertible,
  79. isIntConv,
  80. isSubtype,
  81. isSubrange, # subrange of the wanted type; no type conversion
  82. # but apart from that counts as ``isSubtype``
  83. isBothMetaConvertible # generic proc parameter was matched against
  84. # generic type, e.g., map(mySeq, x=>x+1),
  85. # maybe recoverable by rerun if the parameter is
  86. # the proc's return value
  87. isInferred, # generic proc was matched against a concrete type
  88. isInferredConvertible, # same as above, but requiring proc CC conversion
  89. isGeneric,
  90. isFromIntLit, # conversion *from* int literal; proven safe
  91. isEqual
  92. const
  93. isNilConversion = isConvertible # maybe 'isIntConv' fits better?
  94. proc markUsed*(c: PContext; info: TLineInfo, s: PSym)
  95. proc markOwnerModuleAsUsed*(c: PContext; s: PSym)
  96. template hasFauxMatch*(c: TCandidate): bool = c.fauxMatch != tyNone
  97. proc initCandidateAux(ctx: PContext,
  98. c: var TCandidate, callee: PType) {.inline.} =
  99. c.c = ctx
  100. c.exactMatches = 0
  101. c.subtypeMatches = 0
  102. c.convMatches = 0
  103. c.intConvMatches = 0
  104. c.genericMatches = 0
  105. c.state = csEmpty
  106. c.firstMismatch = MismatchInfo()
  107. c.callee = callee
  108. c.call = nil
  109. c.baseTypeMatch = false
  110. c.genericConverter = false
  111. c.inheritancePenalty = 0
  112. proc initCandidate*(ctx: PContext, c: var TCandidate, callee: PType) =
  113. initCandidateAux(ctx, c, callee)
  114. c.calleeSym = nil
  115. initIdTable(c.bindings)
  116. proc put(c: var TCandidate, key, val: PType) {.inline.} =
  117. ## Given: proc foo[T](x: T); foo(4)
  118. ## key: 'T'
  119. ## val: 'int' (typeof(4))
  120. when false:
  121. let old = PType(idTableGet(c.bindings, key))
  122. if old != nil:
  123. echo "Putting ", typeToString(key), " ", typeToString(val), " and old is ", typeToString(old)
  124. if typeToString(old) == "float32":
  125. writeStackTrace()
  126. if c.c.module.name.s == "temp3":
  127. echo "binding ", key, " -> ", val
  128. idTablePut(c.bindings, key, val.skipIntLit)
  129. proc initCandidate*(ctx: PContext, c: var TCandidate, callee: PSym,
  130. binding: PNode, calleeScope = -1,
  131. diagnosticsEnabled = false) =
  132. initCandidateAux(ctx, c, callee.typ)
  133. c.calleeSym = callee
  134. if callee.kind in skProcKinds and calleeScope == -1:
  135. if callee.originatingModule == ctx.module:
  136. c.calleeScope = 2
  137. var owner = callee
  138. while true:
  139. owner = owner.skipGenericOwner
  140. if owner.kind == skModule: break
  141. inc c.calleeScope
  142. else:
  143. c.calleeScope = 1
  144. else:
  145. c.calleeScope = calleeScope
  146. c.diagnostics = @[] # if diagnosticsEnabled: @[] else: nil
  147. c.diagnosticsEnabled = diagnosticsEnabled
  148. c.magic = c.calleeSym.magic
  149. initIdTable(c.bindings)
  150. if binding != nil and callee.kind in routineKinds:
  151. var typeParams = callee.ast[genericParamsPos]
  152. for i in 1..min(typeParams.len, binding.len-1):
  153. var formalTypeParam = typeParams[i-1].typ
  154. var bound = binding[i].typ
  155. if bound != nil:
  156. if formalTypeParam.kind == tyTypeDesc:
  157. if bound.kind != tyTypeDesc:
  158. bound = makeTypeDesc(ctx, bound)
  159. else:
  160. bound = bound.skipTypes({tyTypeDesc})
  161. put(c, formalTypeParam, bound)
  162. proc newCandidate*(ctx: PContext, callee: PSym,
  163. binding: PNode, calleeScope = -1): TCandidate =
  164. initCandidate(ctx, result, callee, binding, calleeScope)
  165. proc newCandidate*(ctx: PContext, callee: PType): TCandidate =
  166. initCandidate(ctx, result, callee)
  167. proc copyCandidate(a: var TCandidate, b: TCandidate) =
  168. a.c = b.c
  169. a.exactMatches = b.exactMatches
  170. a.subtypeMatches = b.subtypeMatches
  171. a.convMatches = b.convMatches
  172. a.intConvMatches = b.intConvMatches
  173. a.genericMatches = b.genericMatches
  174. a.state = b.state
  175. a.callee = b.callee
  176. a.calleeSym = b.calleeSym
  177. a.call = copyTree(b.call)
  178. a.baseTypeMatch = b.baseTypeMatch
  179. copyIdTable(a.bindings, b.bindings)
  180. proc sumGeneric(t: PType): int =
  181. # count the "genericness" so that Foo[Foo[T]] has the value 3
  182. # and Foo[T] has the value 2 so that we know Foo[Foo[T]] is more
  183. # specific than Foo[T].
  184. var t = t
  185. var isvar = 1
  186. while true:
  187. case t.kind
  188. of tyGenericInst, tyArray, tyRef, tyPtr, tyDistinct, tyUncheckedArray,
  189. tyOpenArray, tyVarargs, tySet, tyRange, tySequence, tyGenericBody,
  190. tyLent, tyOwned:
  191. t = t.lastSon
  192. inc result
  193. of tyOr:
  194. var maxBranch = 0
  195. for branch in t.sons:
  196. let branchSum = sumGeneric(branch)
  197. if branchSum > maxBranch: maxBranch = branchSum
  198. inc result, maxBranch
  199. break
  200. of tyVar:
  201. t = t[0]
  202. inc result
  203. inc isvar
  204. of tyTypeDesc:
  205. t = t.lastSon
  206. if t.kind == tyEmpty: break
  207. inc result
  208. of tyGenericInvocation, tyTuple, tyProc, tyAnd:
  209. result += ord(t.kind in {tyGenericInvocation, tyAnd})
  210. for i in 0..<t.len:
  211. if t[i] != nil:
  212. result += sumGeneric(t[i])
  213. break
  214. of tyStatic:
  215. return sumGeneric(t[0]) + 1
  216. of tyGenericParam, tyUntyped, tyTyped: break
  217. of tyAlias, tySink: t = t.lastSon
  218. of tyBool, tyChar, tyEnum, tyObject, tyPointer,
  219. tyString, tyCString, tyInt..tyInt64, tyFloat..tyFloat128,
  220. tyUInt..tyUInt64, tyCompositeTypeClass:
  221. return isvar
  222. else:
  223. return 0
  224. #var ggDebug: bool
  225. proc complexDisambiguation(a, b: PType): int =
  226. # 'a' matches better if *every* argument matches better or equal than 'b'.
  227. var winner = 0
  228. for i in 1..<min(a.len, b.len):
  229. let x = a[i].sumGeneric
  230. let y = b[i].sumGeneric
  231. #if ggDebug:
  232. #echo "came herA ", typeToString(a[i]), " ", x
  233. #echo "came herB ", typeToString(b[i]), " ", y
  234. if x != y:
  235. if winner == 0:
  236. if x > y: winner = 1
  237. else: winner = -1
  238. elif x > y:
  239. if winner != 1:
  240. # contradiction
  241. return 0
  242. else:
  243. if winner != -1:
  244. return 0
  245. result = winner
  246. when false:
  247. var x, y: int
  248. for i in 1..<a.len: x += a[i].sumGeneric
  249. for i in 1..<b.len: y += b[i].sumGeneric
  250. result = x - y
  251. proc writeMatches*(c: TCandidate) =
  252. echo "Candidate '", c.calleeSym.name.s, "' at ", c.c.config $ c.calleeSym.info
  253. echo " exact matches: ", c.exactMatches
  254. echo " generic matches: ", c.genericMatches
  255. echo " subtype matches: ", c.subtypeMatches
  256. echo " intconv matches: ", c.intConvMatches
  257. echo " conv matches: ", c.convMatches
  258. echo " inheritance: ", c.inheritancePenalty
  259. proc cmpCandidates*(a, b: TCandidate): int =
  260. result = a.exactMatches - b.exactMatches
  261. if result != 0: return
  262. result = a.genericMatches - b.genericMatches
  263. if result != 0: return
  264. result = a.subtypeMatches - b.subtypeMatches
  265. if result != 0: return
  266. result = a.intConvMatches - b.intConvMatches
  267. if result != 0: return
  268. result = a.convMatches - b.convMatches
  269. if result != 0: return
  270. # the other way round because of other semantics:
  271. result = b.inheritancePenalty - a.inheritancePenalty
  272. if result != 0: return
  273. # prefer more specialized generic over more general generic:
  274. result = complexDisambiguation(a.callee, b.callee)
  275. # only as a last resort, consider scoping:
  276. if result != 0: return
  277. result = a.calleeScope - b.calleeScope
  278. proc argTypeToString(arg: PNode; prefer: TPreferedDesc): string =
  279. if arg.kind in nkSymChoices:
  280. result = typeToString(arg[0].typ, prefer)
  281. for i in 1..<arg.len:
  282. result.add(" | ")
  283. result.add typeToString(arg[i].typ, prefer)
  284. elif arg.typ == nil:
  285. result = "void"
  286. else:
  287. result = arg.typ.typeToString(prefer)
  288. proc describeArgs*(c: PContext, n: PNode, startIdx = 1;
  289. prefer: TPreferedDesc = preferName): string =
  290. result = ""
  291. for i in startIdx..<n.len:
  292. var arg = n[i]
  293. if n[i].kind == nkExprEqExpr:
  294. result.add(renderTree(n[i][0]))
  295. result.add(": ")
  296. if arg.typ.isNil and arg.kind notin {nkStmtList, nkDo}:
  297. # XXX we really need to 'tryExpr' here!
  298. arg = c.semOperand(c, n[i][1])
  299. n[i].typ = arg.typ
  300. n[i][1] = arg
  301. else:
  302. if arg.typ.isNil and arg.kind notin {nkStmtList, nkDo, nkElse,
  303. nkOfBranch, nkElifBranch,
  304. nkExceptBranch}:
  305. arg = c.semOperand(c, n[i])
  306. n[i] = arg
  307. if arg.typ != nil and arg.typ.kind == tyError: return
  308. result.add(argTypeToString(arg, prefer))
  309. if i != n.len - 1: result.add(", ")
  310. proc typeRel*(c: var TCandidate, f, aOrig: PType,
  311. flags: TTypeRelFlags = {}): TTypeRelation
  312. proc concreteType(c: TCandidate, t: PType; f: PType = nil): PType =
  313. case t.kind
  314. of tyTypeDesc:
  315. if c.isNoCall: result = t
  316. else: result = nil
  317. of tySequence, tySet:
  318. if t[0].kind == tyEmpty: result = nil
  319. else: result = t
  320. of tyGenericParam, tyAnything:
  321. result = t
  322. while true:
  323. result = PType(idTableGet(c.bindings, t))
  324. if result == nil:
  325. break # it's ok, no match
  326. # example code that triggers it:
  327. # proc sort[T](cmp: proc(a, b: T): int = cmp)
  328. if result.kind != tyGenericParam: break
  329. of tyGenericInvocation:
  330. result = t
  331. doAssert(false, "cannot resolve type: " & typeToString(t))
  332. of tyOwned:
  333. # bug #11257: the comparison system.`==`[T: proc](x, y: T) works
  334. # better without the 'owned' type:
  335. if f != nil and f.len > 0 and f[0].skipTypes({tyBuiltInTypeClass}).kind == tyProc:
  336. result = t.lastSon
  337. else:
  338. result = t
  339. else:
  340. result = t # Note: empty is valid here
  341. proc handleRange(f, a: PType, min, max: TTypeKind): TTypeRelation =
  342. if a.kind == f.kind:
  343. result = isEqual
  344. else:
  345. let ab = skipTypes(a, {tyRange})
  346. let k = ab.kind
  347. if k == f.kind: result = isSubrange
  348. elif k == tyInt and f.kind in {tyRange, tyInt8..tyInt64,
  349. tyUInt..tyUInt64} and
  350. isIntLit(ab) and getInt(ab.n) >= firstOrd(nil, f) and
  351. getInt(ab.n) <= lastOrd(nil, f):
  352. # passing 'nil' to firstOrd/lastOrd here as type checking rules should
  353. # not depend on the target integer size configurations!
  354. # integer literal in the proper range; we want ``i16 + 4`` to stay an
  355. # ``int16`` operation so we declare the ``4`` pseudo-equal to int16
  356. result = isFromIntLit
  357. elif f.kind == tyInt and k in {tyInt8..tyInt32}:
  358. result = isIntConv
  359. elif f.kind == tyUInt and k in {tyUInt8..tyUInt32}:
  360. result = isIntConv
  361. elif k >= min and k <= max:
  362. result = isConvertible
  363. elif a.kind == tyRange and
  364. # Make sure the conversion happens between types w/ same signedness
  365. (f.kind in {tyInt..tyInt64} and a[0].kind in {tyInt..tyInt64} or
  366. f.kind in {tyUInt8..tyUInt32} and a[0].kind in {tyUInt8..tyInt32}) and
  367. a.n[0].intVal >= firstOrd(nil, f) and a.n[1].intVal <= lastOrd(nil, f):
  368. # passing 'nil' to firstOrd/lastOrd here as type checking rules should
  369. # not depend on the target integer size configurations!
  370. result = isConvertible
  371. else: result = isNone
  372. proc isConvertibleToRange(f, a: PType): bool =
  373. if f.kind in {tyInt..tyInt64, tyUInt..tyUInt64} and
  374. a.kind in {tyInt..tyInt64, tyUInt..tyUInt64}:
  375. case f.kind
  376. of tyInt8: result = isIntLit(a) or a.kind in {tyInt8}
  377. of tyInt16: result = isIntLit(a) or a.kind in {tyInt8, tyInt16}
  378. of tyInt32: result = isIntLit(a) or a.kind in {tyInt8, tyInt16, tyInt32}
  379. # This is wrong, but seems like there's a lot of code that relies on it :(
  380. of tyInt, tyUInt, tyUInt64: result = true
  381. of tyInt64: result = isIntLit(a) or a.kind in {tyInt8, tyInt16, tyInt32, tyInt, tyInt64}
  382. of tyUInt8: result = isIntLit(a) or a.kind in {tyUInt8}
  383. of tyUInt16: result = isIntLit(a) or a.kind in {tyUInt8, tyUInt16}
  384. of tyUInt32: result = isIntLit(a) or a.kind in {tyUInt8, tyUInt16, tyUInt32}
  385. #of tyUInt: result = isIntLit(a) or a.kind in {tyUInt8, tyUInt16, tyUInt32, tyUInt}
  386. #of tyUInt64: result = isIntLit(a) or a.kind in {tyUInt8, tyUInt16, tyUInt32, tyUInt, tyUInt64}
  387. else: result = false
  388. elif f.kind in {tyFloat..tyFloat128}:
  389. # `isIntLit` is correct and should be used above as well, see PR:
  390. # https://github.com/nim-lang/Nim/pull/11197
  391. result = isIntLit(a) or a.kind in {tyFloat..tyFloat128}
  392. proc handleFloatRange(f, a: PType): TTypeRelation =
  393. if a.kind == f.kind:
  394. result = isEqual
  395. else:
  396. let ab = skipTypes(a, {tyRange})
  397. var k = ab.kind
  398. if k == f.kind: result = isSubrange
  399. elif isFloatLit(ab): result = isFromIntLit
  400. elif isIntLit(ab): result = isConvertible
  401. elif k >= tyFloat and k <= tyFloat128:
  402. # conversion to "float32" is not as good:
  403. if f.kind == tyFloat32: result = isConvertible
  404. else: result = isIntConv
  405. else: result = isNone
  406. proc genericParamPut(c: var TCandidate; last, fGenericOrigin: PType) =
  407. if fGenericOrigin != nil and last.kind == tyGenericInst and
  408. last.len-1 == fGenericOrigin.len:
  409. for i in 1..<fGenericOrigin.len:
  410. let x = PType(idTableGet(c.bindings, fGenericOrigin[i]))
  411. if x == nil:
  412. put(c, fGenericOrigin[i], last[i])
  413. proc isObjectSubtype(c: var TCandidate; a, f, fGenericOrigin: PType): int =
  414. var t = a
  415. assert t.kind == tyObject
  416. var depth = 0
  417. var last = a
  418. while t != nil and not sameObjectTypes(f, t):
  419. assert t.kind == tyObject
  420. t = t[0]
  421. if t == nil: break
  422. last = t
  423. t = skipTypes(t, skipPtrs)
  424. inc depth
  425. if t != nil:
  426. genericParamPut(c, last, fGenericOrigin)
  427. result = depth
  428. else:
  429. result = -1
  430. type
  431. SkippedPtr = enum skippedNone, skippedRef, skippedPtr
  432. proc skipToObject(t: PType; skipped: var SkippedPtr): PType =
  433. var r = t
  434. # we're allowed to skip one level of ptr/ref:
  435. var ptrs = 0
  436. while r != nil:
  437. case r.kind
  438. of tyGenericInvocation:
  439. r = r[0]
  440. of tyRef:
  441. inc ptrs
  442. skipped = skippedRef
  443. r = r.lastSon
  444. of tyPtr:
  445. inc ptrs
  446. skipped = skippedPtr
  447. r = r.lastSon
  448. of tyGenericBody, tyGenericInst, tyAlias, tySink, tyOwned:
  449. r = r.lastSon
  450. else:
  451. break
  452. if r.kind == tyObject and ptrs <= 1: result = r
  453. proc isGenericSubtype(c: var TCandidate; a, f: PType, d: var int, fGenericOrigin: PType): bool =
  454. assert f.kind in {tyGenericInst, tyGenericInvocation, tyGenericBody}
  455. var askip = skippedNone
  456. var fskip = skippedNone
  457. var t = a.skipToObject(askip)
  458. let r = f.skipToObject(fskip)
  459. if r == nil: return false
  460. var depth = 0
  461. var last = a
  462. # XXX sameObjectType can return false here. Need to investigate
  463. # why that is but sameObjectType does way too much work here anyway.
  464. while t != nil and r.sym != t.sym and askip == fskip:
  465. t = t[0]
  466. if t == nil: break
  467. last = t
  468. t = t.skipToObject(askip)
  469. inc depth
  470. if t != nil and askip == fskip:
  471. genericParamPut(c, last, fGenericOrigin)
  472. d = depth
  473. result = true
  474. proc minRel(a, b: TTypeRelation): TTypeRelation =
  475. if a <= b: result = a
  476. else: result = b
  477. proc recordRel(c: var TCandidate, f, a: PType): TTypeRelation =
  478. result = isNone
  479. if sameType(f, a):
  480. result = isEqual
  481. elif a.len == f.len:
  482. result = isEqual
  483. let firstField = if f.kind == tyTuple: 0
  484. else: 1
  485. for i in firstField..<f.len:
  486. var m = typeRel(c, f[i], a[i])
  487. if m < isSubtype: return isNone
  488. result = minRel(result, m)
  489. if f.n != nil and a.n != nil:
  490. for i in 0..<f.n.len:
  491. # check field names:
  492. if f.n[i].kind != nkSym: return isNone
  493. elif a.n[i].kind != nkSym: return isNone
  494. else:
  495. var x = f.n[i].sym
  496. var y = a.n[i].sym
  497. if f.kind == tyObject and typeRel(c, x.typ, y.typ) < isSubtype:
  498. return isNone
  499. if x.name.id != y.name.id: return isNone
  500. proc allowsNil(f: PType): TTypeRelation {.inline.} =
  501. result = if tfNotNil notin f.flags: isSubtype else: isNone
  502. proc allowsNilDeprecated(c: TCandidate, f: PType): TTypeRelation =
  503. if optNilSeqs in c.c.config.options:
  504. result = allowsNil(f)
  505. else:
  506. result = isNone
  507. proc inconsistentVarTypes(f, a: PType): bool {.inline.} =
  508. result = f.kind != a.kind and
  509. (f.kind in {tyVar, tyLent, tySink} or a.kind in {tyVar, tyLent, tySink})
  510. proc procParamTypeRel(c: var TCandidate, f, a: PType): TTypeRelation =
  511. ## For example we have:
  512. ##..code-block:: nim
  513. ## proc myMap[T,S](sIn: seq[T], f: proc(x: T): S): seq[S] = ...
  514. ## proc innerProc[Q,W](q: Q): W = ...
  515. ## And we want to match: myMap(@[1,2,3], innerProc)
  516. ## This proc (procParamTypeRel) will do the following steps in
  517. ## three different calls:
  518. ## - matches f=T to a=Q. Since f is metatype, we resolve it
  519. ## to int (which is already known at this point). So in this case
  520. ## Q=int mapping will be saved to c.bindings.
  521. ## - matches f=S to a=W. Both of these metatypes are unknown, so we
  522. ## return with isBothMetaConvertible to ask for rerun.
  523. ## - matches f=S to a=W. At this point the return type of innerProc
  524. ## is known (we get it from c.bindings). We can use that value
  525. ## to match with f, and save back to c.bindings.
  526. var
  527. f = f
  528. a = a
  529. if a.isMetaType:
  530. let aResolved = PType(idTableGet(c.bindings, a))
  531. if aResolved != nil:
  532. a = aResolved
  533. if a.isMetaType:
  534. if f.isMetaType:
  535. # We are matching a generic proc (as proc param)
  536. # to another generic type appearing in the proc
  537. # signature. There is a change that the target
  538. # type is already fully-determined, so we are
  539. # going to try resolve it
  540. if c.call != nil:
  541. f = generateTypeInstance(c.c, c.bindings, c.call.info, f)
  542. else:
  543. f = nil
  544. if f == nil or f.isMetaType:
  545. # no luck resolving the type, so the inference fails
  546. return isBothMetaConvertible
  547. # Note that this typeRel call will save a's resolved type into c.bindings
  548. let reverseRel = typeRel(c, a, f)
  549. if reverseRel >= isGeneric:
  550. result = isInferred
  551. #inc c.genericMatches
  552. else:
  553. # Note that this typeRel call will save f's resolved type into c.bindings
  554. # if f is metatype.
  555. result = typeRel(c, f, a)
  556. if result <= isSubtype or inconsistentVarTypes(f, a):
  557. result = isNone
  558. #if result == isEqual:
  559. # inc c.exactMatches
  560. proc procTypeRel(c: var TCandidate, f, a: PType): TTypeRelation =
  561. case a.kind
  562. of tyProc:
  563. if f.len != a.len: return
  564. result = isEqual # start with maximum; also correct for no
  565. # params at all
  566. template checkParam(f, a) =
  567. result = minRel(result, procParamTypeRel(c, f, a))
  568. if result == isNone: return
  569. # Note: We have to do unification for the parameters before the
  570. # return type!
  571. for i in 1..<f.len:
  572. checkParam(f[i], a[i])
  573. if f[0] != nil:
  574. if a[0] != nil:
  575. checkParam(f[0], a[0])
  576. else:
  577. return isNone
  578. elif a[0] != nil:
  579. return isNone
  580. if tfNoSideEffect in f.flags and tfNoSideEffect notin a.flags:
  581. return isNone
  582. elif tfThread in f.flags and a.flags * {tfThread, tfNoSideEffect} == {} and
  583. optThreadAnalysis in c.c.config.globalOptions:
  584. # noSideEffect implies ``tfThread``!
  585. return isNone
  586. elif f.flags * {tfIterator} != a.flags * {tfIterator}:
  587. return isNone
  588. elif f.callConv != a.callConv:
  589. # valid to pass a 'nimcall' thingie to 'closure':
  590. if f.callConv == ccClosure and a.callConv == ccDefault:
  591. result = if result == isInferred: isInferredConvertible
  592. elif result == isBothMetaConvertible: isBothMetaConvertible
  593. else: isConvertible
  594. else:
  595. return isNone
  596. when useEffectSystem:
  597. if compatibleEffects(f, a) != efCompat: return isNone
  598. when defined(drnim):
  599. if not c.c.graph.compatibleProps(c.c.graph, f, a): return isNone
  600. of tyNil:
  601. result = f.allowsNil
  602. else: discard
  603. proc typeRangeRel(f, a: PType): TTypeRelation {.noinline.} =
  604. template checkRange[T](a0, a1, f0, f1: T): TTypeRelation =
  605. if a0 == f0 and a1 == f1:
  606. isEqual
  607. elif a0 >= f0 and a1 <= f1:
  608. isConvertible
  609. elif a0 <= f1 and f0 <= a1:
  610. # X..Y and C..D overlap iff (X <= D and C <= Y)
  611. isConvertible
  612. else:
  613. isNone
  614. if f.isOrdinalType:
  615. checkRange(firstOrd(nil, a), lastOrd(nil, a), firstOrd(nil, f), lastOrd(nil, f))
  616. else:
  617. checkRange(firstFloat(a), lastFloat(a), firstFloat(f), lastFloat(f))
  618. proc matchUserTypeClass*(m: var TCandidate; ff, a: PType): PType =
  619. var
  620. c = m.c
  621. typeClass = ff.skipTypes({tyUserTypeClassInst})
  622. body = typeClass.n[3]
  623. matchedConceptContext: TMatchedConcept
  624. prevMatchedConcept = c.matchedConcept
  625. prevCandidateType = typeClass[0][0]
  626. if prevMatchedConcept != nil:
  627. matchedConceptContext.prev = prevMatchedConcept
  628. matchedConceptContext.depth = prevMatchedConcept.depth + 1
  629. if prevMatchedConcept.depth > 4:
  630. localError(m.c.graph.config, body.info, $body & " too nested for type matching")
  631. return nil
  632. openScope(c)
  633. matchedConceptContext.candidateType = a
  634. typeClass[0][0] = a
  635. c.matchedConcept = addr(matchedConceptContext)
  636. defer:
  637. c.matchedConcept = prevMatchedConcept
  638. typeClass[0][0] = prevCandidateType
  639. closeScope(c)
  640. var typeParams: seq[(PSym, PType)]
  641. if ff.kind == tyUserTypeClassInst:
  642. for i in 1..<(ff.len - 1):
  643. var
  644. typeParamName = ff.base[i-1].sym.name
  645. typ = ff[i]
  646. param: PSym
  647. alreadyBound = PType(idTableGet(m.bindings, typ))
  648. if alreadyBound != nil: typ = alreadyBound
  649. template paramSym(kind): untyped =
  650. newSym(kind, typeParamName, typeClass.sym, typeClass.sym.info, {})
  651. block addTypeParam:
  652. for prev in typeParams:
  653. if prev[1].id == typ.id:
  654. param = paramSym prev[0].kind
  655. param.typ = prev[0].typ
  656. break addTypeParam
  657. case typ.kind
  658. of tyStatic:
  659. param = paramSym skConst
  660. param.typ = typ.exactReplica
  661. if typ.n == nil:
  662. param.typ.flags.incl tfInferrableStatic
  663. else:
  664. param.ast = typ.n
  665. of tyUnknown:
  666. param = paramSym skVar
  667. param.typ = typ.exactReplica
  668. else:
  669. param = paramSym skType
  670. param.typ = if typ.isMetaType:
  671. c.newTypeWithSons(tyInferred, @[typ])
  672. else:
  673. makeTypeDesc(c, typ)
  674. typeParams.add((param, typ))
  675. addDecl(c, param)
  676. var
  677. oldWriteHook: type(m.c.config.writelnHook)
  678. diagnostics: seq[string]
  679. errorPrefix: string
  680. flags: TExprFlags = {}
  681. collectDiagnostics = m.diagnosticsEnabled or
  682. sfExplain in typeClass.sym.flags
  683. if collectDiagnostics:
  684. oldWriteHook = m.c.config.writelnHook
  685. # XXX: we can't write to m.diagnostics directly, because
  686. # Nim doesn't support capturing var params in closures
  687. diagnostics = @[]
  688. flags = {efExplain}
  689. m.c.config.writelnHook = proc (s: string) =
  690. if errorPrefix.len == 0: errorPrefix = typeClass.sym.name.s & ":"
  691. let msg = s.replace("Error:", errorPrefix)
  692. if oldWriteHook != nil: oldWriteHook msg
  693. diagnostics.add msg
  694. var checkedBody = c.semTryExpr(c, body.copyTree, flags)
  695. if collectDiagnostics:
  696. m.c.config.writelnHook = oldWriteHook
  697. for msg in diagnostics:
  698. m.diagnostics.add msg
  699. m.diagnosticsEnabled = true
  700. if checkedBody == nil: return nil
  701. # The inferrable type params have been identified during the semTryExpr above.
  702. # We need to put them in the current sigmatch's binding table in order for them
  703. # to be resolvable while matching the rest of the parameters
  704. for p in typeParams:
  705. put(m, p[1], p[0].typ)
  706. if ff.kind == tyUserTypeClassInst:
  707. result = generateTypeInstance(c, m.bindings, typeClass.sym.info, ff)
  708. else:
  709. result = copyType(ff, ff.owner, true)
  710. result.n = checkedBody
  711. proc shouldSkipDistinct(m: TCandidate; rules: PNode, callIdent: PIdent): bool =
  712. # XXX This is bad as 'considerQuotedIdent' can produce an error!
  713. if rules.kind == nkWith:
  714. for r in rules:
  715. if considerQuotedIdent(m.c, r) == callIdent: return true
  716. return false
  717. else:
  718. for r in rules:
  719. if considerQuotedIdent(m.c, r) == callIdent: return false
  720. return true
  721. proc maybeSkipDistinct(m: TCandidate; t: PType, callee: PSym): PType =
  722. if t != nil and t.kind == tyDistinct and t.n != nil and
  723. shouldSkipDistinct(m, t.n, callee.name):
  724. result = t.base
  725. else:
  726. result = t
  727. proc tryResolvingStaticExpr(c: var TCandidate, n: PNode,
  728. allowUnresolved = false): PNode =
  729. # Consider this example:
  730. # type Value[N: static[int]] = object
  731. # proc foo[N](a: Value[N], r: range[0..(N-1)])
  732. # Here, N-1 will be initially nkStaticExpr that can be evaluated only after
  733. # N is bound to a concrete value during the matching of the first param.
  734. # This proc is used to evaluate such static expressions.
  735. let instantiated = replaceTypesInBody(c.c, c.bindings, n, nil,
  736. allowMetaTypes = allowUnresolved)
  737. result = c.c.semExpr(c.c, instantiated)
  738. proc inferStaticParam*(c: var TCandidate, lhs: PNode, rhs: BiggestInt): bool =
  739. # This is a simple integer arithimetic equation solver,
  740. # capable of deriving the value of a static parameter in
  741. # expressions such as (N + 5) / 2 = rhs
  742. #
  743. # Preconditions:
  744. #
  745. # * The input of this proc must be semantized
  746. # - all templates should be expanded
  747. # - aby constant folding possible should already be performed
  748. #
  749. # * There must be exactly one unresolved static parameter
  750. #
  751. # Result:
  752. #
  753. # The proc will return true if the static types was successfully
  754. # inferred. The result will be bound to the original static type
  755. # in the TCandidate.
  756. #
  757. if lhs.kind in nkCallKinds and lhs[0].kind == nkSym:
  758. case lhs[0].sym.magic
  759. of mAddI, mAddU, mInc, mSucc:
  760. if lhs[1].kind == nkIntLit:
  761. return inferStaticParam(c, lhs[2], rhs - lhs[1].intVal)
  762. elif lhs[2].kind == nkIntLit:
  763. return inferStaticParam(c, lhs[1], rhs - lhs[2].intVal)
  764. of mDec, mSubI, mSubU, mPred:
  765. if lhs[1].kind == nkIntLit:
  766. return inferStaticParam(c, lhs[2], lhs[1].intVal - rhs)
  767. elif lhs[2].kind == nkIntLit:
  768. return inferStaticParam(c, lhs[1], rhs + lhs[2].intVal)
  769. of mMulI, mMulU:
  770. if lhs[1].kind == nkIntLit:
  771. if rhs mod lhs[1].intVal == 0:
  772. return inferStaticParam(c, lhs[2], rhs div lhs[1].intVal)
  773. elif lhs[2].kind == nkIntLit:
  774. if rhs mod lhs[2].intVal == 0:
  775. return inferStaticParam(c, lhs[1], rhs div lhs[2].intVal)
  776. of mDivI, mDivU:
  777. if lhs[1].kind == nkIntLit:
  778. if lhs[1].intVal mod rhs == 0:
  779. return inferStaticParam(c, lhs[2], lhs[1].intVal div rhs)
  780. elif lhs[2].kind == nkIntLit:
  781. return inferStaticParam(c, lhs[1], lhs[2].intVal * rhs)
  782. of mShlI:
  783. if lhs[2].kind == nkIntLit:
  784. return inferStaticParam(c, lhs[1], rhs shr lhs[2].intVal)
  785. of mShrI:
  786. if lhs[2].kind == nkIntLit:
  787. return inferStaticParam(c, lhs[1], rhs shl lhs[2].intVal)
  788. of mAshrI:
  789. if lhs[2].kind == nkIntLit:
  790. return inferStaticParam(c, lhs[1], ashr(rhs, lhs[2].intVal))
  791. of mUnaryMinusI:
  792. return inferStaticParam(c, lhs[1], -rhs)
  793. of mUnaryPlusI:
  794. return inferStaticParam(c, lhs[1], rhs)
  795. else: discard
  796. elif lhs.kind == nkSym and lhs.typ.kind == tyStatic and lhs.typ.n == nil:
  797. var inferred = newTypeWithSons(c.c, tyStatic, lhs.typ.sons)
  798. inferred.n = newIntNode(nkIntLit, rhs)
  799. put(c, lhs.typ, inferred)
  800. if c.c.matchedConcept != nil:
  801. # inside concepts, binding is currently done with
  802. # direct mutation of the involved types:
  803. lhs.typ.n = inferred.n
  804. return true
  805. return false
  806. proc failureToInferStaticParam(conf: ConfigRef; n: PNode) =
  807. let staticParam = n.findUnresolvedStatic
  808. let name = if staticParam != nil: staticParam.sym.name.s
  809. else: "unknown"
  810. localError(conf, n.info, "cannot infer the value of the static param '" & name & "'")
  811. proc inferStaticsInRange(c: var TCandidate,
  812. inferred, concrete: PType): TTypeRelation =
  813. let lowerBound = tryResolvingStaticExpr(c, inferred.n[0],
  814. allowUnresolved = true)
  815. let upperBound = tryResolvingStaticExpr(c, inferred.n[1],
  816. allowUnresolved = true)
  817. template doInferStatic(e: PNode, r: Int128) =
  818. var exp = e
  819. var rhs = r
  820. if inferStaticParam(c, exp, toInt64(rhs)):
  821. return isGeneric
  822. else:
  823. failureToInferStaticParam(c.c.config, exp)
  824. if lowerBound.kind == nkIntLit:
  825. if upperBound.kind == nkIntLit:
  826. if lengthOrd(c.c.config, concrete) == upperBound.intVal - lowerBound.intVal + 1:
  827. return isGeneric
  828. else:
  829. return isNone
  830. doInferStatic(upperBound, lengthOrd(c.c.config, concrete) + lowerBound.intVal - 1)
  831. elif upperBound.kind == nkIntLit:
  832. doInferStatic(lowerBound, getInt(upperBound) + 1 - lengthOrd(c.c.config, concrete))
  833. template subtypeCheck() =
  834. if result <= isSubrange and f.lastSon.skipTypes(abstractInst).kind in {
  835. tyRef, tyPtr, tyVar, tyLent, tyOwned}:
  836. result = isNone
  837. proc isCovariantPtr(c: var TCandidate, f, a: PType): bool =
  838. # this proc is always called for a pair of matching types
  839. assert f.kind == a.kind
  840. template baseTypesCheck(lhs, rhs: PType): bool =
  841. lhs.kind notin {tyPtr, tyRef, tyVar, tyLent, tyOwned} and
  842. typeRel(c, lhs, rhs, {trNoCovariance}) == isSubtype
  843. case f.kind
  844. of tyRef, tyPtr, tyOwned:
  845. return baseTypesCheck(f.base, a.base)
  846. of tyGenericInst:
  847. let body = f.base
  848. return body == a.base and
  849. a.len == 3 and
  850. tfWeakCovariant notin body[0].flags and
  851. baseTypesCheck(f[1], a[1])
  852. else:
  853. return false
  854. when false:
  855. proc maxNumericType(prev, candidate: PType): PType =
  856. let c = candidate.skipTypes({tyRange})
  857. template greater(s) =
  858. if c.kind in s: result = c
  859. case prev.kind
  860. of tyInt: greater({tyInt64})
  861. of tyInt8: greater({tyInt, tyInt16, tyInt32, tyInt64})
  862. of tyInt16: greater({tyInt, tyInt32, tyInt64})
  863. of tyInt32: greater({tyInt64})
  864. of tyUInt: greater({tyUInt64})
  865. of tyUInt8: greater({tyUInt, tyUInt16, tyUInt32, tyUInt64})
  866. of tyUInt16: greater({tyUInt, tyUInt32, tyUInt64})
  867. of tyUInt32: greater({tyUInt64})
  868. of tyFloat32: greater({tyFloat64, tyFloat128})
  869. of tyFloat64: greater({tyFloat128})
  870. else: discard
  871. template skipOwned(a) =
  872. if a.kind == tyOwned: a = a.skipTypes({tyOwned, tyGenericInst})
  873. proc typeRel(c: var TCandidate, f, aOrig: PType,
  874. flags: TTypeRelFlags = {}): TTypeRelation =
  875. # typeRel can be used to establish various relationships between types:
  876. #
  877. # 1) When used with concrete types, it will check for type equivalence
  878. # or a subtype relationship.
  879. #
  880. # 2) When used with a concrete type against a type class (such as generic
  881. # signature of a proc), it will check whether the concrete type is a member
  882. # of the designated type class.
  883. #
  884. # 3) When used with two type classes, it will check whether the types
  885. # matching the first type class are a strict subset of the types matching
  886. # the other. This allows us to compare the signatures of generic procs in
  887. # order to give preferrence to the most specific one:
  888. #
  889. # seq[seq[any]] is a strict subset of seq[any] and hence more specific.
  890. result = isNone
  891. assert(f != nil)
  892. if f.kind == tyUntyped:
  893. if aOrig != nil: put(c, f, aOrig)
  894. return isGeneric
  895. assert(aOrig != nil)
  896. var
  897. useTypeLoweringRuleInTypeClass = c.c.matchedConcept != nil and
  898. not c.isNoCall and
  899. f.kind != tyTypeDesc and
  900. tfExplicit notin aOrig.flags and
  901. tfConceptMatchedTypeSym notin aOrig.flags
  902. aOrig = if useTypeLoweringRuleInTypeClass:
  903. aOrig.skipTypes({tyTypeDesc})
  904. else:
  905. aOrig
  906. if aOrig.kind == tyInferred:
  907. let prev = aOrig.previouslyInferred
  908. if prev != nil:
  909. return typeRel(c, f, prev)
  910. else:
  911. var candidate = f
  912. case f.kind
  913. of tyGenericParam:
  914. var prev = PType(idTableGet(c.bindings, f))
  915. if prev != nil: candidate = prev
  916. of tyFromExpr:
  917. let computedType = tryResolvingStaticExpr(c, f.n).typ
  918. case computedType.kind
  919. of tyTypeDesc:
  920. candidate = computedType.base
  921. of tyStatic:
  922. candidate = computedType
  923. else:
  924. # XXX What is this non-sense? Error reporting in signature matching?
  925. discard "localError(f.n.info, errTypeExpected)"
  926. else:
  927. discard
  928. result = typeRel(c, aOrig.base, candidate)
  929. if result != isNone:
  930. c.inferredTypes.add aOrig
  931. aOrig.add candidate
  932. result = isEqual
  933. return
  934. template doBind: bool = trDontBind notin flags
  935. # var, sink and static arguments match regular modifier-free types
  936. var a = maybeSkipDistinct(c, aOrig.skipTypes({tyStatic, tyVar, tyLent, tySink}), c.calleeSym)
  937. # XXX: Theoretically, maybeSkipDistinct could be called before we even
  938. # start the param matching process. This could be done in `prepareOperand`
  939. # for example, but unfortunately `prepareOperand` is not called in certain
  940. # situation when nkDotExpr are rotated to nkDotCalls
  941. if aOrig.kind in {tyAlias, tySink}:
  942. return typeRel(c, f, lastSon(aOrig))
  943. if a.kind == tyGenericInst and
  944. skipTypes(f, {tyVar, tyLent, tySink}).kind notin {
  945. tyGenericBody, tyGenericInvocation,
  946. tyGenericInst, tyGenericParam} + tyTypeClasses:
  947. return typeRel(c, f, lastSon(a))
  948. if a.isResolvedUserTypeClass:
  949. return typeRel(c, f, a.lastSon)
  950. template bindingRet(res) =
  951. if doBind:
  952. let bound = aOrig.skipTypes({tyRange}).skipIntLit
  953. put(c, f, bound)
  954. return res
  955. template considerPreviousT(body: untyped) =
  956. var prev = PType(idTableGet(c.bindings, f))
  957. if prev == nil: body
  958. else: return typeRel(c, prev, a)
  959. case a.kind
  960. of tyOr:
  961. # XXX: deal with the current dual meaning of tyGenericParam
  962. c.typedescMatched = true
  963. # seq[int|string] vs seq[number]
  964. # both int and string must match against number
  965. # but ensure that '[T: A|A]' matches as good as '[T: A]' (bug #2219):
  966. result = isGeneric
  967. for branch in a.sons:
  968. let x = typeRel(c, f, branch, flags + {trDontBind})
  969. if x == isNone: return isNone
  970. if x < result: result = x
  971. return result
  972. of tyAnd:
  973. # XXX: deal with the current dual meaning of tyGenericParam
  974. c.typedescMatched = true
  975. # seq[Sortable and Iterable] vs seq[Sortable]
  976. # only one match is enough
  977. for branch in a.sons:
  978. let x = typeRel(c, f, branch, flags + {trDontBind})
  979. if x != isNone:
  980. return if x >= isGeneric: isGeneric else: x
  981. return isNone
  982. of tyNot:
  983. case f.kind
  984. of tyNot:
  985. # seq[!int] vs seq[!number]
  986. # seq[float] matches the first, but not the second
  987. # we must turn the problem around:
  988. # is number a subset of int?
  989. return typeRel(c, a.lastSon, f.lastSon)
  990. else:
  991. # negative type classes are essentially infinite,
  992. # so only the `any` type class is their superset
  993. return if f.kind == tyAnything: isGeneric
  994. else: isNone
  995. of tyAnything:
  996. if f.kind == tyAnything: return isGeneric
  997. else: return isNone
  998. of tyUserTypeClass, tyUserTypeClassInst:
  999. if c.c.matchedConcept != nil and c.c.matchedConcept.depth <= 4:
  1000. # consider this: 'var g: Node' *within* a concept where 'Node'
  1001. # is a concept too (tgraph)
  1002. inc c.c.matchedConcept.depth
  1003. let x = typeRel(c, a, f, flags + {trDontBind})
  1004. if x >= isGeneric:
  1005. return isGeneric
  1006. else: discard
  1007. case f.kind
  1008. of tyEnum:
  1009. if a.kind == f.kind and sameEnumTypes(f, a): result = isEqual
  1010. elif sameEnumTypes(f, skipTypes(a, {tyRange})): result = isSubtype
  1011. of tyBool, tyChar:
  1012. if a.kind == f.kind: result = isEqual
  1013. elif skipTypes(a, {tyRange}).kind == f.kind: result = isSubtype
  1014. of tyRange:
  1015. if a.kind == f.kind:
  1016. if f.base.kind == tyNone: return isGeneric
  1017. result = typeRel(c, base(f), base(a))
  1018. # bugfix: accept integer conversions here
  1019. #if result < isGeneric: result = isNone
  1020. if result notin {isNone, isGeneric}:
  1021. # resolve any late-bound static expressions
  1022. # that may appear in the range:
  1023. for i in 0..1:
  1024. if f.n[i].kind == nkStaticExpr:
  1025. f.n[i] = tryResolvingStaticExpr(c, f.n[i])
  1026. result = typeRangeRel(f, a)
  1027. else:
  1028. let f = skipTypes(f, {tyRange})
  1029. if f.kind == a.kind and (f.kind != tyEnum or sameEnumTypes(f, a)):
  1030. result = isIntConv
  1031. elif isConvertibleToRange(f, a):
  1032. result = isConvertible # a convertible to f
  1033. of tyInt: result = handleRange(f, a, tyInt8, tyInt32)
  1034. of tyInt8: result = handleRange(f, a, tyInt8, tyInt8)
  1035. of tyInt16: result = handleRange(f, a, tyInt8, tyInt16)
  1036. of tyInt32: result = handleRange(f, a, tyInt8, tyInt32)
  1037. of tyInt64: result = handleRange(f, a, tyInt, tyInt64)
  1038. of tyUInt: result = handleRange(f, a, tyUInt8, tyUInt32)
  1039. of tyUInt8: result = handleRange(f, a, tyUInt8, tyUInt8)
  1040. of tyUInt16: result = handleRange(f, a, tyUInt8, tyUInt16)
  1041. of tyUInt32: result = handleRange(f, a, tyUInt8, tyUInt32)
  1042. of tyUInt64: result = handleRange(f, a, tyUInt, tyUInt64)
  1043. of tyFloat: result = handleFloatRange(f, a)
  1044. of tyFloat32: result = handleFloatRange(f, a)
  1045. of tyFloat64: result = handleFloatRange(f, a)
  1046. of tyFloat128: result = handleFloatRange(f, a)
  1047. of tyVar, tyLent:
  1048. if aOrig.kind == f.kind: result = typeRel(c, f.base, aOrig.base)
  1049. else: result = typeRel(c, f.base, aOrig, flags + {trNoCovariance})
  1050. subtypeCheck()
  1051. of tyArray:
  1052. case a.kind
  1053. of tyArray:
  1054. var fRange = f[0]
  1055. var aRange = a[0]
  1056. if fRange.kind == tyGenericParam:
  1057. var prev = PType(idTableGet(c.bindings, fRange))
  1058. if prev == nil:
  1059. put(c, fRange, a[0])
  1060. fRange = a
  1061. else:
  1062. fRange = prev
  1063. let ff = f[1].skipTypes({tyTypeDesc})
  1064. # This typeDesc rule is wrong, see bug #7331
  1065. let aa = a[1] #.skipTypes({tyTypeDesc})
  1066. if f[0].kind != tyGenericParam and aa.kind == tyEmpty:
  1067. result = isGeneric
  1068. else:
  1069. result = typeRel(c, ff, aa)
  1070. if result < isGeneric:
  1071. if nimEnableCovariance and
  1072. trNoCovariance notin flags and
  1073. ff.kind == aa.kind and
  1074. isCovariantPtr(c, ff, aa):
  1075. result = isSubtype
  1076. else:
  1077. return isNone
  1078. if fRange.rangeHasUnresolvedStatic:
  1079. return inferStaticsInRange(c, fRange, a)
  1080. elif c.c.matchedConcept != nil and aRange.rangeHasUnresolvedStatic:
  1081. return inferStaticsInRange(c, aRange, f)
  1082. else:
  1083. if lengthOrd(c.c.config, fRange) != lengthOrd(c.c.config, aRange):
  1084. result = isNone
  1085. else: discard
  1086. of tyUncheckedArray:
  1087. if a.kind == tyUncheckedArray:
  1088. result = typeRel(c, base(f), base(a))
  1089. if result < isGeneric: result = isNone
  1090. else: discard
  1091. of tyOpenArray, tyVarargs:
  1092. # varargs[expr] is special too but handled earlier. So we only need to
  1093. # handle varargs[stmt] which is the same as varargs[typed]:
  1094. if f.kind == tyVarargs:
  1095. if tfVarargs in a.flags:
  1096. return typeRel(c, f.base, a.lastSon)
  1097. if f[0].kind == tyTyped: return
  1098. template matchArrayOrSeq(aBase: PType) =
  1099. let ff = f.base
  1100. let aa = aBase
  1101. let baseRel = typeRel(c, ff, aa)
  1102. if baseRel >= isGeneric:
  1103. result = isConvertible
  1104. elif nimEnableCovariance and
  1105. trNoCovariance notin flags and
  1106. ff.kind == aa.kind and
  1107. isCovariantPtr(c, ff, aa):
  1108. result = isConvertible
  1109. case a.kind
  1110. of tyOpenArray, tyVarargs:
  1111. result = typeRel(c, base(f), base(a))
  1112. if result < isGeneric: result = isNone
  1113. of tyArray:
  1114. if (f[0].kind != tyGenericParam) and (a[1].kind == tyEmpty):
  1115. return isSubtype
  1116. matchArrayOrSeq(a[1])
  1117. of tySequence:
  1118. if (f[0].kind != tyGenericParam) and (a[0].kind == tyEmpty):
  1119. return isConvertible
  1120. matchArrayOrSeq(a[0])
  1121. of tyString:
  1122. if f.kind == tyOpenArray:
  1123. if f[0].kind == tyChar:
  1124. result = isConvertible
  1125. elif f[0].kind == tyGenericParam and a.len > 0 and
  1126. typeRel(c, base(f), base(a)) >= isGeneric:
  1127. result = isConvertible
  1128. else: discard
  1129. of tySequence:
  1130. case a.kind
  1131. of tySequence:
  1132. if (f[0].kind != tyGenericParam) and (a[0].kind == tyEmpty):
  1133. result = isSubtype
  1134. else:
  1135. let ff = f[0]
  1136. let aa = a[0]
  1137. result = typeRel(c, ff, aa)
  1138. if result < isGeneric:
  1139. if nimEnableCovariance and
  1140. trNoCovariance notin flags and
  1141. ff.kind == aa.kind and
  1142. isCovariantPtr(c, ff, aa):
  1143. result = isSubtype
  1144. else:
  1145. result = isNone
  1146. elif tfNotNil in f.flags and tfNotNil notin a.flags:
  1147. result = isNilConversion
  1148. of tyNil: result = allowsNilDeprecated(c, f)
  1149. else: discard
  1150. of tyOrdinal:
  1151. if isOrdinalType(a):
  1152. var x = if a.kind == tyOrdinal: a[0] else: a
  1153. if f[0].kind == tyNone:
  1154. result = isGeneric
  1155. else:
  1156. result = typeRel(c, f[0], x)
  1157. if result < isGeneric: result = isNone
  1158. elif a.kind == tyGenericParam:
  1159. result = isGeneric
  1160. of tyForward:
  1161. #internalError("forward type in typeRel()")
  1162. result = isNone
  1163. of tyNil:
  1164. skipOwned(a)
  1165. if a.kind == f.kind: result = isEqual
  1166. of tyTuple:
  1167. if a.kind == tyTuple: result = recordRel(c, f, a)
  1168. of tyObject:
  1169. if a.kind == tyObject:
  1170. if sameObjectTypes(f, a):
  1171. result = isEqual
  1172. # elif tfHasMeta in f.flags: result = recordRel(c, f, a)
  1173. else:
  1174. var depth = isObjectSubtype(c, a, f, nil)
  1175. if depth > 0:
  1176. inc(c.inheritancePenalty, depth)
  1177. result = isSubtype
  1178. of tyDistinct:
  1179. a = a.skipTypes({tyOwned, tyGenericInst, tyRange})
  1180. if a.kind == tyDistinct:
  1181. if sameDistinctTypes(f, a): result = isEqual
  1182. #elif f.base.kind == tyAnything: result = isGeneric # issue 4435
  1183. elif c.coerceDistincts: result = typeRel(c, f.base, a)
  1184. elif a.kind == tyNil and f.base.kind in NilableTypes:
  1185. result = f.allowsNil # XXX remove this typing rule, it is not in the spec
  1186. elif c.coerceDistincts: result = typeRel(c, f.base, a)
  1187. of tySet:
  1188. if a.kind == tySet:
  1189. if f[0].kind != tyGenericParam and a[0].kind == tyEmpty:
  1190. result = isSubtype
  1191. else:
  1192. result = typeRel(c, f[0], a[0])
  1193. if result <= isConvertible:
  1194. result = isNone # BUGFIX!
  1195. of tyPtr, tyRef:
  1196. skipOwned(a)
  1197. if a.kind == f.kind:
  1198. # ptr[R, T] can be passed to ptr[T], but not the other way round:
  1199. if a.len < f.len: return isNone
  1200. for i in 0..<f.len-1:
  1201. if typeRel(c, f[i], a[i]) == isNone: return isNone
  1202. result = typeRel(c, f.lastSon, a.lastSon, flags + {trNoCovariance})
  1203. subtypeCheck()
  1204. if result <= isIntConv: result = isNone
  1205. elif tfNotNil in f.flags and tfNotNil notin a.flags:
  1206. result = isNilConversion
  1207. elif a.kind == tyNil: result = f.allowsNil
  1208. else: discard
  1209. of tyProc:
  1210. skipOwned(a)
  1211. result = procTypeRel(c, f, a)
  1212. if result != isNone and tfNotNil in f.flags and tfNotNil notin a.flags:
  1213. result = isNilConversion
  1214. of tyOwned:
  1215. case a.kind
  1216. of tyOwned:
  1217. result = typeRel(c, lastSon(f), lastSon(a))
  1218. of tyNil: result = f.allowsNil
  1219. else: discard
  1220. of tyPointer:
  1221. skipOwned(a)
  1222. case a.kind
  1223. of tyPointer:
  1224. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1225. result = isNilConversion
  1226. else:
  1227. result = isEqual
  1228. of tyNil: result = f.allowsNil
  1229. of tyProc:
  1230. if a.callConv != ccClosure: result = isConvertible
  1231. of tyPtr:
  1232. # 'pointer' is NOT compatible to regionized pointers
  1233. # so 'dealloc(regionPtr)' fails:
  1234. if a.len == 1: result = isConvertible
  1235. of tyCString: result = isConvertible
  1236. else: discard
  1237. of tyString:
  1238. case a.kind
  1239. of tyString:
  1240. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1241. result = isNilConversion
  1242. else:
  1243. result = isEqual
  1244. of tyNil: result = allowsNilDeprecated(c, f)
  1245. else: discard
  1246. of tyCString:
  1247. # conversion from string to cstring is automatic:
  1248. case a.kind
  1249. of tyCString:
  1250. if tfNotNil in f.flags and tfNotNil notin a.flags:
  1251. result = isNilConversion
  1252. else:
  1253. result = isEqual
  1254. of tyNil: result = f.allowsNil
  1255. of tyString: result = isConvertible
  1256. of tyPtr:
  1257. # ptr[Tag, char] is not convertible to 'cstring' for now:
  1258. if a.len == 1:
  1259. let pointsTo = a[0].skipTypes(abstractInst)
  1260. if pointsTo.kind == tyChar: result = isConvertible
  1261. elif pointsTo.kind == tyUncheckedArray and pointsTo[0].kind == tyChar:
  1262. result = isConvertible
  1263. elif pointsTo.kind == tyArray and firstOrd(nil, pointsTo[0]) == 0 and
  1264. skipTypes(pointsTo[0], {tyRange}).kind in {tyInt..tyInt64} and
  1265. pointsTo[1].kind == tyChar:
  1266. result = isConvertible
  1267. else: discard
  1268. of tyEmpty, tyVoid:
  1269. if a.kind == f.kind: result = isEqual
  1270. of tyAlias, tySink:
  1271. result = typeRel(c, lastSon(f), a)
  1272. of tyGenericInst:
  1273. var prev = PType(idTableGet(c.bindings, f))
  1274. let origF = f
  1275. var f = if prev == nil: f else: prev
  1276. let roota = a.skipGenericAlias
  1277. let rootf = f.skipGenericAlias
  1278. var m = c
  1279. if a.kind == tyGenericInst:
  1280. if roota.base == rootf.base:
  1281. let nextFlags = flags + {trNoCovariance}
  1282. var hasCovariance = false
  1283. # YYYY
  1284. result = isEqual
  1285. for i in 1..<rootf.len-1:
  1286. let ff = rootf[i]
  1287. let aa = roota[i]
  1288. let res = typeRel(c, ff, aa, nextFlags)
  1289. if res != isNone and res != isEqual: result = isGeneric
  1290. if res notin {isEqual, isGeneric}:
  1291. if trNoCovariance notin flags and ff.kind == aa.kind:
  1292. let paramFlags = rootf.base[i-1].flags
  1293. hasCovariance =
  1294. if tfCovariant in paramFlags:
  1295. if tfWeakCovariant in paramFlags:
  1296. isCovariantPtr(c, ff, aa)
  1297. else:
  1298. ff.kind notin {tyRef, tyPtr} and res == isSubtype
  1299. else:
  1300. tfContravariant in paramFlags and
  1301. typeRel(c, aa, ff) == isSubtype
  1302. if hasCovariance:
  1303. continue
  1304. return isNone
  1305. if prev == nil: put(c, f, a)
  1306. else:
  1307. let fKind = rootf.lastSon.kind
  1308. if fKind in {tyAnd, tyOr}:
  1309. result = typeRel(c, lastSon(f), a)
  1310. if result != isNone: put(c, f, a)
  1311. return
  1312. var aAsObject = roota.lastSon
  1313. if fKind in {tyRef, tyPtr}:
  1314. if aAsObject.kind == tyObject:
  1315. # bug #7600, tyObject cannot be passed
  1316. # as argument to tyRef/tyPtr
  1317. return isNone
  1318. elif aAsObject.kind == fKind:
  1319. aAsObject = aAsObject.base
  1320. if aAsObject.kind == tyObject:
  1321. let baseType = aAsObject.base
  1322. if baseType != nil:
  1323. c.inheritancePenalty += 1
  1324. let ret = typeRel(c, f, baseType)
  1325. return if ret == isEqual: isSubtype else: ret
  1326. result = isNone
  1327. else:
  1328. assert lastSon(origF) != nil
  1329. result = typeRel(c, lastSon(origF), a)
  1330. if result != isNone and a.kind != tyNil:
  1331. put(c, f, a)
  1332. of tyGenericBody:
  1333. considerPreviousT:
  1334. if a == f or a.kind == tyGenericInst and a[0] == f:
  1335. bindingRet isGeneric
  1336. let ff = lastSon(f)
  1337. if ff != nil:
  1338. result = typeRel(c, ff, a)
  1339. of tyGenericInvocation:
  1340. var x = a.skipGenericAlias
  1341. var preventHack = false
  1342. if x.kind == tyOwned and f[0].kind != tyOwned:
  1343. preventHack = true
  1344. x = x.lastSon
  1345. # XXX: This is very hacky. It should be moved back into liftTypeParam
  1346. if x.kind in {tyGenericInst, tyArray} and
  1347. c.calleeSym != nil and
  1348. c.calleeSym.kind in {skProc, skFunc} and c.call != nil and not preventHack:
  1349. let inst = prepareMetatypeForSigmatch(c.c, c.bindings, c.call.info, f)
  1350. #echo "inferred ", typeToString(inst), " for ", f
  1351. return typeRel(c, inst, a)
  1352. var depth = 0
  1353. if x.kind == tyGenericInvocation or f[0].kind != tyGenericBody:
  1354. #InternalError("typeRel: tyGenericInvocation -> tyGenericInvocation")
  1355. # simply no match for now:
  1356. discard
  1357. elif x.kind == tyGenericInst and f[0] == x[0] and
  1358. x.len - 1 == f.len:
  1359. for i in 1..<f.len:
  1360. if x[i].kind == tyGenericParam:
  1361. internalError(c.c.graph.config, "wrong instantiated type!")
  1362. elif typeRel(c, f[i], x[i]) <= isSubtype:
  1363. # Workaround for regression #4589
  1364. if f[i].kind != tyTypeDesc: return
  1365. result = isGeneric
  1366. elif x.kind == tyGenericInst and isGenericSubtype(c, x, f, depth, f) and
  1367. (x.len - 1 == f.len):
  1368. # do not recurse here in order to not K bind twice for this code:
  1369. #
  1370. # type
  1371. # BaseFruit[T] = object of RootObj
  1372. # Banana[T] = object of BaseFruit[uint32] # Concrete type here, not T!
  1373. # proc setColor[K](self: var BaseFruit[K])
  1374. # var x: Banana[float64]
  1375. # x.setColor()
  1376. c.inheritancePenalty += depth
  1377. result = isGeneric
  1378. else:
  1379. let genericBody = f[0]
  1380. var askip = skippedNone
  1381. var fskip = skippedNone
  1382. let aobj = x.skipToObject(askip)
  1383. let fobj = genericBody.lastSon.skipToObject(fskip)
  1384. var depth = -1
  1385. if fobj != nil and aobj != nil and askip == fskip:
  1386. depth = isObjectSubtype(c, aobj, fobj, f)
  1387. result = typeRel(c, genericBody, x)
  1388. if result != isNone:
  1389. # see tests/generics/tgeneric3.nim for an example that triggers this
  1390. # piece of code:
  1391. #
  1392. # proc internalFind[T,D](n: PNode[T,D], key: T): ref TItem[T,D]
  1393. # proc internalPut[T,D](ANode: ref TNode[T,D], Akey: T, Avalue: D,
  1394. # Oldvalue: var D): ref TNode[T,D]
  1395. # var root = internalPut[int, int](nil, 312, 312, oldvalue)
  1396. # var it1 = internalFind(root, 312) # cannot instantiate: 'D'
  1397. #
  1398. # we steal the generic parameters from the tyGenericBody:
  1399. for i in 1..<f.len:
  1400. let x = PType(idTableGet(c.bindings, genericBody[i-1]))
  1401. if x == nil:
  1402. discard "maybe fine (for eg. a==tyNil)"
  1403. elif x.kind in {tyGenericInvocation, tyGenericParam}:
  1404. internalError(c.c.graph.config, "wrong instantiated type!")
  1405. else:
  1406. let key = f[i]
  1407. let old = PType(idTableGet(c.bindings, key))
  1408. if old == nil:
  1409. put(c, key, x)
  1410. elif typeRel(c, old, x, flags + {trDontBind}) == isNone:
  1411. return isNone
  1412. if result == isNone:
  1413. # Here object inheriting from generic/specialized generic object
  1414. # crossing path with metatypes/aliases, so we need to separate them
  1415. # by checking sym.id
  1416. let genericSubtype = isGenericSubtype(c, x, f, depth, f)
  1417. if not (genericSubtype and aobj.sym.id != fobj.sym.id) and aOrig.kind != tyGenericBody:
  1418. depth = -1
  1419. if depth >= 0:
  1420. c.inheritancePenalty += depth
  1421. # bug #4863: We still need to bind generic alias crap, so
  1422. # we cannot return immediately:
  1423. result = if depth == 0: isGeneric else: isSubtype
  1424. of tyAnd:
  1425. considerPreviousT:
  1426. result = isEqual
  1427. for branch in f.sons:
  1428. let x = typeRel(c, branch, aOrig)
  1429. if x < isSubtype: return isNone
  1430. # 'and' implies minimum matching result:
  1431. if x < result: result = x
  1432. if result > isGeneric: result = isGeneric
  1433. bindingRet result
  1434. of tyOr:
  1435. considerPreviousT:
  1436. result = isNone
  1437. let oldInheritancePenalty = c.inheritancePenalty
  1438. var maxInheritance = 0
  1439. for branch in f.sons:
  1440. c.inheritancePenalty = 0
  1441. let x = typeRel(c, branch, aOrig)
  1442. maxInheritance = max(maxInheritance, c.inheritancePenalty)
  1443. # 'or' implies maximum matching result:
  1444. if x > result: result = x
  1445. if result >= isSubtype:
  1446. if result > isGeneric: result = isGeneric
  1447. bindingRet result
  1448. else:
  1449. result = isNone
  1450. c.inheritancePenalty = oldInheritancePenalty + maxInheritance
  1451. of tyNot:
  1452. considerPreviousT:
  1453. for branch in f.sons:
  1454. if typeRel(c, branch, aOrig) != isNone:
  1455. return isNone
  1456. bindingRet isGeneric
  1457. of tyAnything:
  1458. considerPreviousT:
  1459. var concrete = concreteType(c, a)
  1460. if concrete != nil and doBind:
  1461. put(c, f, concrete)
  1462. return isGeneric
  1463. of tyBuiltInTypeClass:
  1464. considerPreviousT:
  1465. let targetKind = f[0].kind
  1466. let effectiveArgType = a.skipTypes({tyRange, tyGenericInst,
  1467. tyBuiltInTypeClass, tyAlias, tySink, tyOwned})
  1468. let typeClassMatches = targetKind == effectiveArgType.kind and
  1469. not effectiveArgType.isEmptyContainer
  1470. if typeClassMatches or
  1471. (targetKind in {tyProc, tyPointer} and effectiveArgType.kind == tyNil):
  1472. put(c, f, a)
  1473. return isGeneric
  1474. else:
  1475. return isNone
  1476. of tyUserTypeClassInst, tyUserTypeClass:
  1477. if f.isResolvedUserTypeClass:
  1478. result = typeRel(c, f.lastSon, a)
  1479. else:
  1480. considerPreviousT:
  1481. if aOrig == f: return isEqual
  1482. var matched = matchUserTypeClass(c, f, aOrig)
  1483. if matched != nil:
  1484. bindConcreteTypeToUserTypeClass(matched, a)
  1485. if doBind: put(c, f, matched)
  1486. result = isGeneric
  1487. else:
  1488. result = isNone
  1489. of tyCompositeTypeClass:
  1490. considerPreviousT:
  1491. let roota = a.skipGenericAlias
  1492. let rootf = f.lastSon.skipGenericAlias
  1493. if a.kind == tyGenericInst and roota.base == rootf.base:
  1494. for i in 1..<rootf.len-1:
  1495. let ff = rootf[i]
  1496. let aa = roota[i]
  1497. result = typeRel(c, ff, aa)
  1498. if result == isNone: return
  1499. if ff.kind == tyRange and result != isEqual: return isNone
  1500. else:
  1501. result = typeRel(c, rootf.lastSon, a)
  1502. if result != isNone:
  1503. put(c, f, a)
  1504. result = isGeneric
  1505. of tyGenericParam:
  1506. var x = PType(idTableGet(c.bindings, f))
  1507. if x == nil:
  1508. if c.callee.kind == tyGenericBody and not c.typedescMatched:
  1509. # XXX: The fact that generic types currently use tyGenericParam for
  1510. # their parameters is really a misnomer. tyGenericParam means "match
  1511. # any value" and what we need is "match any type", which can be encoded
  1512. # by a tyTypeDesc params. Unfortunately, this requires more substantial
  1513. # changes in semtypinst and elsewhere.
  1514. if tfWildcard in a.flags:
  1515. result = isGeneric
  1516. elif a.kind == tyTypeDesc:
  1517. if f.len == 0:
  1518. result = isGeneric
  1519. else:
  1520. internalAssert c.c.graph.config, a.len > 0
  1521. c.typedescMatched = true
  1522. var aa = a
  1523. while aa.kind in {tyTypeDesc, tyGenericParam} and aa.len > 0:
  1524. aa = lastSon(aa)
  1525. if aa.kind == tyGenericParam:
  1526. return isGeneric
  1527. result = typeRel(c, f.base, aa)
  1528. if result > isGeneric: result = isGeneric
  1529. elif c.isNoCall:
  1530. if doBind:
  1531. let concrete = concreteType(c, a, f)
  1532. if concrete == nil: return isNone
  1533. put(c, f, concrete)
  1534. result = isGeneric
  1535. else:
  1536. result = isNone
  1537. else:
  1538. # check if 'T' has a constraint as in 'proc p[T: Constraint](x: T)'
  1539. if f.len > 0 and f[0].kind != tyNone:
  1540. let oldInheritancePenalty = c.inheritancePenalty
  1541. result = typeRel(c, f[0], a, flags + {trDontBind})
  1542. if doBind and result notin {isNone, isGeneric}:
  1543. let concrete = concreteType(c, a, f)
  1544. if concrete == nil: return isNone
  1545. put(c, f, concrete)
  1546. # bug #6526
  1547. if result in {isEqual, isSubtype}:
  1548. # 'T: Class' is a *better* match than just 'T'
  1549. # but 'T: Subclass' is even better:
  1550. c.inheritancePenalty = oldInheritancePenalty - c.inheritancePenalty -
  1551. 100 * ord(result == isEqual)
  1552. result = isGeneric
  1553. elif a.kind == tyTypeDesc:
  1554. # somewhat special typing rule, the following is illegal:
  1555. # proc p[T](x: T)
  1556. # p(int)
  1557. result = isNone
  1558. else:
  1559. result = isGeneric
  1560. if result == isGeneric:
  1561. var concrete = a
  1562. if tfWildcard in a.flags:
  1563. a.sym.transitionGenericParamToType()
  1564. a.flags.excl tfWildcard
  1565. else:
  1566. concrete = concreteType(c, a, f)
  1567. if concrete == nil:
  1568. return isNone
  1569. if doBind:
  1570. put(c, f, concrete)
  1571. elif result > isGeneric:
  1572. result = isGeneric
  1573. elif a.kind == tyEmpty:
  1574. result = isGeneric
  1575. elif x.kind == tyGenericParam:
  1576. result = isGeneric
  1577. else:
  1578. result = typeRel(c, x, a) # check if it fits
  1579. if result > isGeneric: result = isGeneric
  1580. of tyStatic:
  1581. let prev = PType(idTableGet(c.bindings, f))
  1582. if prev == nil:
  1583. if aOrig.kind == tyStatic:
  1584. if f.base.kind != tyNone:
  1585. result = typeRel(c, f.base, a)
  1586. if result != isNone and f.n != nil:
  1587. if not exprStructuralEquivalent(f.n, aOrig.n):
  1588. result = isNone
  1589. else:
  1590. result = isGeneric
  1591. if result != isNone: put(c, f, aOrig)
  1592. elif aOrig.n != nil and aOrig.n.typ != nil:
  1593. result = if f.base.kind != tyNone: typeRel(c, f.lastSon, aOrig.n.typ)
  1594. else: isGeneric
  1595. if result != isNone:
  1596. var boundType = newTypeWithSons(c.c, tyStatic, @[aOrig.n.typ])
  1597. boundType.n = aOrig.n
  1598. put(c, f, boundType)
  1599. else:
  1600. result = isNone
  1601. elif prev.kind == tyStatic:
  1602. if aOrig.kind == tyStatic:
  1603. result = typeRel(c, prev.lastSon, a)
  1604. if result != isNone and prev.n != nil:
  1605. if not exprStructuralEquivalent(prev.n, aOrig.n):
  1606. result = isNone
  1607. else: result = isNone
  1608. else:
  1609. # XXX endless recursion?
  1610. #result = typeRel(c, prev, aOrig)
  1611. result = isNone
  1612. of tyInferred:
  1613. let prev = f.previouslyInferred
  1614. if prev != nil:
  1615. result = typeRel(c, prev, a)
  1616. else:
  1617. result = typeRel(c, f.base, a)
  1618. if result != isNone:
  1619. c.inferredTypes.add f
  1620. f.add a
  1621. of tyTypeDesc:
  1622. var prev = PType(idTableGet(c.bindings, f))
  1623. if prev == nil:
  1624. # proc foo(T: typedesc, x: T)
  1625. # when `f` is an unresolved typedesc, `a` could be any
  1626. # type, so we should not perform this check earlier
  1627. if a.kind != tyTypeDesc:
  1628. if a.kind == tyGenericParam and tfWildcard in a.flags:
  1629. # TODO: prevent `a` from matching as a wildcard again
  1630. result = isGeneric
  1631. else:
  1632. result = isNone
  1633. elif f.base.kind == tyNone:
  1634. result = isGeneric
  1635. else:
  1636. result = typeRel(c, f.base, a.base)
  1637. if result != isNone:
  1638. put(c, f, a)
  1639. else:
  1640. if tfUnresolved in f.flags:
  1641. result = typeRel(c, prev.base, a)
  1642. elif a.kind == tyTypeDesc:
  1643. result = typeRel(c, prev.base, a.base)
  1644. else:
  1645. result = isNone
  1646. of tyTyped:
  1647. if aOrig != nil:
  1648. put(c, f, aOrig)
  1649. result = isGeneric
  1650. of tyProxy:
  1651. result = isEqual
  1652. of tyFromExpr:
  1653. # fix the expression, so it contains the already instantiated types
  1654. if f.n == nil or f.n.kind == nkEmpty: return isGeneric
  1655. let reevaluated = tryResolvingStaticExpr(c, f.n)
  1656. case reevaluated.typ.kind
  1657. of tyTypeDesc:
  1658. result = typeRel(c, a, reevaluated.typ.base)
  1659. of tyStatic:
  1660. result = typeRel(c, a, reevaluated.typ.base)
  1661. if result != isNone and reevaluated.typ.n != nil:
  1662. if not exprStructuralEquivalent(aOrig.n, reevaluated.typ.n):
  1663. result = isNone
  1664. else:
  1665. localError(c.c.graph.config, f.n.info, "type expected")
  1666. result = isNone
  1667. of tyNone:
  1668. if a.kind == tyNone: result = isEqual
  1669. else:
  1670. internalError c.c.graph.config, " unknown type kind " & $f.kind
  1671. when false:
  1672. var nowDebug = false
  1673. var dbgCount = 0
  1674. proc typeRel(c: var TCandidate, f, aOrig: PType,
  1675. flags: TTypeRelFlags = {}): TTypeRelation =
  1676. if nowDebug:
  1677. echo f, " <- ", aOrig
  1678. inc dbgCount
  1679. if dbgCount == 2:
  1680. writeStackTrace()
  1681. result = typeRelImpl(c, f, aOrig, flags)
  1682. if nowDebug:
  1683. echo f, " <- ", aOrig, " res ", result
  1684. proc cmpTypes*(c: PContext, f, a: PType): TTypeRelation =
  1685. var m = newCandidate(c, f)
  1686. result = typeRel(m, f, a)
  1687. proc getInstantiatedType(c: PContext, arg: PNode, m: TCandidate,
  1688. f: PType): PType =
  1689. result = PType(idTableGet(m.bindings, f))
  1690. if result == nil:
  1691. result = generateTypeInstance(c, m.bindings, arg, f)
  1692. if result == nil:
  1693. internalError(c.graph.config, arg.info, "getInstantiatedType")
  1694. result = errorType(c)
  1695. proc implicitConv(kind: TNodeKind, f: PType, arg: PNode, m: TCandidate,
  1696. c: PContext): PNode =
  1697. result = newNodeI(kind, arg.info)
  1698. if containsGenericType(f):
  1699. if not m.hasFauxMatch:
  1700. result.typ = getInstantiatedType(c, arg, m, f).skipTypes({tySink})
  1701. else:
  1702. result.typ = errorType(c)
  1703. else:
  1704. result.typ = f.skipTypes({tySink})
  1705. if result.typ == nil: internalError(c.graph.config, arg.info, "implicitConv")
  1706. result.add c.graph.emptyNode
  1707. result.add arg
  1708. proc userConvMatch(c: PContext, m: var TCandidate, f, a: PType,
  1709. arg: PNode): PNode =
  1710. result = nil
  1711. for i in 0..<c.converters.len:
  1712. var src = c.converters[i].typ[1]
  1713. var dest = c.converters[i].typ[0]
  1714. # for generic type converters we need to check 'src <- a' before
  1715. # 'f <- dest' in order to not break the unification:
  1716. # see tests/tgenericconverter:
  1717. let srca = typeRel(m, src, a)
  1718. if srca notin {isEqual, isGeneric, isSubtype}: continue
  1719. # What's done below matches the logic in ``matchesAux``
  1720. let constraint = c.converters[i].typ.n[1].sym.constraint
  1721. if not constraint.isNil and not matchNodeKinds(constraint, arg):
  1722. continue
  1723. if src.kind in {tyVar, tyLent} and not arg.isLValue:
  1724. continue
  1725. let destIsGeneric = containsGenericType(dest)
  1726. if destIsGeneric:
  1727. dest = generateTypeInstance(c, m.bindings, arg, dest)
  1728. let fdest = typeRel(m, f, dest)
  1729. if fdest in {isEqual, isGeneric} and not (dest.kind == tyLent and f.kind == tyVar):
  1730. markUsed(c, arg.info, c.converters[i])
  1731. var s = newSymNode(c.converters[i])
  1732. s.typ = c.converters[i].typ
  1733. s.info = arg.info
  1734. result = newNodeIT(nkHiddenCallConv, arg.info, dest)
  1735. result.add s
  1736. # We build the call expression by ourselves in order to avoid passing this
  1737. # expression trough the semantic check phase once again so let's make sure
  1738. # it is correct
  1739. var param: PNode = nil
  1740. if srca == isSubtype:
  1741. param = implicitConv(nkHiddenSubConv, src, copyTree(arg), m, c)
  1742. elif src.kind == tyVar:
  1743. # Analyse the converter return type
  1744. param = newNodeIT(nkHiddenAddr, arg.info, s.typ[1])
  1745. param.add copyTree(arg)
  1746. else:
  1747. param = copyTree(arg)
  1748. result.add param
  1749. if dest.kind in {tyVar, tyLent}:
  1750. dest.flags.incl tfVarIsPtr
  1751. result = newDeref(result)
  1752. inc(m.convMatches)
  1753. if not m.genericConverter:
  1754. m.genericConverter = srca == isGeneric or destIsGeneric
  1755. return result
  1756. proc localConvMatch(c: PContext, m: var TCandidate, f, a: PType,
  1757. arg: PNode): PNode =
  1758. # arg.typ can be nil in 'suggest':
  1759. if isNil(arg.typ): return nil
  1760. # sem'checking for 'echo' needs to be re-entrant:
  1761. # XXX we will revisit this issue after 0.10.2 is released
  1762. if f == arg.typ and arg.kind == nkHiddenStdConv: return arg
  1763. var call = newNodeI(nkCall, arg.info)
  1764. call.add(f.n.copyTree)
  1765. call.add(arg.copyTree)
  1766. # XXX: This would be much nicer if we don't use `semTryExpr` and
  1767. # instead we directly search for overloads with `resolveOverloads`:
  1768. result = c.semTryExpr(c, call, {efNoSem2Check})
  1769. if result != nil:
  1770. if result.typ == nil: return nil
  1771. # bug #13378, ensure we produce a real generic instantiation:
  1772. result = c.semExpr(c, call)
  1773. # resulting type must be consistent with the other arguments:
  1774. var r = typeRel(m, f[0], result.typ)
  1775. if r < isGeneric: return nil
  1776. if result.kind == nkCall: result.transitionSonsKind(nkHiddenCallConv)
  1777. inc(m.convMatches)
  1778. if r == isGeneric:
  1779. result.typ = getInstantiatedType(c, arg, m, base(f))
  1780. m.baseTypeMatch = true
  1781. proc incMatches(m: var TCandidate; r: TTypeRelation; convMatch = 1) =
  1782. case r
  1783. of isConvertible, isIntConv: inc(m.convMatches, convMatch)
  1784. of isSubtype, isSubrange: inc(m.subtypeMatches)
  1785. of isGeneric, isInferred, isBothMetaConvertible: inc(m.genericMatches)
  1786. of isFromIntLit: inc(m.intConvMatches, 256)
  1787. of isInferredConvertible:
  1788. inc(m.convMatches)
  1789. of isEqual: inc(m.exactMatches)
  1790. of isNone: discard
  1791. template matchesVoidProc(t: PType): bool =
  1792. (t.kind == tyProc and t.len == 1 and t[0] == nil) or
  1793. (t.kind == tyBuiltInTypeClass and t[0].kind == tyProc)
  1794. proc paramTypesMatchAux(m: var TCandidate, f, a: PType,
  1795. argSemantized, argOrig: PNode): PNode =
  1796. var
  1797. fMaybeStatic = f.skipTypes({tyDistinct})
  1798. arg = argSemantized
  1799. a = a
  1800. c = m.c
  1801. if tfHasStatic in fMaybeStatic.flags:
  1802. # XXX: When implicit statics are the default
  1803. # this will be done earlier - we just have to
  1804. # make sure that static types enter here
  1805. # Zahary: weaken tyGenericParam and call it tyGenericPlaceholder
  1806. # and finally start using tyTypedesc for generic types properly.
  1807. # Araq: This would only shift the problems around, in 'proc p[T](x: T)'
  1808. # the T is NOT a typedesc.
  1809. if a.kind == tyGenericParam and tfWildcard in a.flags:
  1810. a.assignType(f)
  1811. # put(m.bindings, f, a)
  1812. return argSemantized
  1813. if a.kind == tyStatic:
  1814. if m.callee.kind == tyGenericBody and
  1815. a.n == nil and
  1816. tfGenericTypeParam notin a.flags:
  1817. return newNodeIT(nkType, argOrig.info, makeTypeFromExpr(c, arg))
  1818. else:
  1819. var evaluated = c.semTryConstExpr(c, arg)
  1820. if evaluated != nil:
  1821. # Don't build the type in-place because `evaluated` and `arg` may point
  1822. # to the same object and we'd end up creating recursive types (#9255)
  1823. let typ = newTypeS(tyStatic, c)
  1824. typ.sons = @[evaluated.typ]
  1825. typ.n = evaluated
  1826. arg.typ = typ
  1827. a = typ
  1828. else:
  1829. if m.callee.kind == tyGenericBody:
  1830. if f.kind == tyStatic and typeRel(m, f.base, a) != isNone:
  1831. result = makeStaticExpr(m.c, arg)
  1832. result.typ.flags.incl tfUnresolved
  1833. result.typ.n = arg
  1834. return
  1835. let oldInheritancePenalty = m.inheritancePenalty
  1836. var r = typeRel(m, f, a)
  1837. # This special typing rule for macros and templates is not documented
  1838. # anywhere and breaks symmetry. It's hard to get rid of though, my
  1839. # custom seqs example fails to compile without this:
  1840. if r != isNone and m.calleeSym != nil and
  1841. m.calleeSym.kind in {skMacro, skTemplate}:
  1842. # XXX: duplicating this is ugly, but we cannot (!) move this
  1843. # directly into typeRel using return-like templates
  1844. incMatches(m, r)
  1845. if f.kind == tyTyped:
  1846. return arg
  1847. elif f.kind == tyTypeDesc:
  1848. return arg
  1849. elif f.kind == tyStatic and arg.typ.n != nil:
  1850. return arg.typ.n
  1851. else:
  1852. return argSemantized # argOrig
  1853. # If r == isBothMetaConvertible then we rerun typeRel.
  1854. # bothMetaCounter is for safety to avoid any infinite loop,
  1855. # I don't have any example when it is needed.
  1856. # lastBindingsLenth is used to check whether m.bindings remains the same,
  1857. # because in that case there is no point in continuing.
  1858. var bothMetaCounter = 0
  1859. var lastBindingsLength = -1
  1860. while r == isBothMetaConvertible and
  1861. lastBindingsLength != m.bindings.counter and
  1862. bothMetaCounter < 100:
  1863. lastBindingsLength = m.bindings.counter
  1864. inc(bothMetaCounter)
  1865. if arg.kind in {nkProcDef, nkFuncDef, nkIteratorDef} + nkLambdaKinds:
  1866. result = c.semInferredLambda(c, m.bindings, arg)
  1867. elif arg.kind != nkSym:
  1868. return nil
  1869. else:
  1870. let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info)
  1871. result = newSymNode(inferred, arg.info)
  1872. inc(m.convMatches)
  1873. arg = result
  1874. r = typeRel(m, f, arg.typ)
  1875. case r
  1876. of isConvertible:
  1877. inc(m.convMatches)
  1878. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1879. of isIntConv:
  1880. # I'm too lazy to introduce another ``*matches`` field, so we conflate
  1881. # ``isIntConv`` and ``isIntLit`` here:
  1882. inc(m.intConvMatches)
  1883. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1884. of isSubtype:
  1885. inc(m.subtypeMatches)
  1886. if f.kind == tyTypeDesc:
  1887. result = arg
  1888. else:
  1889. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1890. of isSubrange:
  1891. inc(m.subtypeMatches)
  1892. if f.kind == tyVar:
  1893. result = arg
  1894. else:
  1895. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1896. of isInferred, isInferredConvertible:
  1897. if arg.kind in {nkProcDef, nkFuncDef, nkIteratorDef} + nkLambdaKinds:
  1898. result = c.semInferredLambda(c, m.bindings, arg)
  1899. elif arg.kind != nkSym:
  1900. return nil
  1901. else:
  1902. let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info)
  1903. result = newSymNode(inferred, arg.info)
  1904. if r == isInferredConvertible:
  1905. inc(m.convMatches)
  1906. result = implicitConv(nkHiddenStdConv, f, result, m, c)
  1907. else:
  1908. inc(m.genericMatches)
  1909. of isGeneric:
  1910. inc(m.genericMatches)
  1911. if arg.typ == nil:
  1912. result = arg
  1913. elif skipTypes(arg.typ, abstractVar-{tyTypeDesc}).kind == tyTuple or
  1914. m.inheritancePenalty > oldInheritancePenalty:
  1915. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1916. elif arg.typ.isEmptyContainer:
  1917. result = arg.copyTree
  1918. result.typ = getInstantiatedType(c, arg, m, f)
  1919. else:
  1920. result = arg
  1921. of isBothMetaConvertible:
  1922. # This is the result for the 101th time.
  1923. result = nil
  1924. of isFromIntLit:
  1925. # too lazy to introduce another ``*matches`` field, so we conflate
  1926. # ``isIntConv`` and ``isIntLit`` here:
  1927. inc(m.intConvMatches, 256)
  1928. result = implicitConv(nkHiddenStdConv, f, arg, m, c)
  1929. of isEqual:
  1930. inc(m.exactMatches)
  1931. result = arg
  1932. if skipTypes(f, abstractVar-{tyTypeDesc}).kind == tyTuple or
  1933. (arg.typ != nil and skipTypes(arg.typ, abstractVar-{tyTypeDesc}).kind == tyTuple):
  1934. result = implicitConv(nkHiddenSubConv, f, arg, m, c)
  1935. of isNone:
  1936. # do not do this in ``typeRel`` as it then can't infer T in ``ref T``:
  1937. if a.kind in {tyProxy, tyUnknown}:
  1938. inc(m.genericMatches)
  1939. m.fauxMatch = a.kind
  1940. return arg
  1941. elif a.kind == tyVoid and f.matchesVoidProc and argOrig.kind == nkStmtList:
  1942. # lift do blocks without params to lambdas
  1943. let p = c.graph
  1944. let lifted = c.semExpr(c, newProcNode(nkDo, argOrig.info, body = argOrig,
  1945. params = nkFormalParams.newTree(p.emptyNode), name = p.emptyNode, pattern = p.emptyNode,
  1946. genericParams = p.emptyNode, pragmas = p.emptyNode, exceptions = p.emptyNode), {})
  1947. if f.kind == tyBuiltInTypeClass:
  1948. inc m.genericMatches
  1949. put(m, f, lifted.typ)
  1950. inc m.convMatches
  1951. return implicitConv(nkHiddenStdConv, f, lifted, m, c)
  1952. result = userConvMatch(c, m, f, a, arg)
  1953. # check for a base type match, which supports varargs[T] without []
  1954. # constructor in a call:
  1955. if result == nil and f.kind == tyVarargs:
  1956. if f.n != nil:
  1957. # Forward to the varargs converter
  1958. result = localConvMatch(c, m, f, a, arg)
  1959. else:
  1960. r = typeRel(m, base(f), a)
  1961. case r
  1962. of isGeneric:
  1963. inc(m.convMatches)
  1964. result = copyTree(arg)
  1965. result.typ = getInstantiatedType(c, arg, m, base(f))
  1966. m.baseTypeMatch = true
  1967. of isFromIntLit:
  1968. inc(m.intConvMatches, 256)
  1969. result = implicitConv(nkHiddenStdConv, f[0], arg, m, c)
  1970. m.baseTypeMatch = true
  1971. of isEqual:
  1972. inc(m.convMatches)
  1973. result = copyTree(arg)
  1974. m.baseTypeMatch = true
  1975. of isSubtype: # bug #4799, varargs accepting subtype relation object
  1976. inc(m.subtypeMatches)
  1977. if base(f).kind == tyTypeDesc:
  1978. result = arg
  1979. else:
  1980. result = implicitConv(nkHiddenSubConv, base(f), arg, m, c)
  1981. m.baseTypeMatch = true
  1982. else:
  1983. result = userConvMatch(c, m, base(f), a, arg)
  1984. if result != nil: m.baseTypeMatch = true
  1985. proc paramTypesMatch*(m: var TCandidate, f, a: PType,
  1986. arg, argOrig: PNode): PNode =
  1987. if arg == nil or arg.kind notin nkSymChoices:
  1988. result = paramTypesMatchAux(m, f, a, arg, argOrig)
  1989. else:
  1990. # CAUTION: The order depends on the used hashing scheme. Thus it is
  1991. # incorrect to simply use the first fitting match. However, to implement
  1992. # this correctly is inefficient. We have to copy `m` here to be able to
  1993. # roll back the side effects of the unification algorithm.
  1994. let c = m.c
  1995. var
  1996. x = newCandidate(c, m.callee)
  1997. y = newCandidate(c, m.callee)
  1998. z = newCandidate(c, m.callee)
  1999. x.calleeSym = m.calleeSym
  2000. y.calleeSym = m.calleeSym
  2001. z.calleeSym = m.calleeSym
  2002. var best = -1
  2003. for i in 0..<arg.len:
  2004. if arg[i].sym.kind in {skProc, skFunc, skMethod, skConverter,
  2005. skIterator, skMacro, skTemplate}:
  2006. copyCandidate(z, m)
  2007. z.callee = arg[i].typ
  2008. if tfUnresolved in z.callee.flags: continue
  2009. z.calleeSym = arg[i].sym
  2010. #if arg[i].sym.name.s == "cmp":
  2011. # ggDebug = true
  2012. # echo "CALLLEEEEEEEE A ", typeToString(z.callee)
  2013. # XXX this is still all wrong: (T, T) should be 2 generic matches
  2014. # and (int, int) 2 exact matches, etc. Essentially you cannot call
  2015. # typeRel here and expect things to work!
  2016. let r = typeRel(z, f, arg[i].typ)
  2017. incMatches(z, r, 2)
  2018. #if arg[i].sym.name.s == "cmp": # and arg.info.line == 606:
  2019. # echo "M ", r, " ", arg.info, " ", typeToString(arg[i].sym.typ)
  2020. # writeMatches(z)
  2021. if r != isNone:
  2022. z.state = csMatch
  2023. case x.state
  2024. of csEmpty, csNoMatch:
  2025. x = z
  2026. best = i
  2027. of csMatch:
  2028. let cmp = cmpCandidates(x, z)
  2029. if cmp < 0:
  2030. best = i
  2031. x = z
  2032. elif cmp == 0:
  2033. y = z # z is as good as x
  2034. if x.state == csEmpty:
  2035. result = nil
  2036. elif y.state == csMatch and cmpCandidates(x, y) == 0:
  2037. if x.state != csMatch:
  2038. internalError(m.c.graph.config, arg.info, "x.state is not csMatch")
  2039. # ambiguous: more than one symbol fits!
  2040. # See tsymchoice_for_expr as an example. 'f.kind == tyUntyped' should match
  2041. # anyway:
  2042. if f.kind in {tyUntyped, tyTyped}: result = arg
  2043. else: result = nil
  2044. else:
  2045. # only one valid interpretation found:
  2046. markUsed(m.c, arg.info, arg[best].sym)
  2047. onUse(arg.info, arg[best].sym)
  2048. result = paramTypesMatchAux(m, f, arg[best].typ, arg[best], argOrig)
  2049. when false:
  2050. if m.calleeSym != nil and m.calleeSym.name.s == "[]":
  2051. echo m.c.config $ arg.info, " for ", m.calleeSym.name.s, " ", m.c.config $ m.calleeSym.info
  2052. writeMatches(m)
  2053. proc setSon(father: PNode, at: int, son: PNode) =
  2054. let oldLen = father.len
  2055. if oldLen <= at:
  2056. setLen(father.sons, at + 1)
  2057. father[at] = son
  2058. # insert potential 'void' parameters:
  2059. #for i in oldLen..<at:
  2060. # father[i] = newNodeIT(nkEmpty, son.info, getSysType(tyVoid))
  2061. # we are allowed to modify the calling node in the 'prepare*' procs:
  2062. proc prepareOperand(c: PContext; formal: PType; a: PNode): PNode =
  2063. if formal.kind == tyUntyped and formal.len != 1:
  2064. # {tyTypeDesc, tyUntyped, tyTyped, tyProxy}:
  2065. # a.typ == nil is valid
  2066. result = a
  2067. elif a.typ.isNil:
  2068. # XXX This is unsound! 'formal' can differ from overloaded routine to
  2069. # overloaded routine!
  2070. let flags = {efDetermineType, efAllowStmt}
  2071. #if formal.kind == tyIter: {efDetermineType, efWantIterator}
  2072. #else: {efDetermineType, efAllowStmt}
  2073. #elif formal.kind == tyTyped: {efDetermineType, efWantStmt}
  2074. #else: {efDetermineType}
  2075. result = c.semOperand(c, a, flags)
  2076. else:
  2077. result = a
  2078. considerGenSyms(c, result)
  2079. proc prepareOperand(c: PContext; a: PNode): PNode =
  2080. if a.typ.isNil:
  2081. result = c.semOperand(c, a, {efDetermineType})
  2082. else:
  2083. result = a
  2084. considerGenSyms(c, result)
  2085. proc prepareNamedParam(a: PNode; c: PContext) =
  2086. if a[0].kind != nkIdent:
  2087. var info = a[0].info
  2088. a[0] = newIdentNode(considerQuotedIdent(c, a[0]), info)
  2089. proc arrayConstr(c: PContext, n: PNode): PType =
  2090. result = newTypeS(tyArray, c)
  2091. rawAddSon(result, makeRangeType(c, 0, 0, n.info))
  2092. addSonSkipIntLit(result, skipTypes(n.typ,
  2093. {tyGenericInst, tyVar, tyLent, tyOrdinal}))
  2094. proc arrayConstr(c: PContext, info: TLineInfo): PType =
  2095. result = newTypeS(tyArray, c)
  2096. rawAddSon(result, makeRangeType(c, 0, -1, info))
  2097. rawAddSon(result, newTypeS(tyEmpty, c)) # needs an empty basetype!
  2098. proc incrIndexType(t: PType) =
  2099. assert t.kind == tyArray
  2100. inc t[0].n[1].intVal
  2101. template isVarargsUntyped(x): untyped =
  2102. x.kind == tyVarargs and x[0].kind == tyUntyped
  2103. proc matchesAux(c: PContext, n, nOrig: PNode,
  2104. m: var TCandidate, marker: var IntSet) =
  2105. var
  2106. a = 1 # iterates over the actual given arguments
  2107. f = if m.callee.kind != tyGenericBody: 1
  2108. else: 0 # iterates over formal parameters
  2109. arg: PNode # current prepared argument
  2110. formal: PSym # current routine parameter
  2111. template noMatch() =
  2112. m.state = csNoMatch
  2113. m.firstMismatch.arg = a
  2114. m.firstMismatch.formal = formal
  2115. template checkConstraint(n: untyped) {.dirty.} =
  2116. if not formal.constraint.isNil:
  2117. if matchNodeKinds(formal.constraint, n):
  2118. # better match over other routines with no such restriction:
  2119. inc(m.genericMatches, 100)
  2120. else:
  2121. noMatch()
  2122. return
  2123. if formal.typ.kind == tyVar:
  2124. let argConverter = if arg.kind == nkHiddenDeref: arg[0] else: arg
  2125. if argConverter.kind == nkHiddenCallConv:
  2126. if argConverter.typ.kind != tyVar:
  2127. m.firstMismatch.kind = kVarNeeded
  2128. noMatch()
  2129. return
  2130. elif not n.isLValue:
  2131. m.firstMismatch.kind = kVarNeeded
  2132. noMatch()
  2133. return
  2134. m.state = csMatch # until proven otherwise
  2135. m.firstMismatch = MismatchInfo()
  2136. m.call = newNodeI(n.kind, n.info)
  2137. m.call.typ = base(m.callee) # may be nil
  2138. var formalLen = m.callee.n.len
  2139. m.call.add n[0]
  2140. var container: PNode = nil # constructed container
  2141. formal = if formalLen > 1: m.callee.n[1].sym else: nil
  2142. while a < n.len:
  2143. if a >= formalLen-1 and f < formalLen and m.callee.n[f].typ.isVarargsUntyped:
  2144. formal = m.callee.n[f].sym
  2145. incl(marker, formal.position)
  2146. if n[a].kind == nkHiddenStdConv:
  2147. doAssert n[a][0].kind == nkEmpty and
  2148. n[a][1].kind in {nkBracket, nkArgList}
  2149. # Steal the container and pass it along
  2150. setSon(m.call, formal.position + 1, n[a][1])
  2151. else:
  2152. if container.isNil:
  2153. container = newNodeIT(nkArgList, n[a].info, arrayConstr(c, n.info))
  2154. setSon(m.call, formal.position + 1, container)
  2155. else:
  2156. incrIndexType(container.typ)
  2157. container.add n[a]
  2158. elif n[a].kind == nkExprEqExpr:
  2159. # named param
  2160. m.firstMismatch.kind = kUnknownNamedParam
  2161. # check if m.callee has such a param:
  2162. prepareNamedParam(n[a], c)
  2163. if n[a][0].kind != nkIdent:
  2164. localError(c.config, n[a].info, "named parameter has to be an identifier")
  2165. noMatch()
  2166. return
  2167. formal = getNamedParamFromList(m.callee.n, n[a][0].ident)
  2168. if formal == nil:
  2169. # no error message!
  2170. noMatch()
  2171. return
  2172. if containsOrIncl(marker, formal.position):
  2173. m.firstMismatch.kind = kAlreadyGiven
  2174. # already in namedParams, so no match
  2175. # we used to produce 'errCannotBindXTwice' here but see
  2176. # bug #3836 of why that is not sound (other overload with
  2177. # different parameter names could match later on):
  2178. when false: localError(n[a].info, errCannotBindXTwice, formal.name.s)
  2179. noMatch()
  2180. return
  2181. m.baseTypeMatch = false
  2182. m.typedescMatched = false
  2183. n[a][1] = prepareOperand(c, formal.typ, n[a][1])
  2184. n[a].typ = n[a][1].typ
  2185. arg = paramTypesMatch(m, formal.typ, n[a].typ,
  2186. n[a][1], n[a][1])
  2187. m.firstMismatch.kind = kTypeMismatch
  2188. if arg == nil:
  2189. noMatch()
  2190. return
  2191. checkConstraint(n[a][1])
  2192. if m.baseTypeMatch:
  2193. #assert(container == nil)
  2194. container = newNodeIT(nkBracket, n[a].info, arrayConstr(c, arg))
  2195. container.add arg
  2196. setSon(m.call, formal.position + 1, container)
  2197. if f != formalLen - 1: container = nil
  2198. else:
  2199. setSon(m.call, formal.position + 1, arg)
  2200. inc f
  2201. else:
  2202. # unnamed param
  2203. if f >= formalLen:
  2204. # too many arguments?
  2205. if tfVarargs in m.callee.flags:
  2206. # is ok... but don't increment any counters...
  2207. # we have no formal here to snoop at:
  2208. n[a] = prepareOperand(c, n[a])
  2209. if skipTypes(n[a].typ, abstractVar-{tyTypeDesc}).kind==tyString:
  2210. m.call.add implicitConv(nkHiddenStdConv,
  2211. getSysType(c.graph, n[a].info, tyCString),
  2212. copyTree(n[a]), m, c)
  2213. else:
  2214. m.call.add copyTree(n[a])
  2215. elif formal != nil and formal.typ.kind == tyVarargs:
  2216. m.firstMismatch.kind = kTypeMismatch
  2217. # beware of the side-effects in 'prepareOperand'! So only do it for
  2218. # varargs matching. See tests/metatype/tstatic_overloading.
  2219. m.baseTypeMatch = false
  2220. m.typedescMatched = false
  2221. incl(marker, formal.position)
  2222. n[a] = prepareOperand(c, formal.typ, n[a])
  2223. arg = paramTypesMatch(m, formal.typ, n[a].typ,
  2224. n[a], nOrig[a])
  2225. if arg != nil and m.baseTypeMatch and container != nil:
  2226. container.add arg
  2227. incrIndexType(container.typ)
  2228. checkConstraint(n[a])
  2229. else:
  2230. noMatch()
  2231. return
  2232. else:
  2233. m.firstMismatch.kind = kExtraArg
  2234. noMatch()
  2235. return
  2236. else:
  2237. if m.callee.n[f].kind != nkSym:
  2238. internalError(c.config, n[a].info, "matches")
  2239. noMatch()
  2240. return
  2241. formal = m.callee.n[f].sym
  2242. m.firstMismatch.kind = kTypeMismatch
  2243. if containsOrIncl(marker, formal.position) and container.isNil:
  2244. m.firstMismatch.kind = kPositionalAlreadyGiven
  2245. # positional param already in namedParams: (see above remark)
  2246. when false: localError(n[a].info, errCannotBindXTwice, formal.name.s)
  2247. noMatch()
  2248. return
  2249. if formal.typ.isVarargsUntyped:
  2250. if container.isNil:
  2251. container = newNodeIT(nkArgList, n[a].info, arrayConstr(c, n.info))
  2252. setSon(m.call, formal.position + 1, container)
  2253. else:
  2254. incrIndexType(container.typ)
  2255. container.add n[a]
  2256. else:
  2257. m.baseTypeMatch = false
  2258. m.typedescMatched = false
  2259. n[a] = prepareOperand(c, formal.typ, n[a])
  2260. arg = paramTypesMatch(m, formal.typ, n[a].typ,
  2261. n[a], nOrig[a])
  2262. if arg == nil:
  2263. noMatch()
  2264. return
  2265. if m.baseTypeMatch:
  2266. assert formal.typ.kind == tyVarargs
  2267. #assert(container == nil)
  2268. if container.isNil:
  2269. container = newNodeIT(nkBracket, n[a].info, arrayConstr(c, arg))
  2270. container.typ.flags.incl tfVarargs
  2271. else:
  2272. incrIndexType(container.typ)
  2273. container.add arg
  2274. setSon(m.call, formal.position + 1,
  2275. implicitConv(nkHiddenStdConv, formal.typ, container, m, c))
  2276. #if f != formalLen - 1: container = nil
  2277. # pick the formal from the end, so that 'x, y, varargs, z' works:
  2278. f = max(f, formalLen - n.len + a + 1)
  2279. elif formal.typ.kind != tyVarargs or container == nil:
  2280. setSon(m.call, formal.position + 1, arg)
  2281. inc(f)
  2282. container = nil
  2283. else:
  2284. # we end up here if the argument can be converted into the varargs
  2285. # formal (eg. seq[T] -> varargs[T]) but we have already instantiated
  2286. # a container
  2287. #assert arg.kind == nkHiddenStdConv # for 'nim check'
  2288. # this assertion can be off
  2289. localError(c.config, n[a].info, "cannot convert $1 to $2" % [
  2290. typeToString(n[a].typ), typeToString(formal.typ) ])
  2291. noMatch()
  2292. return
  2293. checkConstraint(n[a])
  2294. inc(a)
  2295. # for some edge cases (see tdont_return_unowned_from_owned test case)
  2296. m.firstMismatch.arg = a
  2297. m.firstMismatch.formal = formal
  2298. proc semFinishOperands*(c: PContext, n: PNode) =
  2299. # this needs to be called to ensure that after overloading resolution every
  2300. # argument has been sem'checked:
  2301. for i in 1..<n.len:
  2302. n[i] = prepareOperand(c, n[i])
  2303. proc partialMatch*(c: PContext, n, nOrig: PNode, m: var TCandidate) =
  2304. # for 'suggest' support:
  2305. var marker = initIntSet()
  2306. matchesAux(c, n, nOrig, m, marker)
  2307. proc matches*(c: PContext, n, nOrig: PNode, m: var TCandidate) =
  2308. if m.magic in {mArrGet, mArrPut}:
  2309. m.state = csMatch
  2310. m.call = n
  2311. # Note the following doesn't work as it would produce ambiguities.
  2312. # Instead we patch system.nim, see bug #8049.
  2313. when false:
  2314. inc m.genericMatches
  2315. inc m.exactMatches
  2316. return
  2317. var marker = initIntSet()
  2318. matchesAux(c, n, nOrig, m, marker)
  2319. if m.state == csNoMatch: return
  2320. # check that every formal parameter got a value:
  2321. for f in 1..<m.callee.n.len:
  2322. var formal = m.callee.n[f].sym
  2323. if not containsOrIncl(marker, formal.position):
  2324. if formal.ast == nil:
  2325. if formal.typ.kind == tyVarargs:
  2326. # For consistency with what happens in `matchesAux` select the
  2327. # container node kind accordingly
  2328. let cnKind = if formal.typ.isVarargsUntyped: nkArgList else: nkBracket
  2329. var container = newNodeIT(cnKind, n.info, arrayConstr(c, n.info))
  2330. setSon(m.call, formal.position + 1,
  2331. implicitConv(nkHiddenStdConv, formal.typ, container, m, c))
  2332. else:
  2333. # no default value
  2334. m.state = csNoMatch
  2335. m.firstMismatch.kind = kMissingParam
  2336. m.firstMismatch.formal = formal
  2337. break
  2338. else:
  2339. if formal.ast.kind == nkEmpty:
  2340. # The default param value is set to empty in `instantiateProcType`
  2341. # when the type of the default expression doesn't match the type
  2342. # of the instantiated proc param:
  2343. localError(c.config, m.call.info,
  2344. ("The default parameter '$1' has incompatible type " &
  2345. "with the explicitly requested proc instantiation") %
  2346. formal.name.s)
  2347. if nfDefaultRefsParam in formal.ast.flags:
  2348. m.call.flags.incl nfDefaultRefsParam
  2349. var defaultValue = copyTree(formal.ast)
  2350. if defaultValue.kind == nkNilLit:
  2351. defaultValue = implicitConv(nkHiddenStdConv, formal.typ, defaultValue, m, c)
  2352. # proc foo(x: T = 0.0)
  2353. # foo()
  2354. if {tfImplicitTypeParam, tfGenericTypeParam} * formal.typ.flags != {}:
  2355. let existing = PType(idTableGet(m.bindings, formal.typ))
  2356. if existing == nil or existing.kind == tyTypeDesc:
  2357. # see bug #11600:
  2358. put(m, formal.typ, defaultValue.typ)
  2359. defaultValue.flags.incl nfDefaultParam
  2360. setSon(m.call, formal.position + 1, defaultValue)
  2361. # forget all inferred types if the overload matching failed
  2362. if m.state == csNoMatch:
  2363. for t in m.inferredTypes:
  2364. if t.len > 1: t.sons.setLen 1
  2365. proc argtypeMatches*(c: PContext, f, a: PType, fromHlo = false): bool =
  2366. var m = newCandidate(c, f)
  2367. let res = paramTypesMatch(m, f, a, c.graph.emptyNode, nil)
  2368. #instantiateGenericConverters(c, res, m)
  2369. # XXX this is used by patterns.nim too; I think it's better to not
  2370. # instantiate generic converters for that
  2371. if not fromHlo:
  2372. res != nil
  2373. else:
  2374. # pattern templates do not allow for conversions except from int literal
  2375. res != nil and m.convMatches == 0 and m.intConvMatches in [0, 256]
  2376. proc instTypeBoundOp*(c: PContext; dc: PSym; t: PType; info: TLineInfo;
  2377. op: TTypeAttachedOp; col: int): PSym =
  2378. var m = newCandidate(c, dc.typ)
  2379. if col >= dc.typ.len:
  2380. localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'")
  2381. return nil
  2382. var f = dc.typ[col]
  2383. if op == attachedDeepCopy:
  2384. if f.kind in {tyRef, tyPtr}: f = f.lastSon
  2385. else:
  2386. if f.kind == tyVar: f = f.lastSon
  2387. if typeRel(m, f, t) == isNone:
  2388. localError(c.config, info, "cannot instantiate: '" & dc.name.s & "'")
  2389. else:
  2390. result = c.semGenerateInstance(c, dc, m.bindings, info)
  2391. if op == attachedDeepCopy:
  2392. assert sfFromGeneric in result.flags
  2393. include suggest
  2394. when not declared(tests):
  2395. template tests(s: untyped) = discard
  2396. tests:
  2397. var dummyOwner = newSym(skModule, getIdent("test_module"), nil, unknownLineInfo)
  2398. proc `|` (t1, t2: PType): PType =
  2399. result = newType(tyOr, dummyOwner)
  2400. result.rawAddSon(t1)
  2401. result.rawAddSon(t2)
  2402. proc `&` (t1, t2: PType): PType =
  2403. result = newType(tyAnd, dummyOwner)
  2404. result.rawAddSon(t1)
  2405. result.rawAddSon(t2)
  2406. proc `!` (t: PType): PType =
  2407. result = newType(tyNot, dummyOwner)
  2408. result.rawAddSon(t)
  2409. proc seq(t: PType): PType =
  2410. result = newType(tySequence, dummyOwner)
  2411. result.rawAddSon(t)
  2412. proc array(x: int, t: PType): PType =
  2413. result = newType(tyArray, dummyOwner)
  2414. var n = newNodeI(nkRange, unknownLineInfo)
  2415. n.add newIntNode(nkIntLit, 0)
  2416. n.add newIntNode(nkIntLit, x)
  2417. let range = newType(tyRange, dummyOwner)
  2418. result.rawAddSon(range)
  2419. result.rawAddSon(t)
  2420. suite "type classes":
  2421. let
  2422. int = newType(tyInt, dummyOwner)
  2423. float = newType(tyFloat, dummyOwner)
  2424. string = newType(tyString, dummyOwner)
  2425. ordinal = newType(tyOrdinal, dummyOwner)
  2426. any = newType(tyAnything, dummyOwner)
  2427. number = int | float
  2428. var TFoo = newType(tyObject, dummyOwner)
  2429. TFoo.sym = newSym(skType, getIdent"TFoo", dummyOwner, unknownLineInfo)
  2430. var T1 = newType(tyGenericParam, dummyOwner)
  2431. T1.sym = newSym(skType, getIdent"T1", dummyOwner, unknownLineInfo)
  2432. T1.sym.position = 0
  2433. var T2 = newType(tyGenericParam, dummyOwner)
  2434. T2.sym = newSym(skType, getIdent"T2", dummyOwner, unknownLineInfo)
  2435. T2.sym.position = 1
  2436. setup:
  2437. var c = newCandidate(nil, nil)
  2438. template yes(x, y) =
  2439. test astToStr(x) & " is " & astToStr(y):
  2440. check typeRel(c, y, x) == isGeneric
  2441. template no(x, y) =
  2442. test astToStr(x) & " is not " & astToStr(y):
  2443. check typeRel(c, y, x) == isNone
  2444. yes seq(any), array(10, int) | seq(any)
  2445. # Sure, seq[any] is directly included
  2446. yes seq(int), seq(any)
  2447. yes seq(int), seq(number)
  2448. # Sure, the int sequence is certainly
  2449. # part of the number sequences (and all sequences)
  2450. no seq(any), seq(float)
  2451. # Nope, seq[any] includes types that are not seq[float] (e.g. seq[int])
  2452. yes seq(int|string), seq(any)
  2453. # Sure
  2454. yes seq(int&string), seq(any)
  2455. # Again
  2456. yes seq(int&string), seq(int)
  2457. # A bit more complicated
  2458. # seq[int&string] is not a real type, but it's analogous to
  2459. # seq[Sortable and Iterable], which is certainly a subset of seq[Sortable]
  2460. no seq(int|string), seq(int|float)
  2461. # Nope, seq[string] is not included in not included in
  2462. # the seq[int|float] set
  2463. no seq(!(int|string)), seq(string)
  2464. # A sequence that is neither seq[int] or seq[string]
  2465. # is obviously not seq[string]
  2466. no seq(!int), seq(number)
  2467. # Now your head should start to hurt a bit
  2468. # A sequence that is not seq[int] is not necessarily a number sequence
  2469. # it could well be seq[string] for example
  2470. yes seq(!(int|string)), seq(!string)
  2471. # all sequnece types besides seq[int] and seq[string]
  2472. # are subset of all sequence types that are not seq[string]
  2473. no seq(!(int|string)), seq(!(string|TFoo))
  2474. # Nope, seq[TFoo] is included in the first set, but not in the second
  2475. no seq(!string), seq(!number)
  2476. # Nope, seq[int] in included in the first set, but not in the second
  2477. yes seq(!number), seq(any)
  2478. yes seq(!int), seq(any)
  2479. no seq(any), seq(!any)
  2480. no seq(!int), seq(!any)
  2481. yes int, ordinal
  2482. no string, ordinal