semcall.nim 25 KB

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