semcall.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. proc sameMethodDispatcher(a, b: PSym): bool =
  12. result = false
  13. if a.kind == skMethod and b.kind == skMethod:
  14. var aa = lastSon(a.ast)
  15. var bb = lastSon(b.ast)
  16. if aa.kind == nkSym and bb.kind == nkSym:
  17. if aa.sym == bb.sym:
  18. result = true
  19. else:
  20. discard
  21. # generics have no dispatcher yet, so we need to compare the method
  22. # names; however, the names are equal anyway because otherwise we
  23. # wouldn't even consider them to be overloaded. But even this does
  24. # not work reliably! See tmultim6 for an example:
  25. # method collide[T](a: TThing, b: TUnit[T]) is instantiated and not
  26. # method collide[T](a: TUnit[T], b: TThing)! This means we need to
  27. # *instantiate* every candidate! However, we don't keep more than 2-3
  28. # candidates around so we cannot implement that for now. So in order
  29. # to avoid subtle problems, the call remains ambiguous and needs to
  30. # be disambiguated by the programmer; this way the right generic is
  31. # instantiated.
  32. proc determineType(c: PContext, s: PSym)
  33. proc initCandidateSymbols(c: PContext, headSymbol: PNode,
  34. initialBinding: PNode,
  35. filter: TSymKinds,
  36. best, alt: var TCandidate,
  37. o: var TOverloadIter,
  38. diagnostics: bool): seq[tuple[s: PSym, scope: int]] =
  39. result = @[]
  40. var symx = initOverloadIter(o, c, headSymbol)
  41. while symx != nil:
  42. if symx.kind in filter:
  43. result.add((symx, o.lastOverloadScope))
  44. symx = nextOverloadIter(o, c, headSymbol)
  45. if result.len > 0:
  46. initCandidate(c, best, result[0].s, initialBinding,
  47. result[0].scope, diagnostics)
  48. initCandidate(c, alt, result[0].s, initialBinding,
  49. result[0].scope, diagnostics)
  50. best.state = csNoMatch
  51. proc pickBestCandidate(c: PContext, headSymbol: PNode,
  52. n, orig: PNode,
  53. initialBinding: PNode,
  54. filter: TSymKinds,
  55. best, alt: var TCandidate,
  56. errors: var CandidateErrors,
  57. diagnosticsFlag: bool,
  58. errorsEnabled: bool) =
  59. var o: TOverloadIter
  60. var sym = initOverloadIter(o, c, headSymbol)
  61. var scope = o.lastOverloadScope
  62. # Thanks to the lazy semchecking for operands, we need to check whether
  63. # 'initCandidate' modifies the symbol table (via semExpr).
  64. # This can occur in cases like 'init(a, 1, (var b = new(Type2); b))'
  65. let counterInitial = c.currentScope.symbols.counter
  66. var syms: seq[tuple[s: PSym, scope: int]]
  67. var noSyms = true
  68. var nextSymIndex = 0
  69. while sym != nil:
  70. if sym.kind in filter:
  71. # Initialise 'best' and 'alt' with the first available symbol
  72. initCandidate(c, best, sym, initialBinding, scope, diagnosticsFlag)
  73. initCandidate(c, alt, sym, initialBinding, scope, diagnosticsFlag)
  74. best.state = csNoMatch
  75. break
  76. else:
  77. sym = nextOverloadIter(o, c, headSymbol)
  78. scope = o.lastOverloadScope
  79. var z: TCandidate
  80. while sym != nil:
  81. if sym.kind notin filter:
  82. sym = nextOverloadIter(o, c, headSymbol)
  83. scope = o.lastOverloadScope
  84. continue
  85. determineType(c, sym)
  86. initCandidate(c, z, sym, initialBinding, scope, diagnosticsFlag)
  87. if c.currentScope.symbols.counter == counterInitial or syms.len != 0:
  88. matches(c, n, orig, z)
  89. if z.state == csMatch:
  90. #if sym.name.s == "==" and (n.info ?? "temp3"):
  91. # echo typeToString(sym.typ)
  92. # writeMatches(z)
  93. # little hack so that iterators are preferred over everything else:
  94. if sym.kind == skIterator: inc(z.exactMatches, 200)
  95. case best.state
  96. of csEmpty, csNoMatch: best = z
  97. of csMatch:
  98. var cmp = cmpCandidates(best, z)
  99. if cmp < 0: best = z # x is better than the best so far
  100. elif cmp == 0: alt = z # x is as good as the best so far
  101. elif errorsEnabled or z.diagnosticsEnabled:
  102. errors.safeAdd(CandidateError(
  103. sym: sym,
  104. unmatchedVarParam: int z.mutabilityProblem,
  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) =
  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. proc renderNotLValue(n: PNode): string =
  132. result = $n
  133. if n.kind == nkHiddenCallConv and n.len > 1:
  134. result = $n[0] & "(" & result & ")"
  135. elif n.kind in {nkHiddenStdConv, nkHiddenSubConv} and n.len == 2:
  136. result = typeToString(n.typ.skipTypes(abstractVar)) & "(" & result & ")"
  137. proc presentFailedCandidates(c: PContext, n: PNode, errors: CandidateErrors):
  138. (TPreferedDesc, string) =
  139. var prefer = preferName
  140. # to avoid confusing errors like:
  141. # got (SslPtr, SocketHandle)
  142. # but expected one of:
  143. # openssl.SSL_set_fd(ssl: SslPtr, fd: SocketHandle): cint
  144. # we do a pre-analysis. If all types produce the same string, we will add
  145. # module information.
  146. let proto = describeArgs(c, n, 1, preferName)
  147. for err in errors:
  148. var errProto = ""
  149. let n = err.sym.typ.n
  150. for i in countup(1, n.len - 1):
  151. var p = n.sons[i]
  152. if p.kind == nkSym:
  153. add(errProto, typeToString(p.sym.typ, preferName))
  154. if i != n.len-1: add(errProto, ", ")
  155. # else: ignore internal error as we're already in error handling mode
  156. if errProto == proto:
  157. prefer = preferModuleInfo
  158. break
  159. when false:
  160. # we pretend procs are attached to the type of the first
  161. # argument in order to remove plenty of candidates. This is
  162. # comparable to what C# does and C# is doing fine.
  163. var filterOnlyFirst = false
  164. for err in errors:
  165. if err.firstMismatch > 1:
  166. filterOnlyFirst = true
  167. break
  168. var candidates = ""
  169. for err in errors:
  170. when false:
  171. if filterOnlyFirst and err.firstMismatch == 1: continue
  172. if err.sym.kind in routineKinds and err.sym.ast != nil:
  173. add(candidates, renderTree(err.sym.ast,
  174. {renderNoBody, renderNoComments, renderNoPragmas}))
  175. else:
  176. add(candidates, getProcHeader(c.config, err.sym, prefer))
  177. add(candidates, "\n")
  178. if err.firstMismatch != 0 and n.len > 1:
  179. let cond = n.len > 2
  180. if cond:
  181. candidates.add(" first type mismatch at position: " & $abs(err.firstMismatch))
  182. if err.firstMismatch >= 0: candidates.add("\n required type: ")
  183. else: candidates.add("\n unknown named parameter: " & $n[-err.firstMismatch][0])
  184. var wanted, got: PType = nil
  185. if err.firstMismatch < 0:
  186. discard
  187. elif err.firstMismatch < err.sym.typ.len:
  188. wanted = err.sym.typ.sons[err.firstMismatch]
  189. if cond: candidates.add typeToString(wanted)
  190. else:
  191. if cond: candidates.add "none"
  192. if err.firstMismatch > 0 and err.firstMismatch < n.len:
  193. if cond:
  194. candidates.add "\n but expression '"
  195. candidates.add renderTree(n[err.firstMismatch])
  196. candidates.add "' is of type: "
  197. got = n[err.firstMismatch].typ
  198. if cond: candidates.add typeToString(got)
  199. if wanted != nil and got != nil:
  200. effectProblem(wanted, got, candidates)
  201. if cond: candidates.add "\n"
  202. if err.unmatchedVarParam != 0 and err.unmatchedVarParam < n.len:
  203. candidates.add(" for a 'var' type a variable needs to be passed, but '" &
  204. renderNotLValue(n[err.unmatchedVarParam]) &
  205. "' is immutable\n")
  206. for diag in err.diagnostics:
  207. candidates.add(diag & "\n")
  208. result = (prefer, candidates)
  209. const
  210. errTypeMismatch = "type mismatch: got <"
  211. errButExpected = "but expected one of: "
  212. errUndeclaredField = "undeclared field: '$1'"
  213. errUndeclaredRoutine = "attempting to call undeclared routine: '$1'"
  214. errAmbiguousCallXYZ = "ambiguous call; both $1 and $2 match for: $3"
  215. proc notFoundError*(c: PContext, n: PNode, errors: CandidateErrors) =
  216. # Gives a detailed error message; this is separated from semOverloadedCall,
  217. # as semOverlodedCall is already pretty slow (and we need this information
  218. # only in case of an error).
  219. if c.config.m.errorOutputs == {}:
  220. # fail fast:
  221. globalError(c.config, n.info, "type mismatch")
  222. if errors.len == 0:
  223. localError(c.config, n.info, "expression '$1' cannot be called" % n[0].renderTree)
  224. return
  225. let (prefer, candidates) = presentFailedCandidates(c, n, errors)
  226. var result = errTypeMismatch
  227. add(result, describeArgs(c, n, 1, prefer))
  228. add(result, '>')
  229. if candidates != "":
  230. add(result, "\n" & errButExpected & "\n" & candidates)
  231. localError(c.config, n.info, result & "\nexpression: " & $n)
  232. proc bracketNotFoundError(c: PContext; n: PNode) =
  233. var errors: CandidateErrors = @[]
  234. var o: TOverloadIter
  235. let headSymbol = n[0]
  236. var symx = initOverloadIter(o, c, headSymbol)
  237. while symx != nil:
  238. if symx.kind in routineKinds:
  239. errors.add(CandidateError(sym: symx,
  240. unmatchedVarParam: 0, firstMismatch: 0,
  241. diagnostics: @[],
  242. enabled: false))
  243. symx = nextOverloadIter(o, c, headSymbol)
  244. if errors.len == 0:
  245. localError(c.config, n.info, "could not resolve: " & $n)
  246. else:
  247. notFoundError(c, n, errors)
  248. proc resolveOverloads(c: PContext, n, orig: PNode,
  249. filter: TSymKinds, flags: TExprFlags,
  250. errors: var CandidateErrors,
  251. errorsEnabled: bool): TCandidate =
  252. var initialBinding: PNode
  253. var alt: TCandidate
  254. var f = n.sons[0]
  255. if f.kind == nkBracketExpr:
  256. # fill in the bindings:
  257. semOpAux(c, f)
  258. initialBinding = f
  259. f = f.sons[0]
  260. else:
  261. initialBinding = nil
  262. template pickBest(headSymbol) =
  263. pickBestCandidate(c, headSymbol, n, orig, initialBinding,
  264. filter, result, alt, errors, efExplain in flags,
  265. errorsEnabled)
  266. pickBest(f)
  267. let overloadsState = result.state
  268. if overloadsState != csMatch:
  269. if c.p != nil and c.p.selfSym != nil:
  270. # we need to enforce semchecking of selfSym again because it
  271. # might need auto-deref:
  272. var hiddenArg = newSymNode(c.p.selfSym)
  273. hiddenArg.typ = nil
  274. n.sons.insert(hiddenArg, 1)
  275. orig.sons.insert(hiddenArg, 1)
  276. pickBest(f)
  277. if result.state != csMatch:
  278. n.sons.delete(1)
  279. orig.sons.delete(1)
  280. excl n.flags, nfExprCall
  281. else: return
  282. if nfDotField in n.flags:
  283. internalAssert c.config, f.kind == nkIdent and n.len >= 2
  284. # leave the op head symbol empty,
  285. # we are going to try multiple variants
  286. n.sons[0..1] = [nil, n[1], f]
  287. orig.sons[0..1] = [nil, orig[1], f]
  288. template tryOp(x) =
  289. let op = newIdentNode(getIdent(c.cache, x), n.info)
  290. n.sons[0] = op
  291. orig.sons[0] = op
  292. pickBest(op)
  293. if nfExplicitCall in n.flags:
  294. tryOp ".()"
  295. if result.state in {csEmpty, csNoMatch}:
  296. tryOp "."
  297. elif nfDotSetter in n.flags and f.kind == nkIdent and n.len == 3:
  298. # we need to strip away the trailing '=' here:
  299. let calleeName = newIdentNode(getIdent(c.cache, f.ident.s[0..f.ident.s.len-2]), n.info)
  300. let callOp = newIdentNode(getIdent(c.cache, ".="), n.info)
  301. n.sons[0..1] = [callOp, n[1], calleeName]
  302. orig.sons[0..1] = [callOp, orig[1], calleeName]
  303. pickBest(callOp)
  304. if overloadsState == csEmpty and result.state == csEmpty:
  305. if nfDotField in n.flags and nfExplicitCall notin n.flags:
  306. localError(c.config, n.info, errUndeclaredField % considerQuotedIdent(c, f, n).s)
  307. else:
  308. localError(c.config, n.info, errUndeclaredRoutine % considerQuotedIdent(c, f, n).s)
  309. return
  310. elif result.state != csMatch:
  311. if nfExprCall in n.flags:
  312. localError(c.config, n.info, "expression '$1' cannot be called" %
  313. renderTree(n, {renderNoComments}))
  314. else:
  315. if {nfDotField, nfDotSetter} * n.flags != {}:
  316. # clean up the inserted ops
  317. n.sons.delete(2)
  318. n.sons[0] = f
  319. return
  320. if alt.state == csMatch and cmpCandidates(result, alt) == 0 and
  321. not sameMethodDispatcher(result.calleeSym, alt.calleeSym):
  322. internalAssert c.config, result.state == csMatch
  323. #writeMatches(result)
  324. #writeMatches(alt)
  325. if c.config.m.errorOutputs == {}:
  326. # quick error message for performance of 'compiles' built-in:
  327. globalError(c.config, n.info, errGenerated, "ambiguous call")
  328. elif c.config.errorCounter == 0:
  329. # don't cascade errors
  330. var args = "("
  331. for i in countup(1, sonsLen(n) - 1):
  332. if i > 1: add(args, ", ")
  333. add(args, typeToString(n.sons[i].typ))
  334. add(args, ")")
  335. localError(c.config, n.info, errAmbiguousCallXYZ % [
  336. getProcHeader(c.config, result.calleeSym),
  337. getProcHeader(c.config, alt.calleeSym),
  338. args])
  339. proc instGenericConvertersArg*(c: PContext, a: PNode, x: TCandidate) =
  340. if a.kind == nkHiddenCallConv and a.sons[0].kind == nkSym:
  341. let s = a.sons[0].sym
  342. if s.ast != nil and s.ast[genericParamsPos].kind != nkEmpty:
  343. let finalCallee = generateInstance(c, s, x.bindings, a.info)
  344. a.sons[0].sym = finalCallee
  345. a.sons[0].typ = finalCallee.typ
  346. #a.typ = finalCallee.typ.sons[0]
  347. proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) =
  348. assert n.kind in nkCallKinds
  349. if x.genericConverter:
  350. for i in 1 ..< n.len:
  351. instGenericConvertersArg(c, n.sons[i], x)
  352. proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode =
  353. var m: TCandidate
  354. initCandidate(c, m, f)
  355. result = paramTypesMatch(m, f, a, arg, nil)
  356. if m.genericConverter and result != nil:
  357. instGenericConvertersArg(c, result, m)
  358. proc inferWithMetatype(c: PContext, formal: PType,
  359. arg: PNode, coerceDistincts = false): PNode =
  360. var m: TCandidate
  361. initCandidate(c, m, formal)
  362. m.coerceDistincts = coerceDistincts
  363. result = paramTypesMatch(m, formal, arg.typ, arg, nil)
  364. if m.genericConverter and result != nil:
  365. instGenericConvertersArg(c, result, m)
  366. if result != nil:
  367. # This almost exactly replicates the steps taken by the compiler during
  368. # param matching. It performs an embarrassing amount of back-and-forth
  369. # type jugling, but it's the price to pay for consistency and correctness
  370. result.typ = generateTypeInstance(c, m.bindings, arg.info,
  371. formal.skipTypes({tyCompositeTypeClass}))
  372. else:
  373. typeMismatch(c.config, arg.info, formal, arg.typ)
  374. # error correction:
  375. result = copyTree(arg)
  376. result.typ = formal
  377. proc updateDefaultParams(call: PNode) =
  378. # In generic procs, the default parameter may be unique for each
  379. # instantiation (see tlateboundgenericparams).
  380. # After a call is resolved, we need to re-assign any default value
  381. # that was used during sigmatch. sigmatch is responsible for marking
  382. # the default params with `nfDefaultParam` and `instantiateProcType`
  383. # computes correctly the default values for each instantiation.
  384. let calleeParams = call[0].sym.typ.n
  385. for i in 1..<call.len:
  386. if nfDefaultParam in call[i].flags:
  387. let def = calleeParams[i].sym.ast
  388. if nfDefaultRefsParam in def.flags: call.flags.incl nfDefaultRefsParam
  389. call[i] = def
  390. proc semResolvedCall(c: PContext, x: TCandidate,
  391. n: PNode, flags: TExprFlags): PNode =
  392. assert x.state == csMatch
  393. var finalCallee = x.calleeSym
  394. markUsed(c.config, n.sons[0].info, finalCallee, c.graph.usageSym)
  395. styleCheckUse(n.sons[0].info, finalCallee)
  396. assert finalCallee.ast != nil
  397. if x.hasFauxMatch:
  398. result = x.call
  399. result.sons[0] = newSymNode(finalCallee, result.sons[0].info)
  400. if containsGenericType(result.typ) or x.fauxMatch == tyUnknown:
  401. result.typ = newTypeS(x.fauxMatch, c)
  402. return
  403. let gp = finalCallee.ast.sons[genericParamsPos]
  404. if gp.kind != nkEmpty:
  405. if x.calleeSym.kind notin {skMacro, skTemplate}:
  406. if x.calleeSym.magic in {mArrGet, mArrPut}:
  407. finalCallee = x.calleeSym
  408. else:
  409. finalCallee = generateInstance(c, x.calleeSym, x.bindings, n.info)
  410. else:
  411. # For macros and templates, the resolved generic params
  412. # are added as normal params.
  413. for s in instantiateGenericParamList(c, gp, x.bindings):
  414. case s.kind
  415. of skConst:
  416. x.call.add s.ast
  417. of skType:
  418. x.call.add newSymNode(s, n.info)
  419. else:
  420. internalAssert c.config, false
  421. result = x.call
  422. instGenericConvertersSons(c, result, x)
  423. result[0] = newSymNode(finalCallee, result[0].info)
  424. result.typ = finalCallee.typ.sons[0]
  425. updateDefaultParams(result)
  426. proc canDeref(n: PNode): bool {.inline.} =
  427. result = n.len >= 2 and (let t = n[1].typ;
  428. t != nil and t.skipTypes({tyGenericInst, tyAlias, tySink}).kind in {tyPtr, tyRef})
  429. proc tryDeref(n: PNode): PNode =
  430. result = newNodeI(nkHiddenDeref, n.info)
  431. result.typ = n.typ.skipTypes(abstractInst).sons[0]
  432. result.addSon(n)
  433. proc semOverloadedCall(c: PContext, n, nOrig: PNode,
  434. filter: TSymKinds, flags: TExprFlags): PNode =
  435. var errors: CandidateErrors = @[] # if efExplain in flags: @[] else: nil
  436. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  437. if r.state == csMatch:
  438. # this may be triggered, when the explain pragma is used
  439. if errors.len > 0:
  440. let (_, candidates) = presentFailedCandidates(c, n, errors)
  441. message(c.config, n.info, hintUserRaw,
  442. "Non-matching candidates for " & renderTree(n) & "\n" &
  443. candidates)
  444. result = semResolvedCall(c, r, n, flags)
  445. elif implicitDeref in c.features and canDeref(n):
  446. # try to deref the first argument and then try overloading resolution again:
  447. #
  448. # XXX: why is this here?
  449. # it could be added to the long list of alternatives tried
  450. # inside `resolveOverloads` or it could be moved all the way
  451. # into sigmatch with hidden conversion produced there
  452. #
  453. n.sons[1] = n.sons[1].tryDeref
  454. var r = resolveOverloads(c, n, nOrig, filter, flags, errors, efExplain in flags)
  455. if r.state == csMatch: result = semResolvedCall(c, r, n, flags)
  456. else:
  457. # get rid of the deref again for a better error message:
  458. n.sons[1] = n.sons[1].sons[0]
  459. #notFoundError(c, n, errors)
  460. if efExplain notin flags:
  461. # repeat the overload resolution,
  462. # this time enabling all the diagnostic output (this should fail again)
  463. discard semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  464. else:
  465. notFoundError(c, n, errors)
  466. else:
  467. if efExplain notin flags:
  468. # repeat the overload resolution,
  469. # this time enabling all the diagnostic output (this should fail again)
  470. discard semOverloadedCall(c, n, nOrig, filter, flags + {efExplain})
  471. else:
  472. notFoundError(c, n, errors)
  473. proc explicitGenericInstError(c: PContext; n: PNode): PNode =
  474. localError(c.config, n.info, errCannotInstantiateX % renderTree(n))
  475. result = n
  476. proc explicitGenericSym(c: PContext, n: PNode, s: PSym): PNode =
  477. var m: TCandidate
  478. # binding has to stay 'nil' for this to work!
  479. initCandidate(c, m, s, nil)
  480. for i in 1..sonsLen(n)-1:
  481. let formal = s.ast.sons[genericParamsPos].sons[i-1].typ
  482. var arg = n[i].typ
  483. # try transforming the argument into a static one before feeding it into
  484. # typeRel
  485. if formal.kind == tyStatic and arg.kind != tyStatic:
  486. let evaluated = c.semTryConstExpr(c, n[i])
  487. if evaluated != nil:
  488. arg = newTypeS(tyStatic, c)
  489. arg.sons = @[evaluated.typ]
  490. arg.n = evaluated
  491. let tm = typeRel(m, formal, arg)
  492. if tm in {isNone, isConvertible}: return nil
  493. var newInst = generateInstance(c, s, m.bindings, n.info)
  494. newInst.typ.flags.excl tfUnresolved
  495. markUsed(c.config, n.info, s, c.graph.usageSym)
  496. styleCheckUse(n.info, s)
  497. result = newSymNode(newInst, n.info)
  498. proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode =
  499. assert n.kind == nkBracketExpr
  500. for i in 1..sonsLen(n)-1:
  501. let e = semExpr(c, n.sons[i])
  502. n.sons[i].typ = e.typ.skipTypes({tyTypeDesc})
  503. var s = s
  504. var a = n.sons[0]
  505. if a.kind == nkSym:
  506. # common case; check the only candidate has the right
  507. # number of generic type parameters:
  508. if safeLen(s.ast.sons[genericParamsPos]) != n.len-1:
  509. let expected = safeLen(s.ast.sons[genericParamsPos])
  510. localError(c.config, n.info, errGenerated, "cannot instantiate: '" & renderTree(n) &
  511. "'; got " & $(n.len-1) & " type(s) but expected " & $expected)
  512. return n
  513. result = explicitGenericSym(c, n, s)
  514. if result == nil: result = explicitGenericInstError(c, n)
  515. elif a.kind in {nkClosedSymChoice, nkOpenSymChoice}:
  516. # choose the generic proc with the proper number of type parameters.
  517. # XXX I think this could be improved by reusing sigmatch.paramTypesMatch.
  518. # It's good enough for now.
  519. result = newNodeI(a.kind, n.info)
  520. for i in countup(0, len(a)-1):
  521. var candidate = a.sons[i].sym
  522. if candidate.kind in {skProc, skMethod, skConverter,
  523. skFunc, skIterator}:
  524. # it suffices that the candidate has the proper number of generic
  525. # type parameters:
  526. if safeLen(candidate.ast.sons[genericParamsPos]) == n.len-1:
  527. let x = explicitGenericSym(c, n, candidate)
  528. if x != nil: result.add(x)
  529. # get rid of nkClosedSymChoice if not ambiguous:
  530. if result.len == 1 and a.kind == nkClosedSymChoice:
  531. result = result[0]
  532. elif result.len == 0: result = explicitGenericInstError(c, n)
  533. # candidateCount != 1: return explicitGenericInstError(c, n)
  534. else:
  535. result = explicitGenericInstError(c, n)
  536. proc searchForBorrowProc(c: PContext, startScope: PScope, fn: PSym): PSym =
  537. # Searchs for the fn in the symbol table. If the parameter lists are suitable
  538. # for borrowing the sym in the symbol table is returned, else nil.
  539. # New approach: generate fn(x, y, z) where x, y, z have the proper types
  540. # and use the overloading resolution mechanism:
  541. var call = newNodeI(nkCall, fn.info)
  542. var hasDistinct = false
  543. call.add(newIdentNode(fn.name, fn.info))
  544. for i in 1..<fn.typ.n.len:
  545. let param = fn.typ.n.sons[i]
  546. let t = skipTypes(param.typ, abstractVar-{tyTypeDesc, tyDistinct})
  547. if t.kind == tyDistinct or param.typ.kind == tyDistinct: hasDistinct = true
  548. var x: PType
  549. if param.typ.kind == tyVar:
  550. x = newTypeS(tyVar, c)
  551. x.addSonSkipIntLit t.baseOfDistinct
  552. else:
  553. x = t.baseOfDistinct
  554. call.add(newNodeIT(nkEmpty, fn.info, x))
  555. if hasDistinct:
  556. var resolved = semOverloadedCall(c, call, call, {fn.kind}, {})
  557. if resolved != nil:
  558. result = resolved.sons[0].sym
  559. if not compareTypes(result.typ.sons[0], fn.typ.sons[0], dcEqIgnoreDistinct):
  560. result = nil
  561. elif result.magic in {mArrPut, mArrGet}:
  562. # cannot borrow these magics for now
  563. result = nil