lookups.nim 31 KB

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