sigmatch.nim 92 KB

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