lookups.nim 31 KB

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