lookups.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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
  11. intsets, ast, astalgo, idents, semdata, types, msgs, options,
  12. renderer, nimfix/prettybase, lineinfos, strutils
  13. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope)
  14. proc noidentError(conf: ConfigRef; n, origin: PNode) =
  15. var m = ""
  16. if origin != nil:
  17. m.add "in expression '" & origin.renderTree & "': "
  18. m.add "identifier expected, but found '" & n.renderTree & "'"
  19. localError(conf, n.info, m)
  20. proc considerQuotedIdent*(c: PContext; n: PNode, origin: PNode = nil): PIdent =
  21. ## Retrieve a PIdent from a PNode, taking into account accent nodes.
  22. ## ``origin`` can be nil. If it is not nil, it is used for a better
  23. ## error message.
  24. template handleError(n, origin: PNode) =
  25. noidentError(c.config, n, origin)
  26. result = getIdent(c.cache, "<Error>")
  27. case n.kind
  28. of nkIdent: result = n.ident
  29. of nkSym: result = n.sym.name
  30. of nkAccQuoted:
  31. case n.len
  32. of 0: handleError(n, origin)
  33. of 1: result = considerQuotedIdent(c, n[0], origin)
  34. else:
  35. var id = ""
  36. for i in 0..<n.len:
  37. let x = n[i]
  38. case x.kind
  39. of nkIdent: id.add(x.ident.s)
  40. of nkSym: id.add(x.sym.name.s)
  41. of nkLiterals - nkFloatLiterals: id.add(x.renderTree)
  42. else: handleError(n, origin)
  43. result = getIdent(c.cache, id)
  44. of nkOpenSymChoice, nkClosedSymChoice:
  45. if n[0].kind == nkSym:
  46. result = n[0].sym.name
  47. else:
  48. handleError(n, origin)
  49. else:
  50. handleError(n, origin)
  51. template addSym*(scope: PScope, s: PSym) =
  52. strTableAdd(scope.symbols, s)
  53. proc addUniqueSym*(scope: PScope, s: PSym): PSym =
  54. result = strTableInclReportConflict(scope.symbols, s)
  55. proc openScope*(c: PContext): PScope {.discardable.} =
  56. result = PScope(parent: c.currentScope,
  57. symbols: newStrTable(),
  58. depthLevel: c.scopeDepth + 1)
  59. c.currentScope = result
  60. proc rawCloseScope*(c: PContext) =
  61. c.currentScope = c.currentScope.parent
  62. proc closeScope*(c: PContext) =
  63. ensureNoMissingOrUnusedSymbols(c, c.currentScope)
  64. rawCloseScope(c)
  65. iterator walkScopes*(scope: PScope): PScope =
  66. var current = scope
  67. while current != nil:
  68. yield current
  69. current = current.parent
  70. proc skipAlias*(s: PSym; n: PNode; conf: ConfigRef): PSym =
  71. if s == nil or s.kind != skAlias:
  72. result = s
  73. else:
  74. result = s.owner
  75. if conf.cmd == cmdPretty:
  76. prettybase.replaceDeprecated(conf, n.info, s, result)
  77. else:
  78. message(conf, n.info, warnDeprecated, "use " & result.name.s & " instead; " &
  79. s.name.s & " is deprecated")
  80. proc isShadowScope*(s: PScope): bool {.inline.} = s.parent != nil and s.parent.depthLevel == s.depthLevel
  81. proc localSearchInScope*(c: PContext, s: PIdent): PSym =
  82. var scope = c.currentScope
  83. result = strTableGet(scope.symbols, s)
  84. while result == nil and scope.isShadowScope:
  85. # We are in a shadow scope, check in the parent too
  86. scope = scope.parent
  87. result = strTableGet(scope.symbols, s)
  88. proc searchInScopes*(c: PContext, s: PIdent): PSym =
  89. for scope in walkScopes(c.currentScope):
  90. result = strTableGet(scope.symbols, s)
  91. if result != nil: return
  92. result = nil
  93. proc debugScopes*(c: PContext; limit=0) {.deprecated.} =
  94. var i = 0
  95. for scope in walkScopes(c.currentScope):
  96. echo "scope ", i
  97. for h in 0..high(scope.symbols.data):
  98. if scope.symbols.data[h] != nil:
  99. echo scope.symbols.data[h].name.s
  100. if i == limit: break
  101. inc i
  102. proc searchInScopes*(c: PContext, s: PIdent, filter: TSymKinds): PSym =
  103. for scope in walkScopes(c.currentScope):
  104. var ti: TIdentIter
  105. var candidate = initIdentIter(ti, scope.symbols, s)
  106. while candidate != nil:
  107. if candidate.kind in filter: return candidate
  108. candidate = nextIdentIter(ti, scope.symbols)
  109. result = nil
  110. proc errorSym*(c: PContext, n: PNode): PSym =
  111. ## creates an error symbol to avoid cascading errors (for IDE support)
  112. var m = n
  113. # ensure that 'considerQuotedIdent' can't fail:
  114. if m.kind == nkDotExpr: m = m[1]
  115. let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
  116. considerQuotedIdent(c, m)
  117. else:
  118. getIdent(c.cache, "err:" & renderTree(m))
  119. result = newSym(skError, ident, getCurrOwner(c), n.info, {})
  120. result.typ = errorType(c)
  121. incl(result.flags, sfDiscardable)
  122. # pretend it's imported from some unknown module to prevent cascading errors:
  123. if c.config.cmd != cmdInteractive and c.compilesContextId == 0:
  124. c.importTable.addSym(result)
  125. type
  126. TOverloadIterMode* = enum
  127. oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
  128. oimSymChoiceLocalLookup
  129. TOverloadIter* = object
  130. it*: TIdentIter
  131. m*: PSym
  132. mode*: TOverloadIterMode
  133. symChoiceIndex*: int
  134. scope*: PScope
  135. inSymChoice: IntSet
  136. proc getSymRepr*(conf: ConfigRef; s: PSym): string =
  137. case s.kind
  138. of routineKinds, skType:
  139. result = getProcHeader(conf, s)
  140. else:
  141. result = s.name.s
  142. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope) =
  143. # check if all symbols have been used and defined:
  144. var it: TTabIter
  145. var s = initTabIter(it, scope.symbols)
  146. var missingImpls = 0
  147. while s != nil:
  148. if sfForward in s.flags and s.kind notin {skType, skModule}:
  149. # too many 'implementation of X' errors are annoying
  150. # and slow 'suggest' down:
  151. if missingImpls == 0:
  152. localError(c.config, s.info, "implementation of '$1' expected" %
  153. getSymRepr(c.config, s))
  154. inc missingImpls
  155. elif {sfUsed, sfExported} * s.flags == {}:
  156. if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam, skEnumField}:
  157. # XXX: implicit type params are currently skTypes
  158. # maybe they can be made skGenericParam as well.
  159. if s.typ != nil and tfImplicitTypeParam notin s.typ.flags and
  160. s.typ.kind != tyGenericParam:
  161. message(c.config, s.info, hintXDeclaredButNotUsed, s.name.s)
  162. s = nextIter(it, scope.symbols)
  163. proc wrongRedefinition*(c: PContext; info: TLineInfo, s: string;
  164. conflictsWith: TLineInfo) =
  165. if c.config.cmd != cmdInteractive:
  166. localError(c.config, info,
  167. "redefinition of '$1'; previous declaration here: $2" %
  168. [s, c.config $ conflictsWith])
  169. proc addDecl*(c: PContext, sym: PSym, info: TLineInfo) =
  170. let conflict = c.currentScope.addUniqueSym(sym)
  171. if conflict != nil:
  172. wrongRedefinition(c, info, sym.name.s, conflict.info)
  173. proc addDecl*(c: PContext, sym: PSym) =
  174. let conflict = strTableInclReportConflict(c.currentScope.symbols, sym, true)
  175. if conflict != nil:
  176. wrongRedefinition(c, sym.info, sym.name.s, conflict.info)
  177. proc addPrelimDecl*(c: PContext, sym: PSym) =
  178. discard c.currentScope.addUniqueSym(sym)
  179. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym) =
  180. let conflict = scope.addUniqueSym(sym)
  181. if conflict != nil:
  182. wrongRedefinition(c, sym.info, sym.name.s, conflict.info)
  183. proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  184. if sfExported in sym.flags:
  185. # add to interface:
  186. if c.module != nil: strTableAdd(c.module.tab, sym)
  187. else: internalError(c.config, sym.info, "addInterfaceDeclAux")
  188. proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  189. addDeclAt(c, scope, sym)
  190. addInterfaceDeclAux(c, sym)
  191. proc addOverloadableSymAt*(c: PContext; scope: PScope, fn: PSym) =
  192. if fn.kind notin OverloadableSyms:
  193. internalError(c.config, fn.info, "addOverloadableSymAt")
  194. return
  195. let check = strTableGet(scope.symbols, fn.name)
  196. if check != nil and check.kind notin OverloadableSyms:
  197. wrongRedefinition(c, fn.info, fn.name.s, check.info)
  198. else:
  199. scope.addSym(fn)
  200. proc addInterfaceDecl*(c: PContext, sym: PSym) =
  201. # it adds the symbol to the interface if appropriate
  202. addDecl(c, sym)
  203. addInterfaceDeclAux(c, sym)
  204. proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  205. # it adds the symbol to the interface if appropriate
  206. addOverloadableSymAt(c, scope, sym)
  207. addInterfaceDeclAux(c, sym)
  208. proc openShadowScope*(c: PContext) =
  209. c.currentScope = PScope(parent: c.currentScope,
  210. symbols: newStrTable(),
  211. depthLevel: c.scopeDepth)
  212. proc closeShadowScope*(c: PContext) =
  213. c.closeScope
  214. proc mergeShadowScope*(c: PContext) =
  215. let shadowScope = c.currentScope
  216. c.rawCloseScope
  217. for sym in shadowScope.symbols:
  218. if sym.kind in OverloadableSyms:
  219. c.addInterfaceOverloadableSymAt(c.currentScope, sym)
  220. else:
  221. c.addInterfaceDecl(sym)
  222. when defined(nimfix):
  223. # when we cannot find the identifier, retry with a changed identifier:
  224. proc altSpelling(x: PIdent): PIdent =
  225. case x.s[0]
  226. of 'A'..'Z': result = getIdent(toLowerAscii(x.s[0]) & x.s.substr(1))
  227. of 'a'..'z': result = getIdent(toLowerAscii(x.s[0]) & x.s.substr(1))
  228. else: result = x
  229. template fixSpelling(n: PNode; ident: PIdent; op: untyped) =
  230. let alt = ident.altSpelling
  231. result = op(c, alt).skipAlias(n)
  232. if result != nil:
  233. prettybase.replaceDeprecated(n.info, ident, alt)
  234. return result
  235. else:
  236. template fixSpelling(n: PNode; ident: PIdent; op: untyped) = discard
  237. proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
  238. var err = "ambiguous identifier: '" & s.name.s & "'"
  239. var ti: TIdentIter
  240. var candidate = initIdentIter(ti, c.importTable.symbols, s.name)
  241. var i = 0
  242. while candidate != nil:
  243. if i == 0: err.add " -- use one of the following:\n"
  244. else: err.add "\n"
  245. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  246. err.add ": " & typeToString(candidate.typ)
  247. candidate = nextIdentIter(ti, c.importTable.symbols)
  248. inc i
  249. localError(c.config, info, errGenerated, err)
  250. proc errorUndeclaredIdentifier*(c: PContext; info: TLineInfo; name: string) =
  251. var err = "undeclared identifier: '" & name & "'"
  252. if c.recursiveDep.len > 0:
  253. err.add "\nThis might be caused by a recursive module dependency:\n"
  254. err.add c.recursiveDep
  255. # prevent excessive errors for 'nim check'
  256. c.recursiveDep = ""
  257. localError(c.config, info, errGenerated, err)
  258. proc lookUp*(c: PContext, n: PNode): PSym =
  259. # Looks up a symbol. Generates an error in case of nil.
  260. case n.kind
  261. of nkIdent:
  262. result = searchInScopes(c, n.ident).skipAlias(n, c.config)
  263. if result == nil:
  264. fixSpelling(n, n.ident, searchInScopes)
  265. errorUndeclaredIdentifier(c, n.info, n.ident.s)
  266. result = errorSym(c, n)
  267. of nkSym:
  268. result = n.sym
  269. of nkAccQuoted:
  270. var ident = considerQuotedIdent(c, n)
  271. result = searchInScopes(c, ident).skipAlias(n, c.config)
  272. if result == nil:
  273. fixSpelling(n, ident, searchInScopes)
  274. errorUndeclaredIdentifier(c, n.info, ident.s)
  275. result = errorSym(c, n)
  276. else:
  277. internalError(c.config, n.info, "lookUp")
  278. return
  279. if contains(c.ambiguousSymbols, result.id):
  280. errorUseQualifier(c, n.info, result)
  281. when false:
  282. if result.kind == skStub: loadStub(result)
  283. type
  284. TLookupFlag* = enum
  285. checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
  286. proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  287. const allExceptModule = {low(TSymKind)..high(TSymKind)}-{skModule,skPackage}
  288. case n.kind
  289. of nkIdent, nkAccQuoted:
  290. var ident = considerQuotedIdent(c, n)
  291. if checkModule in flags:
  292. result = searchInScopes(c, ident).skipAlias(n, c.config)
  293. else:
  294. result = searchInScopes(c, ident, allExceptModule).skipAlias(n, c.config)
  295. if result == nil and checkPureEnumFields in flags:
  296. result = strTableGet(c.pureEnumFields, ident)
  297. if result == nil and checkUndeclared in flags:
  298. fixSpelling(n, ident, searchInScopes)
  299. errorUndeclaredIdentifier(c, n.info, ident.s)
  300. result = errorSym(c, n)
  301. elif checkAmbiguity in flags and result != nil and result.id in c.ambiguousSymbols:
  302. errorUseQualifier(c, n.info, result)
  303. of nkSym:
  304. result = n.sym
  305. if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id):
  306. errorUseQualifier(c, n.info, n.sym)
  307. of nkDotExpr:
  308. result = nil
  309. var m = qualifiedLookUp(c, n[0], (flags*{checkUndeclared})+{checkModule})
  310. if m != nil and m.kind == skModule:
  311. var ident: PIdent = nil
  312. if n[1].kind == nkIdent:
  313. ident = n[1].ident
  314. elif n[1].kind == nkAccQuoted:
  315. ident = considerQuotedIdent(c, n[1])
  316. if ident != nil:
  317. if m == c.module:
  318. result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n, c.config)
  319. else:
  320. result = strTableGet(m.tab, ident).skipAlias(n, c.config)
  321. if result == nil and checkUndeclared in flags:
  322. fixSpelling(n[1], ident, searchInScopes)
  323. errorUndeclaredIdentifier(c, n[1].info, ident.s)
  324. result = errorSym(c, n[1])
  325. elif n[1].kind == nkSym:
  326. result = n[1].sym
  327. elif checkUndeclared in flags and
  328. n[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  329. localError(c.config, n[1].info, "identifier expected, but got: " &
  330. renderTree(n[1]))
  331. result = errorSym(c, n[1])
  332. else:
  333. result = nil
  334. when false:
  335. if result != nil and result.kind == skStub: loadStub(result)
  336. proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  337. case n.kind
  338. of nkIdent, nkAccQuoted:
  339. var ident = considerQuotedIdent(c, n)
  340. o.scope = c.currentScope
  341. o.mode = oimNoQualifier
  342. while true:
  343. result = initIdentIter(o.it, o.scope.symbols, ident).skipAlias(n, c.config)
  344. if result != nil:
  345. break
  346. else:
  347. o.scope = o.scope.parent
  348. if o.scope == nil: break
  349. of nkSym:
  350. result = n.sym
  351. o.mode = oimDone
  352. of nkDotExpr:
  353. o.mode = oimOtherModule
  354. o.m = qualifiedLookUp(c, n[0], {checkUndeclared, checkModule})
  355. if o.m != nil and o.m.kind == skModule:
  356. var ident: PIdent = nil
  357. if n[1].kind == nkIdent:
  358. ident = n[1].ident
  359. elif n[1].kind == nkAccQuoted:
  360. ident = considerQuotedIdent(c, n[1], n)
  361. if ident != nil:
  362. if o.m == c.module:
  363. # a module may access its private members:
  364. result = initIdentIter(o.it, c.topLevelScope.symbols,
  365. ident).skipAlias(n, c.config)
  366. o.mode = oimSelfModule
  367. else:
  368. result = initIdentIter(o.it, o.m.tab, ident).skipAlias(n, c.config)
  369. else:
  370. noidentError(c.config, n[1], n)
  371. result = errorSym(c, n[1])
  372. of nkClosedSymChoice, nkOpenSymChoice:
  373. o.mode = oimSymChoice
  374. if n[0].kind == nkSym:
  375. result = n[0].sym
  376. else:
  377. o.mode = oimDone
  378. return nil
  379. o.symChoiceIndex = 1
  380. o.inSymChoice = initIntSet()
  381. incl(o.inSymChoice, result.id)
  382. else: discard
  383. when false:
  384. if result != nil and result.kind == skStub: loadStub(result)
  385. proc lastOverloadScope*(o: TOverloadIter): int =
  386. case o.mode
  387. of oimNoQualifier: result = if o.scope.isNil: -1 else: o.scope.depthLevel
  388. of oimSelfModule: result = 1
  389. of oimOtherModule: result = 0
  390. else: result = -1
  391. proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  392. case o.mode
  393. of oimDone:
  394. result = nil
  395. of oimNoQualifier:
  396. if o.scope != nil:
  397. result = nextIdentIter(o.it, o.scope.symbols).skipAlias(n, c.config)
  398. while result == nil:
  399. o.scope = o.scope.parent
  400. if o.scope == nil: break
  401. result = initIdentIter(o.it, o.scope.symbols, o.it.name).skipAlias(n, c.config)
  402. # BUGFIX: o.it.name <-> n.ident
  403. else:
  404. result = nil
  405. of oimSelfModule:
  406. result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n, c.config)
  407. of oimOtherModule:
  408. result = nextIdentIter(o.it, o.m.tab).skipAlias(n, c.config)
  409. of oimSymChoice:
  410. if o.symChoiceIndex < n.len:
  411. result = n[o.symChoiceIndex].sym
  412. incl(o.inSymChoice, result.id)
  413. inc o.symChoiceIndex
  414. elif n.kind == nkOpenSymChoice:
  415. # try 'local' symbols too for Koenig's lookup:
  416. o.mode = oimSymChoiceLocalLookup
  417. o.scope = c.currentScope
  418. result = firstIdentExcluding(o.it, o.scope.symbols,
  419. n[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
  420. while result == nil:
  421. o.scope = o.scope.parent
  422. if o.scope == nil: break
  423. result = firstIdentExcluding(o.it, o.scope.symbols,
  424. n[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
  425. of oimSymChoiceLocalLookup:
  426. result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice).skipAlias(n, c.config)
  427. while result == nil:
  428. o.scope = o.scope.parent
  429. if o.scope == nil: break
  430. result = firstIdentExcluding(o.it, o.scope.symbols,
  431. n[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
  432. when false:
  433. if result != nil and result.kind == skStub: loadStub(result)
  434. proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
  435. flags: TSymFlags = {}): PSym =
  436. var o: TOverloadIter
  437. var a = initOverloadIter(o, c, n)
  438. while a != nil:
  439. if a.kind in kinds and flags <= a.flags:
  440. if result == nil: result = a
  441. else: return nil # ambiguous
  442. a = nextOverloadIter(o, c, n)