Skip to content

Commit 7c77293

Browse files
committed
Fix #3979: Completion for renamed imports
We introduce a new `RenameAwareScope` that tracks the name associated with a symbol in the scope. Calling `toListWithNames` returns the list of symbols in this scope along with the name that should be used to refer to the symbol in this scope. Fixes #3979
1 parent 94d70d4 commit 7c77293

File tree

5 files changed

+82
-32
lines changed

5 files changed

+82
-32
lines changed

compiler/src/dotty/tools/dotc/interactive/Interactive.scala

+45-26
Original file line numberDiff line numberDiff line change
@@ -147,15 +147,15 @@ object Interactive {
147147

148148
/** Get possible completions from tree at `pos`
149149
*
150-
* @return offset and list of symbols for possible completions
150+
* @return offset and list of (symbol, name in scope) for possible completions
151151
*/
152-
def completions(pos: SourcePosition)(implicit ctx: Context): (Int, List[Symbol]) = {
152+
def completions(pos: SourcePosition)(implicit ctx: Context): (Int, List[(Symbol, Name)]) = {
153153
val path = pathTo(ctx.compilationUnit.tpdTree, pos.pos)
154154
computeCompletions(pos, path)(contextOfPath(path))
155155
}
156156

157-
private def computeCompletions(pos: SourcePosition, path: List[Tree])(implicit ctx: Context): (Int, List[Symbol]) = {
158-
val completions = Scopes.newScope.openForMutations
157+
private def computeCompletions(pos: SourcePosition, path: List[Tree])(implicit ctx: Context): (Int, List[(Symbol, Name)]) = {
158+
val completions = new RenameAwareScope
159159

160160
val (completionPos, prefix, termOnly, typeOnly) = path match {
161161
case (ref: RefTree) :: _ =>
@@ -179,53 +179,53 @@ object Interactive {
179179
* as completion results. However, if a user explicitly writes all '$' characters in an
180180
* identifier, we should complete the rest.
181181
*/
182-
def include(sym: Symbol) =
183-
sym.name.startsWith(prefix) &&
184-
!sym.name.toString.drop(prefix.length).contains('$') &&
182+
def include(sym: Symbol, nameInScope: Name) =
183+
nameInScope.startsWith(prefix) &&
184+
!nameInScope.toString.drop(prefix.length).contains('$') &&
185185
(!termOnly || sym.isTerm) &&
186186
(!typeOnly || sym.isType)
187187

188-
def enter(sym: Symbol) =
189-
if (include(sym)) completions.enter(sym)
188+
def enter(sym: Symbol, nameInScope: Name) =
189+
if (include(sym, nameInScope)) completions.enter(sym, nameInScope)
190190

191191
def add(sym: Symbol) =
192-
if (sym.exists && !completions.lookup(sym.name).exists) enter(sym)
192+
if (sym.exists && !completions.lookup(sym.name).exists) enter(sym, sym.name)
193193

194-
def addMember(site: Type, name: Name) =
195-
if (!completions.lookup(name).exists)
196-
for (alt <- site.member(name).alternatives) enter(alt.symbol)
194+
def addMember(site: Type, name: Name, nameInScope: Name) =
195+
if (!completions.lookup(nameInScope).exists)
196+
for (alt <- site.member(name).alternatives) enter(alt.symbol, nameInScope)
197197

198198
def accessibleMembers(site: Type, superAccess: Boolean = true): Seq[Symbol] = site match {
199199
case site: NamedType if site.symbol.is(Package) =>
200-
site.decls.toList.filter(include) // Don't look inside package members -- it's too expensive.
200+
site.decls.toList.filter(sym => include(sym, sym.name)) // Don't look inside package members -- it's too expensive.
201201
case _ =>
202202
def appendMemberSyms(name: Name, buf: mutable.Buffer[SingleDenotation]): Unit =
203203
try buf ++= site.member(name).alternatives
204204
catch { case ex: TypeError => }
205205
site.memberDenots(takeAllFilter, appendMemberSyms).collect {
206-
case mbr if include(mbr.symbol) => mbr.accessibleFrom(site, superAccess).symbol
206+
case mbr if include(mbr.symbol, mbr.symbol.name) => mbr.accessibleFrom(site, superAccess).symbol
207207
case _ => NoSymbol
208208
}.filter(_.exists)
209209
}
210210

211211
def addAccessibleMembers(site: Type, superAccess: Boolean = true): Unit =
212-
for (mbr <- accessibleMembers(site)) addMember(site, mbr.name)
212+
for (mbr <- accessibleMembers(site)) addMember(site, mbr.name, mbr.name)
213213

214214
def getImportCompletions(ictx: Context): Unit = {
215215
implicit val ctx = ictx
216216
val imp = ctx.importInfo
217217
if (imp != null) {
218-
def addImport(name: TermName) = {
219-
addMember(imp.site, name)
220-
addMember(imp.site, name.toTypeName)
218+
def addImport(original: TermName, nameInScope: TermName) = {
219+
addMember(imp.site, original, nameInScope)
220+
addMember(imp.site, original.toTypeName, nameInScope.toTypeName)
221+
}
222+
imp.reverseMapping.foreachBinding { (nameInScope, original) =>
223+
if (original != nameInScope || !imp.excluded.contains(original))
224+
addImport(original, nameInScope)
221225
}
222-
// FIXME: We need to also take renamed items into account for completions,
223-
// That means we have to return list of a pairs (Name, Symbol) instead of a list
224-
// of symbols from `completions`.!=
225-
for (imported <- imp.originals if !imp.excluded.contains(imported)) addImport(imported)
226226
if (imp.isWildcardImport)
227227
for (mbr <- accessibleMembers(imp.site) if !imp.excluded.contains(mbr.name.toTermName))
228-
addMember(imp.site, mbr.name)
228+
addMember(imp.site, mbr.name, mbr.name)
229229
}
230230
}
231231

@@ -270,7 +270,7 @@ object Interactive {
270270
case _ => getScopeCompletions(ctx)
271271
}
272272

273-
val completionList = completions.toList
273+
val completionList = completions.toListWithNames
274274
interactiv.println(i"completion with pos = $pos, prefix = $prefix, termOnly = $termOnly, typeOnly = $typeOnly = $completionList%, %")
275275
(completionPos, completionList)
276276
}
@@ -284,7 +284,7 @@ object Interactive {
284284
def addMember(name: Name, buf: mutable.Buffer[SingleDenotation]): Unit =
285285
buf ++= prefix.member(name).altsWith(sym =>
286286
!exclude(sym) && sym.isAccessibleFrom(prefix)(boundaryCtx))
287-
prefix.memberDenots(completionsFilter, addMember).map(_.symbol).toList
287+
prefix.memberDenots(completionsFilter, addMember).map(_.symbol).toList
288288
}
289289
else Nil
290290
}
@@ -490,4 +490,23 @@ object Interactive {
490490
}
491491
}
492492

493+
/** A scope that tracks renames of the entered symbols.
494+
* Useful for providing completions for renamed symbols
495+
* in the REPL and the IDE.
496+
*/
497+
private class RenameAwareScope extends Scopes.MutableScope {
498+
private[this] val renames: mutable.Map[Symbol, Name] = mutable.Map.empty
499+
500+
/** Enter the symbol `sym` in this scope, recording a potential renaming. */
501+
def enter[T <: Symbol](sym: T, name: Name)(implicit ctx: Context): T = {
502+
if (name != sym.name) renames += sym -> name
503+
newScopeEntry(name, sym)
504+
sym
505+
}
506+
507+
/** Lists the symbols in this scope along with the name associated with them. */
508+
def toListWithNames(implicit ctx: Context): List[(Symbol, Name)] =
509+
toList.map(sym => (sym, renames.get(sym).getOrElse(sym.name)))
510+
}
511+
493512
}

compiler/src/dotty/tools/repl/ReplDriver.scala

+3-3
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,8 @@ class ReplDriver(settings: Array[String],
149149

150150
/** Extract possible completions at the index of `cursor` in `expr` */
151151
protected[this] final def completions(cursor: Int, expr: String, state0: State): List[Candidate] = {
152-
def makeCandidate(completion: Symbol)(implicit ctx: Context) = {
153-
val displ = completion.name.toString
152+
def makeCandidate(name: Name)(implicit ctx: Context) = {
153+
val displ = name.toString
154154
new Candidate(
155155
/* value = */ displ,
156156
/* displ = */ displ, // displayed value
@@ -171,7 +171,7 @@ class ReplDriver(settings: Array[String],
171171
implicit val ctx = state.context.fresh.setCompilationUnit(unit)
172172
val srcPos = SourcePosition(file, Position(cursor))
173173
val (_, completions) = Interactive.completions(srcPos)
174-
completions.map(makeCandidate)
174+
completions.map(c => makeCandidate(c._2))
175175
}
176176
.getOrElse(Nil)
177177
}

compiler/test/dotty/tools/repl/TabcompleteTests.scala

+10
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,14 @@ class TabcompleteTests extends ReplTest {
8080
val expected = List("FileDescriptor")
8181
assertEquals(expected, tabComplete("val foo: FileDesc"))
8282
}
83+
84+
@Test def tabCompleteRenamedImport =
85+
fromInitialState { implicit state =>
86+
val src = "import java.io.{FileDescriptor => Renamed}"
87+
run(src)
88+
}
89+
.andThen { implicit state =>
90+
val expected = List("Renamed")
91+
assertEquals(expected, tabComplete("val foo: Rena"))
92+
}
8393
}

language-server/src/dotty/tools/languageserver/DottyLanguageServer.scala

+3-3
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ class DottyLanguageServer extends LanguageServer
256256
}
257257

258258
JEither.forRight(new CompletionList(
259-
/*isIncomplete = */ false, items.map(completionItem).asJava))
259+
/*isIncomplete = */ false, items.map(completionItem.tupled).asJava))
260260
}
261261

262262
/** If cursor is on a reference, show its definition and all overriding definitions in
@@ -568,7 +568,7 @@ object DottyLanguageServer {
568568
}
569569

570570
/** Create an lsp4j.CompletionItem from a Symbol */
571-
def completionItem(sym: Symbol)(implicit ctx: Context): lsp4j.CompletionItem = {
571+
def completionItem(sym: Symbol, name: Name)(implicit ctx: Context): lsp4j.CompletionItem = {
572572
def completionItemKind(sym: Symbol)(implicit ctx: Context): lsp4j.CompletionItemKind = {
573573
import lsp4j.{CompletionItemKind => CIK}
574574

@@ -586,7 +586,7 @@ object DottyLanguageServer {
586586
CIK.Field
587587
}
588588

589-
val label = sym.name.show
589+
val label = name.show
590590
val item = new lsp4j.CompletionItem(label)
591591
item.setDetail(sym.info.widenTermRefExpr.show)
592592
item.setKind(completionItemKind(sym))

language-server/test/dotty/tools/languageserver/CompletionTest.scala

+21
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,25 @@ class CompletionTest {
1919
code"object Main { import Foo._; val bar: Bar = new Bar; bar.b${m1} }"
2020
) .completion(m1, Set(("baz", CompletionItemKind.Method, "=> Int")))
2121
}
22+
23+
@Test def completionOnImport: Unit = {
24+
code"""import java.io.FileDescriptor
25+
trait Foo { val x: FileDesc$m1 }""".withSource
26+
.completion(m1, Set(("FileDescriptor", CompletionItemKind.Class, "Object{...}")))
27+
}
28+
29+
@Test def completionOnRenamedImport: Unit = {
30+
code"""import java.io.{FileDescriptor => AwesomeStuff}
31+
trait Foo { val x: Awesom$m1 }""".withSource
32+
.completion(m1, Set(("AwesomeStuff", CompletionItemKind.Class, "Object{...}")))
33+
}
34+
35+
@Test def completionOnRenamedImport2: Unit = {
36+
code"""import java.util.{HashMap => MyImportedSymbol}
37+
trait Foo {
38+
import java.io.{FileDescriptor => MyImportedSymbol}
39+
val x: MyImp$m1
40+
}""".withSource
41+
.completion(m1, Set(("MyImportedSymbol", CompletionItemKind.Class, "Object{...}")))
42+
}
2243
}

0 commit comments

Comments
 (0)