lookups.nim 16 KB

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