semcall.nim 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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 searchScopesAll(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 presentFailedCandidates(c: PContext, n: PNode, errors: CandidateErrors):
  226. (TPreferedDesc, string) =
  227. var prefer = preferName
  228. # to avoid confusing errors like:
  229. # got (SslPtr, SocketHandle)
  230. # but expected one of:
  231. # openssl.SSL_set_fd(ssl: SslPtr, fd: SocketHandle): cint
  232. # we do a pre-analysis. If all types produce the same string, we will add
  233. # module information.
  234. let proto = describeArgs(c, n, 1, preferName)
  235. for err in errors:
  236. var errProto = ""
  237. let n = err.sym.typ.n
  238. for i in 1..<n.len:
  239. var p = n[i]
  240. if p.kind == nkSym:
  241. errProto.add(typeToString(p.sym.typ, preferName))
  242. if i != n.len-1: errProto.add(", ")
  243. # else: ignore internal error as we're already in error handling mode
  244. if errProto == proto:
  245. prefer = preferModuleInfo
  246. break
  247. # we pretend procs are attached to the type of the first
  248. # argument in order to remove plenty of candidates. This is
  249. # comparable to what C# does and C# is doing fine.
  250. var filterOnlyFirst = false
  251. if optShowAllMismatches notin c.config.globalOptions and verboseTypeMismatch in c.config.legacyFeatures:
  252. for err in errors:
  253. if err.firstMismatch.arg > 1:
  254. filterOnlyFirst = true
  255. break
  256. var maybeWrongSpace = false
  257. var candidatesAll: seq[string] = @[]
  258. var candidates = ""
  259. var skipped = 0
  260. for err in errors:
  261. candidates.setLen 0
  262. if filterOnlyFirst and err.firstMismatch.arg == 1:
  263. inc skipped
  264. continue
  265. if verboseTypeMismatch notin c.config.legacyFeatures:
  266. candidates.add "[" & $err.firstMismatch.arg & "] "
  267. if err.sym.kind in routineKinds and err.sym.ast != nil:
  268. candidates.add(renderTree(err.sym.ast,
  269. {renderNoBody, renderNoComments, renderNoPragmas}))
  270. else:
  271. candidates.add(getProcHeader(c.config, err.sym, prefer))
  272. candidates.addDeclaredLocMaybe(c.config, err.sym)
  273. candidates.add("\n")
  274. const genericParamMismatches = {kGenericParamTypeMismatch, kExtraGenericParam, kMissingGenericParam}
  275. let isGenericMismatch = err.firstMismatch.kind in genericParamMismatches
  276. var argList = n
  277. if isGenericMismatch and n[0].kind == nkBracketExpr:
  278. argList = n[0]
  279. let nArg =
  280. if err.firstMismatch.arg < argList.len:
  281. argList[err.firstMismatch.arg]
  282. else:
  283. nil
  284. let nameParam = if err.firstMismatch.formal != nil: err.firstMismatch.formal.name.s else: ""
  285. if n.len > 1:
  286. if verboseTypeMismatch notin c.config.legacyFeatures:
  287. case err.firstMismatch.kind
  288. of kUnknownNamedParam:
  289. if nArg == nil:
  290. candidates.add(" unknown named parameter")
  291. else:
  292. candidates.add(" unknown named parameter: " & $nArg[0])
  293. candidates.add "\n"
  294. of kAlreadyGiven:
  295. candidates.add(" named param already provided: " & $nArg[0])
  296. candidates.add "\n"
  297. of kPositionalAlreadyGiven:
  298. candidates.add(" positional param was already given as named param")
  299. candidates.add "\n"
  300. of kExtraArg:
  301. candidates.add(" extra argument given")
  302. candidates.add "\n"
  303. of kMissingParam:
  304. candidates.add(" missing parameter: " & nameParam)
  305. candidates.add "\n"
  306. of kExtraGenericParam:
  307. candidates.add(" extra generic param given")
  308. candidates.add "\n"
  309. of kMissingGenericParam:
  310. candidates.add(" missing generic parameter: " & nameParam)
  311. candidates.add "\n"
  312. of kVarNeeded:
  313. doAssert nArg != nil
  314. doAssert err.firstMismatch.formal != nil
  315. candidates.add " expression '"
  316. candidates.add renderNotLValue(nArg)
  317. candidates.add "' is immutable, not 'var'"
  318. candidates.add "\n"
  319. of kTypeMismatch:
  320. doAssert nArg != nil
  321. if nArg.kind in nkSymChoices:
  322. candidates.add ambiguousIdentifierMsg(nArg, indent = 2)
  323. let wanted = err.firstMismatch.formal.typ
  324. doAssert err.firstMismatch.formal != nil
  325. doAssert wanted != nil
  326. let got = nArg.typ
  327. if got != nil and got.kind == tyProc and wanted.kind == tyProc:
  328. # These are proc mismatches so,
  329. # add the extra explict detail of the mismatch
  330. candidates.add " expression '"
  331. candidates.add renderTree(nArg)
  332. candidates.add "' is of type: "
  333. candidates.addTypeDeclVerboseMaybe(c.config, got)
  334. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  335. effectProblem(wanted, got, candidates, c)
  336. candidates.add "\n"
  337. of kGenericParamTypeMismatch:
  338. let pos = err.firstMismatch.arg
  339. doAssert n[0].kind == nkBracketExpr and pos < n[0].len
  340. let arg = n[0][pos]
  341. doAssert arg != nil
  342. var wanted = err.firstMismatch.formal.typ
  343. if wanted.kind == tyGenericParam and wanted.genericParamHasConstraints:
  344. wanted = wanted.genericConstraint
  345. let got = arg.typ.skipTypes({tyTypeDesc})
  346. doAssert err.firstMismatch.formal != nil
  347. doAssert wanted != nil
  348. doAssert got != nil
  349. candidates.add " generic parameter mismatch, expected "
  350. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  351. candidates.add " but got '"
  352. candidates.add renderTree(arg)
  353. candidates.add "' of type: "
  354. candidates.addTypeDeclVerboseMaybe(c.config, got)
  355. if nArg.kind in nkSymChoices:
  356. candidates.add "\n"
  357. candidates.add ambiguousIdentifierMsg(nArg, indent = 2)
  358. if got != nil and got.kind == tyProc and wanted.kind == tyProc:
  359. # These are proc mismatches so,
  360. # add the extra explict detail of the mismatch
  361. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  362. if got != nil:
  363. effectProblem(wanted, got, candidates, c)
  364. candidates.add "\n"
  365. of kUnknown: discard "do not break 'nim check'"
  366. else:
  367. candidates.add(" first type mismatch at position: " & $err.firstMismatch.arg)
  368. if err.firstMismatch.kind in genericParamMismatches:
  369. candidates.add(" in generic parameters")
  370. # candidates.add "\n reason: " & $err.firstMismatch.kind # for debugging
  371. case err.firstMismatch.kind
  372. of kUnknownNamedParam:
  373. if nArg == nil:
  374. candidates.add("\n unknown named parameter")
  375. else:
  376. candidates.add("\n unknown named parameter: " & $nArg[0])
  377. of kAlreadyGiven: candidates.add("\n named param already provided: " & $nArg[0])
  378. of kPositionalAlreadyGiven: candidates.add("\n positional param was already given as named param")
  379. of kExtraArg: candidates.add("\n extra argument given")
  380. of kMissingParam: candidates.add("\n missing parameter: " & nameParam)
  381. of kExtraGenericParam:
  382. candidates.add("\n extra generic param given")
  383. of kMissingGenericParam:
  384. candidates.add("\n missing generic parameter: " & nameParam)
  385. of kTypeMismatch, kGenericParamTypeMismatch, kVarNeeded:
  386. doAssert nArg != nil
  387. var wanted = err.firstMismatch.formal.typ
  388. if isGenericMismatch and wanted.kind == tyGenericParam and
  389. wanted.genericParamHasConstraints:
  390. wanted = wanted.genericConstraint
  391. doAssert err.firstMismatch.formal != nil
  392. candidates.add("\n required type for " & nameParam & ": ")
  393. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  394. candidates.add "\n but expression '"
  395. if err.firstMismatch.kind == kVarNeeded:
  396. candidates.add renderNotLValue(nArg)
  397. candidates.add "' is immutable, not 'var'"
  398. else:
  399. candidates.add renderTree(nArg)
  400. candidates.add "' is of type: "
  401. var got = nArg.typ
  402. if isGenericMismatch: got = got.skipTypes({tyTypeDesc})
  403. candidates.addTypeDeclVerboseMaybe(c.config, got)
  404. if nArg.kind in nkSymChoices:
  405. candidates.add "\n"
  406. candidates.add ambiguousIdentifierMsg(nArg, indent = 2)
  407. doAssert wanted != nil
  408. if got != nil:
  409. if got.kind == tyProc and wanted.kind == tyProc:
  410. # These are proc mismatches so,
  411. # add the extra explict detail of the mismatch
  412. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  413. effectProblem(wanted, got, candidates, c)
  414. of kUnknown: discard "do not break 'nim check'"
  415. candidates.add "\n"
  416. if err.firstMismatch.arg == 1 and nArg != nil and
  417. nArg.kind == nkTupleConstr and n.kind == nkCommand:
  418. maybeWrongSpace = true
  419. for diag in err.diagnostics:
  420. candidates.add(diag & "\n")
  421. candidatesAll.add candidates
  422. candidatesAll.sort # fix #13538
  423. candidates = join(candidatesAll)
  424. if skipped > 0:
  425. candidates.add($skipped & " other mismatching symbols have been " &
  426. "suppressed; compile with --showAllMismatches:on to see them\n")
  427. if maybeWrongSpace:
  428. candidates.add("maybe misplaced space between " & renderTree(n[0]) & " and '(' \n")
  429. result = (prefer, candidates)
  430. const
  431. errTypeMismatch = "type mismatch: got <"
  432. errButExpected = "but expected one of:"
  433. errExpectedPosition = "Expected one of (first mismatch at [position]):"
  434. errUndeclaredField = "undeclared field: '$1'"
  435. errUndeclaredRoutine = "attempting to call undeclared routine: '$1'"
  436. errBadRoutine = "attempting to call routine: '$1'$2"
  437. errAmbiguousCallXYZ = "ambiguous call; both $1 and $2 match for: $3"
  438. proc describeParamList(c: PContext, n: PNode, startIdx = 1; prefer = preferName): string =
  439. result = "Expression: " & $n
  440. for i in startIdx..<n.len:
  441. result.add "\n [" & $i & "] " & renderTree(n[i]) & ": "
  442. result.add describeArg(c, n, i, startIdx, prefer)
  443. result.add "\n"
  444. template legacynotFoundError(c: PContext, n: PNode, errors: CandidateErrors) =
  445. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  446. var result = errTypeMismatch
  447. result.add(describeArgs(c, n, 1, prefer))
  448. result.add('>')
  449. if candidates != "":
  450. result.add("\n" & errButExpected & "\n" & candidates)
  451. localError(c.config, n.info, result & "\nexpression: " & $n)
  452. proc notFoundError*(c: PContext, n: PNode, errors: CandidateErrors) =
  453. # Gives a detailed error message; this is separated from semOverloadedCall,
  454. # as semOverloadedCall is already pretty slow (and we need this information
  455. # only in case of an error).
  456. if c.config.m.errorOutputs == {}:
  457. # fail fast:
  458. globalError(c.config, n.info, "type mismatch")
  459. return
  460. # see getMsgDiagnostic:
  461. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  462. let ident = considerQuotedIdent(c, n[0], n).s
  463. let sym = n[1].typ.typSym
  464. var typeHint = ""
  465. if sym == nil:
  466. discard
  467. else:
  468. typeHint = " for type " & getProcHeader(c.config, sym)
  469. localError(c.config, n.info, errUndeclaredField % ident & typeHint)
  470. return
  471. if errors.len == 0:
  472. if n[0].kind in nkIdentKinds:
  473. let ident = considerQuotedIdent(c, n[0], n).s
  474. localError(c.config, n.info, errUndeclaredRoutine % ident)
  475. else:
  476. localError(c.config, n.info, "expression '$1' cannot be called" % n[0].renderTree)
  477. return
  478. if verboseTypeMismatch in c.config.legacyFeatures:
  479. legacynotFoundError(c, n, errors)
  480. else:
  481. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  482. var result = "type mismatch\n"
  483. result.add describeParamList(c, n, 1, prefer)
  484. if candidates != "":
  485. result.add("\n" & errExpectedPosition & "\n" & candidates)
  486. localError(c.config, n.info, result)
  487. proc getMsgDiagnostic(c: PContext, flags: TExprFlags, n, f: PNode): string =
  488. result = ""
  489. if c.compilesContextId > 0:
  490. # we avoid running more diagnostic when inside a `compiles(expr)`, to
  491. # errors while running diagnostic (see test D20180828T234921), and
  492. # also avoid slowdowns in evaluating `compiles(expr)`.
  493. discard
  494. else:
  495. var o: TOverloadIter = default(TOverloadIter)
  496. var sym = initOverloadIter(o, c, f)
  497. while sym != nil:
  498. result &= "\n found $1" % [getSymRepr(c.config, sym)]
  499. sym = nextOverloadIter(o, c, f)
  500. let ident = considerQuotedIdent(c, f, n).s
  501. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  502. let sym = n[1].typ.typSym
  503. var typeHint = ""
  504. if sym == nil:
  505. # Perhaps we're in a `compiles(foo.bar)` expression, or
  506. # in a concept, e.g.:
  507. # ExplainedConcept {.explain.} = concept x
  508. # x.foo is int
  509. # We could use: `(c.config $ n[1].info)` to get more context.
  510. discard
  511. else:
  512. typeHint = " for type " & getProcHeader(c.config, sym)
  513. let suffix = if result.len > 0: " " & result else: ""
  514. result = errUndeclaredField % ident & typeHint & suffix
  515. else:
  516. if result.len == 0: result = errUndeclaredRoutine % ident
  517. else: result = errBadRoutine % [ident, result]
  518. proc resolveOverloads(c: PContext, n, orig: PNode,
  519. filter: TSymKinds, flags: TExprFlags,
  520. errors: var CandidateErrors,
  521. errorsEnabled: bool): TCandidate =
  522. result = default(TCandidate)
  523. var initialBinding: PNode
  524. var alt: TCandidate = default(TCandidate)
  525. var f = n[0]
  526. if f.kind == nkBracketExpr:
  527. # fill in the bindings:
  528. semOpAux(c, f)
  529. initialBinding = f
  530. f = f[0]
  531. else:
  532. initialBinding = nil
  533. pickBestCandidate(c, f, n, orig, initialBinding,
  534. filter, result, alt, errors, efExplain in flags,
  535. errorsEnabled, flags)
  536. var dummyErrors: CandidateErrors = @[]
  537. template pickSpecialOp(headSymbol) =
  538. pickBestCandidate(c, headSymbol, n, orig, initialBinding,
  539. filter, result, alt, dummyErrors, efExplain in flags,
  540. false, flags)
  541. let overloadsState = result.state
  542. if overloadsState != csMatch:
  543. if nfDotField in n.flags:
  544. internalAssert c.config, f.kind == nkIdent and n.len >= 2
  545. # leave the op head symbol empty,
  546. # we are going to try multiple variants
  547. n.sons[0..1] = [nil, n[1], f]
  548. orig.sons[0..1] = [nil, orig[1], f]
  549. template tryOp(x) =
  550. let op = newIdentNode(getIdent(c.cache, x), n.info)
  551. n[0] = op
  552. orig[0] = op
  553. pickSpecialOp(op)
  554. if nfExplicitCall in n.flags:
  555. tryOp ".()"
  556. if result.state in {csEmpty, csNoMatch}:
  557. tryOp "."
  558. elif nfDotSetter in n.flags and f.kind == nkIdent and n.len == 3:
  559. # we need to strip away the trailing '=' here:
  560. let calleeName = newIdentNode(getIdent(c.cache, f.ident.s[0..^2]), n.info)
  561. let callOp = newIdentNode(getIdent(c.cache, ".="), n.info)
  562. n.sons[0..1] = [callOp, n[1], calleeName]
  563. orig.sons[0..1] = [callOp, orig[1], calleeName]
  564. pickSpecialOp(callOp)
  565. if overloadsState == csEmpty and result.state == csEmpty:
  566. if efNoUndeclared notin flags: # for tests/pragmas/tcustom_pragma.nim
  567. result.state = csNoMatch
  568. if c.inGenericContext > 0 and nfExprCall in n.flags:
  569. # untyped expression calls end up here, see #24099
  570. return
  571. # xxx adapt/use errorUndeclaredIdentifierHint(c, n, f.ident)
  572. localError(c.config, n.info, getMsgDiagnostic(c, flags, n, f))
  573. return
  574. elif result.state != csMatch:
  575. if nfExprCall in n.flags:
  576. localError(c.config, n.info, "expression '$1' cannot be called" %
  577. renderTree(n, {renderNoComments}))
  578. else:
  579. if {nfDotField, nfDotSetter} * n.flags != {}:
  580. # clean up the inserted ops
  581. n.sons.delete(2)
  582. n[0] = f
  583. return
  584. if alt.state == csMatch and cmpCandidates(result, alt) == 0 and
  585. not sameMethodDispatcher(result.calleeSym, alt.calleeSym):
  586. internalAssert c.config, result.state == csMatch
  587. #writeMatches(result)
  588. #writeMatches(alt)
  589. if c.config.m.errorOutputs == {}:
  590. # quick error message for performance of 'compiles' built-in:
  591. globalError(c.config, n.info, errGenerated, "ambiguous call")
  592. elif c.config.errorCounter == 0:
  593. # don't cascade errors
  594. var args = "("
  595. for i in 1..<n.len:
  596. if i > 1: args.add(", ")
  597. args.add(typeToString(n[i].typ))
  598. args.add(")")
  599. localError(c.config, n.info, errAmbiguousCallXYZ % [
  600. getProcHeader(c.config, result.calleeSym),
  601. getProcHeader(c.config, alt.calleeSym),
  602. args])
  603. proc bracketNotFoundError(c: PContext; n: PNode; flags: TExprFlags) =
  604. var errors: CandidateErrors = @[]
  605. let headSymbol = n[0]
  606. block:
  607. # we build a closed symchoice of all `[]` overloads for their errors,
  608. # except add a custom error for the magics which always match
  609. var choice = newNodeIT(nkClosedSymChoice, headSymbol.info, newTypeS(tyNone, c))
  610. var o: TOverloadIter = default(TOverloadIter)
  611. var symx = initOverloadIter(o, c, headSymbol)
  612. while symx != nil:
  613. if symx.kind in routineKinds:
  614. if symx.magic in {mArrGet, mArrPut}:
  615. errors.add(CandidateError(sym: symx,
  616. firstMismatch: MismatchInfo(),
  617. diagnostics: @[],
  618. enabled: false))
  619. else:
  620. choice.add newSymNode(symx, headSymbol.info)
  621. symx = nextOverloadIter(o, c, headSymbol)
  622. n[0] = choice
  623. # copied from semOverloadedCallAnalyzeEffects, might be overkill:
  624. const baseFilter = {skProc, skFunc, skMethod, skConverter, skMacro, skTemplate}
  625. let filter =
  626. if flags*{efInTypeof, efWantIterator, efWantIterable} != {}:
  627. baseFilter + {skIterator}
  628. else: baseFilter
  629. # this will add the errors:
  630. var r = resolveOverloads(c, n, n, filter, flags, errors, true)
  631. if errors.len == 0:
  632. localError(c.config, n.info, "could not resolve: " & $n)
  633. else:
  634. notFoundError(c, n, errors)
  635. proc instGenericConvertersArg*(c: PContext, a: PNode, x: TCandidate) =
  636. let a = if a.kind == nkHiddenDeref: a[0] else: a
  637. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  638. let s = a[0].sym
  639. if s.isGenericRoutineStrict:
  640. var src = s.typ.firstParamType
  641. var convMatch = newCandidate(c, src)
  642. let srca = typeRel(convMatch, src, a[1].typ)
  643. if srca notin {isEqual, isGeneric, isSubtype}:
  644. internalError(c.config, a.info, "generic converter failed rematch")
  645. let finalCallee = generateInstance(c, s, convMatch.bindings, a.info)
  646. a[0].sym = finalCallee
  647. a[0].typ() = finalCallee.typ
  648. #a.typ = finalCallee.typ.returnType
  649. proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) =
  650. assert n.kind in nkCallKinds
  651. if x.genericConverter:
  652. for i in 1..<n.len:
  653. instGenericConvertersArg(c, n[i], x)
  654. proc markConvertersUsed*(c: PContext, n: PNode) =
  655. assert n.kind in nkCallKinds
  656. for i in 1..<n.len:
  657. var a = n[i]
  658. if a == nil: continue
  659. if a.kind == nkHiddenDeref: a = a[0]
  660. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  661. markUsed(c, a.info, a[0].sym)
  662. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode =
  663. var m = newCandidate(c, f)
  664. result = paramTypesMatch(m, f, a, arg, nil)
  665. if m.genericConverter and result != nil:
  666. instGenericConvertersArg(c, result, m)
  667. proc inferWithMetatype(c: PContext, formal: PType,
  668. arg: PNode, coerceDistincts = false): PNode =
  669. var m = newCandidate(c, formal)
  670. m.coerceDistincts = coerceDistincts
  671. result = paramTypesMatch(m, formal, arg.typ, arg, nil)
  672. if m.genericConverter and result != nil:
  673. instGenericConvertersArg(c, result, m)
  674. if result != nil:
  675. # This almost exactly replicates the steps taken by the compiler during
  676. # param matching. It performs an embarrassing amount of back-and-forth
  677. # type jugling, but it's the price to pay for consistency and correctness
  678. result.typ() = generateTypeInstance(c, m.bindings, arg.info,
  679. formal.skipTypes({tyCompositeTypeClass}))
  680. else:
  681. typeMismatch(c.config, arg.info, formal, arg.typ, arg)
  682. # error correction:
  683. result = copyTree(arg)
  684. result.typ() = formal
  685. proc updateDefaultParams(c: PContext, call: PNode) =
  686. # In generic procs, the default parameter may be unique for each
  687. # instantiation (see tlateboundgenericparams).
  688. # After a call is resolved, we need to re-assign any default value
  689. # that was used during sigmatch. sigmatch is responsible for marking
  690. # the default params with `nfDefaultParam` and `instantiateProcType`
  691. # computes correctly the default values for each instantiation.
  692. let calleeParams = call[0].sym.typ.n
  693. for i in 1..<call.len:
  694. if nfDefaultParam in call[i].flags:
  695. let formal = calleeParams[i].sym
  696. let def = formal.ast
  697. if nfDefaultRefsParam in def.flags: call.flags.incl nfDefaultRefsParam
  698. # mirrored with sigmatch:
  699. if def.kind == nkEmpty:
  700. # The default param value is set to empty in `instantiateProcType`
  701. # when the type of the default expression doesn't match the type
  702. # of the instantiated proc param:
  703. pushInfoContext(c.config, call.info, call[0].sym.detailedInfo)
  704. typeMismatch(c.config, def.info, formal.typ, def.typ, formal.ast)
  705. popInfoContext(c.config)
  706. def.typ() = errorType(c)
  707. call[i] = def
  708. proc getCallLineInfo(n: PNode): TLineInfo =
  709. case n.kind
  710. of nkAccQuoted, nkBracketExpr, nkCall, nkCallStrLit, nkCommand:
  711. if len(n) > 0:
  712. return getCallLineInfo(n[0])
  713. of nkDotExpr:
  714. if len(n) > 1:
  715. return getCallLineInfo(n[1])
  716. else:
  717. discard
  718. result = n.info
  719. proc inheritBindings(c: PContext, x: var TCandidate, expectedType: PType) =
  720. ## Helper proc to inherit bound generic parameters from expectedType into x.
  721. ## Does nothing if 'inferGenericTypes' isn't in c.features.
  722. if inferGenericTypes notin c.features: return
  723. if expectedType == nil or x.callee.returnType == nil: return # required for inference
  724. var
  725. flatUnbound: seq[PType] = @[]
  726. flatBound: seq[PType] = @[]
  727. # seq[(result type, expected type)]
  728. var typeStack = newSeq[(PType, PType)]()
  729. template stackPut(a, b) =
  730. ## skips types and puts the skipped version on stack
  731. # It might make sense to skip here one by one. It's not part of the main
  732. # type reduction because the right side normally won't be skipped
  733. const toSkip = {tyVar, tyLent, tyStatic, tyCompositeTypeClass, tySink}
  734. let
  735. x = a.skipTypes(toSkip)
  736. y = if a.kind notin toSkip: b
  737. else: b.skipTypes(toSkip)
  738. typeStack.add((x, y))
  739. stackPut(x.callee.returnType, expectedType)
  740. while typeStack.len() > 0:
  741. let (t, u) = typeStack.pop()
  742. if t == u or t == nil or u == nil or t.kind == tyAnything or u.kind == tyAnything:
  743. continue
  744. case t.kind
  745. of ConcreteTypes, tyGenericInvocation, tyUncheckedArray:
  746. # XXX This logic makes no sense for `tyUncheckedArray`
  747. # nested, add all the types to stack
  748. let
  749. startIdx = if u.kind in ConcreteTypes: 0 else: 1
  750. endIdx = min(u.kidsLen() - startIdx, t.kidsLen())
  751. for i in startIdx ..< endIdx:
  752. # early exit with current impl
  753. if t[i] == nil or u[i] == nil: return
  754. stackPut(t[i], u[i])
  755. of tyGenericParam:
  756. let prebound = x.bindings.lookup(t)
  757. if prebound != nil:
  758. continue # Skip param, already bound
  759. # fully reduced generic param, bind it
  760. if t notin flatUnbound:
  761. flatUnbound.add(t)
  762. flatBound.add(u)
  763. else:
  764. discard
  765. # update bindings
  766. for i in 0 ..< flatUnbound.len():
  767. x.bindings.put(flatUnbound[i], flatBound[i])
  768. proc semResolvedCall(c: PContext, x: var TCandidate,
  769. n: PNode, flags: TExprFlags;
  770. expectedType: PType = nil): PNode =
  771. assert x.state == csMatch
  772. var finalCallee = x.calleeSym
  773. let info = getCallLineInfo(n)
  774. markUsed(c, info, finalCallee)
  775. onUse(info, finalCallee)
  776. assert finalCallee.ast != nil
  777. if x.matchedErrorType:
  778. result = x.call
  779. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  780. if containsGenericType(result.typ):
  781. result.typ() = newTypeS(tyError, c)
  782. incl result.typ.flags, tfCheckedForDestructor
  783. return
  784. let gp = finalCallee.ast[genericParamsPos]
  785. if gp.isGenericParams:
  786. if x.calleeSym.kind notin {skMacro, skTemplate}:
  787. if x.calleeSym.magic in {mArrGet, mArrPut}:
  788. finalCallee = x.calleeSym
  789. else:
  790. c.inheritBindings(x, expectedType)
  791. finalCallee = generateInstance(c, x.calleeSym, x.bindings, n.info)
  792. else:
  793. # For macros and templates, the resolved generic params
  794. # are added as normal params.
  795. c.inheritBindings(x, expectedType)
  796. for s in instantiateGenericParamList(c, gp, x.bindings):
  797. case s.kind
  798. of skConst:
  799. if not s.astdef.isNil:
  800. x.call.add s.astdef
  801. else:
  802. x.call.add c.graph.emptyNode
  803. of skType:
  804. var tn = newSymNode(s, n.info)
  805. # this node will be used in template substitution,
  806. # pretend this is an untyped node and let regular sem handle the type
  807. # to prevent problems where a generic parameter is treated as a value
  808. tn.typ() = nil
  809. x.call.add tn
  810. else:
  811. internalAssert c.config, false
  812. result = x.call
  813. instGenericConvertersSons(c, result, x)
  814. markConvertersUsed(c, result)
  815. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  816. if finalCallee.magic notin {mArrGet, mArrPut}:
  817. result.typ() = finalCallee.typ.returnType
  818. updateDefaultParams(c, result)
  819. proc canDeref(n: PNode): bool {.inline.} =
  820. result = n.len >= 2 and (let t = n[1].typ;
  821. t != nil and t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyPtr, tyRef})
  822. proc tryDeref(n: PNode): PNode =
  823. result = newNodeI(nkHiddenDeref, n.info)
  824. result.typ() = n.typ.skipTypes(abstractInst)[0]
  825. result.add n
  826. proc semOverloadedCall(c: PContext, n, nOrig: PNode,
  827. filter: TSymKinds, flags: TExprFlags;
  828. expectedType: PType = nil): PNode =
  829. var errors: CandidateErrors = @[] # if efExplain in flags: @[] else: nil
  830. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  831. if r.state == csMatch:
  832. # this may be triggered, when the explain pragma is used
  833. if errors.len > 0:
  834. let (_, candidates) = presentFailedCandidates(c, n, errors)
  835. message(c.config, n.info, hintUserRaw,
  836. "Non-matching candidates for " & renderTree(n) & "\n" &
  837. candidates)
  838. result = semResolvedCall(c, r, n, flags, expectedType)
  839. else:
  840. if c.inGenericContext > 0 and c.matchedConcept == nil:
  841. result = semGenericStmt(c, n)
  842. result.typ() = makeTypeFromExpr(c, result.copyTree)
  843. elif efExplain notin flags:
  844. # repeat the overload resolution,
  845. # this time enabling all the diagnostic output (this should fail again)
  846. result = semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  847. elif efNoUndeclared notin flags:
  848. result = nil
  849. notFoundError(c, n, errors)
  850. else:
  851. result = nil
  852. proc explicitGenericInstError(c: PContext; n: PNode): PNode =
  853. localError(c.config, getCallLineInfo(n), errCannotInstantiateX % renderTree(n))
  854. result = n
  855. proc explicitGenericSym(c: PContext, n: PNode, s: PSym, errors: var CandidateErrors, doError: bool): PNode =
  856. if s.kind in {skTemplate, skMacro}:
  857. internalError c.config, n.info, "cannot get explicitly instantiated symbol of " &
  858. (if s.kind == skTemplate: "template" else: "macro")
  859. # binding has to stay 'nil' for this to work!
  860. var m = newCandidate(c, s, nil)
  861. matchGenericParams(m, n, s)
  862. if m.state != csMatch:
  863. # state is csMatch only if *all* generic params were matched,
  864. # including implicit parameters
  865. if doError:
  866. errors.add(CandidateError(
  867. sym: s,
  868. firstMismatch: m.firstMismatch,
  869. diagnostics: m.diagnostics))
  870. return nil
  871. var newInst = generateInstance(c, s, m.bindings, n.info)
  872. newInst.typ.flags.excl tfUnresolved
  873. let info = getCallLineInfo(n)
  874. markUsed(c, info, s)
  875. onUse(info, s)
  876. result = newSymNode(newInst, info)
  877. proc setGenericParams(c: PContext, n, expectedParams: PNode) =
  878. ## sems generic params in subscript expression
  879. for i in 1..<n.len:
  880. let
  881. constraint =
  882. if expectedParams != nil and i <= expectedParams.len:
  883. expectedParams[i - 1].typ
  884. else:
  885. nil
  886. e = semExprWithType(c, n[i], expectedType = constraint)
  887. if e.typ == nil:
  888. n[i].typ() = errorType(c)
  889. else:
  890. n[i].typ() = e.typ.skipTypes({tyTypeDesc})
  891. proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym, doError: bool): PNode =
  892. assert n.kind == nkBracketExpr
  893. setGenericParams(c, n, s.ast[genericParamsPos])
  894. var s = s
  895. var a = n[0]
  896. var errors: CandidateErrors = @[]
  897. if a.kind == nkSym:
  898. # common case; check the only candidate has the right
  899. # number of generic type parameters:
  900. result = explicitGenericSym(c, n, s, errors, doError)
  901. if result == nil:
  902. if c.inGenericContext > 0:
  903. # same as in semOverloadedCall, make expression untyped,
  904. # may have failed match due to unresolved types
  905. result = semGenericStmt(c, n)
  906. result.typ() = makeTypeFromExpr(c, result.copyTree)
  907. elif doError:
  908. notFoundError(c, n, errors)
  909. elif a.kind in {nkClosedSymChoice, nkOpenSymChoice}:
  910. # choose the generic proc with the proper number of type parameters.
  911. result = newNodeI(a.kind, getCallLineInfo(n))
  912. for i in 0..<a.len:
  913. var candidate = a[i].sym
  914. if candidate.kind in {skProc, skMethod, skConverter,
  915. skFunc, skIterator}:
  916. let x = explicitGenericSym(c, n, candidate, errors, doError)
  917. if x != nil: result.add(x)
  918. elif c.inGenericContext > 0:
  919. # same as in semOverloadedCall, make expression untyped,
  920. # may have failed match due to unresolved types
  921. # any failing match stops building the symchoice for correctness,
  922. # can also make it untyped from the start
  923. result = semGenericStmt(c, n)
  924. result.typ() = makeTypeFromExpr(c, result.copyTree)
  925. return
  926. # get rid of nkClosedSymChoice if not ambiguous:
  927. if result.len == 0:
  928. result = nil
  929. if doError:
  930. notFoundError(c, n, errors)
  931. else:
  932. # probably unreachable: we are trying to instantiate `a` which is not
  933. # a sym/symchoice
  934. if doError:
  935. result = explicitGenericInstError(c, n)
  936. else:
  937. result = nil
  938. proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): tuple[s: PSym, state: TBorrowState] =
  939. # Searches for the fn in the symbol table. If the parameter lists are suitable
  940. # for borrowing the sym in the symbol table is returned, else nil.
  941. # New approach: generate fn(x, y, z) where x, y, z have the proper types
  942. # and use the overloading resolution mechanism:
  943. const desiredTypes = abstractVar + {tyCompositeTypeClass} - {tyTypeDesc, tyDistinct}
  944. template getType(isDistinct: bool; t: PType):untyped =
  945. if isDistinct: t.baseOfDistinct(c.graph, c.idgen) else: t
  946. result = default(tuple[s: PSym, state: TBorrowState])
  947. var call = newNodeI(nkCall, fn.info)
  948. var hasDistinct = false
  949. var isDistinct: bool
  950. var x: PType
  951. var t: PType
  952. call.add(newIdentNode(fn.name, fn.info))
  953. for i in 1..<fn.typ.n.len:
  954. let param = fn.typ.n[i]
  955. #[.
  956. # We only want the type not any modifiers such as `ptr`, `var`, `ref` ...
  957. # tyCompositeTypeClass is here for
  958. # when using something like:
  959. type Foo[T] = distinct int
  960. proc `$`(f: Foo): string {.borrow.}
  961. # We want to skip the `Foo` to get `int`
  962. ]#
  963. t = skipTypes(param.typ, desiredTypes)
  964. isDistinct = t.kind == tyDistinct or param.typ.kind == tyDistinct
  965. if t.kind == tyGenericInvocation and t.genericHead.last.kind == tyDistinct:
  966. result.state = bsGeneric
  967. return
  968. if isDistinct: hasDistinct = true
  969. if param.typ.kind == tyVar:
  970. x = newTypeS(param.typ.kind, c)
  971. x.addSonSkipIntLit(getType(isDistinct, t), c.idgen)
  972. else:
  973. x = getType(isDistinct, t)
  974. var s = copySym(param.sym, c.idgen)
  975. s.typ = x
  976. s.info = param.info
  977. call.add(newSymNode(s))
  978. if hasDistinct:
  979. let filter = if fn.kind in {skProc, skFunc}: {skProc, skFunc} else: {fn.kind}
  980. var resolved = semOverloadedCall(c, call, call, filter, {})
  981. if resolved != nil:
  982. result.s = resolved[0].sym
  983. result.state = bsMatch
  984. if not compareTypes(result.s.typ.returnType, fn.typ.returnType, dcEqIgnoreDistinct, {IgnoreFlags}):
  985. result.state = bsReturnNotMatch
  986. elif result.s.magic in {mArrPut, mArrGet}:
  987. # cannot borrow these magics for now
  988. result.state = bsNotSupported
  989. else:
  990. result.state = bsNoDistinct