semcall.nim 33 KB

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