semcall.nim 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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 semantic checking for calls.
  10. # included from sem.nim
  11. from std/algorithm import sort
  12. proc sameMethodDispatcher(a, b: PSym): bool =
  13. result = false
  14. if a.kind == skMethod and b.kind == skMethod:
  15. var aa = lastSon(a.ast)
  16. var bb = lastSon(b.ast)
  17. if aa.kind == nkSym and bb.kind == nkSym:
  18. if aa.sym == bb.sym:
  19. result = true
  20. else:
  21. discard
  22. # generics have no dispatcher yet, so we need to compare the method
  23. # names; however, the names are equal anyway because otherwise we
  24. # wouldn't even consider them to be overloaded. But even this does
  25. # not work reliably! See tmultim6 for an example:
  26. # method collide[T](a: TThing, b: TUnit[T]) is instantiated and not
  27. # method collide[T](a: TUnit[T], b: TThing)! This means we need to
  28. # *instantiate* every candidate! However, we don't keep more than 2-3
  29. # candidates around so we cannot implement that for now. So in order
  30. # to avoid subtle problems, the call remains ambiguous and needs to
  31. # be disambiguated by the programmer; this way the right generic is
  32. # instantiated.
  33. proc determineType(c: PContext, s: PSym)
  34. proc initCandidateSymbols(c: PContext, headSymbol: PNode,
  35. initialBinding: PNode,
  36. filter: TSymKinds,
  37. best, alt: var TCandidate,
  38. o: var TOverloadIter,
  39. diagnostics: bool): seq[tuple[s: PSym, scope: int]] =
  40. ## puts all overloads into a seq and prepares best+alt
  41. result = @[]
  42. var symx = initOverloadIter(o, c, headSymbol)
  43. while symx != nil:
  44. if symx.kind in filter:
  45. result.add((symx, o.lastOverloadScope))
  46. elif symx.kind == skGenericParam:
  47. #[
  48. This code handles looking up a generic parameter when it's a static callable.
  49. For instance:
  50. proc name[T: static proc()]() = T()
  51. name[proc() = echo"hello"]()
  52. ]#
  53. for paramSym in searchInScopesAllCandidatesFilterBy(c, symx.name, {skConst}):
  54. let paramTyp = paramSym.typ
  55. if paramTyp.n.kind == nkSym and paramTyp.n.sym.kind in filter:
  56. result.add((paramTyp.n.sym, o.lastOverloadScope))
  57. symx = nextOverloadIter(o, c, headSymbol)
  58. if result.len > 0:
  59. best = initCandidate(c, result[0].s, initialBinding,
  60. result[0].scope, diagnostics)
  61. alt = initCandidate(c, result[0].s, initialBinding,
  62. result[0].scope, diagnostics)
  63. best.state = csNoMatch
  64. proc isAttachableRoutineTo(prc: PSym, arg: PType): bool =
  65. result = false
  66. if arg.owner != prc.owner: return false
  67. for i in 1 ..< prc.typ.len:
  68. if prc.typ.n[i].kind == nkSym and prc.typ.n[i].sym.ast != nil:
  69. # has default value, parameter is not considered in type attachment
  70. continue
  71. let t = nominalRoot(prc.typ[i])
  72. if t != nil and t.itemId == arg.itemId:
  73. # parameter `i` is a nominal type in this module
  74. # attachable if the nominal root `t` has the same id as `arg`
  75. return true
  76. proc addTypeBoundSymbols(graph: ModuleGraph, arg: PType, name: PIdent,
  77. filter: TSymKinds, marker: var IntSet,
  78. syms: var seq[tuple[s: PSym, scope: int]]) =
  79. # add type bound ops for `name` based on the argument type `arg`
  80. if arg != nil:
  81. # argument must be typed first, meaning arguments always
  82. # matching `untyped` are ignored
  83. let t = nominalRoot(arg)
  84. if t != nil and t.owner.kind == skModule:
  85. # search module for routines attachable to `t`
  86. let module = t.owner
  87. var iter = default(ModuleIter)
  88. var s = initModuleIter(iter, graph, module, name)
  89. while s != nil:
  90. if s.kind in filter and s.isAttachableRoutineTo(t) and
  91. not containsOrIncl(marker, s.id):
  92. # least priority scope, less than explicit imports:
  93. syms.add((s, -2))
  94. s = nextModuleIter(iter, graph)
  95. proc pickBestCandidate(c: PContext, headSymbol: PNode,
  96. n, orig: PNode,
  97. initialBinding: PNode,
  98. filter: TSymKinds,
  99. best, alt: var TCandidate,
  100. errors: var CandidateErrors,
  101. diagnosticsFlag: bool,
  102. errorsEnabled: bool, flags: TExprFlags) =
  103. # `matches` may find new symbols, so keep track of count
  104. var symCount = c.currentScope.symbols.counter
  105. var o: TOverloadIter = default(TOverloadIter)
  106. # https://github.com/nim-lang/Nim/issues/21272
  107. # prevent mutation during iteration by storing them in a seq
  108. # luckily `initCandidateSymbols` does just that
  109. var syms = initCandidateSymbols(c, headSymbol, initialBinding, filter,
  110. best, alt, o, diagnosticsFlag)
  111. if len(syms) == 0:
  112. return
  113. let allowTypeBoundOps = typeBoundOps in c.features and
  114. # qualified or bound symbols cannot refer to type bound ops
  115. headSymbol.kind in {nkIdent, nkAccQuoted, nkOpenSymChoice, nkOpenSym}
  116. var symMarker = initIntSet()
  117. for s in syms:
  118. symMarker.incl(s.s.id)
  119. # current overload being considered
  120. var sym = syms[0].s
  121. let name = sym.name
  122. var scope = syms[0].scope
  123. if allowTypeBoundOps:
  124. for a in 1 ..< n.len:
  125. # for every already typed argument, add type bound ops
  126. let arg = n[a]
  127. addTypeBoundSymbols(c.graph, arg.typ, name, filter, symMarker, syms)
  128. # starts at 1 because 0 is already done with setup, only needs checking
  129. var nextSymIndex = 1
  130. var z: TCandidate # current candidate
  131. while true:
  132. determineType(c, sym)
  133. z = initCandidate(c, sym, initialBinding, scope, diagnosticsFlag)
  134. # this is kinda backwards as without a check here the described
  135. # problems in recalc would not happen, but instead it 100%
  136. # does check forever in some cases
  137. if c.currentScope.symbols.counter == symCount:
  138. # may introduce new symbols with caveats described in recalc branch
  139. matches(c, n, orig, z)
  140. if allowTypeBoundOps:
  141. # this match may have given some arguments new types,
  142. # in which case add their type bound ops as well
  143. # type bound ops of arguments always matching `untyped` are not considered
  144. for x in z.newlyTypedOperands:
  145. let arg = n[x]
  146. addTypeBoundSymbols(c.graph, arg.typ, name, filter, symMarker, syms)
  147. if z.state == csMatch:
  148. # little hack so that iterators are preferred over everything else:
  149. if sym.kind == skIterator:
  150. if not (efWantIterator notin flags and efWantIterable in flags):
  151. inc(z.exactMatches, 200)
  152. else:
  153. dec(z.exactMatches, 200)
  154. case best.state
  155. of csEmpty, csNoMatch: best = z
  156. of csMatch:
  157. var cmp = cmpCandidates(best, z)
  158. if cmp < 0: best = z # x is better than the best so far
  159. elif cmp == 0: alt = z # x is as good as the best so far
  160. elif errorsEnabled or z.diagnosticsEnabled:
  161. errors.add(CandidateError(
  162. sym: sym,
  163. firstMismatch: z.firstMismatch,
  164. diagnostics: z.diagnostics))
  165. else:
  166. # this branch feels like a ticking timebomb
  167. # one of two bad things could happen
  168. # 1) new symbols are discovered but the loop ends before we recalc
  169. # 2) new symbols are discovered and resemmed forever
  170. # not 100% sure if these are possible though as they would rely
  171. # on somehow introducing a new overload during overload resolution
  172. # Symbol table has been modified. Restart and pre-calculate all syms
  173. # before any further candidate init and compare. SLOW, but rare case.
  174. syms = initCandidateSymbols(c, headSymbol, initialBinding, filter,
  175. best, alt, o, diagnosticsFlag)
  176. symMarker = initIntSet()
  177. for s in syms:
  178. symMarker.incl(s.s.id)
  179. if allowTypeBoundOps:
  180. for a in 1 ..< n.len:
  181. # for every already typed argument, add type bound ops
  182. let arg = n[a]
  183. addTypeBoundSymbols(c.graph, arg.typ, name, filter, symMarker, syms)
  184. # reset counter because syms may be in a new order
  185. symCount = c.currentScope.symbols.counter
  186. nextSymIndex = 0
  187. # just in case, should be impossible though
  188. if syms.len == 0:
  189. break
  190. if nextSymIndex > high(syms):
  191. # we have reached the end
  192. break
  193. # advance to next sym
  194. sym = syms[nextSymIndex].s
  195. scope = syms[nextSymIndex].scope
  196. inc(nextSymIndex)
  197. proc effectProblem(f, a: PType; result: var string; c: PContext) =
  198. if f.kind == tyProc and a.kind == tyProc:
  199. if tfThread in f.flags and tfThread notin a.flags:
  200. result.add "\n This expression is not GC-safe. Annotate the " &
  201. "proc with {.gcsafe.} to get extended error information."
  202. elif tfNoSideEffect in f.flags and tfNoSideEffect notin a.flags:
  203. result.add "\n This expression can have side effects. Annotate the " &
  204. "proc with {.noSideEffect.} to get extended error information."
  205. else:
  206. case compatibleEffects(f, a)
  207. of efCompat: discard
  208. of efRaisesDiffer:
  209. result.add "\n The `.raises` requirements differ."
  210. of efRaisesUnknown:
  211. result.add "\n The `.raises` requirements differ. Annotate the " &
  212. "proc with {.raises: [].} to get extended error information."
  213. of efTagsDiffer:
  214. result.add "\n The `.tags` requirements differ."
  215. of efTagsUnknown:
  216. result.add "\n The `.tags` requirements differ. Annotate the " &
  217. "proc with {.tags: [].} to get extended error information."
  218. of efEffectsDelayed:
  219. result.add "\n The `.effectsOf` annotations differ."
  220. of efTagsIllegal:
  221. result.add "\n The `.forbids` requirements caught an illegal tag."
  222. when defined(drnim):
  223. if not c.graph.compatibleProps(c.graph, f, a):
  224. result.add "\n The `.requires` or `.ensures` properties are incompatible."
  225. proc renderNotLValue(n: PNode): string =
  226. result = $n
  227. let n = if n.kind == nkHiddenDeref: n[0] else: n
  228. if n.kind == nkHiddenCallConv and n.len > 1:
  229. result = $n[0] & "(" & result & ")"
  230. elif n.kind in {nkHiddenStdConv, nkHiddenSubConv} and n.len == 2:
  231. result = typeToString(n.typ.skipTypes(abstractVar)) & "(" & result & ")"
  232. proc presentFailedCandidates(c: PContext, n: PNode, errors: CandidateErrors):
  233. (TPreferedDesc, string) =
  234. var prefer = preferName
  235. # to avoid confusing errors like:
  236. # got (SslPtr, SocketHandle)
  237. # but expected one of:
  238. # openssl.SSL_set_fd(ssl: SslPtr, fd: SocketHandle): cint
  239. # we do a pre-analysis. If all types produce the same string, we will add
  240. # module information.
  241. let proto = describeArgs(c, n, 1, preferName)
  242. for err in errors:
  243. var errProto = ""
  244. let n = err.sym.typ.n
  245. for i in 1..<n.len:
  246. var p = n[i]
  247. if p.kind == nkSym:
  248. errProto.add(typeToString(p.sym.typ, preferName))
  249. if i != n.len-1: errProto.add(", ")
  250. # else: ignore internal error as we're already in error handling mode
  251. if errProto == proto:
  252. prefer = preferModuleInfo
  253. break
  254. # we pretend procs are attached to the type of the first
  255. # argument in order to remove plenty of candidates. This is
  256. # comparable to what C# does and C# is doing fine.
  257. var filterOnlyFirst = false
  258. if optShowAllMismatches notin c.config.globalOptions and verboseTypeMismatch in c.config.legacyFeatures:
  259. for err in errors:
  260. if err.firstMismatch.arg > 1:
  261. filterOnlyFirst = true
  262. break
  263. var maybeWrongSpace = false
  264. var candidatesAll: seq[string] = @[]
  265. var candidates = ""
  266. var skipped = 0
  267. for err in errors:
  268. candidates.setLen 0
  269. if filterOnlyFirst and err.firstMismatch.arg == 1:
  270. inc skipped
  271. continue
  272. if verboseTypeMismatch notin c.config.legacyFeatures:
  273. candidates.add "[" & $err.firstMismatch.arg & "] "
  274. if err.sym.kind in routineKinds and err.sym.ast != nil:
  275. candidates.add(renderTree(err.sym.ast,
  276. {renderNoBody, renderNoComments, renderNoPragmas}))
  277. else:
  278. candidates.add(getProcHeader(c.config, err.sym, prefer))
  279. candidates.addDeclaredLocMaybe(c.config, err.sym)
  280. candidates.add("\n")
  281. const genericParamMismatches = {kGenericParamTypeMismatch, kExtraGenericParam, kMissingGenericParam}
  282. let isGenericMismatch = err.firstMismatch.kind in genericParamMismatches
  283. var argList = n
  284. if isGenericMismatch and n[0].kind == nkBracketExpr:
  285. argList = n[0]
  286. let nArg =
  287. if err.firstMismatch.arg < argList.len:
  288. argList[err.firstMismatch.arg]
  289. else:
  290. nil
  291. let nameParam = if err.firstMismatch.formal != nil: err.firstMismatch.formal.name.s else: ""
  292. if n.len > 1:
  293. if verboseTypeMismatch notin c.config.legacyFeatures:
  294. case err.firstMismatch.kind
  295. of kUnknownNamedParam:
  296. if nArg == nil:
  297. candidates.add(" unknown named parameter")
  298. else:
  299. candidates.add(" unknown named parameter: " & $nArg[0])
  300. candidates.add "\n"
  301. of kAlreadyGiven:
  302. candidates.add(" named param already provided: " & $nArg[0])
  303. candidates.add "\n"
  304. of kPositionalAlreadyGiven:
  305. candidates.add(" positional param was already given as named param")
  306. candidates.add "\n"
  307. of kExtraArg:
  308. candidates.add(" extra argument given")
  309. candidates.add "\n"
  310. of kMissingParam:
  311. candidates.add(" missing parameter: " & nameParam)
  312. candidates.add "\n"
  313. of kExtraGenericParam:
  314. candidates.add(" extra generic param given")
  315. candidates.add "\n"
  316. of kMissingGenericParam:
  317. candidates.add(" missing generic parameter: " & nameParam)
  318. candidates.add "\n"
  319. of kVarNeeded:
  320. doAssert nArg != nil
  321. doAssert err.firstMismatch.formal != nil
  322. candidates.add " expression '"
  323. candidates.add renderNotLValue(nArg)
  324. candidates.add "' is immutable, not 'var'"
  325. candidates.add "\n"
  326. of kTypeMismatch:
  327. doAssert nArg != nil
  328. if nArg.kind in nkSymChoices:
  329. candidates.add ambiguousIdentifierMsg(nArg, indent = 2)
  330. let wanted = err.firstMismatch.formal.typ
  331. doAssert err.firstMismatch.formal != nil
  332. doAssert wanted != nil
  333. let got = nArg.typ
  334. if got != nil and got.kind == tyProc and wanted.kind == tyProc:
  335. # These are proc mismatches so,
  336. # add the extra explict detail of the mismatch
  337. candidates.add " expression '"
  338. candidates.add renderTree(nArg)
  339. candidates.add "' is of type: "
  340. candidates.addTypeDeclVerboseMaybe(c.config, got)
  341. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  342. effectProblem(wanted, got, candidates, c)
  343. candidates.add "\n"
  344. of kGenericParamTypeMismatch:
  345. let pos = err.firstMismatch.arg
  346. doAssert n[0].kind == nkBracketExpr and pos < n[0].len
  347. let arg = n[0][pos]
  348. doAssert arg != nil
  349. var wanted = err.firstMismatch.formal.typ
  350. if wanted.kind == tyGenericParam and wanted.genericParamHasConstraints:
  351. wanted = wanted.genericConstraint
  352. let got = arg.typ.skipTypes({tyTypeDesc})
  353. doAssert err.firstMismatch.formal != nil
  354. doAssert wanted != nil
  355. doAssert got != nil
  356. candidates.add " generic parameter mismatch, expected "
  357. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  358. candidates.add " but got '"
  359. candidates.add renderTree(arg)
  360. candidates.add "' of type: "
  361. candidates.addTypeDeclVerboseMaybe(c.config, got)
  362. if nArg.kind in nkSymChoices:
  363. candidates.add "\n"
  364. candidates.add ambiguousIdentifierMsg(nArg, indent = 2)
  365. if got != nil and got.kind == tyProc and wanted.kind == tyProc:
  366. # These are proc mismatches so,
  367. # add the extra explict detail of the mismatch
  368. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  369. if got != nil:
  370. effectProblem(wanted, got, candidates, c)
  371. candidates.add "\n"
  372. of kUnknown: discard "do not break 'nim check'"
  373. else:
  374. candidates.add(" first type mismatch at position: " & $err.firstMismatch.arg)
  375. if err.firstMismatch.kind in genericParamMismatches:
  376. candidates.add(" in generic parameters")
  377. # candidates.add "\n reason: " & $err.firstMismatch.kind # for debugging
  378. case err.firstMismatch.kind
  379. of kUnknownNamedParam:
  380. if nArg == nil:
  381. candidates.add("\n unknown named parameter")
  382. else:
  383. candidates.add("\n unknown named parameter: " & $nArg[0])
  384. of kAlreadyGiven: candidates.add("\n named param already provided: " & $nArg[0])
  385. of kPositionalAlreadyGiven: candidates.add("\n positional param was already given as named param")
  386. of kExtraArg: candidates.add("\n extra argument given")
  387. of kMissingParam: candidates.add("\n missing parameter: " & nameParam)
  388. of kExtraGenericParam:
  389. candidates.add("\n extra generic param given")
  390. of kMissingGenericParam:
  391. candidates.add("\n missing generic parameter: " & nameParam)
  392. of kTypeMismatch, kGenericParamTypeMismatch, kVarNeeded:
  393. doAssert nArg != nil
  394. var wanted = err.firstMismatch.formal.typ
  395. if isGenericMismatch and wanted.kind == tyGenericParam and
  396. wanted.genericParamHasConstraints:
  397. wanted = wanted.genericConstraint
  398. doAssert err.firstMismatch.formal != nil
  399. candidates.add("\n required type for " & nameParam & ": ")
  400. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  401. candidates.add "\n but expression '"
  402. if err.firstMismatch.kind == kVarNeeded:
  403. candidates.add renderNotLValue(nArg)
  404. candidates.add "' is immutable, not 'var'"
  405. else:
  406. candidates.add renderTree(nArg)
  407. candidates.add "' is of type: "
  408. var got = nArg.typ
  409. if isGenericMismatch: got = got.skipTypes({tyTypeDesc})
  410. candidates.addTypeDeclVerboseMaybe(c.config, got)
  411. if nArg.kind in nkSymChoices:
  412. candidates.add "\n"
  413. candidates.add ambiguousIdentifierMsg(nArg, indent = 2)
  414. doAssert wanted != nil
  415. if got != nil:
  416. if got.kind == tyProc and wanted.kind == tyProc:
  417. # These are proc mismatches so,
  418. # add the extra explict detail of the mismatch
  419. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  420. effectProblem(wanted, got, candidates, c)
  421. of kUnknown: discard "do not break 'nim check'"
  422. candidates.add "\n"
  423. if err.firstMismatch.arg == 1 and nArg != nil and
  424. nArg.kind == nkTupleConstr and n.kind == nkCommand:
  425. maybeWrongSpace = true
  426. for diag in err.diagnostics:
  427. candidates.add(diag & "\n")
  428. candidatesAll.add candidates
  429. candidatesAll.sort # fix #13538
  430. candidates = join(candidatesAll)
  431. if skipped > 0:
  432. candidates.add($skipped & " other mismatching symbols have been " &
  433. "suppressed; compile with --showAllMismatches:on to see them\n")
  434. if maybeWrongSpace:
  435. candidates.add("maybe misplaced space between " & renderTree(n[0]) & " and '(' \n")
  436. result = (prefer, candidates)
  437. const
  438. errTypeMismatch = "type mismatch: got <"
  439. errButExpected = "but expected one of:"
  440. errExpectedPosition = "Expected one of (first mismatch at [position]):"
  441. errUndeclaredField = "undeclared field: '$1'"
  442. errUndeclaredRoutine = "attempting to call undeclared routine: '$1'"
  443. errBadRoutine = "attempting to call routine: '$1'$2"
  444. errAmbiguousCallXYZ = "ambiguous call; both $1 and $2 match for: $3"
  445. proc describeParamList(c: PContext, n: PNode, startIdx = 1; prefer = preferName): string =
  446. result = "Expression: " & $n
  447. for i in startIdx..<n.len:
  448. result.add "\n [" & $i & "] " & renderTree(n[i]) & ": "
  449. result.add describeArg(c, n, i, startIdx, prefer)
  450. result.add "\n"
  451. template legacynotFoundError(c: PContext, n: PNode, errors: CandidateErrors) =
  452. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  453. var result = errTypeMismatch
  454. result.add(describeArgs(c, n, 1, prefer))
  455. result.add('>')
  456. if candidates != "":
  457. result.add("\n" & errButExpected & "\n" & candidates)
  458. localError(c.config, n.info, result & "\nexpression: " & $n)
  459. proc notFoundError*(c: PContext, n: PNode, errors: CandidateErrors) =
  460. # Gives a detailed error message; this is separated from semOverloadedCall,
  461. # as semOverloadedCall is already pretty slow (and we need this information
  462. # only in case of an error).
  463. if c.config.m.errorOutputs == {}:
  464. # fail fast:
  465. globalError(c.config, n.info, "type mismatch")
  466. return
  467. # see getMsgDiagnostic:
  468. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  469. let ident = considerQuotedIdent(c, n[0], n).s
  470. let sym = n[1].typ.typSym
  471. var typeHint = ""
  472. if sym == nil:
  473. discard
  474. else:
  475. typeHint = " for type " & getProcHeader(c.config, sym)
  476. localError(c.config, n.info, errUndeclaredField % ident & typeHint)
  477. return
  478. if errors.len == 0:
  479. if n[0].kind in nkIdentKinds:
  480. let ident = considerQuotedIdent(c, n[0], n).s
  481. localError(c.config, n.info, errUndeclaredRoutine % ident)
  482. else:
  483. localError(c.config, n.info, "expression '$1' cannot be called" % n[0].renderTree)
  484. return
  485. if verboseTypeMismatch in c.config.legacyFeatures:
  486. legacynotFoundError(c, n, errors)
  487. else:
  488. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  489. var result = "type mismatch\n"
  490. result.add describeParamList(c, n, 1, prefer)
  491. if candidates != "":
  492. result.add("\n" & errExpectedPosition & "\n" & candidates)
  493. localError(c.config, n.info, result)
  494. proc getMsgDiagnostic(c: PContext, flags: TExprFlags, n, f: PNode): string =
  495. result = ""
  496. if c.compilesContextId > 0:
  497. # we avoid running more diagnostic when inside a `compiles(expr)`, to
  498. # errors while running diagnostic (see test D20180828T234921), and
  499. # also avoid slowdowns in evaluating `compiles(expr)`.
  500. discard
  501. else:
  502. var o: TOverloadIter = default(TOverloadIter)
  503. var sym = initOverloadIter(o, c, f)
  504. while sym != nil:
  505. result &= "\n found $1" % [getSymRepr(c.config, sym)]
  506. sym = nextOverloadIter(o, c, f)
  507. let ident = considerQuotedIdent(c, f, n).s
  508. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  509. let sym = n[1].typ.typSym
  510. var typeHint = ""
  511. if sym == nil:
  512. # Perhaps we're in a `compiles(foo.bar)` expression, or
  513. # in a concept, e.g.:
  514. # ExplainedConcept {.explain.} = concept x
  515. # x.foo is int
  516. # We could use: `(c.config $ n[1].info)` to get more context.
  517. discard
  518. else:
  519. typeHint = " for type " & getProcHeader(c.config, sym)
  520. let suffix = if result.len > 0: " " & result else: ""
  521. result = errUndeclaredField % ident & typeHint & suffix
  522. else:
  523. if result.len == 0: result = errUndeclaredRoutine % ident
  524. else: result = errBadRoutine % [ident, result]
  525. proc resolveOverloads(c: PContext, n, orig: PNode,
  526. filter: TSymKinds, flags: TExprFlags,
  527. errors: var CandidateErrors,
  528. errorsEnabled: bool): TCandidate =
  529. result = default(TCandidate)
  530. var initialBinding: PNode
  531. var alt: TCandidate = default(TCandidate)
  532. var f = n[0]
  533. if f.kind == nkBracketExpr:
  534. # fill in the bindings:
  535. semOpAux(c, f)
  536. initialBinding = f
  537. f = f[0]
  538. else:
  539. initialBinding = nil
  540. pickBestCandidate(c, f, n, orig, initialBinding,
  541. filter, result, alt, errors, efExplain in flags,
  542. errorsEnabled, flags)
  543. var dummyErrors: CandidateErrors = @[]
  544. template pickSpecialOp(headSymbol) =
  545. pickBestCandidate(c, headSymbol, n, orig, initialBinding,
  546. filter, result, alt, dummyErrors, efExplain in flags,
  547. false, flags)
  548. let overloadsState = result.state
  549. if overloadsState != csMatch:
  550. if nfDotField in n.flags:
  551. internalAssert c.config, f.kind == nkIdent and n.len >= 2
  552. # leave the op head symbol empty,
  553. # we are going to try multiple variants
  554. n.sons[0..1] = [nil, n[1], f]
  555. orig.sons[0..1] = [nil, orig[1], f]
  556. template tryOp(x) =
  557. let op = newIdentNode(getIdent(c.cache, x), n.info)
  558. n[0] = op
  559. orig[0] = op
  560. pickSpecialOp(op)
  561. if nfExplicitCall in n.flags:
  562. tryOp ".()"
  563. if result.state in {csEmpty, csNoMatch}:
  564. tryOp "."
  565. elif nfDotSetter in n.flags and f.kind == nkIdent and n.len == 3:
  566. # we need to strip away the trailing '=' here:
  567. let calleeName = newIdentNode(getIdent(c.cache, f.ident.s[0..^2]), n.info)
  568. let callOp = newIdentNode(getIdent(c.cache, ".="), n.info)
  569. n.sons[0..1] = [callOp, n[1], calleeName]
  570. orig.sons[0..1] = [callOp, orig[1], calleeName]
  571. pickSpecialOp(callOp)
  572. if overloadsState == csEmpty and result.state == csEmpty:
  573. if efNoUndeclared notin flags: # for tests/pragmas/tcustom_pragma.nim
  574. result.state = csNoMatch
  575. if c.inGenericContext > 0 and nfExprCall in n.flags:
  576. # untyped expression calls end up here, see #24099
  577. return
  578. # xxx adapt/use errorUndeclaredIdentifierHint(c, n, f.ident)
  579. localError(c.config, n.info, getMsgDiagnostic(c, flags, n, f))
  580. return
  581. elif result.state != csMatch:
  582. if nfExprCall in n.flags:
  583. localError(c.config, n.info, "expression '$1' cannot be called" %
  584. renderTree(n, {renderNoComments}))
  585. else:
  586. if {nfDotField, nfDotSetter} * n.flags != {}:
  587. # clean up the inserted ops
  588. n.sons.delete(2)
  589. n[0] = f
  590. return
  591. if alt.state == csMatch and cmpCandidates(result, alt) == 0 and
  592. not sameMethodDispatcher(result.calleeSym, alt.calleeSym):
  593. internalAssert c.config, result.state == csMatch
  594. #writeMatches(result)
  595. #writeMatches(alt)
  596. if c.config.m.errorOutputs == {}:
  597. # quick error message for performance of 'compiles' built-in:
  598. globalError(c.config, n.info, errGenerated, "ambiguous call")
  599. elif c.config.errorCounter == 0:
  600. # don't cascade errors
  601. var args = "("
  602. for i in 1..<n.len:
  603. if i > 1: args.add(", ")
  604. args.add(typeToString(n[i].typ))
  605. args.add(")")
  606. localError(c.config, n.info, errAmbiguousCallXYZ % [
  607. getProcHeader(c.config, result.calleeSym),
  608. getProcHeader(c.config, alt.calleeSym),
  609. args])
  610. proc bracketNotFoundError(c: PContext; n: PNode; flags: TExprFlags) =
  611. var errors: CandidateErrors = @[]
  612. let headSymbol = n[0]
  613. block:
  614. # we build a closed symchoice of all `[]` overloads for their errors,
  615. # except add a custom error for the magics which always match
  616. var choice = newNodeIT(nkClosedSymChoice, headSymbol.info, newTypeS(tyNone, c))
  617. var o: TOverloadIter = default(TOverloadIter)
  618. var symx = initOverloadIter(o, c, headSymbol)
  619. while symx != nil:
  620. if symx.kind in routineKinds:
  621. if symx.magic in {mArrGet, mArrPut}:
  622. errors.add(CandidateError(sym: symx,
  623. firstMismatch: MismatchInfo(),
  624. diagnostics: @[],
  625. enabled: false))
  626. else:
  627. choice.add newSymNode(symx, headSymbol.info)
  628. symx = nextOverloadIter(o, c, headSymbol)
  629. n[0] = choice
  630. # copied from semOverloadedCallAnalyzeEffects, might be overkill:
  631. const baseFilter = {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate}
  632. let filter =
  633. if flags*{efInTypeof, efWantIterator, efWantIterable} != {}:
  634. baseFilter + {skIterator}
  635. else: baseFilter
  636. # this will add the errors:
  637. var r = resolveOverloads(c, n, n, filter, flags, errors, true)
  638. if errors.len == 0:
  639. localError(c.config, n.info, "could not resolve: " & $n)
  640. else:
  641. notFoundError(c, n, errors)
  642. proc instGenericConvertersArg*(c: PContext, a: PNode, x: TCandidate) =
  643. let a = if a.kind == nkHiddenDeref: a[0] else: a
  644. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  645. let s = a[0].sym
  646. if s.isGenericRoutineStrict:
  647. let finalCallee = generateInstance(c, s, x.bindings, a.info)
  648. a[0].sym = finalCallee
  649. a[0].typ() = finalCallee.typ
  650. #a.typ = finalCallee.typ.returnType
  651. proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) =
  652. assert n.kind in nkCallKinds
  653. if x.genericConverter:
  654. for i in 1..<n.len:
  655. instGenericConvertersArg(c, n[i], x)
  656. proc markConvertersUsed*(c: PContext, n: PNode) =
  657. assert n.kind in nkCallKinds
  658. for i in 1..<n.len:
  659. var a = n[i]
  660. if a == nil: continue
  661. if a.kind == nkHiddenDeref: a = a[0]
  662. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  663. markUsed(c, a.info, a[0].sym)
  664. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode =
  665. var m = newCandidate(c, f)
  666. result = paramTypesMatch(m, f, a, arg, nil)
  667. if m.genericConverter and result != nil:
  668. instGenericConvertersArg(c, result, m)
  669. proc inferWithMetatype(c: PContext, formal: PType,
  670. arg: PNode, coerceDistincts = false): PNode =
  671. var m = newCandidate(c, formal)
  672. m.coerceDistincts = coerceDistincts
  673. result = paramTypesMatch(m, formal, arg.typ, arg, nil)
  674. if m.genericConverter and result != nil:
  675. instGenericConvertersArg(c, result, m)
  676. if result != nil:
  677. # This almost exactly replicates the steps taken by the compiler during
  678. # param matching. It performs an embarrassing amount of back-and-forth
  679. # type jugling, but it's the price to pay for consistency and correctness
  680. result.typ() = generateTypeInstance(c, m.bindings, arg.info,
  681. formal.skipTypes({tyCompositeTypeClass}))
  682. else:
  683. typeMismatch(c.config, arg.info, formal, arg.typ, arg)
  684. # error correction:
  685. result = copyTree(arg)
  686. result.typ() = formal
  687. proc updateDefaultParams(c: PContext, call: PNode) =
  688. # In generic procs, the default parameter may be unique for each
  689. # instantiation (see tlateboundgenericparams).
  690. # After a call is resolved, we need to re-assign any default value
  691. # that was used during sigmatch. sigmatch is responsible for marking
  692. # the default params with `nfDefaultParam` and `instantiateProcType`
  693. # computes correctly the default values for each instantiation.
  694. let calleeParams = call[0].sym.typ.n
  695. for i in 1..<call.len:
  696. if nfDefaultParam in call[i].flags:
  697. let formal = calleeParams[i].sym
  698. let def = formal.ast
  699. if nfDefaultRefsParam in def.flags: call.flags.incl nfDefaultRefsParam
  700. # mirrored with sigmatch:
  701. if def.kind == nkEmpty:
  702. # The default param value is set to empty in `instantiateProcType`
  703. # when the type of the default expression doesn't match the type
  704. # of the instantiated proc param:
  705. pushInfoContext(c.config, call.info, call[0].sym.detailedInfo)
  706. typeMismatch(c.config, def.info, formal.typ, def.typ, formal.ast)
  707. popInfoContext(c.config)
  708. def.typ() = errorType(c)
  709. call[i] = def
  710. proc getCallLineInfo(n: PNode): TLineInfo =
  711. case n.kind
  712. of nkAccQuoted, nkBracketExpr, nkCall, nkCallStrLit, nkCommand:
  713. if len(n) > 0:
  714. return getCallLineInfo(n[0])
  715. of nkDotExpr:
  716. if len(n) > 1:
  717. return getCallLineInfo(n[1])
  718. else:
  719. discard
  720. result = n.info
  721. proc inheritBindings(c: PContext, x: var TCandidate, expectedType: PType) =
  722. ## Helper proc to inherit bound generic parameters from expectedType into x.
  723. ## Does nothing if 'inferGenericTypes' isn't in c.features.
  724. if inferGenericTypes notin c.features: return
  725. if expectedType == nil or x.callee.returnType == nil: return # required for inference
  726. var
  727. flatUnbound: seq[PType] = @[]
  728. flatBound: seq[PType] = @[]
  729. # seq[(result type, expected type)]
  730. var typeStack = newSeq[(PType, PType)]()
  731. template stackPut(a, b) =
  732. ## skips types and puts the skipped version on stack
  733. # It might make sense to skip here one by one. It's not part of the main
  734. # type reduction because the right side normally won't be skipped
  735. const toSkip = {tyVar, tyLent, tyStatic, tyCompositeTypeClass, tySink}
  736. let
  737. x = a.skipTypes(toSkip)
  738. y = if a.kind notin toSkip: b
  739. else: b.skipTypes(toSkip)
  740. typeStack.add((x, y))
  741. stackPut(x.callee.returnType, expectedType)
  742. while typeStack.len() > 0:
  743. let (t, u) = typeStack.pop()
  744. if t == u or t == nil or u == nil or t.kind == tyAnything or u.kind == tyAnything:
  745. continue
  746. case t.kind
  747. of ConcreteTypes, tyGenericInvocation, tyUncheckedArray:
  748. # XXX This logic makes no sense for `tyUncheckedArray`
  749. # nested, add all the types to stack
  750. let
  751. startIdx = if u.kind in ConcreteTypes: 0 else: 1
  752. endIdx = min(u.kidsLen() - startIdx, t.kidsLen())
  753. for i in startIdx ..< endIdx:
  754. # early exit with current impl
  755. if t[i] == nil or u[i] == nil: return
  756. stackPut(t[i], u[i])
  757. of tyGenericParam:
  758. let prebound = x.bindings.lookup(t)
  759. if prebound != nil:
  760. continue # Skip param, already bound
  761. # fully reduced generic param, bind it
  762. if t notin flatUnbound:
  763. flatUnbound.add(t)
  764. flatBound.add(u)
  765. else:
  766. discard
  767. # update bindings
  768. for i in 0 ..< flatUnbound.len():
  769. x.bindings.put(flatUnbound[i], flatBound[i])
  770. proc semResolvedCall(c: PContext, x: var TCandidate,
  771. n: PNode, flags: TExprFlags;
  772. expectedType: PType = nil): PNode =
  773. assert x.state == csMatch
  774. var finalCallee = x.calleeSym
  775. let info = getCallLineInfo(n)
  776. markUsed(c, info, finalCallee)
  777. onUse(info, finalCallee)
  778. assert finalCallee.ast != nil
  779. if x.matchedErrorType:
  780. result = x.call
  781. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  782. if containsGenericType(result.typ):
  783. result.typ() = newTypeS(tyError, c)
  784. incl result.typ.flags, tfCheckedForDestructor
  785. return
  786. let gp = finalCallee.ast[genericParamsPos]
  787. if gp.isGenericParams:
  788. if x.calleeSym.kind notin {skMacro, skTemplate}:
  789. if x.calleeSym.magic in {mArrGet, mArrPut}:
  790. finalCallee = x.calleeSym
  791. else:
  792. c.inheritBindings(x, expectedType)
  793. finalCallee = generateInstance(c, x.calleeSym, x.bindings, n.info)
  794. else:
  795. # For macros and templates, the resolved generic params
  796. # are added as normal params.
  797. c.inheritBindings(x, expectedType)
  798. for s in instantiateGenericParamList(c, gp, x.bindings):
  799. case s.kind
  800. of skConst:
  801. if not s.astdef.isNil:
  802. x.call.add s.astdef
  803. else:
  804. x.call.add c.graph.emptyNode
  805. of skType:
  806. var tn = newSymNode(s, n.info)
  807. # this node will be used in template substitution,
  808. # pretend this is an untyped node and let regular sem handle the type
  809. # to prevent problems where a generic parameter is treated as a value
  810. tn.typ() = nil
  811. x.call.add tn
  812. else:
  813. internalAssert c.config, false
  814. result = x.call
  815. instGenericConvertersSons(c, result, x)
  816. markConvertersUsed(c, result)
  817. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  818. if finalCallee.magic notin {mArrGet, mArrPut}:
  819. result.typ() = finalCallee.typ.returnType
  820. updateDefaultParams(c, result)
  821. proc canDeref(n: PNode): bool {.inline.} =
  822. result = n.len >= 2 and (let t = n[1].typ;
  823. t != nil and t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyPtr, tyRef})
  824. proc tryDeref(n: PNode): PNode =
  825. result = newNodeI(nkHiddenDeref, n.info)
  826. result.typ() = n.typ.skipTypes(abstractInst)[0]
  827. result.add n
  828. proc semOverloadedCall(c: PContext, n, nOrig: PNode,
  829. filter: TSymKinds, flags: TExprFlags;
  830. expectedType: PType = nil): PNode =
  831. var errors: CandidateErrors = @[] # if efExplain in flags: @[] else: nil
  832. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  833. if r.state == csMatch:
  834. # this may be triggered, when the explain pragma is used
  835. if errors.len > 0:
  836. let (_, candidates) = presentFailedCandidates(c, n, errors)
  837. message(c.config, n.info, hintUserRaw,
  838. "Non-matching candidates for " & renderTree(n) & "\n" &
  839. candidates)
  840. result = semResolvedCall(c, r, n, flags, expectedType)
  841. else:
  842. if c.inGenericContext > 0 and c.matchedConcept == nil:
  843. result = semGenericStmt(c, n)
  844. result.typ() = makeTypeFromExpr(c, result.copyTree)
  845. elif efExplain notin flags:
  846. # repeat the overload resolution,
  847. # this time enabling all the diagnostic output (this should fail again)
  848. result = semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  849. elif efNoUndeclared notin flags:
  850. result = nil
  851. notFoundError(c, n, errors)
  852. else:
  853. result = nil
  854. proc explicitGenericInstError(c: PContext; n: PNode): PNode =
  855. localError(c.config, getCallLineInfo(n), errCannotInstantiateX % renderTree(n))
  856. result = n
  857. proc explicitGenericSym(c: PContext, n: PNode, s: PSym, errors: var CandidateErrors, doError: bool): PNode =
  858. if s.kind in {skTemplate, skMacro}:
  859. internalError c.config, n.info, "cannot get explicitly instantiated symbol of " &
  860. (if s.kind == skTemplate: "template" else: "macro")
  861. # binding has to stay 'nil' for this to work!
  862. var m = newCandidate(c, s, nil)
  863. matchGenericParams(m, n, s)
  864. if m.state != csMatch:
  865. # state is csMatch only if *all* generic params were matched,
  866. # including implicit parameters
  867. if doError:
  868. errors.add(CandidateError(
  869. sym: s,
  870. firstMismatch: m.firstMismatch,
  871. diagnostics: m.diagnostics))
  872. return nil
  873. var newInst = generateInstance(c, s, m.bindings, n.info)
  874. newInst.typ.flags.excl tfUnresolved
  875. let info = getCallLineInfo(n)
  876. markUsed(c, info, s)
  877. onUse(info, s)
  878. result = newSymNode(newInst, info)
  879. proc setGenericParams(c: PContext, n, expectedParams: PNode) =
  880. ## sems generic params in subscript expression
  881. for i in 1..<n.len:
  882. let
  883. constraint =
  884. if expectedParams != nil and i <= expectedParams.len:
  885. expectedParams[i - 1].typ
  886. else:
  887. nil
  888. e = semExprWithType(c, n[i], expectedType = constraint)
  889. if e.typ == nil:
  890. n[i].typ() = errorType(c)
  891. else:
  892. n[i].typ() = e.typ.skipTypes({tyTypeDesc})
  893. proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym, doError: bool): PNode =
  894. assert n.kind == nkBracketExpr
  895. setGenericParams(c, n, s.ast[genericParamsPos])
  896. var s = s
  897. var a = n[0]
  898. var errors: CandidateErrors = @[]
  899. if a.kind == nkSym:
  900. # common case; check the only candidate has the right
  901. # number of generic type parameters:
  902. result = explicitGenericSym(c, n, s, errors, doError)
  903. if result == nil:
  904. if c.inGenericContext > 0:
  905. # same as in semOverloadedCall, make expression untyped,
  906. # may have failed match due to unresolved types
  907. result = semGenericStmt(c, n)
  908. result.typ() = makeTypeFromExpr(c, result.copyTree)
  909. elif doError:
  910. notFoundError(c, n, errors)
  911. elif a.kind in {nkClosedSymChoice, nkOpenSymChoice}:
  912. # choose the generic proc with the proper number of type parameters.
  913. result = newNodeI(a.kind, getCallLineInfo(n))
  914. for i in 0..<a.len:
  915. var candidate = a[i].sym
  916. if candidate.kind in {skProc, skMethod, skConverter,
  917. skFunc, skIterator}:
  918. let x = explicitGenericSym(c, n, candidate, errors, doError)
  919. if x != nil: result.add(x)
  920. elif c.inGenericContext > 0:
  921. # same as in semOverloadedCall, make expression untyped,
  922. # may have failed match due to unresolved types
  923. # any failing match stops building the symchoice for correctness,
  924. # can also make it untyped from the start
  925. result = semGenericStmt(c, n)
  926. result.typ() = makeTypeFromExpr(c, result.copyTree)
  927. return
  928. # get rid of nkClosedSymChoice if not ambiguous:
  929. if result.len == 0:
  930. result = nil
  931. if doError:
  932. notFoundError(c, n, errors)
  933. else:
  934. # probably unreachable: we are trying to instantiate `a` which is not
  935. # a sym/symchoice
  936. if doError:
  937. result = explicitGenericInstError(c, n)
  938. else:
  939. result = nil
  940. proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): tuple[s: PSym, state: TBorrowState] =
  941. # Searches for the fn in the symbol table. If the parameter lists are suitable
  942. # for borrowing the sym in the symbol table is returned, else nil.
  943. # New approach: generate fn(x, y, z) where x, y, z have the proper types
  944. # and use the overloading resolution mechanism:
  945. const desiredTypes = abstractVar + {tyCompositeTypeClass} - {tyTypeDesc, tyDistinct}
  946. template getType(isDistinct: bool; t: PType):untyped =
  947. if isDistinct: t.baseOfDistinct(c.graph, c.idgen) else: t
  948. result = default(tuple[s: PSym, state: TBorrowState])
  949. var call = newNodeI(nkCall, fn.info)
  950. var hasDistinct = false
  951. var isDistinct: bool
  952. var x: PType
  953. var t: PType
  954. call.add(newIdentNode(fn.name, fn.info))
  955. for i in 1..<fn.typ.n.len:
  956. let param = fn.typ.n[i]
  957. #[.
  958. # We only want the type not any modifiers such as `ptr`, `var`, `ref` ...
  959. # tyCompositeTypeClass is here for
  960. # when using something like:
  961. type Foo[T] = distinct int
  962. proc `$`(f: Foo): string {.borrow.}
  963. # We want to skip the `Foo` to get `int`
  964. ]#
  965. t = skipTypes(param.typ, desiredTypes)
  966. isDistinct = t.kind == tyDistinct or param.typ.kind == tyDistinct
  967. if t.kind == tyGenericInvocation and t.genericHead.last.kind == tyDistinct:
  968. result.state = bsGeneric
  969. return
  970. if isDistinct: hasDistinct = true
  971. if param.typ.kind == tyVar:
  972. x = newTypeS(param.typ.kind, c)
  973. x.addSonSkipIntLit(getType(isDistinct, t), c.idgen)
  974. else:
  975. x = getType(isDistinct, t)
  976. var s = copySym(param.sym, c.idgen)
  977. s.typ = x
  978. s.info = param.info
  979. call.add(newSymNode(s))
  980. if hasDistinct:
  981. let filter = if fn.kind in {skProc, skFunc}: {skProc, skFunc} else: {fn.kind}
  982. var resolved = semOverloadedCall(c, call, call, filter, {})
  983. if resolved != nil:
  984. result.s = resolved[0].sym
  985. result.state = bsMatch
  986. if not compareTypes(result.s.typ.returnType, fn.typ.returnType, dcEqIgnoreDistinct, {IgnoreFlags}):
  987. result.state = bsReturnNotMatch
  988. elif result.s.magic in {mArrPut, mArrGet}:
  989. # cannot borrow these magics for now
  990. result.state = bsNotSupported
  991. else:
  992. result.state = bsNoDistinct