lookups.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 errorSym*(c: PContext, n: PNode): PSym =
  224. ## creates an error symbol to avoid cascading errors (for IDE support)
  225. var m = n
  226. # ensure that 'considerQuotedIdent' can't fail:
  227. if m.kind == nkDotExpr: m = m[1]
  228. let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
  229. considerQuotedIdent(c, m)
  230. else:
  231. getIdent(c.cache, "err:" & renderTree(m))
  232. result = newSym(skError, ident, c.idgen, getCurrOwner(c), n.info, {})
  233. result.typ = errorType(c)
  234. incl(result.flags, sfDiscardable)
  235. # pretend it's from the top level scope to prevent cascading errors:
  236. if c.config.cmd != cmdInteractive and c.compilesContextId == 0:
  237. c.moduleScope.addSym(result)
  238. type
  239. TOverloadIterMode* = enum
  240. oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
  241. oimSymChoiceLocalLookup
  242. TOverloadIter* = object
  243. it*: TIdentIter
  244. mit*: ModuleIter
  245. m*: PSym
  246. mode*: TOverloadIterMode
  247. symChoiceIndex*: int
  248. currentScope: PScope
  249. importIdx: int
  250. marked: IntSet
  251. proc getSymRepr*(conf: ConfigRef; s: PSym, getDeclarationPath = true): string =
  252. case s.kind
  253. of routineKinds, skType:
  254. result = getProcHeader(conf, s, getDeclarationPath = getDeclarationPath)
  255. else:
  256. result = "'$1'" % s.name.s
  257. if getDeclarationPath:
  258. result.addDeclaredLoc(conf, s)
  259. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope) =
  260. # check if all symbols have been used and defined:
  261. var it: TTabIter
  262. var s = initTabIter(it, scope.symbols)
  263. var missingImpls = 0
  264. var unusedSyms: seq[tuple[sym: PSym, key: string]] = @[]
  265. while s != nil:
  266. if sfForward in s.flags and s.kind notin {skType, skModule}:
  267. # too many 'implementation of X' errors are annoying
  268. # and slow 'suggest' down:
  269. if missingImpls == 0:
  270. localError(c.config, s.info, "implementation of '$1' expected" %
  271. getSymRepr(c.config, s, getDeclarationPath=false))
  272. inc missingImpls
  273. elif {sfUsed, sfExported} * s.flags == {}:
  274. if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam, skEnumField}:
  275. # XXX: implicit type params are currently skTypes
  276. # maybe they can be made skGenericParam as well.
  277. if s.typ != nil and tfImplicitTypeParam notin s.typ.flags and
  278. s.typ.kind != tyGenericParam:
  279. unusedSyms.add (s, toFileLineCol(c.config, s.info))
  280. s = nextIter(it, scope.symbols)
  281. for (s, _) in sortedByIt(unusedSyms, it.key):
  282. message(c.config, s.info, hintXDeclaredButNotUsed, s.name.s)
  283. proc wrongRedefinition*(c: PContext; info: TLineInfo, s: string;
  284. conflictsWith: TLineInfo, note = errGenerated) =
  285. ## Emit a redefinition error if in non-interactive mode
  286. if c.config.cmd != cmdInteractive:
  287. localError(c.config, info, note,
  288. "redefinition of '$1'; previous declaration here: $2" %
  289. [s, c.config $ conflictsWith])
  290. # xxx pending bootstrap >= 1.4, replace all those overloads with a single one:
  291. # proc addDecl*(c: PContext, sym: PSym, info = sym.info, scope = c.currentScope) {.inline.} =
  292. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym, info: TLineInfo) =
  293. if sym.name.id == ord(wUnderscore): return
  294. let conflict = scope.addUniqueSym(sym)
  295. if conflict != nil:
  296. if sym.kind == skModule and conflict.kind == skModule:
  297. # e.g.: import foo; import foo
  298. # xxx we could refine this by issuing a different hint for the case
  299. # where a duplicate import happens inside an include.
  300. if c.importModuleMap[sym.id] == c.importModuleMap[conflict.id]:
  301. #only hints if the conflict is the actual module not just a shared name
  302. localError(c.config, info, hintDuplicateModuleImport,
  303. "duplicate import of '$1'; previous import here: $2" %
  304. [sym.name.s, c.config $ conflict.info])
  305. else:
  306. wrongRedefinition(c, info, sym.name.s, conflict.info, errGenerated)
  307. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym) {.inline.} =
  308. addDeclAt(c, scope, sym, sym.info)
  309. proc addDecl*(c: PContext, sym: PSym, info: TLineInfo) {.inline.} =
  310. addDeclAt(c, c.currentScope, sym, info)
  311. proc addDecl*(c: PContext, sym: PSym) {.inline.} =
  312. addDeclAt(c, c.currentScope, sym)
  313. proc addPrelimDecl*(c: PContext, sym: PSym) =
  314. discard c.currentScope.addUniqueSym(sym)
  315. from ic / ic import addHidden
  316. proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  317. ## adds symbol to the module for either private or public access.
  318. if sfExported in sym.flags:
  319. # add to interface:
  320. if c.module != nil: exportSym(c, sym)
  321. else: internalError(c.config, sym.info, "addInterfaceDeclAux")
  322. elif sym.kind in ExportableSymKinds and c.module != nil and isTopLevelInsideDeclaration(c, sym):
  323. strTableAdd(semtabAll(c.graph, c.module), sym)
  324. if c.config.symbolFiles != disabledSf:
  325. addHidden(c.encoder, c.packedRepr, sym)
  326. proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  327. ## adds a symbol on the scope and the interface if appropriate
  328. addDeclAt(c, scope, sym)
  329. if not scope.isShadowScope:
  330. # adding into a non-shadow scope, we need to handle exports, etc
  331. addInterfaceDeclAux(c, sym)
  332. proc addInterfaceDecl*(c: PContext, sym: PSym) {.inline.} =
  333. ## adds a decl and the interface if appropriate
  334. addInterfaceDeclAt(c, c.currentScope, sym)
  335. proc addOverloadableSymAt*(c: PContext; scope: PScope, fn: PSym) =
  336. ## adds an symbol to the given scope, will check for and raise errors if it's
  337. ## a redefinition as opposed to an overload.
  338. if fn.kind notin OverloadableSyms:
  339. internalError(c.config, fn.info, "addOverloadableSymAt")
  340. return
  341. if fn.name.id != ord(wUnderscore):
  342. let check = strTableGet(scope.symbols, fn.name)
  343. if check != nil and check.kind notin OverloadableSyms:
  344. wrongRedefinition(c, fn.info, fn.name.s, check.info)
  345. else:
  346. scope.addSym(fn)
  347. proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  348. ## adds an overloadable symbol on the scope and the interface if appropriate
  349. addOverloadableSymAt(c, scope, sym)
  350. if not scope.isShadowScope:
  351. # adding into a non-shadow scope, we need to handle exports, etc
  352. addInterfaceDeclAux(c, sym)
  353. proc openShadowScope*(c: PContext) =
  354. ## opens a shadow scope, just like any other scope except the depth is the
  355. ## same as the parent -- see `isShadowScope`.
  356. c.currentScope = PScope(parent: c.currentScope,
  357. symbols: initStrTable(),
  358. depthLevel: c.scopeDepth)
  359. proc closeShadowScope*(c: PContext) =
  360. ## closes the shadow scope, but doesn't merge any of the symbols
  361. ## Does not check for unused symbols or missing forward decls since a macro
  362. ## or template consumes this AST
  363. rawCloseScope(c)
  364. proc mergeShadowScope*(c: PContext) =
  365. ## close the existing scope and merge in all defined symbols, this will also
  366. ## trigger any export related code if this is into a non-shadow scope.
  367. ##
  368. ## Merges:
  369. ## shadow -> shadow: add symbols to the parent but check for redefinitions etc
  370. ## shadow -> non-shadow: the above, but also handle exports and all that
  371. let shadowScope = c.currentScope
  372. c.rawCloseScope
  373. for sym in shadowScope.symbols:
  374. if sym.kind in OverloadableSyms:
  375. c.addInterfaceOverloadableSymAt(c.currentScope, sym)
  376. else:
  377. c.addInterfaceDecl(sym)
  378. import std/editdistance, heapqueue
  379. type SpellCandidate = object
  380. dist: int
  381. depth: int
  382. msg: string
  383. sym: PSym
  384. template toOrderTup(a: SpellCandidate): (int, int, string) =
  385. # `dist` is first, to favor nearby matches
  386. # `depth` is next, to favor nearby enclosing scopes among ties
  387. # `sym.name.s` is last, to make the list ordered and deterministic among ties
  388. (a.dist, a.depth, a.msg)
  389. proc `<`(a, b: SpellCandidate): bool =
  390. a.toOrderTup < b.toOrderTup
  391. proc mustFixSpelling(c: PContext): bool {.inline.} =
  392. result = c.config.spellSuggestMax != 0 and c.compilesContextId == 0
  393. # don't slowdown inside compiles()
  394. proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) =
  395. ## when we cannot find the identifier, suggest nearby spellings
  396. var list = initHeapQueue[SpellCandidate]()
  397. let name0 = ident.s.nimIdentNormalize
  398. for (sym, depth, isLocal) in allSyms(c):
  399. let depth = -depth - 1
  400. let dist = editDistance(name0, sym.name.s.nimIdentNormalize)
  401. var msg: string = ""
  402. msg.add "\n ($1, $2): '$3'" % [$dist, $depth, sym.name.s]
  403. list.push SpellCandidate(dist: dist, depth: depth, msg: msg, sym: sym)
  404. if list.len == 0: return
  405. let e0 = list[0]
  406. var
  407. count = 0
  408. last: PIdent = nil
  409. while true:
  410. # pending https://github.com/timotheecour/Nim/issues/373 use more efficient `itemsSorted`.
  411. if list.len == 0: break
  412. let e = list.pop()
  413. if c.config.spellSuggestMax == spellSuggestSecretSauce:
  414. const
  415. minLengthForSuggestion = 4
  416. maxCount = 3 # avoids ton of matches; three counts for equal distances
  417. if e.dist > e0.dist or count >= maxCount or name0.len < minLengthForSuggestion: break
  418. elif count >= c.config.spellSuggestMax: break
  419. if count == 0:
  420. result.add "\ncandidates (edit distance, scope distance); see '--spellSuggest': "
  421. if e.sym.name != last:
  422. result.add e.msg
  423. count.inc
  424. last = e.sym.name
  425. proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym; amb: var bool): PSym =
  426. var err = "ambiguous identifier: '" & s.name.s & "'"
  427. var i = 0
  428. var ignoredModules = 0
  429. result = nil
  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: string
  466. if name == "_":
  467. err = "the special identifier '_' is ignored in declarations and cannot be used"
  468. else:
  469. err = "undeclared identifier: '" & name & "'" & extra
  470. if c.recursiveDep.len > 0:
  471. err.add "\nThis might be caused by a recursive module dependency:\n"
  472. err.add c.recursiveDep
  473. # prevent excessive errors for 'nim check'
  474. c.recursiveDep = ""
  475. localError(c.config, info, errGenerated, err)
  476. proc errorUndeclaredIdentifierHint*(c: PContext; n: PNode, ident: PIdent): PSym =
  477. var extra = ""
  478. if c.mustFixSpelling: fixSpelling(c, n, ident, extra)
  479. errorUndeclaredIdentifier(c, n.info, ident.s, extra)
  480. result = errorSym(c, n)
  481. proc lookUp*(c: PContext, n: PNode): PSym =
  482. # Looks up a symbol. Generates an error in case of nil.
  483. var amb = false
  484. case n.kind
  485. of nkIdent:
  486. result = searchInScopes(c, n.ident, amb)
  487. if result == nil: result = errorUndeclaredIdentifierHint(c, n, n.ident)
  488. of nkSym:
  489. result = n.sym
  490. of nkAccQuoted:
  491. var ident = considerQuotedIdent(c, n)
  492. result = searchInScopes(c, ident, amb)
  493. if result == nil: result = errorUndeclaredIdentifierHint(c, n, ident)
  494. else:
  495. internalError(c.config, n.info, "lookUp")
  496. return
  497. if amb:
  498. #contains(c.ambiguousSymbols, result.id):
  499. result = errorUseQualifier(c, n.info, result, amb)
  500. when false:
  501. if result.kind == skStub: loadStub(result)
  502. type
  503. TLookupFlag* = enum
  504. checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
  505. proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  506. const allExceptModule = {low(TSymKind)..high(TSymKind)} - {skModule, skPackage}
  507. case n.kind
  508. of nkIdent, nkAccQuoted:
  509. var amb = false
  510. var ident = considerQuotedIdent(c, n)
  511. if checkModule in flags:
  512. result = searchInScopes(c, ident, amb)
  513. else:
  514. let candidates = searchInScopesFilterBy(c, ident, allExceptModule)
  515. if candidates.len > 0:
  516. result = candidates[0]
  517. amb = candidates.len > 1
  518. if amb and checkAmbiguity in flags:
  519. errorUseQualifier(c, n.info, candidates)
  520. else:
  521. result = nil
  522. if result == nil:
  523. let candidates = allPureEnumFields(c, ident)
  524. if candidates.len > 0:
  525. result = candidates[0]
  526. amb = candidates.len > 1
  527. if amb and checkAmbiguity in flags:
  528. errorUseQualifier(c, n.info, candidates)
  529. if result == nil and checkUndeclared in flags:
  530. result = errorUndeclaredIdentifierHint(c, n, ident)
  531. elif checkAmbiguity in flags and result != nil and amb:
  532. result = errorUseQualifier(c, n.info, result, amb)
  533. c.isAmbiguous = amb
  534. of nkSym:
  535. result = n.sym
  536. of nkDotExpr:
  537. result = nil
  538. var m = qualifiedLookUp(c, n[0], (flags * {checkUndeclared}) + {checkModule})
  539. if m != nil and m.kind == skModule:
  540. var ident: PIdent = nil
  541. if n[1].kind == nkIdent:
  542. ident = n[1].ident
  543. elif n[1].kind == nkAccQuoted:
  544. ident = considerQuotedIdent(c, n[1])
  545. if ident != nil:
  546. if m == c.module:
  547. result = strTableGet(c.topLevelScope.symbols, ident)
  548. else:
  549. if c.importModuleLookup.getOrDefault(m.name.id).len > 1:
  550. var amb: bool
  551. result = errorUseQualifier(c, n.info, m, amb)
  552. else:
  553. result = someSym(c.graph, m, ident)
  554. if result == nil and checkUndeclared in flags:
  555. result = errorUndeclaredIdentifierHint(c, n[1], ident)
  556. elif n[1].kind == nkSym:
  557. result = n[1].sym
  558. if result.owner != nil and result.owner != m and checkUndeclared in flags:
  559. # dotExpr in templates can end up here
  560. result = errorUndeclaredIdentifierHint(c, n[1], considerQuotedIdent(c, n[1]))
  561. elif checkUndeclared in flags and
  562. n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  563. localError(c.config, n[1].info, "identifier expected, but got: " &
  564. renderTree(n[1]))
  565. result = errorSym(c, n[1])
  566. else:
  567. result = nil
  568. when false:
  569. if result != nil and result.kind == skStub: loadStub(result)
  570. proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  571. o.importIdx = -1
  572. o.marked = initIntSet()
  573. case n.kind
  574. of nkIdent, nkAccQuoted:
  575. result = nil
  576. var ident = considerQuotedIdent(c, n)
  577. var scope = c.currentScope
  578. o.mode = oimNoQualifier
  579. while true:
  580. result = initIdentIter(o.it, scope.symbols, ident)
  581. if result != nil:
  582. o.currentScope = scope
  583. break
  584. else:
  585. scope = scope.parent
  586. if scope == nil:
  587. for i in 0..c.imports.high:
  588. result = initIdentIter(o.mit, o.marked, c.imports[i], ident, c.graph)
  589. if result != nil:
  590. o.currentScope = nil
  591. o.importIdx = i
  592. return result
  593. return nil
  594. of nkSym:
  595. result = n.sym
  596. o.mode = oimDone
  597. of nkDotExpr:
  598. result = nil
  599. o.mode = oimOtherModule
  600. o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
  601. if o.m != nil and o.m.kind == skModule:
  602. var ident: PIdent = nil
  603. if n[1].kind == nkIdent:
  604. ident = n[1].ident
  605. elif n[1].kind == nkAccQuoted:
  606. ident = considerQuotedIdent(c, n[1], n)
  607. if ident != nil:
  608. if o.m == c.module:
  609. # a module may access its private members:
  610. result = initIdentIter(o.it, c.topLevelScope.symbols,
  611. ident)
  612. o.mode = oimSelfModule
  613. else:
  614. result = initModuleIter(o.mit, c.graph, o.m, ident)
  615. else:
  616. noidentError(c.config, n[1], n)
  617. result = errorSym(c, n[1])
  618. of nkClosedSymChoice, nkOpenSymChoice:
  619. o.mode = oimSymChoice
  620. if n[0].kind == nkSym:
  621. result = n[0].sym
  622. else:
  623. o.mode = oimDone
  624. return nil
  625. o.symChoiceIndex = 1
  626. o.marked = initIntSet()
  627. incl(o.marked, result.id)
  628. else: result = nil
  629. when false:
  630. if result != nil and result.kind == skStub: loadStub(result)
  631. proc lastOverloadScope*(o: TOverloadIter): int =
  632. case o.mode
  633. of oimNoQualifier:
  634. result = if o.importIdx >= 0: 0
  635. elif o.currentScope.isNil: -1
  636. else: o.currentScope.depthLevel
  637. of oimSelfModule: result = 1
  638. of oimOtherModule: result = 0
  639. else: result = -1
  640. proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  641. result = nil
  642. assert o.currentScope == nil
  643. var idx = o.importIdx+1
  644. o.importIdx = c.imports.len # assume the other imported modules lack this symbol too
  645. while idx < c.imports.len:
  646. result = initIdentIter(o.mit, o.marked, c.imports[idx], o.it.name, c.graph)
  647. if result != nil:
  648. # oh, we were wrong, some other module had the symbol, so remember that:
  649. o.importIdx = idx
  650. break
  651. inc idx
  652. proc symChoiceExtension(o: var TOverloadIter; c: PContext; n: PNode): PSym =
  653. result = nil
  654. assert o.currentScope == nil
  655. while o.importIdx < c.imports.len:
  656. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph)
  657. #while result != nil and result.id in o.marked:
  658. # result = nextIdentIter(o.it, o.marked, c.imports[o.importIdx])
  659. if result != nil:
  660. #assert result.id notin o.marked
  661. return result
  662. inc o.importIdx
  663. proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  664. case o.mode
  665. of oimDone:
  666. result = nil
  667. of oimNoQualifier:
  668. if o.currentScope != nil:
  669. assert o.importIdx < 0
  670. result = nextIdentIter(o.it, o.currentScope.symbols)
  671. while result == nil:
  672. o.currentScope = o.currentScope.parent
  673. if o.currentScope != nil:
  674. result = initIdentIter(o.it, o.currentScope.symbols, o.it.name)
  675. # BUGFIX: o.it.name <-> n.ident
  676. else:
  677. o.importIdx = 0
  678. if c.imports.len > 0:
  679. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph)
  680. if result == nil:
  681. result = nextOverloadIterImports(o, c, n)
  682. break
  683. elif o.importIdx < c.imports.len:
  684. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph)
  685. if result == nil:
  686. result = nextOverloadIterImports(o, c, n)
  687. else:
  688. result = nil
  689. of oimSelfModule:
  690. result = nextIdentIter(o.it, c.topLevelScope.symbols)
  691. of oimOtherModule:
  692. result = nextModuleIter(o.mit, c.graph)
  693. of oimSymChoice:
  694. if o.symChoiceIndex < n.len:
  695. result = n[o.symChoiceIndex].sym
  696. incl(o.marked, result.id)
  697. inc o.symChoiceIndex
  698. elif n.kind == nkOpenSymChoice:
  699. # try 'local' symbols too for Koenig's lookup:
  700. o.mode = oimSymChoiceLocalLookup
  701. o.currentScope = c.currentScope
  702. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  703. n[0].sym.name, o.marked)
  704. while result == nil:
  705. o.currentScope = o.currentScope.parent
  706. if o.currentScope != nil:
  707. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  708. n[0].sym.name, o.marked)
  709. else:
  710. o.importIdx = 0
  711. result = symChoiceExtension(o, c, n)
  712. break
  713. if result != nil:
  714. incl o.marked, result.id
  715. else:
  716. result = nil
  717. of oimSymChoiceLocalLookup:
  718. if o.currentScope != nil:
  719. result = nextIdentExcluding(o.it, o.currentScope.symbols, o.marked)
  720. while result == nil:
  721. o.currentScope = o.currentScope.parent
  722. if o.currentScope != nil:
  723. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  724. n[0].sym.name, o.marked)
  725. else:
  726. o.importIdx = 0
  727. result = symChoiceExtension(o, c, n)
  728. break
  729. if result != nil:
  730. incl o.marked, result.id
  731. elif o.importIdx < c.imports.len:
  732. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph)
  733. #assert result.id notin o.marked
  734. #while result != nil and result.id in o.marked:
  735. # result = nextIdentIter(o.it, c.imports[o.importIdx])
  736. if result == nil:
  737. inc o.importIdx
  738. result = symChoiceExtension(o, c, n)
  739. else:
  740. result = nil
  741. when false:
  742. if result != nil and result.kind == skStub: loadStub(result)
  743. proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
  744. flags: TSymFlags = {}): PSym =
  745. result = nil
  746. var o: TOverloadIter = default(TOverloadIter)
  747. var a = initOverloadIter(o, c, n)
  748. while a != nil:
  749. if a.kind in kinds and flags <= a.flags:
  750. if result == nil: result = a
  751. else: return nil # ambiguous
  752. a = nextOverloadIter(o, c, n)