lookups.nim 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 & " 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. 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 routineKinds, skType:
  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 == {}:
  151. if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam, skEnumField}:
  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, s.name.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 = strTableInclReportConflict(c.currentScope.symbols, sym, true)
  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 one of the following:\n"
  225. else: err.add "\n"
  226. err.add " " & candidate.owner.name.s & "." & candidate.name.s
  227. err.add ": " & typeToString(candidate.typ)
  228. candidate = nextIdentIter(ti, c.importTable.symbols)
  229. inc i
  230. localError(c.config, info, errGenerated, err)
  231. proc errorUndeclaredIdentifier*(c: PContext; info: TLineInfo; name: string) =
  232. var err = "undeclared identifier: '" & name & "'"
  233. if c.recursiveDep.len > 0:
  234. err.add "\nThis might be caused by a recursive module dependency:\n"
  235. err.add c.recursiveDep
  236. # prevent excessive errors for 'nim check'
  237. c.recursiveDep = ""
  238. localError(c.config, info, errGenerated, err)
  239. proc lookUp*(c: PContext, n: PNode): PSym =
  240. # Looks up a symbol. Generates an error in case of nil.
  241. case n.kind
  242. of nkIdent:
  243. result = searchInScopes(c, n.ident).skipAlias(n, c.config)
  244. if result == nil:
  245. fixSpelling(n, n.ident, searchInScopes)
  246. errorUndeclaredIdentifier(c, n.info, n.ident.s)
  247. result = errorSym(c, n)
  248. of nkSym:
  249. result = n.sym
  250. of nkAccQuoted:
  251. var ident = considerQuotedIdent(c, n)
  252. result = searchInScopes(c, ident).skipAlias(n, c.config)
  253. if result == nil:
  254. fixSpelling(n, ident, searchInScopes)
  255. errorUndeclaredIdentifier(c, n.info, ident.s)
  256. result = errorSym(c, n)
  257. else:
  258. internalError(c.config, n.info, "lookUp")
  259. return
  260. if contains(c.ambiguousSymbols, result.id):
  261. errorUseQualifier(c, n.info, result)
  262. when false:
  263. if result.kind == skStub: loadStub(result)
  264. type
  265. TLookupFlag* = enum
  266. checkAmbiguity, checkUndeclared, checkModule, checkPureEnumFields
  267. proc qualifiedLookUp*(c: PContext, n: PNode, flags: set[TLookupFlag]): PSym =
  268. const allExceptModule = {low(TSymKind)..high(TSymKind)}-{skModule,skPackage}
  269. case n.kind
  270. of nkIdent, nkAccQuoted:
  271. var ident = considerQuotedIdent(c, n)
  272. if checkModule in flags:
  273. result = searchInScopes(c, ident).skipAlias(n, c.config)
  274. else:
  275. result = searchInScopes(c, ident, allExceptModule).skipAlias(n, c.config)
  276. if result == nil and checkPureEnumFields in flags:
  277. result = strTableGet(c.pureEnumFields, ident)
  278. if result == nil and checkUndeclared in flags:
  279. fixSpelling(n, ident, searchInScopes)
  280. errorUndeclaredIdentifier(c, n.info, ident.s)
  281. result = errorSym(c, n)
  282. elif checkAmbiguity in flags and result != nil and
  283. contains(c.ambiguousSymbols, result.id):
  284. errorUseQualifier(c, n.info, result)
  285. of nkSym:
  286. result = n.sym
  287. if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id):
  288. errorUseQualifier(c, n.info, n.sym)
  289. of nkDotExpr:
  290. result = nil
  291. var m = qualifiedLookUp(c, n.sons[0], (flags*{checkUndeclared})+{checkModule})
  292. if m != nil and m.kind == skModule:
  293. var ident: PIdent = nil
  294. if n.sons[1].kind == nkIdent:
  295. ident = n.sons[1].ident
  296. elif n.sons[1].kind == nkAccQuoted:
  297. ident = considerQuotedIdent(c, n.sons[1])
  298. if ident != nil:
  299. if m == c.module:
  300. result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n, c.config)
  301. else:
  302. result = strTableGet(m.tab, ident).skipAlias(n, c.config)
  303. if result == nil and checkUndeclared in flags:
  304. fixSpelling(n.sons[1], ident, searchInScopes)
  305. errorUndeclaredIdentifier(c, n.sons[1].info, ident.s)
  306. result = errorSym(c, n.sons[1])
  307. elif n.sons[1].kind == nkSym:
  308. result = n.sons[1].sym
  309. elif checkUndeclared in flags and
  310. n.sons[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
  311. localError(c.config, n.sons[1].info, "identifier expected, but got: " &
  312. renderTree(n.sons[1]))
  313. result = errorSym(c, n.sons[1])
  314. else:
  315. result = nil
  316. when false:
  317. if result != nil and result.kind == skStub: loadStub(result)
  318. proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  319. case n.kind
  320. of nkIdent, nkAccQuoted:
  321. var ident = considerQuotedIdent(c, n)
  322. o.scope = c.currentScope
  323. o.mode = oimNoQualifier
  324. while true:
  325. result = initIdentIter(o.it, o.scope.symbols, ident).skipAlias(n, c.config)
  326. if result != nil:
  327. break
  328. else:
  329. o.scope = o.scope.parent
  330. if o.scope == nil: break
  331. of nkSym:
  332. result = n.sym
  333. o.mode = oimDone
  334. of nkDotExpr:
  335. o.mode = oimOtherModule
  336. o.m = qualifiedLookUp(c, n.sons[0], {checkUndeclared, checkModule})
  337. if o.m != nil and o.m.kind == skModule:
  338. var ident: PIdent = nil
  339. if n.sons[1].kind == nkIdent:
  340. ident = n.sons[1].ident
  341. elif n.sons[1].kind == nkAccQuoted:
  342. ident = considerQuotedIdent(c, n.sons[1], n)
  343. if ident != nil:
  344. if o.m == c.module:
  345. # a module may access its private members:
  346. result = initIdentIter(o.it, c.topLevelScope.symbols,
  347. ident).skipAlias(n, c.config)
  348. o.mode = oimSelfModule
  349. else:
  350. result = initIdentIter(o.it, o.m.tab, ident).skipAlias(n, c.config)
  351. else:
  352. noidentError(c.config, n.sons[1], n)
  353. result = errorSym(c, n.sons[1])
  354. of nkClosedSymChoice, nkOpenSymChoice:
  355. o.mode = oimSymChoice
  356. if n[0].kind == nkSym:
  357. result = n.sons[0].sym
  358. else:
  359. o.mode = oimDone
  360. return nil
  361. o.symChoiceIndex = 1
  362. o.inSymChoice = initIntSet()
  363. incl(o.inSymChoice, result.id)
  364. else: discard
  365. when false:
  366. if result != nil and result.kind == skStub: loadStub(result)
  367. proc lastOverloadScope*(o: TOverloadIter): int =
  368. case o.mode
  369. of oimNoQualifier: result = if o.scope.isNil: -1 else: o.scope.depthLevel
  370. of oimSelfModule: result = 1
  371. of oimOtherModule: result = 0
  372. else: result = -1
  373. proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  374. case o.mode
  375. of oimDone:
  376. result = nil
  377. of oimNoQualifier:
  378. if o.scope != nil:
  379. result = nextIdentIter(o.it, o.scope.symbols).skipAlias(n, c.config)
  380. while result == nil:
  381. o.scope = o.scope.parent
  382. if o.scope == nil: break
  383. result = initIdentIter(o.it, o.scope.symbols, o.it.name).skipAlias(n, c.config)
  384. # BUGFIX: o.it.name <-> n.ident
  385. else:
  386. result = nil
  387. of oimSelfModule:
  388. result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n, c.config)
  389. of oimOtherModule:
  390. result = nextIdentIter(o.it, o.m.tab).skipAlias(n, c.config)
  391. of oimSymChoice:
  392. if o.symChoiceIndex < sonsLen(n):
  393. result = n.sons[o.symChoiceIndex].sym
  394. incl(o.inSymChoice, result.id)
  395. inc o.symChoiceIndex
  396. elif n.kind == nkOpenSymChoice:
  397. # try 'local' symbols too for Koenig's lookup:
  398. o.mode = oimSymChoiceLocalLookup
  399. o.scope = c.currentScope
  400. result = firstIdentExcluding(o.it, o.scope.symbols,
  401. n.sons[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
  402. while result == nil:
  403. o.scope = o.scope.parent
  404. if o.scope == nil: break
  405. result = firstIdentExcluding(o.it, o.scope.symbols,
  406. n.sons[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
  407. of oimSymChoiceLocalLookup:
  408. result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice).skipAlias(n, c.config)
  409. while result == nil:
  410. o.scope = o.scope.parent
  411. if o.scope == nil: break
  412. result = firstIdentExcluding(o.it, o.scope.symbols,
  413. n.sons[0].sym.name, o.inSymChoice).skipAlias(n, c.config)
  414. when false:
  415. if result != nil and result.kind == skStub: loadStub(result)
  416. proc pickSym*(c: PContext, n: PNode; kinds: set[TSymKind];
  417. flags: TSymFlags = {}): PSym =
  418. var o: TOverloadIter
  419. var a = initOverloadIter(o, c, n)
  420. while a != nil:
  421. if a.kind in kinds and flags <= a.flags:
  422. if result == nil: result = a
  423. else: return nil # ambiguous
  424. a = nextOverloadIter(o, c, n)