semcall.nim 27 KB

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