semcall.nim 27 KB

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