lookups.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module implements lookup helpers.
  10. import std/[algorithm, strutils, tables]
  11. import
  12. intsets, ast, astalgo, idents, semdata, types, msgs, options,
  13. renderer, nimfix/prettybase, lineinfos, modulegraphs, astmsgs, wordrecg
  14. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope)
  15. proc noidentError(conf: ConfigRef; n, origin: PNode) =
  16. var m = ""
  17. if origin != nil:
  18. m.add "in expression '" & origin.renderTree & "': "
  19. m.add "identifier expected, but found '" & n.renderTree & "'"
  20. localError(conf, n.info, m)
  21. proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
  22. ## Retrieve a PIdent from a PNode, taking into account accent nodes.
  23. ## ``origin`` can be nil. If it is not nil, it is used for a better
  24. ## error message.
  25. template handleError(n, origin: PNode) =
  26. noidentError(c.config, n, origin)
  27. result = getIdent(c.cache, "<Error>")
  28. case n.kind
  29. of nkIdent: result = n.ident
  30. of nkSym: result = n.sym.name
  31. of nkAccQuoted:
  32. case n.len
  33. of 0: handleError(n, origin)
  34. of 1: result = considerQuotedIdent(c, n[0], origin)
  35. else:
  36. var id = ""
  37. for i in 0..<n.len:
  38. let x = n[i]
  39. case x.kind
  40. of nkIdent: id.add(x.ident.s)
  41. of nkSym: id.add(x.sym.name.s)
  42. of nkSymChoices:
  43. if x[0].kind == nkSym:
  44. id.add(x[0].sym.name.s)
  45. else:
  46. handleError(n, origin)
  47. of nkLiterals - nkFloatLiterals: id.add(x.renderTree)
  48. else: handleError(n, origin)
  49. result = getIdent(c.cache, id)
  50. of nkOpenSymChoice, nkClosedSymChoice:
  51. if n[0].kind == nkSym:
  52. result = n[0].sym.name
  53. else:
  54. handleError(n, origin)
  55. else:
  56. handleError(n, origin)
  57. template addSym*(scope: PScope, s: PSym) =
  58. strTableAdd(scope.symbols, s)
  59. proc addUniqueSym*(scope: PScope, s: PSym): PSym =
  60. result = strTableInclReportConflict(scope.symbols, s)
  61. proc openScope*(c: PContext): PScope {.discardable.} =
  62. result = PScope(parent: c.currentScope,
  63. symbols: newStrTable(),
  64. depthLevel: c.scopeDepth + 1)
  65. c.currentScope = result
  66. proc rawCloseScope*(c: PContext) =
  67. c.currentScope = c.currentScope.parent
  68. proc closeScope*(c: PContext) =
  69. ensureNoMissingOrUnusedSymbols(c, c.currentScope)
  70. rawCloseScope(c)
  71. iterator allScopes*(scope: PScope): PScope =
  72. var current = scope
  73. while current != nil:
  74. yield current
  75. current = current.parent
  76. iterator localScopesFrom*(c: PContext; scope: PScope): PScope =
  77. for s in allScopes(scope):
  78. if s == c.topLevelScope: break
  79. yield s
  80. proc skipAlias*(s: PSym; n: PNode; conf: ConfigRef): PSym =
  81. if s == nil or s.kind != skAlias:
  82. result = s
  83. else:
  84. result = s.owner
  85. if conf.cmd == cmdNimfix:
  86. prettybase.replaceDeprecated(conf, n.info, s, result)
  87. else:
  88. message(conf, n.info, warnDeprecated, "use " & result.name.s & " instead; " &
  89. s.name.s & " is deprecated")
  90. proc isShadowScope*(s: PScope): bool {.inline.} =
  91. s.parent != nil and s.parent.depthLevel == s.depthLevel
  92. proc localSearchInScope*(c: PContext, s: PIdent): PSym =
  93. var scope = c.currentScope
  94. result = strTableGet(scope.symbols, s)
  95. while result == nil and scope.isShadowScope:
  96. # We are in a shadow scope, check in the parent too
  97. scope = scope.parent
  98. result = strTableGet(scope.symbols, s)
  99. proc initIdentIter(ti: var ModuleIter; marked: var IntSet; im: ImportedModule; name: PIdent;
  100. g: ModuleGraph): PSym =
  101. result = initModuleIter(ti, g, im.m, name)
  102. while result != nil:
  103. let b =
  104. case im.mode
  105. of importAll: true
  106. of importSet: result.id in im.imported
  107. of importExcept: name.id notin im.exceptSet
  108. if b and not containsOrIncl(marked, result.id):
  109. return result
  110. result = nextModuleIter(ti, g)
  111. proc nextIdentIter(ti: var ModuleIter; marked: var IntSet; im: ImportedModule;
  112. g: ModuleGraph): PSym =
  113. while true:
  114. result = nextModuleIter(ti, g)
  115. if result == nil: return nil
  116. case im.mode
  117. of importAll:
  118. if not containsOrIncl(marked, result.id):
  119. return result
  120. of importSet:
  121. if result.id in im.imported and not containsOrIncl(marked, result.id):
  122. return result
  123. of importExcept:
  124. if result.name.id notin im.exceptSet and not containsOrIncl(marked, result.id):
  125. return result
  126. iterator symbols(im: ImportedModule; marked: var IntSet; name: PIdent; g: ModuleGraph): PSym =
  127. var ti: ModuleIter
  128. var candidate = initIdentIter(ti, marked, im, name, g)
  129. while candidate != nil:
  130. yield candidate
  131. candidate = nextIdentIter(ti, marked, im, g)
  132. iterator importedItems*(c: PContext; name: PIdent): PSym =
  133. var marked = initIntSet()
  134. for im in c.imports.mitems:
  135. for s in symbols(im, marked, name, c.graph):
  136. yield s
  137. proc allPureEnumFields(c: PContext; name: PIdent): seq[PSym] =
  138. var ti: TIdentIter
  139. result = @[]
  140. var res = initIdentIter(ti, c.pureEnumFields, name)
  141. while res != nil:
  142. result.add res
  143. res = nextIdentIter(ti, c.pureEnumFields)
  144. iterator allSyms*(c: PContext): (PSym, int, bool) =
  145. # really iterate over all symbols in all the scopes. This is expensive
  146. # and only used by suggest.nim.
  147. var isLocal = true
  148. var scopeN = 0
  149. for scope in allScopes(c.currentScope):
  150. if scope == c.topLevelScope: isLocal = false
  151. dec scopeN
  152. for item in scope.symbols:
  153. yield (item, scopeN, isLocal)
  154. dec scopeN
  155. isLocal = false
  156. for im in c.imports.mitems:
  157. for s in modulegraphs.allSyms(c.graph, im.m):
  158. assert s != nil
  159. yield (s, scopeN, isLocal)
  160. proc someSymFromImportTable*(c: PContext; name: PIdent; ambiguous: var bool): PSym =
  161. var marked = initIntSet()
  162. var symSet = OverloadableSyms
  163. if overloadableEnums notin c.features:
  164. symSet.excl skEnumField
  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:
  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. if c.importModuleMap[sym.id] == c.importModuleMap[conflict.id]:
  286. #only hints if the conflict is the actual module not just a shared name
  287. localError(c.config, info, hintDuplicateModuleImport,
  288. "duplicate import of '$1'; previous import here: $2" %
  289. [sym.name.s, c.config $ conflict.info])
  290. else:
  291. wrongRedefinition(c, info, sym.name.s, conflict.info, errGenerated)
  292. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym) {.inline.} =
  293. addDeclAt(c, scope, sym, sym.info)
  294. proc addDecl*(c: PContext, sym: PSym, info: TLineInfo) {.inline.} =
  295. addDeclAt(c, c.currentScope, sym, info)
  296. proc addDecl*(c: PContext, sym: PSym) {.inline.} =
  297. addDeclAt(c, c.currentScope, sym)
  298. proc addPrelimDecl*(c: PContext, sym: PSym) =
  299. discard c.currentScope.addUniqueSym(sym)
  300. from ic / ic import addHidden
  301. proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  302. ## adds symbol to the module for either private or public access.
  303. if sfExported in sym.flags:
  304. # add to interface:
  305. if c.module != nil: exportSym(c, sym)
  306. else: internalError(c.config, sym.info, "addInterfaceDeclAux")
  307. elif sym.kind in ExportableSymKinds and c.module != nil and isTopLevelInsideDeclaration(c, sym):
  308. strTableAdd(semtabAll(c.graph, c.module), sym)
  309. if c.config.symbolFiles != disabledSf:
  310. addHidden(c.encoder, c.packedRepr, sym)
  311. proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  312. ## adds a symbol on the scope and the interface if appropriate
  313. addDeclAt(c, scope, sym)
  314. if not scope.isShadowScope:
  315. # adding into a non-shadow scope, we need to handle exports, etc
  316. addInterfaceDeclAux(c, sym)
  317. proc addInterfaceDecl*(c: PContext, sym: PSym) {.inline.} =
  318. ## adds a decl and the interface if appropriate
  319. addInterfaceDeclAt(c, c.currentScope, sym)
  320. proc addOverloadableSymAt*(c: PContext; scope: PScope, fn: PSym) =
  321. ## adds an symbol to the given scope, will check for and raise errors if it's
  322. ## a redefinition as opposed to an overload.
  323. if fn.kind notin OverloadableSyms:
  324. internalError(c.config, fn.info, "addOverloadableSymAt")
  325. return
  326. let check = strTableGet(scope.symbols, fn.name)
  327. if check != nil and check.kind notin OverloadableSyms:
  328. wrongRedefinition(c, fn.info, fn.name.s, check.info)
  329. else:
  330. scope.addSym(fn)
  331. proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  332. ## adds an overloadable symbol on the scope and the interface if appropriate
  333. addOverloadableSymAt(c, scope, sym)
  334. if not scope.isShadowScope:
  335. # adding into a non-shadow scope, we need to handle exports, etc
  336. addInterfaceDeclAux(c, sym)
  337. proc openShadowScope*(c: PContext) =
  338. ## opens a shadow scope, just like any other scope except the depth is the
  339. ## same as the parent -- see `isShadowScope`.
  340. c.currentScope = PScope(parent: c.currentScope,
  341. symbols: newStrTable(),
  342. depthLevel: c.scopeDepth)
  343. proc closeShadowScope*(c: PContext) =
  344. ## closes the shadow scope, but doesn't merge any of the symbols
  345. ## Does not check for unused symbols or missing forward decls since a macro
  346. ## or template consumes this AST
  347. rawCloseScope(c)
  348. proc mergeShadowScope*(c: PContext) =
  349. ## close the existing scope and merge in all defined symbols, this will also
  350. ## trigger any export related code if this is into a non-shadow scope.
  351. ##
  352. ## Merges:
  353. ## shadow -> shadow: add symbols to the parent but check for redefinitions etc
  354. ## shadow -> non-shadow: the above, but also handle exports and all that
  355. let shadowScope = c.currentScope
  356. c.rawCloseScope
  357. for sym in shadowScope.symbols:
  358. if sym.kind in OverloadableSyms:
  359. c.addInterfaceOverloadableSymAt(c.currentScope, sym)
  360. else:
  361. c.addInterfaceDecl(sym)
  362. when false:
  363. # `nimfix` used to call `altSpelling` and prettybase.replaceDeprecated(n.info, ident, alt)
  364. proc altSpelling(c: PContext, x: PIdent): PIdent =
  365. case x.s[0]
  366. of 'A'..'Z': result = getIdent(c.cache, toLowerAscii(x.s[0]) & x.s.substr(1))
  367. of 'a'..'z': result = getIdent(c.cache, toLowerAscii(x.s[0]) & x.s.substr(1))
  368. else: result = x
  369. import std/editdistance, heapqueue
  370. type SpellCandidate = object
  371. dist: int
  372. depth: int
  373. msg: string
  374. sym: PSym
  375. template toOrderTup(a: SpellCandidate): (int, int, string) =
  376. # `dist` is first, to favor nearby matches
  377. # `depth` is next, to favor nearby enclosing scopes among ties
  378. # `sym.name.s` is last, to make the list ordered and deterministic among ties
  379. (a.dist, a.depth, a.msg)
  380. proc `<`(a, b: SpellCandidate): bool =
  381. a.toOrderTup < b.toOrderTup
  382. proc mustFixSpelling(c: PContext): bool {.inline.} =
  383. result = c.config.spellSuggestMax != 0 and c.compilesContextId == 0
  384. # don't slowdown inside compiles()
  385. proc fixSpelling(c: PContext, n: PNode, ident: PIdent, result: var string) =
  386. ## when we cannot find the identifier, suggest nearby spellings
  387. var list = initHeapQueue[SpellCandidate]()
  388. let name0 = ident.s.nimIdentNormalize
  389. for (sym, depth, isLocal) in allSyms(c):
  390. let depth = -depth - 1
  391. let dist = editDistance(name0, sym.name.s.nimIdentNormalize)
  392. var msg: string
  393. msg.add "\n ($1, $2): '$3'" % [$dist, $depth, sym.name.s]
  394. addDeclaredLoc(msg, c.config, sym) # `msg` needed for deterministic ordering.
  395. list.push SpellCandidate(dist: dist, depth: depth, msg: msg, sym: sym)
  396. if list.len == 0: return
  397. let e0 = list[0]
  398. var count = 0
  399. while true:
  400. # pending https://github.com/timotheecour/Nim/issues/373 use more efficient `itemsSorted`.
  401. if list.len == 0: break
  402. let e = list.pop()
  403. if c.config.spellSuggestMax == spellSuggestSecretSauce:
  404. const
  405. smallThres = 2
  406. maxCountForSmall = 4
  407. # avoids ton of operator matches when mis-matching short symbols such as `i`
  408. # other heuristics could be devised, such as only suggesting operators if `name0`
  409. # is an operator (likewise with non-operators).
  410. if e.dist > e0.dist or (name0.len <= smallThres and count >= maxCountForSmall): break
  411. elif count >= c.config.spellSuggestMax: break
  412. if count == 0:
  413. result.add "\ncandidates (edit distance, scope distance); see '--spellSuggest': "
  414. result.add e.msg
  415. count.inc
  416. proc errorUseQualifier(c: PContext; info: TLineInfo; s: PSym; amb: var bool): PSym =
  417. var err = "ambiguous identifier: '" & s.name.s & "'"
  418. var i = 0
  419. var ignoredModules = 0
  420. for candidate in importedItems(c, s.name):
  421. if i == 0: err.add " -- use one of the following:\n"
  422. else: err.add "\n"
  423. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  424. err.add ": " & typeToString(candidate.typ)
  425. if candidate.kind == skModule:
  426. inc ignoredModules
  427. else:
  428. result = candidate
  429. inc i
  430. if ignoredModules != i-1:
  431. localError(c.config, info, errGenerated, err)
  432. result = nil
  433. else:
  434. amb = false
  435. proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
  436. var amb: bool
  437. discard errorUseQualifier(c, info, s, amb)
  438. proc errorUseQualifier(c: PContext; info: TLineInfo; candidates: seq[PSym]; prefix = "use one of") =
  439. var err = "ambiguous identifier: '" & candidates[0].name.s & "'"
  440. var i = 0
  441. for candidate in candidates:
  442. if i == 0: err.add " -- $1 the following:\n" % prefix
  443. else: err.add "\n"
  444. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  445. err.add ": " & typeToString(candidate.typ)
  446. inc i
  447. localError(c.config, info, errGenerated, err)
  448. proc errorUseQualifier*(c: PContext; info:TLineInfo; choices: PNode) =
  449. var candidates = newSeq[PSym](choices.len)
  450. let prefix = if choices[0].typ.kind != tyProc: "use one of" else: "you need a helper proc to disambiguate"
  451. for i, n in choices:
  452. candidates[i] = n.sym
  453. errorUseQualifier(c, info, candidates, prefix)
  454. proc errorUndeclaredIdentifier*(c: PContext; info: TLineInfo; name: string, extra = "") =
  455. var err = "undeclared identifier: '" & name & "'" & extra
  456. if c.recursiveDep.len > 0:
  457. err.add "\nThis might be caused by a recursive module dependency:\n"
  458. err.add c.recursiveDep
  459. # prevent excessive errors for 'nim check'
  460. c.recursiveDep = ""
  461. localError(c.config, info, errGenerated, err)
  462. proc errorUndeclaredIdentifierHint*(c: PContext; n: PNode, ident: PIdent): PSym =
  463. var extra = ""
  464. if c.mustFixSpelling: fixSpelling(c, n, ident, extra)
  465. errorUndeclaredIdentifier(c, n.info, ident.s, extra)
  466. result = errorSym(c, n)
  467. proc lookUp*(c: PContext, n: PNode): PSym =
  468. # Looks up a symbol. Generates an error in case of nil.
  469. var amb = false
  470. case n.kind
  471. of nkIdent:
  472. result = searchInScopes(c, n.ident, amb).skipAlias(n, c.config)
  473. if result == nil: result = errorUndeclaredIdentifierHint(c, n, n.ident)
  474. of nkSym:
  475. result = n.sym
  476. of nkAccQuoted:
  477. var ident = considerQuotedIdent(c, n)
  478. result = searchInScopes(c, ident, amb).skipAlias(n, c.config)
  479. if result == nil: result = errorUndeclaredIdentifierHint(c, n, ident)
  480. else:
  481. internalError(c.config, n.info, "lookUp")
  482. return
  483. if amb:
  484. #contains(c.ambiguousSymbols, result.id):
  485. result = errorUseQualifier(c, n.info, result, amb)
  486. when false:
  487. if result.kind == skStub: loadStub(result)
  488. type
  489. TLookupFlag* = enum
  490. checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
  491. proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  492. const allExceptModule = {low(TSymKind)..high(TSymKind)} - {skModule, skPackage}
  493. case n.kind
  494. of nkIdent, nkAccQuoted:
  495. var amb = false
  496. var ident = considerQuotedIdent(c, n)
  497. if checkModule in flags:
  498. result = searchInScopes(c, ident, amb).skipAlias(n, c.config)
  499. else:
  500. let candidates = searchInScopesFilterBy(c, ident, allExceptModule) #.skipAlias(n, c.config)
  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:
  507. let candidates = allPureEnumFields(c, ident)
  508. if candidates.len > 0:
  509. result = candidates[0]
  510. amb = candidates.len > 1
  511. if amb and checkAmbiguity in flags:
  512. errorUseQualifier(c, n.info, candidates)
  513. if result == nil and checkUndeclared in flags:
  514. result = errorUndeclaredIdentifierHint(c, n, ident)
  515. elif checkAmbiguity in flags and result != nil and amb:
  516. result = errorUseQualifier(c, n.info, result, amb)
  517. c.isAmbiguous = amb
  518. of nkSym:
  519. result = n.sym
  520. of nkDotExpr:
  521. result = nil
  522. var m = qualifiedLookUp(c, n[0], (flags * {checkUndeclared}) + {checkModule})
  523. if m != nil and m.kind == skModule:
  524. var ident: PIdent = nil
  525. if n[1].kind == nkIdent:
  526. ident = n[1].ident
  527. elif n[1].kind == nkAccQuoted:
  528. ident = considerQuotedIdent(c, n[1])
  529. if ident != nil:
  530. if m == c.module:
  531. result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n, c.config)
  532. else:
  533. if c.importModuleLookup.getOrDefault(m.name.id).len > 1:
  534. var amb: bool
  535. result = errorUseQualifier(c, n.info, m, amb)
  536. else:
  537. result = someSym(c.graph, m, ident).skipAlias(n, c.config)
  538. if result == nil and checkUndeclared in flags:
  539. result = errorUndeclaredIdentifierHint(c, n[1], ident)
  540. elif n[1].kind == nkSym:
  541. result = n[1].sym
  542. if result.owner != nil and result.owner != m and checkUndeclared in flags:
  543. # dotExpr in templates can end up here
  544. result = errorUndeclaredIdentifierHint(c, n[1], considerQuotedIdent(c, n[1]))
  545. elif checkUndeclared in flags and
  546. n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  547. localError(c.config, n[1].info, "identifier expected, but got: " &
  548. renderTree(n[1]))
  549. result = errorSym(c, n[1])
  550. else:
  551. result = nil
  552. when false:
  553. if result != nil and result.kind == skStub: loadStub(result)
  554. proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  555. o.importIdx = -1
  556. o.marked = initIntSet()
  557. case n.kind
  558. of nkIdent, nkAccQuoted:
  559. var ident = considerQuotedIdent(c, n)
  560. var scope = c.currentScope
  561. o.mode = oimNoQualifier
  562. while true:
  563. result = initIdentIter(o.it, scope.symbols, ident).skipAlias(n, c.config)
  564. if result != nil:
  565. o.currentScope = scope
  566. break
  567. else:
  568. scope = scope.parent
  569. if scope == nil:
  570. for i in 0..c.imports.high:
  571. result = initIdentIter(o.mit, o.marked, c.imports[i], ident, c.graph).skipAlias(n, c.config)
  572. if result != nil:
  573. o.currentScope = nil
  574. o.importIdx = i
  575. return result
  576. return nil
  577. of nkSym:
  578. result = n.sym
  579. o.mode = oimDone
  580. of nkDotExpr:
  581. o.mode = oimOtherModule
  582. o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
  583. if o.m != nil and o.m.kind == skModule:
  584. var ident: PIdent = nil
  585. if n[1].kind == nkIdent:
  586. ident = n[1].ident
  587. elif n[1].kind == nkAccQuoted:
  588. ident = considerQuotedIdent(c, n[1], n)
  589. if ident != nil:
  590. if o.m == c.module:
  591. # a module may access its private members:
  592. result = initIdentIter(o.it, c.topLevelScope.symbols,
  593. ident).skipAlias(n, c.config)
  594. o.mode = oimSelfModule
  595. else:
  596. result = initModuleIter(o.mit, c.graph, o.m, ident).skipAlias(n, c.config)
  597. else:
  598. noidentError(c.config, n[1], n)
  599. result = errorSym(c, n[1])
  600. of nkClosedSymChoice, nkOpenSymChoice:
  601. o.mode = oimSymChoice
  602. if n[0].kind == nkSym:
  603. result = n[0].sym
  604. else:
  605. o.mode = oimDone
  606. return nil
  607. o.symChoiceIndex = 1
  608. o.marked = initIntSet()
  609. incl(o.marked, result.id)
  610. else: discard
  611. when false:
  612. if result != nil and result.kind == skStub: loadStub(result)
  613. proc lastOverloadScope*(o: TOverloadIter): int =
  614. case o.mode
  615. of oimNoQualifier:
  616. result = if o.importIdx >= 0: 0
  617. elif o.currentScope.isNil: -1
  618. else: o.currentScope.depthLevel
  619. of oimSelfModule: result = 1
  620. of oimOtherModule: result = 0
  621. else: result = -1
  622. proc nextOverloadIterImports(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  623. assert o.currentScope == nil
  624. var idx = o.importIdx+1
  625. o.importIdx = c.imports.len # assume the other imported modules lack this symbol too
  626. while idx < c.imports.len:
  627. result = initIdentIter(o.mit, o.marked, c.imports[idx], o.it.name, c.graph).skipAlias(n, c.config)
  628. if result != nil:
  629. # oh, we were wrong, some other module had the symbol, so remember that:
  630. o.importIdx = idx
  631. break
  632. inc idx
  633. proc symChoiceExtension(o: var TOverloadIter; c: PContext; n: PNode): PSym =
  634. assert o.currentScope == nil
  635. while o.importIdx < c.imports.len:
  636. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph).skipAlias(n, c.config)
  637. #while result != nil and result.id in o.marked:
  638. # result = nextIdentIter(o.it, o.marked, c.imports[o.importIdx])
  639. if result != nil:
  640. #assert result.id notin o.marked
  641. return result
  642. inc o.importIdx
  643. proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  644. case o.mode
  645. of oimDone:
  646. result = nil
  647. of oimNoQualifier:
  648. if o.currentScope != nil:
  649. assert o.importIdx < 0
  650. result = nextIdentIter(o.it, o.currentScope.symbols).skipAlias(n, c.config)
  651. while result == nil:
  652. o.currentScope = o.currentScope.parent
  653. if o.currentScope != nil:
  654. result = initIdentIter(o.it, o.currentScope.symbols, o.it.name).skipAlias(n, c.config)
  655. # BUGFIX: o.it.name <-> n.ident
  656. else:
  657. o.importIdx = 0
  658. if c.imports.len > 0:
  659. result = initIdentIter(o.mit, o.marked, c.imports[o.importIdx], o.it.name, c.graph).skipAlias(n, c.config)
  660. if result == nil:
  661. result = nextOverloadIterImports(o, c, n)
  662. break
  663. elif o.importIdx < c.imports.len:
  664. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph).skipAlias(n, c.config)
  665. if result == nil:
  666. result = nextOverloadIterImports(o, c, n)
  667. else:
  668. result = nil
  669. of oimSelfModule:
  670. result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n, c.config)
  671. of oimOtherModule:
  672. result = nextModuleIter(o.mit, c.graph).skipAlias(n, c.config)
  673. of oimSymChoice:
  674. if o.symChoiceIndex < n.len:
  675. result = n[o.symChoiceIndex].sym
  676. incl(o.marked, result.id)
  677. inc o.symChoiceIndex
  678. elif n.kind == nkOpenSymChoice:
  679. # try 'local' symbols too for Koenig's lookup:
  680. o.mode = oimSymChoiceLocalLookup
  681. o.currentScope = c.currentScope
  682. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  683. n[0].sym.name, 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. of oimSymChoiceLocalLookup:
  696. if o.currentScope != nil:
  697. result = nextIdentExcluding(o.it, o.currentScope.symbols, o.marked).skipAlias(n, c.config)
  698. while result == nil:
  699. o.currentScope = o.currentScope.parent
  700. if o.currentScope != nil:
  701. result = firstIdentExcluding(o.it, o.currentScope.symbols,
  702. n[0].sym.name, o.marked).skipAlias(n, c.config)
  703. else:
  704. o.importIdx = 0
  705. result = symChoiceExtension(o, c, n)
  706. break
  707. if result != nil:
  708. incl o.marked, result.id
  709. elif o.importIdx < c.imports.len:
  710. result = nextIdentIter(o.mit, o.marked, c.imports[o.importIdx], c.graph).skipAlias(n, c.config)
  711. #assert result.id notin o.marked
  712. #while result != nil and result.id in o.marked:
  713. # result = nextIdentIter(o.it, c.imports[o.importIdx]).skipAlias(n, c.config)
  714. if result == nil:
  715. inc o.importIdx
  716. result = symChoiceExtension(o, c, n)
  717. when false:
  718. if result != nil and result.kind == skStub: loadStub(result)
  719. proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
  720. flags: TSymFlags = {}): PSym =
  721. var o: TOverloadIter
  722. var a = initOverloadIter(o, c, n)
  723. while a != nil:
  724. if a.kind in kinds and flags <= a.flags:
  725. if result == nil: result = a
  726. else: return nil # ambiguous
  727. a = nextOverloadIter(o, c, n)