lookups.nim 15 KB

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