semcall.nim 29 KB

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