lookups.nim 32 KB

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