semcall.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. symx = nextOverloadIter(o, c, headSymbol)
  47. if result.len > 0:
  48. initCandidate(c, best, result[0].s, initialBinding,
  49. result[0].scope, diagnostics)
  50. initCandidate(c, alt, result[0].s, initialBinding,
  51. result[0].scope, diagnostics)
  52. best.state = csNoMatch
  53. proc pickBestCandidate(c: PContext, headSymbol: PNode,
  54. n, orig: PNode,
  55. initialBinding: PNode,
  56. filter: TSymKinds,
  57. best, alt: var TCandidate,
  58. errors: var CandidateErrors,
  59. diagnosticsFlag: bool,
  60. errorsEnabled: bool, flags: TExprFlags) =
  61. # `matches` may find new symbols, so keep track of count
  62. var symCount = c.currentScope.symbols.counter
  63. var o: TOverloadIter
  64. # https://github.com/nim-lang/Nim/issues/21272
  65. # prevent mutation during iteration by storing them in a seq
  66. # luckily `initCandidateSymbols` does just that
  67. var syms = initCandidateSymbols(c, headSymbol, initialBinding, filter,
  68. best, alt, o, diagnosticsFlag)
  69. if len(syms) == 0:
  70. return
  71. # current overload being considered
  72. var sym = syms[0].s
  73. var scope = syms[0].scope
  74. # starts at 1 because 0 is already done with setup, only needs checking
  75. var nextSymIndex = 1
  76. var z: TCandidate # current candidate
  77. while true:
  78. determineType(c, sym)
  79. initCandidate(c, z, sym, initialBinding, scope, diagnosticsFlag)
  80. # this is kinda backwards as without a check here the described
  81. # problems in recalc would not happen, but instead it 100%
  82. # does check forever in some cases
  83. if c.currentScope.symbols.counter == symCount:
  84. # may introduce new symbols with caveats described in recalc branch
  85. matches(c, n, orig, z)
  86. if z.state == csMatch:
  87. # little hack so that iterators are preferred over everything else:
  88. if sym.kind == skIterator:
  89. if not (efWantIterator notin flags and efWantIterable in flags):
  90. inc(z.exactMatches, 200)
  91. else:
  92. dec(z.exactMatches, 200)
  93. case best.state
  94. of csEmpty, csNoMatch: best = z
  95. of csMatch:
  96. var cmp = cmpCandidates(best, z)
  97. if cmp < 0: best = z # x is better than the best so far
  98. elif cmp == 0: alt = z # x is as good as the best so far
  99. elif errorsEnabled or z.diagnosticsEnabled:
  100. errors.add(CandidateError(
  101. sym: sym,
  102. firstMismatch: z.firstMismatch,
  103. diagnostics: z.diagnostics))
  104. else:
  105. # this branch feels like a ticking timebomb
  106. # one of two bad things could happen
  107. # 1) new symbols are discovered but the loop ends before we recalc
  108. # 2) new symbols are discovered and resemmed forever
  109. # not 100% sure if these are possible though as they would rely
  110. # on somehow introducing a new overload during overload resolution
  111. # Symbol table has been modified. Restart and pre-calculate all syms
  112. # before any further candidate init and compare. SLOW, but rare case.
  113. syms = initCandidateSymbols(c, headSymbol, initialBinding, filter,
  114. best, alt, o, diagnosticsFlag)
  115. # reset counter because syms may be in a new order
  116. symCount = c.currentScope.symbols.counter
  117. nextSymIndex = 0
  118. # just in case, should be impossible though
  119. if syms.len == 0:
  120. break
  121. if nextSymIndex > high(syms):
  122. # we have reached the end
  123. break
  124. # advance to next sym
  125. sym = syms[nextSymIndex].s
  126. scope = syms[nextSymIndex].scope
  127. inc(nextSymIndex)
  128. proc effectProblem(f, a: PType; result: var string; c: PContext) =
  129. if f.kind == tyProc and a.kind == tyProc:
  130. if tfThread in f.flags and tfThread notin a.flags:
  131. result.add "\n This expression is not GC-safe. Annotate the " &
  132. "proc with {.gcsafe.} to get extended error information."
  133. elif tfNoSideEffect in f.flags and tfNoSideEffect notin a.flags:
  134. result.add "\n This expression can have side effects. Annotate the " &
  135. "proc with {.noSideEffect.} to get extended error information."
  136. else:
  137. case compatibleEffects(f, a)
  138. of efCompat: discard
  139. of efRaisesDiffer:
  140. result.add "\n The `.raises` requirements differ."
  141. of efRaisesUnknown:
  142. result.add "\n The `.raises` requirements differ. Annotate the " &
  143. "proc with {.raises: [].} to get extended error information."
  144. of efTagsDiffer:
  145. result.add "\n The `.tags` requirements differ."
  146. of efTagsUnknown:
  147. result.add "\n The `.tags` requirements differ. Annotate the " &
  148. "proc with {.tags: [].} to get extended error information."
  149. of efEffectsDelayed:
  150. result.add "\n The `.effectsOf` annotations differ."
  151. of efTagsIllegal:
  152. result.add "\n The `.forbids` requirements caught an illegal tag."
  153. when defined(drnim):
  154. if not c.graph.compatibleProps(c.graph, f, a):
  155. result.add "\n The `.requires` or `.ensures` properties are incompatible."
  156. proc renderNotLValue(n: PNode): string =
  157. result = $n
  158. let n = if n.kind == nkHiddenDeref: n[0] else: n
  159. if n.kind == nkHiddenCallConv and n.len > 1:
  160. result = $n[0] & "(" & result & ")"
  161. elif n.kind in {nkHiddenStdConv, nkHiddenSubConv} and n.len == 2:
  162. result = typeToString(n.typ.skipTypes(abstractVar)) & "(" & result & ")"
  163. proc presentFailedCandidates(c: PContext, n: PNode, errors: CandidateErrors):
  164. (TPreferedDesc, string) =
  165. var prefer = preferName
  166. # to avoid confusing errors like:
  167. # got (SslPtr, SocketHandle)
  168. # but expected one of:
  169. # openssl.SSL_set_fd(ssl: SslPtr, fd: SocketHandle): cint
  170. # we do a pre-analysis. If all types produce the same string, we will add
  171. # module information.
  172. let proto = describeArgs(c, n, 1, preferName)
  173. for err in errors:
  174. var errProto = ""
  175. let n = err.sym.typ.n
  176. for i in 1..<n.len:
  177. var p = n[i]
  178. if p.kind == nkSym:
  179. errProto.add(typeToString(p.sym.typ, preferName))
  180. if i != n.len-1: errProto.add(", ")
  181. # else: ignore internal error as we're already in error handling mode
  182. if errProto == proto:
  183. prefer = preferModuleInfo
  184. break
  185. # we pretend procs are attached to the type of the first
  186. # argument in order to remove plenty of candidates. This is
  187. # comparable to what C# does and C# is doing fine.
  188. var filterOnlyFirst = false
  189. if optShowAllMismatches notin c.config.globalOptions and verboseTypeMismatch in c.config.legacyFeatures:
  190. for err in errors:
  191. if err.firstMismatch.arg > 1:
  192. filterOnlyFirst = true
  193. break
  194. var maybeWrongSpace = false
  195. var candidatesAll: seq[string]
  196. var candidates = ""
  197. var skipped = 0
  198. for err in errors:
  199. candidates.setLen 0
  200. if filterOnlyFirst and err.firstMismatch.arg == 1:
  201. inc skipped
  202. continue
  203. if verboseTypeMismatch notin c.config.legacyFeatures:
  204. candidates.add "[" & $err.firstMismatch.arg & "] "
  205. if err.sym.kind in routineKinds and err.sym.ast != nil:
  206. candidates.add(renderTree(err.sym.ast,
  207. {renderNoBody, renderNoComments, renderNoPragmas}))
  208. else:
  209. candidates.add(getProcHeader(c.config, err.sym, prefer))
  210. candidates.addDeclaredLocMaybe(c.config, err.sym)
  211. candidates.add("\n")
  212. let nArg = if err.firstMismatch.arg < n.len: n[err.firstMismatch.arg] else: nil
  213. let nameParam = if err.firstMismatch.formal != nil: err.firstMismatch.formal.name.s else: ""
  214. if n.len > 1 and verboseTypeMismatch in c.config.legacyFeatures:
  215. candidates.add(" first type mismatch at position: " & $err.firstMismatch.arg)
  216. # candidates.add "\n reason: " & $err.firstMismatch.kind # for debugging
  217. case err.firstMismatch.kind
  218. of kUnknownNamedParam:
  219. if nArg == nil:
  220. candidates.add("\n unknown named parameter")
  221. else:
  222. candidates.add("\n unknown named parameter: " & $nArg[0])
  223. of kAlreadyGiven: candidates.add("\n named param already provided: " & $nArg[0])
  224. of kPositionalAlreadyGiven: candidates.add("\n positional param was already given as named param")
  225. of kExtraArg: candidates.add("\n extra argument given")
  226. of kMissingParam: candidates.add("\n missing parameter: " & nameParam)
  227. of kTypeMismatch, kVarNeeded:
  228. doAssert nArg != nil
  229. let wanted = err.firstMismatch.formal.typ
  230. doAssert err.firstMismatch.formal != nil
  231. candidates.add("\n required type for " & nameParam & ": ")
  232. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  233. candidates.add "\n but expression '"
  234. if err.firstMismatch.kind == kVarNeeded:
  235. candidates.add renderNotLValue(nArg)
  236. candidates.add "' is immutable, not 'var'"
  237. else:
  238. candidates.add renderTree(nArg)
  239. candidates.add "' is of type: "
  240. let got = nArg.typ
  241. candidates.addTypeDeclVerboseMaybe(c.config, got)
  242. doAssert wanted != nil
  243. if got != nil:
  244. if got.kind == tyProc and wanted.kind == tyProc:
  245. # These are proc mismatches so,
  246. # add the extra explict detail of the mismatch
  247. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  248. effectProblem(wanted, got, candidates, c)
  249. of kUnknown: discard "do not break 'nim check'"
  250. candidates.add "\n"
  251. if err.firstMismatch.arg == 1 and nArg.kind == nkTupleConstr and
  252. n.kind == nkCommand:
  253. maybeWrongSpace = true
  254. for diag in err.diagnostics:
  255. candidates.add(diag & "\n")
  256. candidatesAll.add candidates
  257. candidatesAll.sort # fix #13538
  258. candidates = join(candidatesAll)
  259. if skipped > 0:
  260. candidates.add($skipped & " other mismatching symbols have been " &
  261. "suppressed; compile with --showAllMismatches:on to see them\n")
  262. if maybeWrongSpace:
  263. candidates.add("maybe misplaced space between " & renderTree(n[0]) & " and '(' \n")
  264. result = (prefer, candidates)
  265. const
  266. errTypeMismatch = "type mismatch: got <"
  267. errButExpected = "but expected one of:"
  268. errExpectedPosition = "Expected one of (first mismatch at [position]):"
  269. errUndeclaredField = "undeclared field: '$1'"
  270. errUndeclaredRoutine = "attempting to call undeclared routine: '$1'"
  271. errBadRoutine = "attempting to call routine: '$1'$2"
  272. errAmbiguousCallXYZ = "ambiguous call; both $1 and $2 match for: $3"
  273. proc describeParamList(c: PContext, n: PNode, startIdx = 1; prefer = preferName): string =
  274. result = "Expression: " & $n
  275. for i in startIdx..<n.len:
  276. result.add "\n [" & $i & "] " & renderTree(n[i]) & ": "
  277. result.add describeArg(c, n, i, startIdx, prefer)
  278. result.add "\n"
  279. template legacynotFoundError(c: PContext, n: PNode, errors: CandidateErrors) =
  280. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  281. var result = errTypeMismatch
  282. result.add(describeArgs(c, n, 1, prefer))
  283. result.add('>')
  284. if candidates != "":
  285. result.add("\n" & errButExpected & "\n" & candidates)
  286. localError(c.config, n.info, result & "\nexpression: " & $n)
  287. proc notFoundError*(c: PContext, n: PNode, errors: CandidateErrors) =
  288. # Gives a detailed error message; this is separated from semOverloadedCall,
  289. # as semOverloadedCall is already pretty slow (and we need this information
  290. # only in case of an error).
  291. if c.config.m.errorOutputs == {}:
  292. # fail fast:
  293. globalError(c.config, n.info, "type mismatch")
  294. return
  295. # see getMsgDiagnostic:
  296. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  297. let ident = considerQuotedIdent(c, n[0], n).s
  298. let sym = n[1].typ.typSym
  299. var typeHint = ""
  300. if sym == nil:
  301. discard
  302. else:
  303. typeHint = " for type " & getProcHeader(c.config, sym)
  304. localError(c.config, n.info, errUndeclaredField % ident & typeHint)
  305. return
  306. if errors.len == 0:
  307. if n[0].kind in nkIdentKinds:
  308. let ident = considerQuotedIdent(c, n[0], n).s
  309. localError(c.config, n.info, errUndeclaredRoutine % ident)
  310. else:
  311. localError(c.config, n.info, "expression '$1' cannot be called" % n[0].renderTree)
  312. return
  313. if verboseTypeMismatch in c.config.legacyFeatures:
  314. legacynotFoundError(c, n, errors)
  315. else:
  316. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  317. var result = "type mismatch\n"
  318. result.add describeParamList(c, n, 1, prefer)
  319. if candidates != "":
  320. result.add("\n" & errExpectedPosition & "\n" & candidates)
  321. localError(c.config, n.info, result)
  322. proc bracketNotFoundError(c: PContext; n: PNode) =
  323. var errors: CandidateErrors = @[]
  324. var o: TOverloadIter
  325. let headSymbol = n[0]
  326. var symx = initOverloadIter(o, c, headSymbol)
  327. while symx != nil:
  328. if symx.kind in routineKinds:
  329. errors.add(CandidateError(sym: symx,
  330. firstMismatch: MismatchInfo(),
  331. diagnostics: @[],
  332. enabled: false))
  333. symx = nextOverloadIter(o, c, headSymbol)
  334. if errors.len == 0:
  335. localError(c.config, n.info, "could not resolve: " & $n)
  336. else:
  337. notFoundError(c, n, errors)
  338. proc getMsgDiagnostic(c: PContext, flags: TExprFlags, n, f: PNode): string =
  339. if c.compilesContextId > 0:
  340. # we avoid running more diagnostic when inside a `compiles(expr)`, to
  341. # errors while running diagnostic (see test D20180828T234921), and
  342. # also avoid slowdowns in evaluating `compiles(expr)`.
  343. discard
  344. else:
  345. var o: TOverloadIter
  346. var sym = initOverloadIter(o, c, f)
  347. while sym != nil:
  348. result &= "\n found $1" % [getSymRepr(c.config, sym)]
  349. sym = nextOverloadIter(o, c, f)
  350. let ident = considerQuotedIdent(c, f, n).s
  351. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  352. let sym = n[1].typ.typSym
  353. var typeHint = ""
  354. if sym == nil:
  355. # Perhaps we're in a `compiles(foo.bar)` expression, or
  356. # in a concept, e.g.:
  357. # ExplainedConcept {.explain.} = concept x
  358. # x.foo is int
  359. # We could use: `(c.config $ n[1].info)` to get more context.
  360. discard
  361. else:
  362. typeHint = " for type " & getProcHeader(c.config, sym)
  363. let suffix = if result.len > 0: " " & result else: ""
  364. result = errUndeclaredField % ident & typeHint & suffix
  365. else:
  366. if result.len == 0: result = errUndeclaredRoutine % ident
  367. else: result = errBadRoutine % [ident, result]
  368. proc resolveOverloads(c: PContext, n, orig: PNode,
  369. filter: TSymKinds, flags: TExprFlags,
  370. errors: var CandidateErrors,
  371. errorsEnabled: bool): TCandidate =
  372. var initialBinding: PNode
  373. var alt: TCandidate
  374. var f = n[0]
  375. if f.kind == nkBracketExpr:
  376. # fill in the bindings:
  377. semOpAux(c, f)
  378. initialBinding = f
  379. f = f[0]
  380. else:
  381. initialBinding = nil
  382. pickBestCandidate(c, f, n, orig, initialBinding,
  383. filter, result, alt, errors, efExplain in flags,
  384. errorsEnabled, flags)
  385. var dummyErrors: CandidateErrors
  386. template pickSpecialOp(headSymbol) =
  387. pickBestCandidate(c, headSymbol, n, orig, initialBinding,
  388. filter, result, alt, dummyErrors, efExplain in flags,
  389. false, flags)
  390. let overloadsState = result.state
  391. if overloadsState != csMatch:
  392. if nfDotField in n.flags:
  393. internalAssert c.config, f.kind == nkIdent and n.len >= 2
  394. # leave the op head symbol empty,
  395. # we are going to try multiple variants
  396. n.sons[0..1] = [nil, n[1], f]
  397. orig.sons[0..1] = [nil, orig[1], f]
  398. template tryOp(x) =
  399. let op = newIdentNode(getIdent(c.cache, x), n.info)
  400. n[0] = op
  401. orig[0] = op
  402. pickSpecialOp(op)
  403. if nfExplicitCall in n.flags:
  404. tryOp ".()"
  405. if result.state in {csEmpty, csNoMatch}:
  406. tryOp "."
  407. elif nfDotSetter in n.flags and f.kind == nkIdent and n.len == 3:
  408. # we need to strip away the trailing '=' here:
  409. let calleeName = newIdentNode(getIdent(c.cache, f.ident.s[0..^2]), n.info)
  410. let callOp = newIdentNode(getIdent(c.cache, ".="), n.info)
  411. n.sons[0..1] = [callOp, n[1], calleeName]
  412. orig.sons[0..1] = [callOp, orig[1], calleeName]
  413. pickSpecialOp(callOp)
  414. if overloadsState == csEmpty and result.state == csEmpty:
  415. if efNoUndeclared notin flags: # for tests/pragmas/tcustom_pragma.nim
  416. result.state = csNoMatch
  417. if efNoDiagnostics in flags:
  418. return
  419. # xxx adapt/use errorUndeclaredIdentifierHint(c, n, f.ident)
  420. localError(c.config, n.info, getMsgDiagnostic(c, flags, n, f))
  421. return
  422. elif result.state != csMatch:
  423. if nfExprCall in n.flags:
  424. localError(c.config, n.info, "expression '$1' cannot be called" %
  425. renderTree(n, {renderNoComments}))
  426. else:
  427. if {nfDotField, nfDotSetter} * n.flags != {}:
  428. # clean up the inserted ops
  429. n.sons.delete(2)
  430. n[0] = f
  431. return
  432. if alt.state == csMatch and cmpCandidates(result, alt) == 0 and
  433. not sameMethodDispatcher(result.calleeSym, alt.calleeSym):
  434. internalAssert c.config, result.state == csMatch
  435. #writeMatches(result)
  436. #writeMatches(alt)
  437. if c.config.m.errorOutputs == {}:
  438. # quick error message for performance of 'compiles' built-in:
  439. globalError(c.config, n.info, errGenerated, "ambiguous call")
  440. elif c.config.errorCounter == 0:
  441. # don't cascade errors
  442. var args = "("
  443. for i in 1..<n.len:
  444. if i > 1: args.add(", ")
  445. args.add(typeToString(n[i].typ))
  446. args.add(")")
  447. localError(c.config, n.info, errAmbiguousCallXYZ % [
  448. getProcHeader(c.config, result.calleeSym),
  449. getProcHeader(c.config, alt.calleeSym),
  450. args])
  451. proc instGenericConvertersArg*(c: PContext, a: PNode, x: TCandidate) =
  452. let a = if a.kind == nkHiddenDeref: a[0] else: a
  453. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  454. let s = a[0].sym
  455. if s.isGenericRoutineStrict:
  456. let finalCallee = generateInstance(c, s, x.bindings, a.info)
  457. a[0].sym = finalCallee
  458. a[0].typ = finalCallee.typ
  459. #a.typ = finalCallee.typ[0]
  460. proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) =
  461. assert n.kind in nkCallKinds
  462. if x.genericConverter:
  463. for i in 1..<n.len:
  464. instGenericConvertersArg(c, n[i], x)
  465. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode =
  466. var m = newCandidate(c, f)
  467. result = paramTypesMatch(m, f, a, arg, nil)
  468. if m.genericConverter and result != nil:
  469. instGenericConvertersArg(c, result, m)
  470. proc inferWithMetatype(c: PContext, formal: PType,
  471. arg: PNode, coerceDistincts = false): PNode =
  472. var m = newCandidate(c, formal)
  473. m.coerceDistincts = coerceDistincts
  474. result = paramTypesMatch(m, formal, arg.typ, arg, nil)
  475. if m.genericConverter and result != nil:
  476. instGenericConvertersArg(c, result, m)
  477. if result != nil:
  478. # This almost exactly replicates the steps taken by the compiler during
  479. # param matching. It performs an embarrassing amount of back-and-forth
  480. # type jugling, but it's the price to pay for consistency and correctness
  481. result.typ = generateTypeInstance(c, m.bindings, arg.info,
  482. formal.skipTypes({tyCompositeTypeClass}))
  483. else:
  484. typeMismatch(c.config, arg.info, formal, arg.typ, arg)
  485. # error correction:
  486. result = copyTree(arg)
  487. result.typ = formal
  488. proc updateDefaultParams(call: PNode) =
  489. # In generic procs, the default parameter may be unique for each
  490. # instantiation (see tlateboundgenericparams).
  491. # After a call is resolved, we need to re-assign any default value
  492. # that was used during sigmatch. sigmatch is responsible for marking
  493. # the default params with `nfDefaultParam` and `instantiateProcType`
  494. # computes correctly the default values for each instantiation.
  495. let calleeParams = call[0].sym.typ.n
  496. for i in 1..<call.len:
  497. if nfDefaultParam in call[i].flags:
  498. let def = calleeParams[i].sym.ast
  499. if nfDefaultRefsParam in def.flags: call.flags.incl nfDefaultRefsParam
  500. call[i] = def
  501. proc getCallLineInfo(n: PNode): TLineInfo =
  502. case n.kind
  503. of nkAccQuoted, nkBracketExpr, nkCall, nkCallStrLit, nkCommand:
  504. if len(n) > 0:
  505. return getCallLineInfo(n[0])
  506. of nkDotExpr:
  507. if len(n) > 1:
  508. return getCallLineInfo(n[1])
  509. else:
  510. discard
  511. result = n.info
  512. proc semResolvedCall(c: PContext, x: TCandidate,
  513. n: PNode, flags: TExprFlags): PNode =
  514. assert x.state == csMatch
  515. var finalCallee = x.calleeSym
  516. let info = getCallLineInfo(n)
  517. markUsed(c, info, finalCallee)
  518. onUse(info, finalCallee)
  519. assert finalCallee.ast != nil
  520. if x.hasFauxMatch:
  521. result = x.call
  522. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  523. if containsGenericType(result.typ) or x.fauxMatch == tyUnknown:
  524. result.typ = newTypeS(x.fauxMatch, c)
  525. if result.typ.kind == tyError: incl result.typ.flags, tfCheckedForDestructor
  526. return
  527. let gp = finalCallee.ast[genericParamsPos]
  528. if gp.isGenericParams:
  529. if x.calleeSym.kind notin {skMacro, skTemplate}:
  530. if x.calleeSym.magic in {mArrGet, mArrPut}:
  531. finalCallee = x.calleeSym
  532. else:
  533. finalCallee = generateInstance(c, x.calleeSym, x.bindings, n.info)
  534. else:
  535. # For macros and templates, the resolved generic params
  536. # are added as normal params.
  537. for s in instantiateGenericParamList(c, gp, x.bindings):
  538. case s.kind
  539. of skConst:
  540. if not s.astdef.isNil:
  541. x.call.add s.astdef
  542. else:
  543. x.call.add c.graph.emptyNode
  544. of skType:
  545. x.call.add newSymNode(s, n.info)
  546. else:
  547. internalAssert c.config, false
  548. result = x.call
  549. instGenericConvertersSons(c, result, x)
  550. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  551. result.typ = finalCallee.typ[0]
  552. updateDefaultParams(result)
  553. proc canDeref(n: PNode): bool {.inline.} =
  554. result = n.len >= 2 and (let t = n[1].typ;
  555. t != nil and t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyPtr, tyRef})
  556. proc tryDeref(n: PNode): PNode =
  557. result = newNodeI(nkHiddenDeref, n.info)
  558. result.typ = n.typ.skipTypes(abstractInst)[0]
  559. result.add n
  560. proc semOverloadedCall(c: PContext, n, nOrig: PNode,
  561. filter: TSymKinds, flags: TExprFlags): PNode =
  562. var errors: CandidateErrors = @[] # if efExplain in flags: @[] else: nil
  563. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  564. if r.state == csMatch:
  565. # this may be triggered, when the explain pragma is used
  566. if errors.len > 0:
  567. let (_, candidates) = presentFailedCandidates(c, n, errors)
  568. message(c.config, n.info, hintUserRaw,
  569. "Non-matching candidates for " & renderTree(n) & "\n" &
  570. candidates)
  571. result = semResolvedCall(c, r, n, flags)
  572. else:
  573. if efExplain notin flags:
  574. # repeat the overload resolution,
  575. # this time enabling all the diagnostic output (this should fail again)
  576. result = semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  577. elif efNoUndeclared notin flags:
  578. notFoundError(c, n, errors)
  579. proc explicitGenericInstError(c: PContext; n: PNode): PNode =
  580. localError(c.config, getCallLineInfo(n), errCannotInstantiateX % renderTree(n))
  581. result = n
  582. proc explicitGenericSym(c: PContext, n: PNode, s: PSym): PNode =
  583. # binding has to stay 'nil' for this to work!
  584. var m = newCandidate(c, s, nil)
  585. for i in 1..<n.len:
  586. let formal = s.ast[genericParamsPos][i-1].typ
  587. var arg = n[i].typ
  588. # try transforming the argument into a static one before feeding it into
  589. # typeRel
  590. if formal.kind == tyStatic and arg.kind != tyStatic:
  591. let evaluated = c.semTryConstExpr(c, n[i])
  592. if evaluated != nil:
  593. arg = newTypeS(tyStatic, c)
  594. arg.sons = @[evaluated.typ]
  595. arg.n = evaluated
  596. let tm = typeRel(m, formal, arg)
  597. if tm in {isNone, isConvertible}: return nil
  598. var newInst = generateInstance(c, s, m.bindings, n.info)
  599. newInst.typ.flags.excl tfUnresolved
  600. let info = getCallLineInfo(n)
  601. markUsed(c, info, s)
  602. onUse(info, s)
  603. result = newSymNode(newInst, info)
  604. proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode =
  605. assert n.kind == nkBracketExpr
  606. for i in 1..<n.len:
  607. let e = semExprWithType(c, n[i])
  608. if e.typ == nil:
  609. n[i].typ = errorType(c)
  610. else:
  611. n[i].typ = e.typ.skipTypes({tyTypeDesc})
  612. var s = s
  613. var a = n[0]
  614. if a.kind == nkSym:
  615. # common case; check the only candidate has the right
  616. # number of generic type parameters:
  617. if s.ast[genericParamsPos].safeLen != n.len-1:
  618. let expected = s.ast[genericParamsPos].safeLen
  619. localError(c.config, getCallLineInfo(n), errGenerated, "cannot instantiate: '" & renderTree(n) &
  620. "'; got " & $(n.len-1) & " typeof(s) but expected " & $expected)
  621. return n
  622. result = explicitGenericSym(c, n, s)
  623. if result == nil: result = explicitGenericInstError(c, n)
  624. elif a.kind in {nkClosedSymChoice, nkOpenSymChoice}:
  625. # choose the generic proc with the proper number of type parameters.
  626. # XXX I think this could be improved by reusing sigmatch.paramTypesMatch.
  627. # It's good enough for now.
  628. result = newNodeI(a.kind, getCallLineInfo(n))
  629. for i in 0..<a.len:
  630. var candidate = a[i].sym
  631. if candidate.kind in {skProc, skMethod, skConverter,
  632. skFunc, skIterator}:
  633. # it suffices that the candidate has the proper number of generic
  634. # type parameters:
  635. if candidate.ast[genericParamsPos].safeLen == n.len-1:
  636. let x = explicitGenericSym(c, n, candidate)
  637. if x != nil: result.add(x)
  638. # get rid of nkClosedSymChoice if not ambiguous:
  639. if result.len == 1 and a.kind == nkClosedSymChoice:
  640. result = result[0]
  641. elif result.len == 0: result = explicitGenericInstError(c, n)
  642. # candidateCount != 1: return explicitGenericInstError(c, n)
  643. else:
  644. result = explicitGenericInstError(c, n)
  645. proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): PSym =
  646. # Searches for the fn in the symbol table. If the parameter lists are suitable
  647. # for borrowing the sym in the symbol table is returned, else nil.
  648. # New approach: generate fn(x, y, z) where x, y, z have the proper types
  649. # and use the overloading resolution mechanism:
  650. var call = newNodeI(nkCall, fn.info)
  651. var hasDistinct = false
  652. call.add(newIdentNode(fn.name, fn.info))
  653. for i in 1..<fn.typ.n.len:
  654. let param = fn.typ.n[i]
  655. const desiredTypes = abstractVar + {tyCompositeTypeClass} - {tyTypeDesc, tyDistinct}
  656. #[.
  657. # We only want the type not any modifiers such as `ptr`, `var`, `ref` ...
  658. # tyCompositeTypeClass is here for
  659. # when using something like:
  660. type Foo[T] = distinct int
  661. proc `$`(f: Foo): string {.borrow.}
  662. # We want to skip the `Foo` to get `int`
  663. ]#
  664. let t = skipTypes(param.typ, desiredTypes)
  665. if t.kind == tyDistinct or param.typ.kind == tyDistinct: hasDistinct = true
  666. var x: PType
  667. if param.typ.kind == tyVar:
  668. x = newTypeS(param.typ.kind, c)
  669. x.addSonSkipIntLit(t.baseOfDistinct(c.graph, c.idgen), c.idgen)
  670. else:
  671. x = t.baseOfDistinct(c.graph, c.idgen)
  672. call.add(newNodeIT(nkEmpty, fn.info, x))
  673. if hasDistinct:
  674. let filter = if fn.kind in {skProc, skFunc}: {skProc, skFunc} else: {fn.kind}
  675. var resolved = semOverloadedCall(c, call, call, filter, {})
  676. if resolved != nil:
  677. result = resolved[0].sym
  678. if not compareTypes(result.typ[0], fn.typ[0], dcEqIgnoreDistinct):
  679. result = nil
  680. elif result.magic in {mArrPut, mArrGet}:
  681. # cannot borrow these magics for now
  682. result = nil