lookups.nim 30 KB

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