semcall.nim 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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 std/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. ## puts all overloads into a seq and prepares best+alt
  41. result = @[]
  42. var symx = initOverloadIter(o, c, headSymbol)
  43. while symx != nil:
  44. if symx.kind in filter:
  45. result.add((symx, o.lastOverloadScope))
  46. elif symx.kind == skGenericParam:
  47. #[
  48. This code handles looking up a generic parameter when it's a static callable.
  49. For instance:
  50. proc name[T: static proc()]() = T()
  51. name[proc() = echo"hello"]()
  52. ]#
  53. for paramSym in searchInScopesAllCandidatesFilterBy(c, symx.name, {skConst}):
  54. let paramTyp = paramSym.typ
  55. if paramTyp.n.kind == nkSym and paramTyp.n.sym.kind in filter:
  56. result.add((paramTyp.n.sym, o.lastOverloadScope))
  57. symx = nextOverloadIter(o, c, headSymbol)
  58. if result.len > 0:
  59. best = initCandidate(c, result[0].s, initialBinding,
  60. result[0].scope, diagnostics)
  61. alt = initCandidate(c, result[0].s, initialBinding,
  62. result[0].scope, diagnostics)
  63. best.state = csNoMatch
  64. proc pickBestCandidate(c: PContext, headSymbol: PNode,
  65. n, orig: PNode,
  66. initialBinding: PNode,
  67. filter: TSymKinds,
  68. best, alt: var TCandidate,
  69. errors: var CandidateErrors,
  70. diagnosticsFlag: bool,
  71. errorsEnabled: bool, flags: TExprFlags) =
  72. # `matches` may find new symbols, so keep track of count
  73. var symCount = c.currentScope.symbols.counter
  74. var o: TOverloadIter = default(TOverloadIter)
  75. # https://github.com/nim-lang/Nim/issues/21272
  76. # prevent mutation during iteration by storing them in a seq
  77. # luckily `initCandidateSymbols` does just that
  78. var syms = initCandidateSymbols(c, headSymbol, initialBinding, filter,
  79. best, alt, o, diagnosticsFlag)
  80. if len(syms) == 0:
  81. return
  82. # current overload being considered
  83. var sym = syms[0].s
  84. var scope = syms[0].scope
  85. # starts at 1 because 0 is already done with setup, only needs checking
  86. var nextSymIndex = 1
  87. var z: TCandidate # current candidate
  88. while true:
  89. determineType(c, sym)
  90. z = initCandidate(c, sym, initialBinding, scope, diagnosticsFlag)
  91. # this is kinda backwards as without a check here the described
  92. # problems in recalc would not happen, but instead it 100%
  93. # does check forever in some cases
  94. if c.currentScope.symbols.counter == symCount:
  95. # may introduce new symbols with caveats described in recalc branch
  96. matches(c, n, orig, z)
  97. if z.state == csMatch:
  98. # little hack so that iterators are preferred over everything else:
  99. if sym.kind == skIterator:
  100. if not (efWantIterator notin flags and efWantIterable in flags):
  101. inc(z.exactMatches, 200)
  102. else:
  103. dec(z.exactMatches, 200)
  104. case best.state
  105. of csEmpty, csNoMatch: best = z
  106. of csMatch:
  107. var cmp = cmpCandidates(best, z)
  108. if cmp < 0: best = z # x is better than the best so far
  109. elif cmp == 0: alt = z # x is as good as the best so far
  110. elif errorsEnabled or z.diagnosticsEnabled:
  111. errors.add(CandidateError(
  112. sym: sym,
  113. firstMismatch: z.firstMismatch,
  114. diagnostics: z.diagnostics))
  115. else:
  116. # this branch feels like a ticking timebomb
  117. # one of two bad things could happen
  118. # 1) new symbols are discovered but the loop ends before we recalc
  119. # 2) new symbols are discovered and resemmed forever
  120. # not 100% sure if these are possible though as they would rely
  121. # on somehow introducing a new overload during overload resolution
  122. # Symbol table has been modified. Restart and pre-calculate all syms
  123. # before any further candidate init and compare. SLOW, but rare case.
  124. syms = initCandidateSymbols(c, headSymbol, initialBinding, filter,
  125. best, alt, o, diagnosticsFlag)
  126. # reset counter because syms may be in a new order
  127. symCount = c.currentScope.symbols.counter
  128. nextSymIndex = 0
  129. # just in case, should be impossible though
  130. if syms.len == 0:
  131. break
  132. if nextSymIndex > high(syms):
  133. # we have reached the end
  134. break
  135. # advance to next sym
  136. sym = syms[nextSymIndex].s
  137. scope = syms[nextSymIndex].scope
  138. inc(nextSymIndex)
  139. proc effectProblem(f, a: PType; result: var string; c: PContext) =
  140. if f.kind == tyProc and a.kind == tyProc:
  141. if tfThread in f.flags and tfThread notin a.flags:
  142. result.add "\n This expression is not GC-safe. Annotate the " &
  143. "proc with {.gcsafe.} to get extended error information."
  144. elif tfNoSideEffect in f.flags and tfNoSideEffect notin a.flags:
  145. result.add "\n This expression can have side effects. Annotate the " &
  146. "proc with {.noSideEffect.} to get extended error information."
  147. else:
  148. case compatibleEffects(f, a)
  149. of efCompat: discard
  150. of efRaisesDiffer:
  151. result.add "\n The `.raises` requirements differ."
  152. of efRaisesUnknown:
  153. result.add "\n The `.raises` requirements differ. Annotate the " &
  154. "proc with {.raises: [].} to get extended error information."
  155. of efTagsDiffer:
  156. result.add "\n The `.tags` requirements differ."
  157. of efTagsUnknown:
  158. result.add "\n The `.tags` requirements differ. Annotate the " &
  159. "proc with {.tags: [].} to get extended error information."
  160. of efEffectsDelayed:
  161. result.add "\n The `.effectsOf` annotations differ."
  162. of efTagsIllegal:
  163. result.add "\n The `.forbids` requirements caught an illegal tag."
  164. when defined(drnim):
  165. if not c.graph.compatibleProps(c.graph, f, a):
  166. result.add "\n The `.requires` or `.ensures` properties are incompatible."
  167. proc renderNotLValue(n: PNode): string =
  168. result = $n
  169. let n = if n.kind == nkHiddenDeref: n[0] else: n
  170. if n.kind == nkHiddenCallConv and n.len > 1:
  171. result = $n[0] & "(" & result & ")"
  172. elif n.kind in {nkHiddenStdConv, nkHiddenSubConv} and n.len == 2:
  173. result = typeToString(n.typ.skipTypes(abstractVar)) & "(" & result & ")"
  174. proc presentFailedCandidates(c: PContext, n: PNode, errors: CandidateErrors):
  175. (TPreferedDesc, string) =
  176. var prefer = preferName
  177. # to avoid confusing errors like:
  178. # got (SslPtr, SocketHandle)
  179. # but expected one of:
  180. # openssl.SSL_set_fd(ssl: SslPtr, fd: SocketHandle): cint
  181. # we do a pre-analysis. If all types produce the same string, we will add
  182. # module information.
  183. let proto = describeArgs(c, n, 1, preferName)
  184. for err in errors:
  185. var errProto = ""
  186. let n = err.sym.typ.n
  187. for i in 1..<n.len:
  188. var p = n[i]
  189. if p.kind == nkSym:
  190. errProto.add(typeToString(p.sym.typ, preferName))
  191. if i != n.len-1: errProto.add(", ")
  192. # else: ignore internal error as we're already in error handling mode
  193. if errProto == proto:
  194. prefer = preferModuleInfo
  195. break
  196. # we pretend procs are attached to the type of the first
  197. # argument in order to remove plenty of candidates. This is
  198. # comparable to what C# does and C# is doing fine.
  199. var filterOnlyFirst = false
  200. if optShowAllMismatches notin c.config.globalOptions and verboseTypeMismatch in c.config.legacyFeatures:
  201. for err in errors:
  202. if err.firstMismatch.arg > 1:
  203. filterOnlyFirst = true
  204. break
  205. var maybeWrongSpace = false
  206. var candidatesAll: seq[string] = @[]
  207. var candidates = ""
  208. var skipped = 0
  209. for err in errors:
  210. candidates.setLen 0
  211. if filterOnlyFirst and err.firstMismatch.arg == 1:
  212. inc skipped
  213. continue
  214. if verboseTypeMismatch notin c.config.legacyFeatures:
  215. candidates.add "[" & $err.firstMismatch.arg & "] "
  216. if err.sym.kind in routineKinds and err.sym.ast != nil:
  217. candidates.add(renderTree(err.sym.ast,
  218. {renderNoBody, renderNoComments, renderNoPragmas}))
  219. else:
  220. candidates.add(getProcHeader(c.config, err.sym, prefer))
  221. candidates.addDeclaredLocMaybe(c.config, err.sym)
  222. candidates.add("\n")
  223. let nArg = if err.firstMismatch.arg < n.len: n[err.firstMismatch.arg] else: nil
  224. let nameParam = if err.firstMismatch.formal != nil: err.firstMismatch.formal.name.s else: ""
  225. if n.len > 1:
  226. if verboseTypeMismatch notin c.config.legacyFeatures:
  227. case err.firstMismatch.kind
  228. of kUnknownNamedParam:
  229. if nArg == nil:
  230. candidates.add(" unknown named parameter")
  231. else:
  232. candidates.add(" unknown named parameter: " & $nArg[0])
  233. candidates.add "\n"
  234. of kAlreadyGiven:
  235. candidates.add(" named param already provided: " & $nArg[0])
  236. candidates.add "\n"
  237. of kPositionalAlreadyGiven:
  238. candidates.add(" positional param was already given as named param")
  239. candidates.add "\n"
  240. of kExtraArg:
  241. candidates.add(" extra argument given")
  242. candidates.add "\n"
  243. of kMissingParam:
  244. candidates.add(" missing parameter: " & nameParam)
  245. candidates.add "\n"
  246. of kVarNeeded:
  247. doAssert nArg != nil
  248. doAssert err.firstMismatch.formal != nil
  249. candidates.add " expression '"
  250. candidates.add renderNotLValue(nArg)
  251. candidates.add "' is immutable, not 'var'"
  252. candidates.add "\n"
  253. of kTypeMismatch:
  254. doAssert nArg != nil
  255. let wanted = err.firstMismatch.formal.typ
  256. doAssert err.firstMismatch.formal != nil
  257. doAssert wanted != nil
  258. let got = nArg.typ
  259. if got != nil and got.kind == tyProc and wanted.kind == tyProc:
  260. # These are proc mismatches so,
  261. # add the extra explict detail of the mismatch
  262. candidates.add " expression '"
  263. candidates.add renderTree(nArg)
  264. candidates.add "' is of type: "
  265. candidates.addTypeDeclVerboseMaybe(c.config, got)
  266. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  267. effectProblem(wanted, got, candidates, c)
  268. candidates.add "\n"
  269. of kUnknown: discard "do not break 'nim check'"
  270. else:
  271. candidates.add(" first type mismatch at position: " & $err.firstMismatch.arg)
  272. # candidates.add "\n reason: " & $err.firstMismatch.kind # for debugging
  273. case err.firstMismatch.kind
  274. of kUnknownNamedParam:
  275. if nArg == nil:
  276. candidates.add("\n unknown named parameter")
  277. else:
  278. candidates.add("\n unknown named parameter: " & $nArg[0])
  279. of kAlreadyGiven: candidates.add("\n named param already provided: " & $nArg[0])
  280. of kPositionalAlreadyGiven: candidates.add("\n positional param was already given as named param")
  281. of kExtraArg: candidates.add("\n extra argument given")
  282. of kMissingParam: candidates.add("\n missing parameter: " & nameParam)
  283. of kTypeMismatch, kVarNeeded:
  284. doAssert nArg != nil
  285. let wanted = err.firstMismatch.formal.typ
  286. doAssert err.firstMismatch.formal != nil
  287. candidates.add("\n required type for " & nameParam & ": ")
  288. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  289. candidates.add "\n but expression '"
  290. if err.firstMismatch.kind == kVarNeeded:
  291. candidates.add renderNotLValue(nArg)
  292. candidates.add "' is immutable, not 'var'"
  293. else:
  294. candidates.add renderTree(nArg)
  295. candidates.add "' is of type: "
  296. let got = nArg.typ
  297. candidates.addTypeDeclVerboseMaybe(c.config, got)
  298. doAssert wanted != nil
  299. if got != nil:
  300. if got.kind == tyProc and wanted.kind == tyProc:
  301. # These are proc mismatches so,
  302. # add the extra explict detail of the mismatch
  303. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  304. effectProblem(wanted, got, candidates, c)
  305. of kUnknown: discard "do not break 'nim check'"
  306. candidates.add "\n"
  307. if err.firstMismatch.arg == 1 and nArg.kind == nkTupleConstr and
  308. n.kind == nkCommand:
  309. maybeWrongSpace = true
  310. for diag in err.diagnostics:
  311. candidates.add(diag & "\n")
  312. candidatesAll.add candidates
  313. candidatesAll.sort # fix #13538
  314. candidates = join(candidatesAll)
  315. if skipped > 0:
  316. candidates.add($skipped & " other mismatching symbols have been " &
  317. "suppressed; compile with --showAllMismatches:on to see them\n")
  318. if maybeWrongSpace:
  319. candidates.add("maybe misplaced space between " & renderTree(n[0]) & " and '(' \n")
  320. result = (prefer, candidates)
  321. const
  322. errTypeMismatch = "type mismatch: got <"
  323. errButExpected = "but expected one of:"
  324. errExpectedPosition = "Expected one of (first mismatch at [position]):"
  325. errUndeclaredField = "undeclared field: '$1'"
  326. errUndeclaredRoutine = "attempting to call undeclared routine: '$1'"
  327. errBadRoutine = "attempting to call routine: '$1'$2"
  328. errAmbiguousCallXYZ = "ambiguous call; both $1 and $2 match for: $3"
  329. proc describeParamList(c: PContext, n: PNode, startIdx = 1; prefer = preferName): string =
  330. result = "Expression: " & $n
  331. for i in startIdx..<n.len:
  332. result.add "\n [" & $i & "] " & renderTree(n[i]) & ": "
  333. result.add describeArg(c, n, i, startIdx, prefer)
  334. result.add "\n"
  335. template legacynotFoundError(c: PContext, n: PNode, errors: CandidateErrors) =
  336. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  337. var result = errTypeMismatch
  338. result.add(describeArgs(c, n, 1, prefer))
  339. result.add('>')
  340. if candidates != "":
  341. result.add("\n" & errButExpected & "\n" & candidates)
  342. localError(c.config, n.info, result & "\nexpression: " & $n)
  343. proc notFoundError*(c: PContext, n: PNode, errors: CandidateErrors) =
  344. # Gives a detailed error message; this is separated from semOverloadedCall,
  345. # as semOverloadedCall is already pretty slow (and we need this information
  346. # only in case of an error).
  347. if c.config.m.errorOutputs == {}:
  348. # fail fast:
  349. globalError(c.config, n.info, "type mismatch")
  350. return
  351. # see getMsgDiagnostic:
  352. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  353. let ident = considerQuotedIdent(c, n[0], n).s
  354. let sym = n[1].typ.typSym
  355. var typeHint = ""
  356. if sym == nil:
  357. discard
  358. else:
  359. typeHint = " for type " & getProcHeader(c.config, sym)
  360. localError(c.config, n.info, errUndeclaredField % ident & typeHint)
  361. return
  362. if errors.len == 0:
  363. if n[0].kind in nkIdentKinds:
  364. let ident = considerQuotedIdent(c, n[0], n).s
  365. localError(c.config, n.info, errUndeclaredRoutine % ident)
  366. else:
  367. localError(c.config, n.info, "expression '$1' cannot be called" % n[0].renderTree)
  368. return
  369. if verboseTypeMismatch in c.config.legacyFeatures:
  370. legacynotFoundError(c, n, errors)
  371. else:
  372. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  373. var result = "type mismatch\n"
  374. result.add describeParamList(c, n, 1, prefer)
  375. if candidates != "":
  376. result.add("\n" & errExpectedPosition & "\n" & candidates)
  377. localError(c.config, n.info, result)
  378. proc bracketNotFoundError(c: PContext; n: PNode) =
  379. var errors: CandidateErrors = @[]
  380. var o: TOverloadIter = default(TOverloadIter)
  381. let headSymbol = n[0]
  382. var symx = initOverloadIter(o, c, headSymbol)
  383. while symx != nil:
  384. if symx.kind in routineKinds:
  385. errors.add(CandidateError(sym: symx,
  386. firstMismatch: MismatchInfo(),
  387. diagnostics: @[],
  388. enabled: false))
  389. symx = nextOverloadIter(o, c, headSymbol)
  390. if errors.len == 0:
  391. localError(c.config, n.info, "could not resolve: " & $n)
  392. else:
  393. notFoundError(c, n, errors)
  394. proc getMsgDiagnostic(c: PContext, flags: TExprFlags, n, f: PNode): string =
  395. result = ""
  396. if c.compilesContextId > 0:
  397. # we avoid running more diagnostic when inside a `compiles(expr)`, to
  398. # errors while running diagnostic (see test D20180828T234921), and
  399. # also avoid slowdowns in evaluating `compiles(expr)`.
  400. discard
  401. else:
  402. var o: TOverloadIter = default(TOverloadIter)
  403. var sym = initOverloadIter(o, c, f)
  404. while sym != nil:
  405. result &= "\n found $1" % [getSymRepr(c.config, sym)]
  406. sym = nextOverloadIter(o, c, f)
  407. let ident = considerQuotedIdent(c, f, n).s
  408. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  409. let sym = n[1].typ.typSym
  410. var typeHint = ""
  411. if sym == nil:
  412. # Perhaps we're in a `compiles(foo.bar)` expression, or
  413. # in a concept, e.g.:
  414. # ExplainedConcept {.explain.} = concept x
  415. # x.foo is int
  416. # We could use: `(c.config $ n[1].info)` to get more context.
  417. discard
  418. else:
  419. typeHint = " for type " & getProcHeader(c.config, sym)
  420. let suffix = if result.len > 0: " " & result else: ""
  421. result = errUndeclaredField % ident & typeHint & suffix
  422. else:
  423. if result.len == 0: result = errUndeclaredRoutine % ident
  424. else: result = errBadRoutine % [ident, result]
  425. proc resolveOverloads(c: PContext, n, orig: PNode,
  426. filter: TSymKinds, flags: TExprFlags,
  427. errors: var CandidateErrors,
  428. errorsEnabled: bool): TCandidate =
  429. result = default(TCandidate)
  430. var initialBinding: PNode
  431. var alt: TCandidate = default(TCandidate)
  432. var f = n[0]
  433. if f.kind == nkBracketExpr:
  434. # fill in the bindings:
  435. semOpAux(c, f)
  436. initialBinding = f
  437. f = f[0]
  438. else:
  439. initialBinding = nil
  440. pickBestCandidate(c, f, n, orig, initialBinding,
  441. filter, result, alt, errors, efExplain in flags,
  442. errorsEnabled, flags)
  443. var dummyErrors: CandidateErrors = @[]
  444. template pickSpecialOp(headSymbol) =
  445. pickBestCandidate(c, headSymbol, n, orig, initialBinding,
  446. filter, result, alt, dummyErrors, efExplain in flags,
  447. false, flags)
  448. let overloadsState = result.state
  449. if overloadsState != csMatch:
  450. if nfDotField in n.flags:
  451. internalAssert c.config, f.kind == nkIdent and n.len >= 2
  452. # leave the op head symbol empty,
  453. # we are going to try multiple variants
  454. n.sons[0..1] = [nil, n[1], f]
  455. orig.sons[0..1] = [nil, orig[1], f]
  456. template tryOp(x) =
  457. let op = newIdentNode(getIdent(c.cache, x), n.info)
  458. n[0] = op
  459. orig[0] = op
  460. pickSpecialOp(op)
  461. if nfExplicitCall in n.flags:
  462. tryOp ".()"
  463. if result.state in {csEmpty, csNoMatch}:
  464. tryOp "."
  465. elif nfDotSetter in n.flags and f.kind == nkIdent and n.len == 3:
  466. # we need to strip away the trailing '=' here:
  467. let calleeName = newIdentNode(getIdent(c.cache, f.ident.s[0..^2]), n.info)
  468. let callOp = newIdentNode(getIdent(c.cache, ".="), n.info)
  469. n.sons[0..1] = [callOp, n[1], calleeName]
  470. orig.sons[0..1] = [callOp, orig[1], calleeName]
  471. pickSpecialOp(callOp)
  472. if overloadsState == csEmpty and result.state == csEmpty:
  473. if efNoUndeclared notin flags: # for tests/pragmas/tcustom_pragma.nim
  474. result.state = csNoMatch
  475. if efNoDiagnostics in flags:
  476. return
  477. # xxx adapt/use errorUndeclaredIdentifierHint(c, n, f.ident)
  478. localError(c.config, n.info, getMsgDiagnostic(c, flags, n, f))
  479. return
  480. elif result.state != csMatch:
  481. if nfExprCall in n.flags:
  482. localError(c.config, n.info, "expression '$1' cannot be called" %
  483. renderTree(n, {renderNoComments}))
  484. else:
  485. if {nfDotField, nfDotSetter} * n.flags != {}:
  486. # clean up the inserted ops
  487. n.sons.delete(2)
  488. n[0] = f
  489. return
  490. if alt.state == csMatch and cmpCandidates(result, alt) == 0 and
  491. not sameMethodDispatcher(result.calleeSym, alt.calleeSym):
  492. internalAssert c.config, result.state == csMatch
  493. #writeMatches(result)
  494. #writeMatches(alt)
  495. if c.config.m.errorOutputs == {}:
  496. # quick error message for performance of 'compiles' built-in:
  497. globalError(c.config, n.info, errGenerated, "ambiguous call")
  498. elif c.config.errorCounter == 0:
  499. # don't cascade errors
  500. var args = "("
  501. for i in 1..<n.len:
  502. if i > 1: args.add(", ")
  503. args.add(typeToString(n[i].typ))
  504. args.add(")")
  505. localError(c.config, n.info, errAmbiguousCallXYZ % [
  506. getProcHeader(c.config, result.calleeSym),
  507. getProcHeader(c.config, alt.calleeSym),
  508. args])
  509. proc instGenericConvertersArg*(c: PContext, a: PNode, x: TCandidate) =
  510. let a = if a.kind == nkHiddenDeref: a[0] else: a
  511. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  512. let s = a[0].sym
  513. if s.isGenericRoutineStrict:
  514. let finalCallee = generateInstance(c, s, x.bindings, a.info)
  515. a[0].sym = finalCallee
  516. a[0].typ = finalCallee.typ
  517. #a.typ = finalCallee.typ.returnType
  518. proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) =
  519. assert n.kind in nkCallKinds
  520. if x.genericConverter:
  521. for i in 1..<n.len:
  522. instGenericConvertersArg(c, n[i], x)
  523. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode =
  524. var m = newCandidate(c, f)
  525. result = paramTypesMatch(m, f, a, arg, nil)
  526. if m.genericConverter and result != nil:
  527. instGenericConvertersArg(c, result, m)
  528. proc inferWithMetatype(c: PContext, formal: PType,
  529. arg: PNode, coerceDistincts = false): PNode =
  530. var m = newCandidate(c, formal)
  531. m.coerceDistincts = coerceDistincts
  532. result = paramTypesMatch(m, formal, arg.typ, arg, nil)
  533. if m.genericConverter and result != nil:
  534. instGenericConvertersArg(c, result, m)
  535. if result != nil:
  536. # This almost exactly replicates the steps taken by the compiler during
  537. # param matching. It performs an embarrassing amount of back-and-forth
  538. # type jugling, but it's the price to pay for consistency and correctness
  539. result.typ = generateTypeInstance(c, m.bindings, arg.info,
  540. formal.skipTypes({tyCompositeTypeClass}))
  541. else:
  542. typeMismatch(c.config, arg.info, formal, arg.typ, arg)
  543. # error correction:
  544. result = copyTree(arg)
  545. result.typ = formal
  546. proc updateDefaultParams(call: PNode) =
  547. # In generic procs, the default parameter may be unique for each
  548. # instantiation (see tlateboundgenericparams).
  549. # After a call is resolved, we need to re-assign any default value
  550. # that was used during sigmatch. sigmatch is responsible for marking
  551. # the default params with `nfDefaultParam` and `instantiateProcType`
  552. # computes correctly the default values for each instantiation.
  553. let calleeParams = call[0].sym.typ.n
  554. for i in 1..<call.len:
  555. if nfDefaultParam in call[i].flags:
  556. let def = calleeParams[i].sym.ast
  557. if nfDefaultRefsParam in def.flags: call.flags.incl nfDefaultRefsParam
  558. call[i] = def
  559. proc getCallLineInfo(n: PNode): TLineInfo =
  560. case n.kind
  561. of nkAccQuoted, nkBracketExpr, nkCall, nkCallStrLit, nkCommand:
  562. if len(n) > 0:
  563. return getCallLineInfo(n[0])
  564. of nkDotExpr:
  565. if len(n) > 1:
  566. return getCallLineInfo(n[1])
  567. else:
  568. discard
  569. result = n.info
  570. proc inheritBindings(c: PContext, x: var TCandidate, expectedType: PType) =
  571. ## Helper proc to inherit bound generic parameters from expectedType into x.
  572. ## Does nothing if 'inferGenericTypes' isn't in c.features.
  573. if inferGenericTypes notin c.features: return
  574. if expectedType == nil or x.callee.returnType == nil: return # required for inference
  575. var
  576. flatUnbound: seq[PType] = @[]
  577. flatBound: seq[PType] = @[]
  578. # seq[(result type, expected type)]
  579. var typeStack = newSeq[(PType, PType)]()
  580. template stackPut(a, b) =
  581. ## skips types and puts the skipped version on stack
  582. # It might make sense to skip here one by one. It's not part of the main
  583. # type reduction because the right side normally won't be skipped
  584. const toSkip = {tyVar, tyLent, tyStatic, tyCompositeTypeClass, tySink}
  585. let
  586. x = a.skipTypes(toSkip)
  587. y = if a.kind notin toSkip: b
  588. else: b.skipTypes(toSkip)
  589. typeStack.add((x, y))
  590. stackPut(x.callee.returnType, expectedType)
  591. while typeStack.len() > 0:
  592. let (t, u) = typeStack.pop()
  593. if t == u or t == nil or u == nil or t.kind == tyAnything or u.kind == tyAnything:
  594. continue
  595. case t.kind
  596. of ConcreteTypes, tyGenericInvocation, tyUncheckedArray:
  597. # XXX This logic makes no sense for `tyUncheckedArray`
  598. # nested, add all the types to stack
  599. let
  600. startIdx = if u.kind in ConcreteTypes: 0 else: 1
  601. endIdx = min(u.kidsLen() - startIdx, t.kidsLen())
  602. for i in startIdx ..< endIdx:
  603. # early exit with current impl
  604. if t[i] == nil or u[i] == nil: return
  605. stackPut(t[i], u[i])
  606. of tyGenericParam:
  607. let prebound = x.bindings.idTableGet(t)
  608. if prebound != nil:
  609. continue # Skip param, already bound
  610. # fully reduced generic param, bind it
  611. if t notin flatUnbound:
  612. flatUnbound.add(t)
  613. flatBound.add(u)
  614. else:
  615. discard
  616. # update bindings
  617. for i in 0 ..< flatUnbound.len():
  618. x.bindings.idTablePut(flatUnbound[i], flatBound[i])
  619. proc semResolvedCall(c: PContext, x: var TCandidate,
  620. n: PNode, flags: TExprFlags;
  621. expectedType: PType = nil): PNode =
  622. assert x.state == csMatch
  623. var finalCallee = x.calleeSym
  624. let info = getCallLineInfo(n)
  625. markUsed(c, info, finalCallee)
  626. onUse(info, finalCallee)
  627. assert finalCallee.ast != nil
  628. if x.hasFauxMatch:
  629. result = x.call
  630. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  631. if containsGenericType(result.typ) or x.fauxMatch == tyUnknown:
  632. result.typ = newTypeS(x.fauxMatch, c)
  633. if result.typ.kind == tyError: incl result.typ.flags, tfCheckedForDestructor
  634. return
  635. let gp = finalCallee.ast[genericParamsPos]
  636. if gp.isGenericParams:
  637. if x.calleeSym.kind notin {skMacro, skTemplate}:
  638. if x.calleeSym.magic in {mArrGet, mArrPut}:
  639. finalCallee = x.calleeSym
  640. else:
  641. c.inheritBindings(x, expectedType)
  642. finalCallee = generateInstance(c, x.calleeSym, x.bindings, n.info)
  643. else:
  644. # For macros and templates, the resolved generic params
  645. # are added as normal params.
  646. c.inheritBindings(x, expectedType)
  647. for s in instantiateGenericParamList(c, gp, x.bindings):
  648. case s.kind
  649. of skConst:
  650. if not s.astdef.isNil:
  651. x.call.add s.astdef
  652. else:
  653. x.call.add c.graph.emptyNode
  654. of skType:
  655. var tn = newSymNode(s, n.info)
  656. # this node will be used in template substitution,
  657. # pretend this is an untyped node and let regular sem handle the type
  658. # to prevent problems where a generic parameter is treated as a value
  659. tn.typ = nil
  660. x.call.add tn
  661. else:
  662. internalAssert c.config, false
  663. result = x.call
  664. instGenericConvertersSons(c, result, x)
  665. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  666. result.typ = finalCallee.typ.returnType
  667. updateDefaultParams(result)
  668. proc canDeref(n: PNode): bool {.inline.} =
  669. result = n.len >= 2 and (let t = n[1].typ;
  670. t != nil and t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyPtr, tyRef})
  671. proc tryDeref(n: PNode): PNode =
  672. result = newNodeI(nkHiddenDeref, n.info)
  673. result.typ = n.typ.skipTypes(abstractInst)[0]
  674. result.add n
  675. proc semOverloadedCall(c: PContext, n, nOrig: PNode,
  676. filter: TSymKinds, flags: TExprFlags;
  677. expectedType: PType = nil): PNode =
  678. var errors: CandidateErrors = @[] # if efExplain in flags: @[] else: nil
  679. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  680. if r.state == csMatch:
  681. # this may be triggered, when the explain pragma is used
  682. if errors.len > 0:
  683. let (_, candidates) = presentFailedCandidates(c, n, errors)
  684. message(c.config, n.info, hintUserRaw,
  685. "Non-matching candidates for " & renderTree(n) & "\n" &
  686. candidates)
  687. result = semResolvedCall(c, r, n, flags, expectedType)
  688. else:
  689. if efDetermineType in flags and c.inGenericContext > 0 and c.matchedConcept == nil:
  690. result = semGenericStmt(c, n)
  691. result.typ = makeTypeFromExpr(c, result.copyTree)
  692. elif efExplain notin flags:
  693. # repeat the overload resolution,
  694. # this time enabling all the diagnostic output (this should fail again)
  695. result = semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  696. elif efNoUndeclared notin flags:
  697. result = nil
  698. notFoundError(c, n, errors)
  699. else:
  700. result = nil
  701. proc explicitGenericInstError(c: PContext; n: PNode): PNode =
  702. localError(c.config, getCallLineInfo(n), errCannotInstantiateX % renderTree(n))
  703. result = n
  704. proc explicitGenericSym(c: PContext, n: PNode, s: PSym): PNode =
  705. # binding has to stay 'nil' for this to work!
  706. var m = newCandidate(c, s, nil)
  707. for i in 1..<n.len:
  708. let formal = s.ast[genericParamsPos][i-1].typ
  709. var arg = n[i].typ
  710. # try transforming the argument into a static one before feeding it into
  711. # typeRel
  712. if formal.kind == tyStatic and arg.kind != tyStatic:
  713. let evaluated = c.semTryConstExpr(c, n[i], n[i].typ)
  714. if evaluated != nil:
  715. arg = newTypeS(tyStatic, c, son = evaluated.typ)
  716. arg.n = evaluated
  717. let tm = typeRel(m, formal, arg)
  718. if tm in {isNone, isConvertible}: return nil
  719. var newInst = generateInstance(c, s, m.bindings, n.info)
  720. newInst.typ.flags.excl tfUnresolved
  721. let info = getCallLineInfo(n)
  722. markUsed(c, info, s)
  723. onUse(info, s)
  724. result = newSymNode(newInst, info)
  725. proc setGenericParams(c: PContext, n, expectedParams: PNode) =
  726. ## sems generic params in subscript expression
  727. for i in 1..<n.len:
  728. let
  729. constraint =
  730. if expectedParams != nil and i <= expectedParams.len:
  731. expectedParams[i - 1].typ
  732. else:
  733. nil
  734. e = semExprWithType(c, n[i], expectedType = constraint)
  735. if e.typ == nil:
  736. n[i].typ = errorType(c)
  737. else:
  738. n[i].typ = e.typ.skipTypes({tyTypeDesc})
  739. proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode =
  740. assert n.kind == nkBracketExpr
  741. setGenericParams(c, n, s.ast[genericParamsPos])
  742. var s = s
  743. var a = n[0]
  744. if a.kind == nkSym:
  745. # common case; check the only candidate has the right
  746. # number of generic type parameters:
  747. if s.ast[genericParamsPos].safeLen != n.len-1:
  748. let expected = s.ast[genericParamsPos].safeLen
  749. localError(c.config, getCallLineInfo(n), errGenerated, "cannot instantiate: '" & renderTree(n) &
  750. "'; got " & $(n.len-1) & " typeof(s) but expected " & $expected)
  751. return n
  752. result = explicitGenericSym(c, n, s)
  753. if result == nil: result = explicitGenericInstError(c, n)
  754. elif a.kind in {nkClosedSymChoice, nkOpenSymChoice}:
  755. # choose the generic proc with the proper number of type parameters.
  756. # XXX I think this could be improved by reusing sigmatch.paramTypesMatch.
  757. # It's good enough for now.
  758. result = newNodeI(a.kind, getCallLineInfo(n))
  759. for i in 0..<a.len:
  760. var candidate = a[i].sym
  761. if candidate.kind in {skProc, skMethod, skConverter,
  762. skFunc, skIterator}:
  763. # it suffices that the candidate has the proper number of generic
  764. # type parameters:
  765. if candidate.ast[genericParamsPos].safeLen == n.len-1:
  766. let x = explicitGenericSym(c, n, candidate)
  767. if x != nil: result.add(x)
  768. # get rid of nkClosedSymChoice if not ambiguous:
  769. if result.len == 1 and a.kind == nkClosedSymChoice:
  770. result = result[0]
  771. elif result.len == 0: result = explicitGenericInstError(c, n)
  772. # candidateCount != 1: return explicitGenericInstError(c, n)
  773. else:
  774. result = explicitGenericInstError(c, n)
  775. proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): tuple[s: PSym, state: TBorrowState] =
  776. # Searches for the fn in the symbol table. If the parameter lists are suitable
  777. # for borrowing the sym in the symbol table is returned, else nil.
  778. # New approach: generate fn(x, y, z) where x, y, z have the proper types
  779. # and use the overloading resolution mechanism:
  780. const desiredTypes = abstractVar + {tyCompositeTypeClass} - {tyTypeDesc, tyDistinct}
  781. template getType(isDistinct: bool; t: PType):untyped =
  782. if isDistinct: t.baseOfDistinct(c.graph, c.idgen) else: t
  783. result = default(tuple[s: PSym, state: TBorrowState])
  784. var call = newNodeI(nkCall, fn.info)
  785. var hasDistinct = false
  786. var isDistinct: bool
  787. var x: PType
  788. var t: PType
  789. call.add(newIdentNode(fn.name, fn.info))
  790. for i in 1..<fn.typ.n.len:
  791. let param = fn.typ.n[i]
  792. #[.
  793. # We only want the type not any modifiers such as `ptr`, `var`, `ref` ...
  794. # tyCompositeTypeClass is here for
  795. # when using something like:
  796. type Foo[T] = distinct int
  797. proc `$`(f: Foo): string {.borrow.}
  798. # We want to skip the `Foo` to get `int`
  799. ]#
  800. t = skipTypes(param.typ, desiredTypes)
  801. isDistinct = t.kind == tyDistinct or param.typ.kind == tyDistinct
  802. if t.kind == tyGenericInvocation and t.genericHead.last.kind == tyDistinct:
  803. result.state = bsGeneric
  804. return
  805. if isDistinct: hasDistinct = true
  806. if param.typ.kind == tyVar:
  807. x = newTypeS(param.typ.kind, c)
  808. x.addSonSkipIntLit(getType(isDistinct, t), c.idgen)
  809. else:
  810. x = getType(isDistinct, t)
  811. var s = copySym(param.sym, c.idgen)
  812. s.typ = x
  813. s.info = param.info
  814. call.add(newSymNode(s))
  815. if hasDistinct:
  816. let filter = if fn.kind in {skProc, skFunc}: {skProc, skFunc} else: {fn.kind}
  817. var resolved = semOverloadedCall(c, call, call, filter, {})
  818. if resolved != nil:
  819. result.s = resolved[0].sym
  820. result.state = bsMatch
  821. if not compareTypes(result.s.typ.returnType, fn.typ.returnType, dcEqIgnoreDistinct, {IgnoreFlags}):
  822. result.state = bsReturnNotMatch
  823. elif result.s.magic in {mArrPut, mArrGet}:
  824. # cannot borrow these magics for now
  825. result.state = bsNotSupported
  826. else:
  827. result.state = bsNoDistinct