lookups.nim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements lookup helpers.
  10. import std/[algorithm, strutils]
  11. when defined(nimPreviewSlimSystem):
  12. import std/assertions
  13. import
  14. intsets, ast, astalgo, idents, semdata, types, msgs, options,
  15. renderer, nimfix/prettybase, lineinfos, modulegraphs, astmsgs, sets
  16. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope)
  17. proc noidentError(conf: ConfigRef; n, origin: PNode) =
  18. var m = ""
  19. if origin != nil:
  20. m.add "in expression '" & origin.renderTree & "': "
  21. m.add "identifier expected, but found '" & n.renderTree & "'"
  22. localError(conf, n.info, m)
  23. proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
  24. ## Retrieve a PIdent from a PNode, taking into account accent nodes.
  25. ## ``origin`` can be nil. If it is not nil, it is used for a better
  26. ## error message.
  27. template handleError(n, origin: PNode) =
  28. noidentError(c.config, n, origin)
  29. result = getIdent(c.cache, "<Error>")
  30. case n.kind
  31. of nkIdent: result = n.ident
  32. of nkSym: result = n.sym.name
  33. of nkAccQuoted:
  34. case n.len
  35. of 0: handleError(n, origin)
  36. of 1: result = considerQuotedIdent(c, n[0], origin)
  37. else:
  38. var id = ""
  39. for i in 0..<n.len:
  40. let x = n[i]
  41. case x.kind
  42. of nkIdent: id.add(x.ident.s)
  43. of nkSym: id.add(x.sym.name.s)
  44. of nkSymChoices:
  45. if x[0].kind == nkSym:
  46. id.add(x[0].sym.name.s)
  47. else:
  48. handleError(n, origin)
  49. of nkLiterals - nkFloatLiterals: id.add(x.renderTree)
  50. else: handleError(n, origin)
  51. result = getIdent(c.cache, id)
  52. of nkOpenSymChoice, nkClosedSymChoice:
  53. if n[0].kind == nkSym:
  54. result = n[0].sym.name
  55. else:
  56. handleError(n, origin)
  57. else:
  58. handleError(n, origin)
  59. template addSym*(scope: PScope, s: PSym) =
  60. strTableAdd(scope.symbols, s)
  61. proc addUniqueSym*(scope: PScope, s: PSym): PSym =
  62. result = strTableInclReportConflict(scope.symbols, s)
  63. proc openScope*(c: PContext): PScope {.discardable.} =
  64. result = PScope(parent: c.currentScope,
  65. symbols: newStrTable(),
  66. depthLevel: c.scopeDepth + 1)
  67. c.currentScope = result
  68. proc rawCloseScope*(c: PContext) =
  69. c.currentScope = c.currentScope.parent
  70. proc closeScope*(c: PContext) =
  71. ensureNoMissingOrUnusedSymbols(c, c.currentScope)
  72. rawCloseScope(c)
  73. iterator allScopes*(scope: PScope): PScope =
  74. var current = scope
  75. while current != nil:
  76. yield current
  77. current = current.parent
  78. iterator localScopesFrom*(c: PContext; scope: PScope): PScope =
  79. for s in allScopes(scope):
  80. if s == c.topLevelScope: break
  81. yield s
  82. proc skipAlias*(s: PSym; n: PNode; conf: ConfigRef): PSym =
  83. if s == nil or s.kind != skAlias:
  84. result = s
  85. else:
  86. result = s.owner
  87. if conf.cmd == cmdNimfix:
  88. prettybase.replaceDeprecated(conf, n.info, s, result)
  89. else:
  90. message(conf, n.info, warnDeprecated, "use " & result.name.s & " instead; " &
  91. s.name.s & " is deprecated")
  92. proc isShadowScope*(s: PScope): bool {.inline.} =
  93. s.parent != nil and s.parent.depthLevel == s.depthLevel
  94. proc localSearchInScope*(c: PContext, s: PIdent): PSym =
  95. var scope = c.currentScope
  96. result = strTableGet(scope.symbols, s)
  97. while result == nil and scope.isShadowScope:
  98. # We are in a shadow scope, check in the parent too
  99. scope = scope.parent
  100. result = strTableGet(scope.symbols, s)
  101. proc initIdentIter(ti: var ModuleIter; marked: var IntSet; im: ImportedModule; name: PIdent;
  102. g: ModuleGraph): PSym =
  103. result = initModuleIter(ti, g, im.m, name)
  104. while result != nil:
  105. let b =
  106. case im.mode
  107. of importAll: true
  108. of importSet: result.id in im.imported
  109. of importExcept: name.id notin im.exceptSet
  110. if b and not containsOrIncl(marked, result.id):
  111. return result
  112. result = nextModuleIter(ti, g)
  113. proc nextIdentIter(ti: var ModuleIter; marked: var IntSet; im: ImportedModule;
  114. g: ModuleGraph): PSym =
  115. while true:
  116. result = nextModuleIter(ti, g)
  117. if result == nil: return nil
  118. case im.mode
  119. of importAll:
  120. if not containsOrIncl(marked, result.id):
  121. return result
  122. of importSet:
  123. if result.id in im.imported and not containsOrIncl(marked, result.id):
  124. return result
  125. of importExcept:
  126. if result.name.id notin im.exceptSet and not containsOrIncl(marked, result.id):
  127. return result
  128. iterator symbols(im: ImportedModule; marked: var IntSet; name: PIdent; g: ModuleGraph): PSym =
  129. var ti: ModuleIter
  130. var candidate = initIdentIter(ti, marked, im, name, g)
  131. while candidate != nil:
  132. yield candidate
  133. candidate = nextIdentIter(ti, marked, im, g)
  134. iterator importedItems*(c: PContext; name: PIdent): PSym =
  135. var marked = initIntSet()
  136. for im in c.imports.mitems:
  137. for s in symbols(im, marked, name, c.graph):
  138. yield s
  139. proc allPureEnumFields(c: PContext; name: PIdent): seq[PSym] =
  140. var ti: TIdentIter
  141. result = @[]
  142. var res = initIdentIter(ti, c.pureEnumFields, name)
  143. while res != nil:
  144. result.add res
  145. res = nextIdentIter(ti, c.pureEnumFields)
  146. iterator allSyms*(c: PContext): (PSym, int, bool) =
  147. # really iterate over all symbols in all the scopes. This is expensive
  148. # and only used by suggest.nim.
  149. var isLocal = true
  150. var scopeN = 0
  151. for scope in allScopes(c.currentScope):
  152. if scope == c.topLevelScope: isLocal = false
  153. dec scopeN
  154. for item in scope.symbols:
  155. yield (item, scopeN, isLocal)
  156. dec scopeN
  157. isLocal = false
  158. for im in c.imports.mitems:
  159. for s in modulegraphs.allSyms(c.graph, im.m):
  160. assert s != nil
  161. yield (s, scopeN, isLocal)
  162. iterator uniqueSyms*(c: PContext): (PSym, int, bool) =
  163. ## Like [allSyms] except only returns unique symbols (Uniqueness determined by line + name)
  164. # Track seen symbols so we don't duplicate them.
  165. # The int is for the symbols name, and line info is
  166. # to be able to tell apart symbols with same name but on different lines
  167. var seen = initHashSet[(TLineInfo, int)]()
  168. for res in allSyms(c):
  169. if not seen.containsOrIncl((res[0].info, res[0].name.id)):
  170. yield res
  171. proc someSymFromImportTable*(c: PContext; name: PIdent; ambiguous: var bool): PSym =
  172. var marked = initIntSet()
  173. var symSet = OverloadableSyms
  174. result = nil
  175. block outer:
  176. for im in c.imports.mitems:
  177. for s in symbols(im, marked, name, c.graph):
  178. if result == nil:
  179. result = s
  180. elif s.kind notin symSet or result.kind notin symSet:
  181. ambiguous = true
  182. break outer
  183. proc searchInScopes*(c: PContext, s: PIdent; ambiguous: var bool): PSym =
  184. for scope in allScopes(c.currentScope):
  185. result = strTableGet(scope.symbols, s)
  186. if result != nil: return result
  187. result = someSymFromImportTable(c, s, ambiguous)
  188. proc debugScopes*(c: PContext; limit=0, max = int.high) {.deprecated.} =
  189. var i = 0
  190. var count = 0
  191. for scope in allScopes(c.currentScope):
  192. echo "scope ", i
  193. for h in 0..high(scope.symbols.data):
  194. if scope.symbols.data[h] != nil:
  195. if count >= max: return
  196. echo count, ": ", scope.symbols.data[h].name.s
  197. count.inc
  198. if i == limit: return
  199. inc i
  200. proc searchInScopesAllCandidatesFilterBy*(c: PContext, s: PIdent, filter: TSymKinds): seq[PSym] =
  201. result = @[]
  202. for scope in allScopes(c.currentScope):
  203. var ti: TIdentIter
  204. var candidate = initIdentIter(ti, scope.symbols, s)
  205. while candidate != nil:
  206. if candidate.kind in filter:
  207. result.add candidate
  208. candidate = nextIdentIter(ti, scope.symbols)
  209. if result.len == 0:
  210. var marked = initIntSet()
  211. for im in c.imports.mitems:
  212. for s in symbols(im, marked, s, c.graph):
  213. if s.kind in filter:
  214. result.add s
  215. proc searchInScopesFilterBy*(c: PContext, s: PIdent, filter: TSymKinds): seq[PSym] =
  216. result = @[]
  217. block outer:
  218. for scope in allScopes(c.currentScope):
  219. var ti: TIdentIter
  220. var candidate = initIdentIter(ti, scope.symbols, s)
  221. while candidate != nil:
  222. if candidate.kind in filter:
  223. result.add candidate
  224. # Break here, because further symbols encountered would be shadowed
  225. break outer
  226. candidate = nextIdentIter(ti, scope.symbols)
  227. if result.len == 0:
  228. var marked = initIntSet()
  229. for im in c.imports.mitems:
  230. for s in symbols(im, marked, s, c.graph):
  231. if s.kind in filter:
  232. result.add s
  233. proc errorSym*(c: PContext, n: PNode): PSym =
  234. ## creates an error symbol to avoid cascading errors (for IDE support)
  235. var m = n
  236. # ensure that 'considerQuotedIdent' can't fail:
  237. if m.kind == nkDotExpr: m = m[1]
  238. let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
  239. considerQuotedIdent(c, m)
  240. else:
  241. getIdent(c.cache, "err:" & renderTree(m))
  242. result = newSym(skError, ident, nextSymId(c.idgen), getCurrOwner(c), n.info, {})
  243. result.typ = errorType(c)
  244. incl(result.flags, sfDiscardable)
  245. # pretend it's from the top level scope to prevent cascading errors:
  246. if c.config.cmd != cmdInteractive and c.compilesContextId == 0:
  247. c.moduleScope.addSym(result)
  248. type
  249. TOverloadIterMode* = enum
  250. oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
  251. oimSymChoiceLocalLookup
  252. TOverloadIter* = object
  253. it*: TIdentIter
  254. mit*: ModuleIter
  255. m*: PSym
  256. mode*: TOverloadIterMode
  257. symChoiceIndex*: int
  258. currentScope: PScope
  259. importIdx: int
  260. marked: IntSet
  261. proc getSymRepr*(conf: ConfigRef; s: PSym, getDeclarationPath = true): string =
  262. case s.kind
  263. of routineKinds, skType:
  264. result = getProcHeader(conf, s, getDeclarationPath = getDeclarationPath)
  265. else:
  266. result = "'$1'" % s.name.s
  267. if getDeclarationPath:
  268. result.addDeclaredLoc(conf, s)
  269. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope) =
  270. # check if all symbols have been used and defined:
  271. var it: TTabIter
  272. var s = initTabIter(it, scope.symbols)
  273. var missingImpls = 0
  274. var unusedSyms: seq[tuple[sym: PSym, key: string]]
  275. while s != nil:
  276. if sfForward in s.flags and s.kind notin {skType, skModule}:
  277. # too many 'implementation of X' errors are annoying
  278. # and slow 'suggest' down:
  279. if missingImpls == 0:
  280. localError(c.config, s.info, "implementation of '$1' expected" %
  281. getSymRepr(c.config, s, getDeclarationPath=false))
  282. inc missingImpls
  283. elif {sfUsed, sfExported} * s.flags == {}:
  284. if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam, skEnumField}:
  285. # XXX: implicit type params are currently skTypes
  286. # maybe they can be made skGenericParam as well.
  287. if s.typ != nil and tfImplicitTypeParam notin s.typ.flags and
  288. s.typ.kind != tyGenericParam:
  289. unusedSyms.add (s, toFileLineCol(c.config, s.info))
  290. s = nextIter(it, scope.symbols)
  291. for (s, _) in sortedByIt(unusedSyms, it.key):
  292. message(c.config, s.info, hintXDeclaredButNotUsed, s.name.s)
  293. proc wrongRedefinition*(c: PContext; info: TLineInfo, s: string;
  294. conflictsWith: TLineInfo, note = errGenerated) =
  295. ## Emit a redefinition error if in non-interactive mode
  296. if c.config.cmd != cmdInteractive:
  297. localError(c.config, info, note,
  298. "redefinition of '$1'; previous declaration here: $2" %
  299. [s, c.config $ conflictsWith])
  300. # xxx pending bootstrap >= 1.4, replace all those overloads with a single one:
  301. # proc addDecl*(c: PContext, sym: PSym, info = sym.info, scope = c.currentScope) {.inline.} =
  302. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym, info: TLineInfo) =
  303. if sym.name.s == "_": return
  304. let conflict = scope.addUniqueSym(sym)
  305. if conflict != nil:
  306. if sym.kind == skModule and conflict.kind == skModule and
  307. sym.position == conflict.position:
  308. # e.g.: import foo; import foo
  309. # xxx we could refine this by issuing a different hint for the case
  310. # where a duplicate import happens inside an include.
  311. localError(c.config, info, hintDuplicateModuleImport,
  312. "duplicate import of '$1'; previous import here: $2" %
  313. [sym.name.s, c.config $ conflict.info])
  314. else:
  315. wrongRedefinition(c, info, sym.name.s, conflict.info, errGenerated)
  316. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym) {.inline.} =
  317. addDeclAt(c, scope, sym, sym.info)
  318. proc addDecl*(c: PContext, sym: PSym, info: TLineInfo) {.inline.} =
  319. addDeclAt(c, c.currentScope, sym, info)
  320. proc addDecl*(c: PContext, sym: PSym) {.inline.} =
  321. addDeclAt(c, c.currentScope, sym)
  322. proc addPrelimDecl*(c: PContext, sym: PSym) =
  323. discard c.currentScope.addUniqueSym(sym)
  324. from ic / ic import addHidden
  325. proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  326. ## adds symbol to the module for either private or public access.
  327. if sfExported in sym.flags:
  328. # add to interface:
  329. if c.module != nil: exportSym(c, sym)
  330. else: internalError(c.config, sym.info, "addInterfaceDeclAux")
  331. elif sym.kind in ExportableSymKinds and c.module != nil and isTopLevelInsideDeclaration(c, sym):
  332. strTableAdd(semtabAll(c.graph, c.module), sym)
  333. if c.config.symbolFiles != disabledSf:
  334. addHidden(c.encoder, c.packedRepr, sym)
  335. proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  336. ## adds a symbol on the scope and the interface if appropriate
  337. addDeclAt(c, scope, sym)
  338. if not scope.isShadowScope:
  339. # adding into a non-shadow scope, we need to handle exports, etc
  340. addInterfaceDeclAux(c, sym)
  341. proc addInterfaceDecl*(c: PContext, sym: PSym) {.inline.} =
  342. ## adds a decl and the interface if appropriate
  343. addInterfaceDeclAt(c, c.currentScope, sym)
  344. proc addOverloadableSymAt*(c: PContext; scope: PScope, fn: PSym) =
  345. ## adds an symbol to the given scope, will check for and raise errors if it's
  346. ## a redefinition as opposed to an overload.
  347. if fn.kind notin OverloadableSyms:
  348. internalError(c.config, fn.info, "addOverloadableSymAt")
  349. return
  350. if fn.name.s != "_":
  351. let check = strTableGet(scope.symbols, fn.name)
  352. if check != nil and check.kind notin OverloadableSyms:
  353. wrongRedefinition(c, fn.info, fn.name.s, check.info)
  354. else:
  355. scope.addSym(fn)
  356. proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  357. ## adds an overloadable symbol on the scope and the interface if appropriate
  358. addOverloadableSymAt(c, scope, sym)
  359. if not scope.isShadowScope:
  360. # adding into a non-shadow scope, we need to handle exports, etc
  361. addInterfaceDeclAux(c, sym)
  362. proc openShadowScope*(c: PContext) =
  363. ## opens a shadow scope, just like any other scope except the depth is the
  364. ## same as the parent -- see `isShadowScope`.
  365. c.currentScope = PScope(parent: c.currentScope,
  366. symbols: newStrTable(),
  367. depthLevel: c.scopeDepth)
  368. proc closeShadowScope*(c: PContext) =
  369. ## closes the shadow scope, but doesn't merge any of the symbols
  370. ## Does not check for unused symbols or missing forward decls since a macro
  371. ## or template consumes this AST
  372. rawCloseScope(c)
  373. proc mergeShadowScope*(c: PContext) =
  374. ## close the existing scope and merge in all defined symbols, this will also
  375. ## trigger any export related code if this is into a non-shadow scope.
  376. ##
  377. ## Merges:
  378. ## shadow -> shadow: add symbols to the parent but check for redefinitions etc
  379. ## shadow -> non-shadow: the above, but also handle exports and all that
  380. let shadowScope = c.currentScope
  381. c.rawCloseScope
  382. for sym in shadowScope.symbols:
  383. if sym.kind in OverloadableSyms:
  384. c.addInterfaceOverloadableSymAt(c.currentScope, sym)
  385. else:
  386. c.addInterfaceDecl(sym)
  387. when false:
  388. # `nimfix` used to call `altSpelling` and prettybase.replaceDeprecated(n.info, ident, alt)
  389. proc altSpelling(c: PContext, x: PIdent): PIdent =
  390. case x.s[0]
  391. of 'A'..'Z': result = getIdent(c.cache, toLowerAscii(x.s[0]) & x.s.substr(1))
  392. of 'a'..'z': result = getIdent(c.cache, toLowerAscii(x.s[0]) & x.s.substr(1))
  393. else: result = x
  394. import std/editdistance, heapqueue
  395. type SpellCandidate = object
  396. dist: int
  397. depth: int
  398. msg: string
  399. sym: PSym
  400. template toOrderTup(a: SpellCandidate): (int, int, string) =
  401. # `dist` is first, to favor nearby matches
  402. # `depth` is next, to favor nearby enclosing scopes among ties
  403. # `sym.name.s` is last, to make the list ordered and deterministic among ties
  404. (a.dist, a.depth, a.msg)
  405. proc `<`(a, b: SpellCandidate): bool =
  406. a.toOrderTup < b.toOrderTup
  407. proc mustFixSpelling(c: PContext): bool {.inline.} =
  408. result = c.config.spellSuggestMax != 0 and c.compilesContextId == 0
  409. # don't slowdown inside compiles()
  410. proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) =
  411. ## when we cannot find the identifier, suggest nearby spellings
  412. var list = initHeapQueue[SpellCandidate]()
  413. let name0 = ident.s.nimIdentNormalize
  414. for (sym, depth, isLocal) in allSyms(c):
  415. let depth = -depth - 1
  416. let dist = editDistance(name0, sym.name.s.nimIdentNormalize)
  417. var msg: string
  418. msg.add "\n ($1, $2): '$3'" % [$dist, $depth, sym.name.s]
  419. list.push SpellCandidate(dist: dist, depth: depth, msg: msg, sym: sym)
  420. if list.len == 0: return
  421. let e0 = list[0]
  422. var
  423. count = 0
  424. last: PIdent = nil
  425. while true:
  426. # pending https://github.com/timotheecour/Nim/issues/373 use more efficient `itemsSorted`.
  427. if list.len == 0: break
  428. let e = list.pop()
  429. if c.config.spellSuggestMax == spellSuggestSecretSauce:
  430. const
  431. smallThres = 2
  432. maxCountForSmall = 4
  433. # avoids ton of operator matches when mis-matching short symbols such as `i`
  434. # other heuristics could be devised, such as only suggesting operators if `name0`
  435. # is an operator (likewise with non-operators).
  436. if e.dist > e0.dist or (name0.len <= smallThres and count >= maxCountForSmall): break
  437. elif count >= c.config.spellSuggestMax: break
  438. if count == 0:
  439. result.add "\ncandidates (edit distance, scope distance); see '--spellSuggest': "
  440. if e.sym.name != last:
  441. result.add e.msg
  442. count.inc
  443. last = e.sym.name
  444. proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym; amb: var bool): PSym =
  445. var err = "ambiguous identifier: '" & s.name.s & "'"
  446. var i = 0
  447. var ignoredModules = 0
  448. for candidate in importedItems(c, s.name):
  449. if i == 0: err.add " -- use one of the following:\n"
  450. else: err.add "\n"
  451. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  452. err.add ": " & typeToString(candidate.typ)
  453. if candidate.kind == skModule:
  454. inc ignoredModules
  455. else:
  456. result = candidate
  457. inc i
  458. if ignoredModules != i-1:
  459. localError(c.config, info, errGenerated, err)
  460. result = nil
  461. else:
  462. amb = false
  463. proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
  464. var amb: bool
  465. discard errorUseQualifier(c, info, s, amb)
  466. proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]; prefix = "use one of") =
  467. var err = "ambiguous identifier: '" & candidates[0].name.s & "'"
  468. var i = 0
  469. for candidate in candidates:
  470. if i == 0: err.add " -- $1 the following:\n" % prefix
  471. else: err.add "\n"
  472. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  473. err.add ": " & typeToString(candidate.typ)
  474. inc i
  475. localError(c.config, info, errGenerated, err)
  476. proc errorUseQualifier*(c: PContext; info:TLineInfo; choices: PNode) =
  477. var candidates = newSeq[PSym](choices.len)
  478. let prefix = if choices[0].typ.kind != tyProc: "use one of" else: "you need a helper proc to disambiguate"
  479. for i, n in choices:
  480. candidates[i] = n.sym
  481. errorUseQualifier(c, info, candidates, prefix)
  482. proc errorUndeclaredIdentifier*(c: PContext; info: TLineInfo; name: string, extra = "") =
  483. var err: string
  484. if name == "_":
  485. err = "the special identifier '_' is ignored in declarations and cannot be used"
  486. else:
  487. err = "undeclared identifier: '" & name & "'" & extra
  488. if c.recursiveDep.len > 0:
  489. err.add "\nThis might be caused by a recursive module dependency:\n"
  490. err.add c.recursiveDep
  491. # prevent excessive errors for 'nim check'
  492. c.recursiveDep = ""
  493. localError(c.config, info, errGenerated, err)
  494. proc errorUndeclaredIdentifierHint*(c: PContext; n: PNode, ident: PIdent): PSym =
  495. var extra = ""
  496. if c.mustFixSpelling: fixSpelling(c, n, ident, extra)
  497. errorUndeclaredIdentifier(c, n.info, ident.s, extra)
  498. result = errorSym(c, n)
  499. proc lookUp*(c: PContext, n: PNode): PSym =
  500. # Looks up a symbol. Generates an error in case of nil.
  501. var amb = false
  502. case n.kind
  503. of nkIdent:
  504. result = searchInScopes(c, n.ident, amb).skipAlias(n, c.config)
  505. if result == nil: result = errorUndeclaredIdentifierHint(c, n, n.ident)
  506. of nkSym:
  507. result = n.sym
  508. of nkAccQuoted:
  509. var ident = considerQuotedIdent(c, n)
  510. result = searchInScopes(c, ident, amb).skipAlias(n, c.config)
  511. if result == nil: result = errorUndeclaredIdentifierHint(c, n, ident)
  512. else:
  513. internalError(c.config, n.info, "lookUp")
  514. return
  515. if amb:
  516. #contains(c.ambiguousSymbols, result.id):
  517. result = errorUseQualifier(c, n.info, result, amb)
  518. when false:
  519. if result.kind == skStub: loadStub(result)
  520. type
  521. TLookupFlag* = enum
  522. checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
  523. proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  524. const allExceptModule = {low(TSymKind)..high(TSymKind)} - {skModule, skPackage}
  525. case n.kind
  526. of nkIdent, nkAccQuoted:
  527. var amb = false
  528. var ident = considerQuotedIdent(c, n)
  529. if checkModule in flags:
  530. result = searchInScopes(c, ident, amb).skipAlias(n, c.config)
  531. else:
  532. let candidates = searchInScopesFilterBy(c, ident, allExceptModule) #.skipAlias(n, c.config)
  533. if candidates.len > 0:
  534. result = candidates[0]
  535. amb = candidates.len > 1
  536. if amb and checkAmbiguity in flags:
  537. errorUseQualifier(c, n.info, candidates)
  538. if result == nil:
  539. let candidates = allPureEnumFields(c, ident)
  540. if candidates.len > 0:
  541. result = candidates[0]
  542. amb = candidates.len > 1
  543. if amb and checkAmbiguity in flags:
  544. errorUseQualifier(c, n.info, candidates)
  545. if result == nil and checkUndeclared in flags:
  546. result = errorUndeclaredIdentifierHint(c, n, ident)
  547. elif checkAmbiguity in flags and result != nil and amb:
  548. result = errorUseQualifier(c, n.info, result, amb)
  549. c.isAmbiguous = amb
  550. of nkSym:
  551. result = n.sym
  552. of nkDotExpr:
  553. result = nil
  554. var m = qualifiedLookUp(c, n[0], (flags * {checkUndeclared}) + {checkModule})
  555. if m != nil and m.kind == skModule:
  556. var ident: PIdent = nil
  557. if n[1].kind == nkIdent:
  558. ident = n[1].ident
  559. elif n[1].kind == nkAccQuoted:
  560. ident = considerQuotedIdent(c, n[1])
  561. if ident != nil:
  562. if m == c.module:
  563. result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n, c.config)
  564. else:
  565. result = someSym(c.graph, m, ident).skipAlias(n, c.config)
  566. if result == nil and checkUndeclared in flags:
  567. result = errorUndeclaredIdentifierHint(c, n[1], ident)
  568. elif n[1].kind == nkSym:
  569. result = n[1].sym
  570. elif checkUndeclared in flags and
  571. n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  572. localError(c.config, n[1].info, "identifier expected, but got: " &
  573. renderTree(n[1]))
  574. result = errorSym(c, n[1])
  575. else:
  576. result = nil
  577. when false:
  578. if result != nil and result.kind == skStub: loadStub(result)
  579. proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  580. o.importIdx = -1
  581. o.marked = initIntSet()
  582. case n.kind
  583. of nkIdent, nkAccQuoted:
  584. var ident = considerQuotedIdent(c, n)
  585. var scope = c.currentScope
  586. o.mode = oimNoQualifier
  587. while true:
  588. result = initIdentIter(o.it, scope.symbols, ident).skipAlias(n, c.config)
  589. if result != nil:
  590. o.currentScope = scope
  591. break
  592. else:
  593. scope = scope.parent
  594. if scope == nil:
  595. for i in 0..c.imports.high:
  596. result = initIdentIter(o.mit, o.marked, c.imports[i], ident, c.graph).skipAlias(n, c.config)
  597. if result != nil:
  598. o.currentScope = nil
  599. o.importIdx = i
  600. return result
  601. return nil
  602. of nkSym:
  603. result = n.sym
  604. o.mode = oimDone
  605. of nkDotExpr:
  606. o.mode = oimOtherModule
  607. o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
  608. if o.m != nil and o.m.kind == skModule:
  609. var ident: PIdent = nil
  610. if n[1].kind == nkIdent:
  611. ident = n[1].ident
  612. elif n[1].kind == nkAccQuoted:
  613. ident = considerQuotedIdent(c, n[1], n)
  614. if ident != nil:
  615. if o.m == c.module:
  616. # a module may access its private members:
  617. result = initIdentIter(o.it, c.topLevelScope.symbols,
  618. ident).skipAlias(n, c.config)
  619. o.mode = oimSelfModule
  620. else:
  621. result = initModuleIter(o.mit, c.graph, o.m, ident).skipAlias(n, c.config)
  622. else:
  623. noidentError(c.config, n[1], n)
  624. result = errorSym(c, n[1])
  625. of nkClosedSymChoice, nkOpenSymChoice:
  626. o.mode = oimSymChoice
  627. if n[0].kind == nkSym:
  628. result = n[0].sym
  629. else:
  630. o.mode = oimDone
  631. return nil
  632. o.symChoiceIndex = 1
  633. o.marked = initIntSet()
  634. incl(o.marked, result.id)
  635. else: discard
  636. when false:
  637. if result != nil and result.kind == skStub: loadStub(result)
  638. proc lastOverloadScope*(o: TOverloadIter): int =
  639. case o.mode
  640. of oimNoQualifier:
  641. result = if o.importIdx >= 0: 0
  642. elif o.currentScope.isNil: -1
  643. else: o.currentScope.depthLevel
  644. of oimSelfModule: result = 1
  645. of oimOtherModule: result = 0
  646. else: result = -1
  647. proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  648. assert o.currentScope == nil
  649. var idx = o.importIdx+1
  650. o.importIdx = c.imports.len # assume the other imported modules lack this symbol too
  651. while idx < c.imports.len:
  652. result = initIdentIter(o.mit, o.marked, c.imports[idx], o.it.name, c.graph).skipAlias(n, c.config)
  653. if result != nil:
  654. # oh, we were wrong, some other module had the symbol, so remember that:
  655. o.importIdx = idx
  656. break
  657. inc idx
  658. proc symChoiceExtension(o: var TOverloadIter; c: PContext; n: PNode): PSym =
  659. assert o.currentScope == nil
  660. while o.importIdx < c.imports.len:
  661. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph).skipAlias(n, c.config)
  662. #while result != nil and result.id in o.marked:
  663. # result = nextIdentIter(o.it, o.marked, c.imports[o.importIdx])
  664. if result != nil:
  665. #assert result.id notin o.marked
  666. return result
  667. inc o.importIdx
  668. proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  669. case o.mode
  670. of oimDone:
  671. result = nil
  672. of oimNoQualifier:
  673. if o.currentScope != nil:
  674. assert o.importIdx < 0
  675. result = nextIdentIter(o.it, o.currentScope.symbols).skipAlias(n, c.config)
  676. while result == nil:
  677. o.currentScope = o.currentScope.parent
  678. if o.currentScope != nil:
  679. result = initIdentIter(o.it, o.currentScope.symbols, o.it.name).skipAlias(n, c.config)
  680. # BUGFIX: o.it.name <-> n.ident
  681. else:
  682. o.importIdx = 0
  683. if c.imports.len > 0:
  684. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph).skipAlias(n, c.config)
  685. if result == nil:
  686. result = nextOverloadIterImports(o, c, n)
  687. break
  688. elif o.importIdx < c.imports.len:
  689. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph).skipAlias(n, c.config)
  690. if result == nil:
  691. result = nextOverloadIterImports(o, c, n)
  692. else:
  693. result = nil
  694. of oimSelfModule:
  695. result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n, c.config)
  696. of oimOtherModule:
  697. result = nextModuleIter(o.mit, c.graph).skipAlias(n, c.config)
  698. of oimSymChoice:
  699. if o.symChoiceIndex < n.len:
  700. result = n[o.symChoiceIndex].sym
  701. incl(o.marked, result.id)
  702. inc o.symChoiceIndex
  703. elif n.kind == nkOpenSymChoice:
  704. # try 'local' symbols too for Koenig's lookup:
  705. o.mode = oimSymChoiceLocalLookup
  706. o.currentScope = c.currentScope
  707. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  708. n[0].sym.name, o.marked).skipAlias(n, c.config)
  709. while result == nil:
  710. o.currentScope = o.currentScope.parent
  711. if o.currentScope != nil:
  712. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  713. n[0].sym.name, o.marked).skipAlias(n, c.config)
  714. else:
  715. o.importIdx = 0
  716. result = symChoiceExtension(o, c, n)
  717. break
  718. if result != nil:
  719. incl o.marked, result.id
  720. of oimSymChoiceLocalLookup:
  721. if o.currentScope != nil:
  722. result = nextIdentExcluding(o.it, o.currentScope.symbols, o.marked).skipAlias(n, c.config)
  723. while result == nil:
  724. o.currentScope = o.currentScope.parent
  725. if o.currentScope != nil:
  726. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  727. n[0].sym.name, o.marked).skipAlias(n, c.config)
  728. else:
  729. o.importIdx = 0
  730. result = symChoiceExtension(o, c, n)
  731. break
  732. if result != nil:
  733. incl o.marked, result.id
  734. elif o.importIdx < c.imports.len:
  735. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph).skipAlias(n, c.config)
  736. #assert result.id notin o.marked
  737. #while result != nil and result.id in o.marked:
  738. # result = nextIdentIter(o.it, c.imports[o.importIdx]).skipAlias(n, c.config)
  739. if result == nil:
  740. inc o.importIdx
  741. result = symChoiceExtension(o, c, n)
  742. when false:
  743. if result != nil and result.kind == skStub: loadStub(result)
  744. proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
  745. flags: TSymFlags = {}): PSym =
  746. var o: TOverloadIter
  747. var a = initOverloadIter(o, c, n)
  748. while a != nil:
  749. if a.kind in kinds and flags <= a.flags:
  750. if result == nil: result = a
  751. else: return nil # ambiguous
  752. a = nextOverloadIter(o, c, n)