lookups.nim 29 KB

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