semcall.nim 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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. best = initCandidate(c, result[0].s, initialBinding,
  49. result[0].scope, diagnostics)
  50. alt = initCandidate(c, 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
  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. z = initCandidate(c, 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 and verboseTypeMismatch in c.config.legacyFeatures:
  215. candidates.add(" first type mismatch at position: " & $err.firstMismatch.arg)
  216. # candidates.add "\n reason: " & $err.firstMismatch.kind # for debugging
  217. case err.firstMismatch.kind
  218. of kUnknownNamedParam:
  219. if nArg == nil:
  220. candidates.add("\n unknown named parameter")
  221. else:
  222. candidates.add("\n unknown named parameter: " & $nArg[0])
  223. of kAlreadyGiven: candidates.add("\n named param already provided: " & $nArg[0])
  224. of kPositionalAlreadyGiven: candidates.add("\n positional param was already given as named param")
  225. of kExtraArg: candidates.add("\n extra argument given")
  226. of kMissingParam: candidates.add("\n missing parameter: " & nameParam)
  227. of kTypeMismatch, kVarNeeded:
  228. doAssert nArg != nil
  229. let wanted = err.firstMismatch.formal.typ
  230. doAssert err.firstMismatch.formal != nil
  231. candidates.add("\n required type for " & nameParam & ": ")
  232. candidates.addTypeDeclVerboseMaybe(c.config, wanted)
  233. candidates.add "\n but expression '"
  234. if err.firstMismatch.kind == kVarNeeded:
  235. candidates.add renderNotLValue(nArg)
  236. candidates.add "' is immutable, not 'var'"
  237. else:
  238. candidates.add renderTree(nArg)
  239. candidates.add "' is of type: "
  240. let got = nArg.typ
  241. candidates.addTypeDeclVerboseMaybe(c.config, got)
  242. doAssert wanted != nil
  243. if got != nil:
  244. if got.kind == tyProc and wanted.kind == tyProc:
  245. # These are proc mismatches so,
  246. # add the extra explict detail of the mismatch
  247. candidates.addPragmaAndCallConvMismatch(wanted, got, c.config)
  248. effectProblem(wanted, got, candidates, c)
  249. of kUnknown: discard "do not break 'nim check'"
  250. candidates.add "\n"
  251. if err.firstMismatch.arg == 1 and nArg.kind == nkTupleConstr and
  252. n.kind == nkCommand:
  253. maybeWrongSpace = true
  254. for diag in err.diagnostics:
  255. candidates.add(diag & "\n")
  256. candidatesAll.add candidates
  257. candidatesAll.sort # fix #13538
  258. candidates = join(candidatesAll)
  259. if skipped > 0:
  260. candidates.add($skipped & " other mismatching symbols have been " &
  261. "suppressed; compile with --showAllMismatches:on to see them\n")
  262. if maybeWrongSpace:
  263. candidates.add("maybe misplaced space between " & renderTree(n[0]) & " and '(' \n")
  264. result = (prefer, candidates)
  265. const
  266. errTypeMismatch = "type mismatch: got <"
  267. errButExpected = "but expected one of:"
  268. errExpectedPosition = "Expected one of (first mismatch at [position]):"
  269. errUndeclaredField = "undeclared field: '$1'"
  270. errUndeclaredRoutine = "attempting to call undeclared routine: '$1'"
  271. errBadRoutine = "attempting to call routine: '$1'$2"
  272. errAmbiguousCallXYZ = "ambiguous call; both $1 and $2 match for: $3"
  273. proc describeParamList(c: PContext, n: PNode, startIdx = 1; prefer = preferName): string =
  274. result = "Expression: " & $n
  275. for i in startIdx..<n.len:
  276. result.add "\n [" & $i & "] " & renderTree(n[i]) & ": "
  277. result.add describeArg(c, n, i, startIdx, prefer)
  278. result.add "\n"
  279. template legacynotFoundError(c: PContext, n: PNode, errors: CandidateErrors) =
  280. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  281. var result = errTypeMismatch
  282. result.add(describeArgs(c, n, 1, prefer))
  283. result.add('>')
  284. if candidates != "":
  285. result.add("\n" & errButExpected & "\n" & candidates)
  286. localError(c.config, n.info, result & "\nexpression: " & $n)
  287. proc notFoundError*(c: PContext, n: PNode, errors: CandidateErrors) =
  288. # Gives a detailed error message; this is separated from semOverloadedCall,
  289. # as semOverloadedCall is already pretty slow (and we need this information
  290. # only in case of an error).
  291. if c.config.m.errorOutputs == {}:
  292. # fail fast:
  293. globalError(c.config, n.info, "type mismatch")
  294. return
  295. # see getMsgDiagnostic:
  296. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  297. let ident = considerQuotedIdent(c, n[0], n).s
  298. let sym = n[1].typ.typSym
  299. var typeHint = ""
  300. if sym == nil:
  301. discard
  302. else:
  303. typeHint = " for type " & getProcHeader(c.config, sym)
  304. localError(c.config, n.info, errUndeclaredField % ident & typeHint)
  305. return
  306. if errors.len == 0:
  307. if n[0].kind in nkIdentKinds:
  308. let ident = considerQuotedIdent(c, n[0], n).s
  309. localError(c.config, n.info, errUndeclaredRoutine % ident)
  310. else:
  311. localError(c.config, n.info, "expression '$1' cannot be called" % n[0].renderTree)
  312. return
  313. if verboseTypeMismatch in c.config.legacyFeatures:
  314. legacynotFoundError(c, n, errors)
  315. else:
  316. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  317. var result = "type mismatch\n"
  318. result.add describeParamList(c, n, 1, prefer)
  319. if candidates != "":
  320. result.add("\n" & errExpectedPosition & "\n" & candidates)
  321. localError(c.config, n.info, result)
  322. proc bracketNotFoundError(c: PContext; n: PNode) =
  323. var errors: CandidateErrors = @[]
  324. var o: TOverloadIter
  325. let headSymbol = n[0]
  326. var symx = initOverloadIter(o, c, headSymbol)
  327. while symx != nil:
  328. if symx.kind in routineKinds:
  329. errors.add(CandidateError(sym: symx,
  330. firstMismatch: MismatchInfo(),
  331. diagnostics: @[],
  332. enabled: false))
  333. symx = nextOverloadIter(o, c, headSymbol)
  334. if errors.len == 0:
  335. localError(c.config, n.info, "could not resolve: " & $n)
  336. else:
  337. notFoundError(c, n, errors)
  338. proc getMsgDiagnostic(c: PContext, flags: TExprFlags, n, f: PNode): string =
  339. result = ""
  340. if c.compilesContextId > 0:
  341. # we avoid running more diagnostic when inside a `compiles(expr)`, to
  342. # errors while running diagnostic (see test D20180828T234921), and
  343. # also avoid slowdowns in evaluating `compiles(expr)`.
  344. discard
  345. else:
  346. var o: TOverloadIter
  347. var sym = initOverloadIter(o, c, f)
  348. while sym != nil:
  349. result &= "\n found $1" % [getSymRepr(c.config, sym)]
  350. sym = nextOverloadIter(o, c, f)
  351. let ident = considerQuotedIdent(c, f, n).s
  352. if nfExplicitCall notin n.flags and {nfDotField, nfDotSetter} * n.flags != {}:
  353. let sym = n[1].typ.typSym
  354. var typeHint = ""
  355. if sym == nil:
  356. # Perhaps we're in a `compiles(foo.bar)` expression, or
  357. # in a concept, e.g.:
  358. # ExplainedConcept {.explain.} = concept x
  359. # x.foo is int
  360. # We could use: `(c.config $ n[1].info)` to get more context.
  361. discard
  362. else:
  363. typeHint = " for type " & getProcHeader(c.config, sym)
  364. let suffix = if result.len > 0: " " & result else: ""
  365. result = errUndeclaredField % ident & typeHint & suffix
  366. else:
  367. if result.len == 0: result = errUndeclaredRoutine % ident
  368. else: result = errBadRoutine % [ident, result]
  369. proc resolveOverloads(c: PContext, n, orig: PNode,
  370. filter: TSymKinds, flags: TExprFlags,
  371. errors: var CandidateErrors,
  372. errorsEnabled: bool): TCandidate =
  373. result = default(TCandidate)
  374. var initialBinding: PNode
  375. var alt: TCandidate = default(TCandidate)
  376. var f = n[0]
  377. if f.kind == nkBracketExpr:
  378. # fill in the bindings:
  379. semOpAux(c, f)
  380. initialBinding = f
  381. f = f[0]
  382. else:
  383. initialBinding = nil
  384. pickBestCandidate(c, f, n, orig, initialBinding,
  385. filter, result, alt, errors, efExplain in flags,
  386. errorsEnabled, flags)
  387. var dummyErrors: CandidateErrors
  388. template pickSpecialOp(headSymbol) =
  389. pickBestCandidate(c, headSymbol, n, orig, initialBinding,
  390. filter, result, alt, dummyErrors, efExplain in flags,
  391. false, flags)
  392. let overloadsState = result.state
  393. if overloadsState != csMatch:
  394. if nfDotField in n.flags:
  395. internalAssert c.config, f.kind == nkIdent and n.len >= 2
  396. # leave the op head symbol empty,
  397. # we are going to try multiple variants
  398. n.sons[0..1] = [nil, n[1], f]
  399. orig.sons[0..1] = [nil, orig[1], f]
  400. template tryOp(x) =
  401. let op = newIdentNode(getIdent(c.cache, x), n.info)
  402. n[0] = op
  403. orig[0] = op
  404. pickSpecialOp(op)
  405. if nfExplicitCall in n.flags:
  406. tryOp ".()"
  407. if result.state in {csEmpty, csNoMatch}:
  408. tryOp "."
  409. elif nfDotSetter in n.flags and f.kind == nkIdent and n.len == 3:
  410. # we need to strip away the trailing '=' here:
  411. let calleeName = newIdentNode(getIdent(c.cache, f.ident.s[0..^2]), n.info)
  412. let callOp = newIdentNode(getIdent(c.cache, ".="), n.info)
  413. n.sons[0..1] = [callOp, n[1], calleeName]
  414. orig.sons[0..1] = [callOp, orig[1], calleeName]
  415. pickSpecialOp(callOp)
  416. if overloadsState == csEmpty and result.state == csEmpty:
  417. if efNoUndeclared notin flags: # for tests/pragmas/tcustom_pragma.nim
  418. result.state = csNoMatch
  419. if efNoDiagnostics in flags:
  420. return
  421. # xxx adapt/use errorUndeclaredIdentifierHint(c, n, f.ident)
  422. localError(c.config, n.info, getMsgDiagnostic(c, flags, n, f))
  423. return
  424. elif result.state != csMatch:
  425. if nfExprCall in n.flags:
  426. localError(c.config, n.info, "expression '$1' cannot be called" %
  427. renderTree(n, {renderNoComments}))
  428. else:
  429. if {nfDotField, nfDotSetter} * n.flags != {}:
  430. # clean up the inserted ops
  431. n.sons.delete(2)
  432. n[0] = f
  433. return
  434. if alt.state == csMatch and cmpCandidates(result, alt) == 0 and
  435. not sameMethodDispatcher(result.calleeSym, alt.calleeSym):
  436. internalAssert c.config, result.state == csMatch
  437. #writeMatches(result)
  438. #writeMatches(alt)
  439. if c.config.m.errorOutputs == {}:
  440. # quick error message for performance of 'compiles' built-in:
  441. globalError(c.config, n.info, errGenerated, "ambiguous call")
  442. elif c.config.errorCounter == 0:
  443. # don't cascade errors
  444. var args = "("
  445. for i in 1..<n.len:
  446. if i > 1: args.add(", ")
  447. args.add(typeToString(n[i].typ))
  448. args.add(")")
  449. localError(c.config, n.info, errAmbiguousCallXYZ % [
  450. getProcHeader(c.config, result.calleeSym),
  451. getProcHeader(c.config, alt.calleeSym),
  452. args])
  453. proc instGenericConvertersArg*(c: PContext, a: PNode, x: TCandidate) =
  454. let a = if a.kind == nkHiddenDeref: a[0] else: a
  455. if a.kind == nkHiddenCallConv and a[0].kind == nkSym:
  456. let s = a[0].sym
  457. if s.isGenericRoutineStrict:
  458. let finalCallee = generateInstance(c, s, x.bindings, a.info)
  459. a[0].sym = finalCallee
  460. a[0].typ = finalCallee.typ
  461. #a.typ = finalCallee.typ[0]
  462. proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) =
  463. assert n.kind in nkCallKinds
  464. if x.genericConverter:
  465. for i in 1..<n.len:
  466. instGenericConvertersArg(c, n[i], x)
  467. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode =
  468. var m = newCandidate(c, f)
  469. result = paramTypesMatch(m, f, a, arg, nil)
  470. if m.genericConverter and result != nil:
  471. instGenericConvertersArg(c, result, m)
  472. proc inferWithMetatype(c: PContext, formal: PType,
  473. arg: PNode, coerceDistincts = false): PNode =
  474. var m = newCandidate(c, formal)
  475. m.coerceDistincts = coerceDistincts
  476. result = paramTypesMatch(m, formal, arg.typ, arg, nil)
  477. if m.genericConverter and result != nil:
  478. instGenericConvertersArg(c, result, m)
  479. if result != nil:
  480. # This almost exactly replicates the steps taken by the compiler during
  481. # param matching. It performs an embarrassing amount of back-and-forth
  482. # type jugling, but it's the price to pay for consistency and correctness
  483. result.typ = generateTypeInstance(c, m.bindings, arg.info,
  484. formal.skipTypes({tyCompositeTypeClass}))
  485. else:
  486. typeMismatch(c.config, arg.info, formal, arg.typ, arg)
  487. # error correction:
  488. result = copyTree(arg)
  489. result.typ = formal
  490. proc updateDefaultParams(call: PNode) =
  491. # In generic procs, the default parameter may be unique for each
  492. # instantiation (see tlateboundgenericparams).
  493. # After a call is resolved, we need to re-assign any default value
  494. # that was used during sigmatch. sigmatch is responsible for marking
  495. # the default params with `nfDefaultParam` and `instantiateProcType`
  496. # computes correctly the default values for each instantiation.
  497. let calleeParams = call[0].sym.typ.n
  498. for i in 1..<call.len:
  499. if nfDefaultParam in call[i].flags:
  500. let def = calleeParams[i].sym.ast
  501. if nfDefaultRefsParam in def.flags: call.flags.incl nfDefaultRefsParam
  502. call[i] = def
  503. proc getCallLineInfo(n: PNode): TLineInfo =
  504. case n.kind
  505. of nkAccQuoted, nkBracketExpr, nkCall, nkCallStrLit, nkCommand:
  506. if len(n) > 0:
  507. return getCallLineInfo(n[0])
  508. of nkDotExpr:
  509. if len(n) > 1:
  510. return getCallLineInfo(n[1])
  511. else:
  512. discard
  513. result = n.info
  514. proc inheritBindings(c: PContext, x: var TCandidate, expectedType: PType) =
  515. ## Helper proc to inherit bound generic parameters from expectedType into x.
  516. ## Does nothing if 'inferGenericTypes' isn't in c.features.
  517. if inferGenericTypes notin c.features: return
  518. if expectedType == nil or x.callee[0] == nil: return # required for inference
  519. var
  520. flatUnbound: seq[PType] = @[]
  521. flatBound: seq[PType] = @[]
  522. # seq[(result type, expected type)]
  523. var typeStack = newSeq[(PType, PType)]()
  524. template stackPut(a, b) =
  525. ## skips types and puts the skipped version on stack
  526. # It might make sense to skip here one by one. It's not part of the main
  527. # type reduction because the right side normally won't be skipped
  528. const toSkip = { tyVar, tyLent, tyStatic, tyCompositeTypeClass, tySink }
  529. let
  530. x = a.skipTypes(toSkip)
  531. y = if a.kind notin toSkip: b
  532. else: b.skipTypes(toSkip)
  533. typeStack.add((x, y))
  534. stackPut(x.callee[0], expectedType)
  535. while typeStack.len() > 0:
  536. let (t, u) = typeStack.pop()
  537. if t == u or t == nil or u == nil or t.kind == tyAnything or u.kind == tyAnything:
  538. continue
  539. case t.kind
  540. of ConcreteTypes, tyGenericInvocation, tyUncheckedArray:
  541. # nested, add all the types to stack
  542. let
  543. startIdx = if u.kind in ConcreteTypes: 0 else: 1
  544. endIdx = min(u.len() - startIdx, t.len())
  545. for i in startIdx ..< endIdx:
  546. # early exit with current impl
  547. if t[i] == nil or u[i] == nil: return
  548. stackPut(t[i], u[i])
  549. of tyGenericParam:
  550. let prebound = x.bindings.idTableGet(t).PType
  551. if prebound != nil:
  552. continue # Skip param, already bound
  553. # fully reduced generic param, bind it
  554. if t notin flatUnbound:
  555. flatUnbound.add(t)
  556. flatBound.add(u)
  557. else:
  558. discard
  559. # update bindings
  560. for i in 0 ..< flatUnbound.len():
  561. x.bindings.idTablePut(flatUnbound[i], flatBound[i])
  562. proc semResolvedCall(c: PContext, x: var TCandidate,
  563. n: PNode, flags: TExprFlags;
  564. expectedType: PType = nil): PNode =
  565. assert x.state == csMatch
  566. var finalCallee = x.calleeSym
  567. let info = getCallLineInfo(n)
  568. markUsed(c, info, finalCallee)
  569. onUse(info, finalCallee)
  570. assert finalCallee.ast != nil
  571. if x.hasFauxMatch:
  572. result = x.call
  573. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  574. if containsGenericType(result.typ) or x.fauxMatch == tyUnknown:
  575. result.typ = newTypeS(x.fauxMatch, c)
  576. if result.typ.kind == tyError: incl result.typ.flags, tfCheckedForDestructor
  577. return
  578. let gp = finalCallee.ast[genericParamsPos]
  579. if gp.isGenericParams:
  580. if x.calleeSym.kind notin {skMacro, skTemplate}:
  581. if x.calleeSym.magic in {mArrGet, mArrPut}:
  582. finalCallee = x.calleeSym
  583. else:
  584. c.inheritBindings(x, expectedType)
  585. finalCallee = generateInstance(c, x.calleeSym, x.bindings, n.info)
  586. else:
  587. # For macros and templates, the resolved generic params
  588. # are added as normal params.
  589. c.inheritBindings(x, expectedType)
  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. result[0] = newSymNode(finalCallee, getCallLineInfo(result[0]))
  609. result.typ = finalCallee.typ[0]
  610. updateDefaultParams(result)
  611. proc canDeref(n: PNode): bool {.inline.} =
  612. result = n.len >= 2 and (let t = n[1].typ;
  613. t != nil and t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyPtr, tyRef})
  614. proc tryDeref(n: PNode): PNode =
  615. result = newNodeI(nkHiddenDeref, n.info)
  616. result.typ = n.typ.skipTypes(abstractInst)[0]
  617. result.add n
  618. proc semOverloadedCall(c: PContext, n, nOrig: PNode,
  619. filter: TSymKinds, flags: TExprFlags;
  620. expectedType: PType = nil): PNode =
  621. var errors: CandidateErrors = @[] # if efExplain in flags: @[] else: nil
  622. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  623. if r.state == csMatch:
  624. # this may be triggered, when the explain pragma is used
  625. if errors.len > 0:
  626. let (_, candidates) = presentFailedCandidates(c, n, errors)
  627. message(c.config, n.info, hintUserRaw,
  628. "Non-matching candidates for " & renderTree(n) & "\n" &
  629. candidates)
  630. result = semResolvedCall(c, r, n, flags, expectedType)
  631. else:
  632. if efDetermineType in flags and c.inGenericContext > 0 and c.matchedConcept == nil:
  633. result = semGenericStmt(c, n)
  634. result.typ = makeTypeFromExpr(c, result.copyTree)
  635. elif efExplain notin flags:
  636. # repeat the overload resolution,
  637. # this time enabling all the diagnostic output (this should fail again)
  638. result = semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  639. elif efNoUndeclared notin flags:
  640. result = nil
  641. notFoundError(c, n, errors)
  642. else:
  643. result = nil
  644. proc explicitGenericInstError(c: PContext; n: PNode): PNode =
  645. localError(c.config, getCallLineInfo(n), errCannotInstantiateX % renderTree(n))
  646. result = n
  647. proc explicitGenericSym(c: PContext, n: PNode, s: PSym): PNode =
  648. # binding has to stay 'nil' for this to work!
  649. var m = newCandidate(c, s, nil)
  650. for i in 1..<n.len:
  651. let formal = s.ast[genericParamsPos][i-1].typ
  652. var arg = n[i].typ
  653. # try transforming the argument into a static one before feeding it into
  654. # typeRel
  655. if formal.kind == tyStatic and arg.kind != tyStatic:
  656. let evaluated = c.semTryConstExpr(c, n[i])
  657. if evaluated != nil:
  658. arg = newTypeS(tyStatic, c, sons = @[evaluated.typ])
  659. arg.n = evaluated
  660. let tm = typeRel(m, formal, arg)
  661. if tm in {isNone, isConvertible}: return nil
  662. var newInst = generateInstance(c, s, m.bindings, n.info)
  663. newInst.typ.flags.excl tfUnresolved
  664. let info = getCallLineInfo(n)
  665. markUsed(c, info, s)
  666. onUse(info, s)
  667. result = newSymNode(newInst, info)
  668. proc setGenericParams(c: PContext, n: PNode) =
  669. ## sems generic params in subscript expression
  670. for i in 1..<n.len:
  671. let e = semExprWithType(c, n[i])
  672. if e.typ == nil:
  673. n[i].typ = errorType(c)
  674. else:
  675. n[i].typ = e.typ.skipTypes({tyTypeDesc})
  676. proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode =
  677. assert n.kind == nkBracketExpr
  678. setGenericParams(c, n)
  679. var s = s
  680. var a = n[0]
  681. if a.kind == nkSym:
  682. # common case; check the only candidate has the right
  683. # number of generic type parameters:
  684. if s.ast[genericParamsPos].safeLen != n.len-1:
  685. let expected = s.ast[genericParamsPos].safeLen
  686. localError(c.config, getCallLineInfo(n), errGenerated, "cannot instantiate: '" & renderTree(n) &
  687. "'; got " & $(n.len-1) & " typeof(s) but expected " & $expected)
  688. return n
  689. result = explicitGenericSym(c, n, s)
  690. if result == nil: result = explicitGenericInstError(c, n)
  691. elif a.kind in {nkClosedSymChoice, nkOpenSymChoice}:
  692. # choose the generic proc with the proper number of type parameters.
  693. # XXX I think this could be improved by reusing sigmatch.paramTypesMatch.
  694. # It's good enough for now.
  695. result = newNodeI(a.kind, getCallLineInfo(n))
  696. for i in 0..<a.len:
  697. var candidate = a[i].sym
  698. if candidate.kind in {skProc, skMethod, skConverter,
  699. skFunc, skIterator}:
  700. # it suffices that the candidate has the proper number of generic
  701. # type parameters:
  702. if candidate.ast[genericParamsPos].safeLen == n.len-1:
  703. let x = explicitGenericSym(c, n, candidate)
  704. if x != nil: result.add(x)
  705. # get rid of nkClosedSymChoice if not ambiguous:
  706. if result.len == 1 and a.kind == nkClosedSymChoice:
  707. result = result[0]
  708. elif result.len == 0: result = explicitGenericInstError(c, n)
  709. # candidateCount != 1: return explicitGenericInstError(c, n)
  710. else:
  711. result = explicitGenericInstError(c, n)
  712. proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): tuple[s: PSym, state: TBorrowState] =
  713. # Searches for the fn in the symbol table. If the parameter lists are suitable
  714. # for borrowing the sym in the symbol table is returned, else nil.
  715. # New approach: generate fn(x, y, z) where x, y, z have the proper types
  716. # and use the overloading resolution mechanism:
  717. const desiredTypes = abstractVar + {tyCompositeTypeClass} - {tyTypeDesc, tyDistinct}
  718. template getType(isDistinct: bool; t: PType):untyped =
  719. if isDistinct: t.baseOfDistinct(c.graph, c.idgen) else: t
  720. result = default(tuple[s: PSym, state: TBorrowState])
  721. var call = newNodeI(nkCall, fn.info)
  722. var hasDistinct = false
  723. var isDistinct: bool
  724. var x: PType
  725. var t: PType
  726. call.add(newIdentNode(fn.name, fn.info))
  727. for i in 1..<fn.typ.n.len:
  728. let param = fn.typ.n[i]
  729. #[.
  730. # We only want the type not any modifiers such as `ptr`, `var`, `ref` ...
  731. # tyCompositeTypeClass is here for
  732. # when using something like:
  733. type Foo[T] = distinct int
  734. proc `$`(f: Foo): string {.borrow.}
  735. # We want to skip the `Foo` to get `int`
  736. ]#
  737. t = skipTypes(param.typ, desiredTypes)
  738. isDistinct = t.kind == tyDistinct or param.typ.kind == tyDistinct
  739. if t.kind == tyGenericInvocation and t[0].lastSon.kind == tyDistinct:
  740. result.state = bsGeneric
  741. return
  742. if isDistinct: hasDistinct = true
  743. if param.typ.kind == tyVar:
  744. x = newTypeS(param.typ.kind, c)
  745. x.addSonSkipIntLit(getType(isDistinct, t), c.idgen)
  746. else:
  747. x = getType(isDistinct, t)
  748. var s = copySym(param.sym, c.idgen)
  749. s.typ = x
  750. s.info = param.info
  751. call.add(newSymNode(s))
  752. if hasDistinct:
  753. let filter = if fn.kind in {skProc, skFunc}: {skProc, skFunc} else: {fn.kind}
  754. var resolved = semOverloadedCall(c, call, call, filter, {})
  755. if resolved != nil:
  756. result.s = resolved[0].sym
  757. result.state = bsMatch
  758. if not compareTypes(result.s.typ[0], fn.typ[0], dcEqIgnoreDistinct):
  759. result.state = bsReturnNotMatch
  760. elif result.s.magic in {mArrPut, mArrGet}:
  761. # cannot borrow these magics for now
  762. result.state = bsNotSupported
  763. else:
  764. result.state = bsNoDistinct