lookups.nim 28 KB

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