semcall.nim 26 KB

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