lookups.nim 29 KB

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