lookups.nim 28 KB

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