semcall.nim 26 KB

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