semcall.nim 30 KB

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