sigmatch.nim 97 KB

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