semcall.nim 29 KB

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