lookups.nim 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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
  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
  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
  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
  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
  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
  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
  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 & "'" & extra
  517. if c.recursiveDep.len > 0:
  518. err.add "\nThis might be caused by a recursive module dependency:\n"
  519. err.add c.recursiveDep
  520. # prevent excessive errors for 'nim check'
  521. c.recursiveDep = ""
  522. localError(c.config, info, errGenerated, err)
  523. proc errorUndeclaredIdentifierHint*(c: PContext; ident: PIdent; info: TLineInfo): PSym =
  524. var extra = ""
  525. if c.mustFixSpelling: fixSpelling(c, ident, extra)
  526. errorUndeclaredIdentifier(c, info, ident.s, extra)
  527. result = errorSym(c, ident, info)
  528. proc lookUp*(c: PContext, n: PNode): PSym =
  529. # Looks up a symbol. Generates an error in case of nil.
  530. var amb = false
  531. case n.kind
  532. of nkIdent:
  533. result = searchInScopes(c, n.ident, amb)
  534. if result == nil: result = errorUndeclaredIdentifierHint(c, n.ident, n.info)
  535. of nkSym:
  536. result = n.sym
  537. of nkAccQuoted:
  538. var ident = considerQuotedIdent(c, n)
  539. result = searchInScopes(c, ident, amb)
  540. if result == nil: result = errorUndeclaredIdentifierHint(c, ident, n.info)
  541. else:
  542. internalError(c.config, n.info, "lookUp")
  543. return nil
  544. if amb:
  545. #contains(c.ambiguousSymbols, result.id):
  546. result = errorUseQualifier(c, n.info, result, amb)
  547. when false:
  548. if result.kind == skStub: loadStub(result)
  549. type
  550. TLookupFlag* = enum
  551. checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
  552. const allExceptModule = {low(TSymKind)..high(TSymKind)} - {skModule, skPackage}
  553. proc lookUpCandidates*(c: PContext, ident: PIdent, filter: set[TSymKind]): seq[PSym] =
  554. result = searchInScopesFilterBy(c, ident, filter)
  555. if result.len == 0:
  556. result.add allPureEnumFields(c, ident)
  557. proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  558. case n.kind
  559. of nkIdent, nkAccQuoted:
  560. var amb = false
  561. var ident = considerQuotedIdent(c, n)
  562. if checkModule in flags:
  563. result = searchInScopes(c, ident, amb)
  564. if result == nil:
  565. let candidates = allPureEnumFields(c, ident)
  566. if candidates.len > 0:
  567. result = candidates[0]
  568. amb = candidates.len > 1
  569. if amb and checkAmbiguity in flags:
  570. errorUseQualifier(c, n.info, candidates)
  571. else:
  572. let candidates = lookUpCandidates(c, ident, allExceptModule)
  573. if candidates.len > 0:
  574. result = candidates[0]
  575. amb = candidates.len > 1
  576. if amb and checkAmbiguity in flags:
  577. errorUseQualifier(c, n.info, candidates)
  578. else:
  579. result = nil
  580. if result == nil and checkUndeclared in flags:
  581. result = errorUndeclaredIdentifierHint(c, ident, n.info)
  582. elif checkAmbiguity in flags and result != nil and amb:
  583. result = errorUseQualifier(c, n.info, result, amb)
  584. c.isAmbiguous = amb
  585. of nkSym:
  586. result = n.sym
  587. of nkDotExpr:
  588. result = nil
  589. var m = qualifiedLookUp(c, n[0], (flags * {checkUndeclared}) + {checkModule})
  590. if m != nil and m.kind == skModule:
  591. var ident: PIdent = nil
  592. if n[1].kind == nkIdent:
  593. ident = n[1].ident
  594. elif n[1].kind == nkAccQuoted:
  595. ident = considerQuotedIdent(c, n[1])
  596. if ident != nil:
  597. if m == c.module:
  598. result = strTableGet(c.topLevelScope.symbols, ident)
  599. else:
  600. if c.importModuleLookup.getOrDefault(m.name.id).len > 1:
  601. var amb: bool
  602. result = errorUseQualifier(c, n.info, m, amb)
  603. else:
  604. result = someSym(c.graph, m, ident)
  605. if result == nil and checkUndeclared in flags:
  606. result = errorUndeclaredIdentifierHint(c, ident, n[1].info)
  607. elif n[1].kind == nkSym:
  608. result = n[1].sym
  609. if result.owner != nil and result.owner != m and checkUndeclared in flags:
  610. # dotExpr in templates can end up here
  611. result = errorUndeclaredIdentifierHint(c, result.name, n[1].info)
  612. elif checkUndeclared in flags and
  613. n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  614. localError(c.config, n[1].info, "identifier expected, but got: " &
  615. renderTree(n[1]))
  616. result = errorSym(c, n[1])
  617. else:
  618. result = nil
  619. when false:
  620. if result != nil and result.kind == skStub: loadStub(result)
  621. proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  622. o.importIdx = -1
  623. o.marked = initIntSet()
  624. case n.kind
  625. of nkIdent, nkAccQuoted:
  626. result = nil
  627. var ident = considerQuotedIdent(c, n)
  628. var scope = c.currentScope
  629. o.mode = oimNoQualifier
  630. while true:
  631. result = initIdentIter(o.it, scope.symbols, ident)
  632. if result != nil:
  633. o.currentScope = scope
  634. break
  635. else:
  636. scope = scope.parent
  637. if scope == nil:
  638. for i in 0..c.imports.high:
  639. result = initIdentIter(o.mit, o.marked, c.imports[i], ident, c.graph)
  640. if result != nil:
  641. o.currentScope = nil
  642. o.importIdx = i
  643. return result
  644. return nil
  645. of nkSym:
  646. result = n.sym
  647. o.mode = oimDone
  648. of nkDotExpr:
  649. result = nil
  650. o.mode = oimOtherModule
  651. o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
  652. if o.m != nil and o.m.kind == skModule:
  653. var ident: PIdent = nil
  654. if n[1].kind == nkIdent:
  655. ident = n[1].ident
  656. elif n[1].kind == nkAccQuoted:
  657. ident = considerQuotedIdent(c, n[1], n)
  658. if ident != nil:
  659. if o.m == c.module:
  660. # a module may access its private members:
  661. result = initIdentIter(o.it, c.topLevelScope.symbols,
  662. ident)
  663. o.mode = oimSelfModule
  664. else:
  665. result = initModuleIter(o.mit, c.graph, o.m, ident)
  666. else:
  667. noidentError(c.config, n[1], n)
  668. result = errorSym(c, n[1])
  669. of nkClosedSymChoice, nkOpenSymChoice:
  670. o.mode = oimSymChoice
  671. if n[0].kind == nkSym:
  672. result = n[0].sym
  673. else:
  674. o.mode = oimDone
  675. return nil
  676. o.symChoiceIndex = 1
  677. o.marked = initIntSet()
  678. incl(o.marked, result.id)
  679. else: result = nil
  680. when false:
  681. if result != nil and result.kind == skStub: loadStub(result)
  682. proc lastOverloadScope*(o: TOverloadIter): int =
  683. case o.mode
  684. of oimNoQualifier:
  685. result = if o.importIdx >= 0: 0
  686. elif o.currentScope.isNil: -1
  687. else: o.currentScope.depthLevel
  688. of oimSelfModule: result = 1
  689. of oimOtherModule: result = 0
  690. else: result = -1
  691. proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  692. result = nil
  693. assert o.currentScope == nil
  694. var idx = o.importIdx+1
  695. o.importIdx = c.imports.len # assume the other imported modules lack this symbol too
  696. while idx < c.imports.len:
  697. result = initIdentIter(o.mit, o.marked, c.imports[idx], o.it.name, c.graph)
  698. if result != nil:
  699. # oh, we were wrong, some other module had the symbol, so remember that:
  700. o.importIdx = idx
  701. break
  702. inc idx
  703. proc symChoiceExtension(o: var TOverloadIter; c: PContext; n: PNode): PSym =
  704. result = nil
  705. assert o.currentScope == nil
  706. while o.importIdx < c.imports.len:
  707. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph)
  708. #while result != nil and result.id in o.marked:
  709. # result = nextIdentIter(o.it, o.marked, c.imports[o.importIdx])
  710. if result != nil:
  711. #assert result.id notin o.marked
  712. return result
  713. inc o.importIdx
  714. proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  715. case o.mode
  716. of oimDone:
  717. result = nil
  718. of oimNoQualifier:
  719. if o.currentScope != nil:
  720. assert o.importIdx < 0
  721. result = nextIdentIter(o.it, o.currentScope.symbols)
  722. while result == nil:
  723. o.currentScope = o.currentScope.parent
  724. if o.currentScope != nil:
  725. result = initIdentIter(o.it, o.currentScope.symbols, o.it.name)
  726. # BUGFIX: o.it.name <-> n.ident
  727. else:
  728. o.importIdx = 0
  729. if c.imports.len > 0:
  730. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph)
  731. if result == nil:
  732. result = nextOverloadIterImports(o, c, n)
  733. break
  734. elif o.importIdx < c.imports.len:
  735. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph)
  736. if result == nil:
  737. result = nextOverloadIterImports(o, c, n)
  738. else:
  739. result = nil
  740. of oimSelfModule:
  741. result = nextIdentIter(o.it, c.topLevelScope.symbols)
  742. of oimOtherModule:
  743. result = nextModuleIter(o.mit, c.graph)
  744. of oimSymChoice:
  745. if o.symChoiceIndex < n.len:
  746. result = n[o.symChoiceIndex].sym
  747. incl(o.marked, result.id)
  748. inc o.symChoiceIndex
  749. elif n.kind == nkOpenSymChoice:
  750. # try 'local' symbols too for Koenig's lookup:
  751. o.mode = oimSymChoiceLocalLookup
  752. o.currentScope = c.currentScope
  753. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  754. n[0].sym.name, o.marked)
  755. while result == nil:
  756. o.currentScope = o.currentScope.parent
  757. if o.currentScope != nil:
  758. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  759. n[0].sym.name, o.marked)
  760. else:
  761. o.importIdx = 0
  762. result = symChoiceExtension(o, c, n)
  763. break
  764. if result != nil:
  765. incl o.marked, result.id
  766. else:
  767. result = nil
  768. of oimSymChoiceLocalLookup:
  769. if o.currentScope != nil:
  770. result = nextIdentExcluding(o.it, o.currentScope.symbols, o.marked)
  771. while result == nil:
  772. o.currentScope = o.currentScope.parent
  773. if o.currentScope != nil:
  774. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  775. n[0].sym.name, o.marked)
  776. else:
  777. o.importIdx = 0
  778. result = symChoiceExtension(o, c, n)
  779. break
  780. if result != nil:
  781. incl o.marked, result.id
  782. elif o.importIdx < c.imports.len:
  783. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph)
  784. #assert result.id notin o.marked
  785. #while result != nil and result.id in o.marked:
  786. # result = nextIdentIter(o.it, c.imports[o.importIdx])
  787. if result == nil:
  788. inc o.importIdx
  789. result = symChoiceExtension(o, c, n)
  790. else:
  791. result = nil
  792. when false:
  793. if result != nil and result.kind == skStub: loadStub(result)
  794. proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
  795. flags: TSymFlags = {}): PSym =
  796. result = nil
  797. var o: TOverloadIter = default(TOverloadIter)
  798. var a = initOverloadIter(o, c, n)
  799. while a != nil:
  800. if a.kind in kinds and flags <= a.flags:
  801. if result == nil: result = a
  802. else: return nil # ambiguous
  803. a = nextOverloadIter(o, c, n)