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, wordrecg, idgen, 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.sons[0], origin)
  34. else:
  35. var id = ""
  36. for i in 0..<n.len:
  37. let x = n.sons[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.sons[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)
  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. when declared(echo):
  88. proc debugScopes*(c: PContext; limit=0) {.deprecated.} =
  89. var i = 0
  90. for scope in walkScopes(c.currentScope):
  91. echo "scope ", i
  92. for h in 0 .. high(scope.symbols.data):
  93. if scope.symbols.data[h] != nil:
  94. echo scope.symbols.data[h].name.s
  95. if i == limit: break
  96. inc i
  97. proc searchInScopes*(c: PContext, s: PIdent, filter: TSymKinds): PSym =
  98. for scope in walkScopes(c.currentScope):
  99. var ti: TIdentIter
  100. var candidate = initIdentIter(ti, scope.symbols, s)
  101. while candidate != nil:
  102. if candidate.kind in filter: return candidate
  103. candidate = nextIdentIter(ti, scope.symbols)
  104. result = nil
  105. proc errorSym*(c: PContext, n: PNode): PSym =
  106. ## creates an error symbol to avoid cascading errors (for IDE support)
  107. var m = n
  108. # ensure that 'considerQuotedIdent' can't fail:
  109. if m.kind == nkDotExpr: m = m.sons[1]
  110. let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
  111. considerQuotedIdent(c, m)
  112. else:
  113. getIdent(c.cache, "err:" & renderTree(m))
  114. result = newSym(skError, ident, getCurrOwner(c), n.info, {})
  115. result.typ = errorType(c)
  116. incl(result.flags, sfDiscardable)
  117. # pretend it's imported from some unknown module to prevent cascading errors:
  118. if c.config.cmd != cmdInteractive and c.compilesContextId == 0:
  119. c.importTable.addSym(result)
  120. type
  121. TOverloadIterMode* = enum
  122. oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
  123. oimSymChoiceLocalLookup
  124. TOverloadIter* = object
  125. it*: TIdentIter
  126. m*: PSym
  127. mode*: TOverloadIterMode
  128. symChoiceIndex*: int
  129. scope*: PScope
  130. inSymChoice: IntSet
  131. proc getSymRepr*(conf: ConfigRef; s: PSym): string =
  132. case s.kind
  133. of skProc, skFunc, skMethod, skConverter, skIterator:
  134. result = getProcHeader(conf, s)
  135. else:
  136. result = s.name.s
  137. proc ensureNoMissingOrUnusedSymbols(c: PContext; scope: PScope) =
  138. # check if all symbols have been used and defined:
  139. var it: TTabIter
  140. var s = initTabIter(it, scope.symbols)
  141. var missingImpls = 0
  142. while s != nil:
  143. if sfForward in s.flags and s.kind notin {skType, skModule}:
  144. # too many 'implementation of X' errors are annoying
  145. # and slow 'suggest' down:
  146. if missingImpls == 0:
  147. localError(c.config, s.info, "implementation of '$1' expected" %
  148. getSymRepr(c.config, s))
  149. inc missingImpls
  150. elif {sfUsed, sfExported} * s.flags == {} and optHints in s.options:
  151. if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam}:
  152. # XXX: implicit type params are currently skTypes
  153. # maybe they can be made skGenericParam as well.
  154. if s.typ != nil and tfImplicitTypeParam notin s.typ.flags and
  155. s.typ.kind != tyGenericParam:
  156. message(c.config, s.info, hintXDeclaredButNotUsed, getSymRepr(c.config, s))
  157. s = nextIter(it, scope.symbols)
  158. proc wrongRedefinition*(c: PContext; info: TLineInfo, s: string;
  159. conflictsWith: TLineInfo) =
  160. if c.config.cmd != cmdInteractive:
  161. localError(c.config, info,
  162. "redefinition of '$1'; previous declaration here: $2" %
  163. [s, c.config $ conflictsWith])
  164. proc addDecl*(c: PContext, sym: PSym, info: TLineInfo) =
  165. let conflict = c.currentScope.addUniqueSym(sym)
  166. if conflict != nil:
  167. wrongRedefinition(c, info, sym.name.s, conflict.info)
  168. proc addDecl*(c: PContext, sym: PSym) =
  169. let conflict = c.currentScope.addUniqueSym(sym)
  170. if conflict != nil:
  171. wrongRedefinition(c, sym.info, sym.name.s, conflict.info)
  172. proc addPrelimDecl*(c: PContext, sym: PSym) =
  173. discard c.currentScope.addUniqueSym(sym)
  174. proc addDeclAt*(c: PContext; scope: PScope, sym: PSym) =
  175. let conflict = scope.addUniqueSym(sym)
  176. if conflict != nil:
  177. wrongRedefinition(c, sym.info, sym.name.s, conflict.info)
  178. proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  179. if sfExported in sym.flags:
  180. # add to interface:
  181. if c.module != nil: strTableAdd(c.module.tab, sym)
  182. else: internalError(c.config, sym.info, "addInterfaceDeclAux")
  183. proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  184. addDeclAt(c, scope, sym)
  185. addInterfaceDeclAux(c, sym)
  186. proc addOverloadableSymAt*(c: PContext; scope: PScope, fn: PSym) =
  187. if fn.kind notin OverloadableSyms:
  188. internalError(c.config, fn.info, "addOverloadableSymAt")
  189. return
  190. let check = strTableGet(scope.symbols, fn.name)
  191. if check != nil and check.kind notin OverloadableSyms:
  192. wrongRedefinition(c, fn.info, fn.name.s, check.info)
  193. else:
  194. scope.addSym(fn)
  195. proc addInterfaceDecl*(c: PContext, sym: PSym) =
  196. # it adds the symbol to the interface if appropriate
  197. addDecl(c, sym)
  198. addInterfaceDeclAux(c, sym)
  199. proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  200. # it adds the symbol to the interface if appropriate
  201. addOverloadableSymAt(c, scope, sym)
  202. addInterfaceDeclAux(c, sym)
  203. when defined(nimfix):
  204. # when we cannot find the identifier, retry with a changed identifer:
  205. proc altSpelling(x: PIdent): PIdent =
  206. case x.s[0]
  207. of 'A'..'Z': result = getIdent(toLowerAscii(x.s[0]) & x.s.substr(1))
  208. of 'a'..'z': result = getIdent(toLowerAscii(x.s[0]) & x.s.substr(1))
  209. else: result = x
  210. template fixSpelling(n: PNode; ident: PIdent; op: untyped) =
  211. let alt = ident.altSpelling
  212. result = op(c, alt).skipAlias(n)
  213. if result != nil:
  214. prettybase.replaceDeprecated(n.info, ident, alt)
  215. return result
  216. else:
  217. template fixSpelling(n: PNode; ident: PIdent; op: untyped) = discard
  218. proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
  219. var err = "ambiguous identifier: '" & s.name.s & "'"
  220. var ti: TIdentIter
  221. var candidate = initIdentIter(ti, c.importTable.symbols, s.name)
  222. var i = 0
  223. while candidate != nil:
  224. if i == 0: err.add " --use "
  225. else: err.add " or "
  226. err.add candidate.owner.name.s & "." & candidate.name.s
  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.sons[0], (flags*{checkUndeclared})+{checkModule})
  291. if m != nil and m.kind == skModule:
  292. var ident: PIdent = nil
  293. if n.sons[1].kind == nkIdent:
  294. ident = n.sons[1].ident
  295. elif n.sons[1].kind == nkAccQuoted:
  296. ident = considerQuotedIdent(c, n.sons[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.sons[1], ident, searchInScopes)
  304. errorUndeclaredIdentifier(c, n.sons[1].info, ident.s)
  305. result = errorSym(c, n.sons[1])
  306. elif n.sons[1].kind == nkSym:
  307. result = n.sons[1].sym
  308. elif checkUndeclared in flags and
  309. n.sons[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  310. localError(c.config, n.sons[1].info, "identifier expected, but got: " &
  311. renderTree(n.sons[1]))
  312. result = errorSym(c, n.sons[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.sons[0], {checkUndeclared, checkModule})
  336. if o.m != nil and o.m.kind == skModule:
  337. var ident: PIdent = nil
  338. if n.sons[1].kind == nkIdent:
  339. ident = n.sons[1].ident
  340. elif n.sons[1].kind == nkAccQuoted:
  341. ident = considerQuotedIdent(c, n.sons[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.sons[1], n)
  352. result = errorSym(c, n.sons[1])
  353. of nkClosedSymChoice, nkOpenSymChoice:
  354. o.mode = oimSymChoice
  355. if n[0].kind == nkSym:
  356. result = n.sons[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 < sonsLen(n):
  392. result = n.sons[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.sons[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.sons[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.sons[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)