Skip to content

Commit b46bcd8

Browse files
committed
Fix scala#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 scala#3979
1 parent 86c4e72 commit b46bcd8

File tree

4 files changed

+73
-32
lines changed

4 files changed

+73
-32
lines changed

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

Lines changed: 46 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,15 @@ object Interactive {
103103

104104
/** Get possible completions from tree at `pos`
105105
*
106-
* @return offset and list of symbols for possible completions
106+
* @return offset and list of (symbol, name in scope) for possible completions
107107
*/
108-
def completions(pos: SourcePosition)(implicit ctx: Context): (Int, List[Symbol]) = {
108+
def completions(pos: SourcePosition)(implicit ctx: Context): (Int, List[(Symbol, Name)]) = {
109109
val path = pathTo(ctx.compilationUnit.tpdTree, pos.pos)
110110
computeCompletions(pos, path)(contextOfPath(path))
111111
}
112112

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

116116
val (completionPos, prefix, termOnly, typeOnly) = path match {
117117
case (ref: RefTree) :: _ =>
@@ -135,53 +135,53 @@ object Interactive {
135135
* as completion results. However, if a user explicitly writes all '$' characters in an
136136
* identifier, we should complete the rest.
137137
*/
138-
def include(sym: Symbol) =
139-
sym.name.startsWith(prefix) &&
140-
!sym.name.toString.drop(prefix.length).contains('$') &&
138+
def include(sym: Symbol, nameInScope: Name) =
139+
nameInScope.startsWith(prefix) &&
140+
!nameInScope.toString.drop(prefix.length).contains('$') &&
141141
(!termOnly || sym.isTerm) &&
142142
(!typeOnly || sym.isType)
143143

144-
def enter(sym: Symbol) =
145-
if (include(sym)) completions.enter(sym)
144+
def enter(sym: Symbol, nameInScope: Name) =
145+
if (include(sym, nameInScope)) completions.enter(sym, nameInScope)
146146

147147
def add(sym: Symbol) =
148-
if (sym.exists && !completions.lookup(sym.name).exists) enter(sym)
148+
if (sym.exists && !completions.lookup(sym.name).exists) enter(sym, sym.name)
149149

150-
def addMember(site: Type, name: Name) =
151-
if (!completions.lookup(name).exists)
152-
for (alt <- site.member(name).alternatives) enter(alt.symbol)
150+
def addMember(site: Type, name: Name, nameInScope: Name) =
151+
if (!completions.lookup(nameInScope).exists)
152+
for (alt <- site.member(name).alternatives) enter(alt.symbol, nameInScope)
153153

154154
def accessibleMembers(site: Type, superAccess: Boolean = true): Seq[Symbol] = site match {
155155
case site: NamedType if site.symbol.is(Package) =>
156-
site.decls.toList.filter(include) // Don't look inside package members -- it's too expensive.
156+
site.decls.toList.filter(sym => include(sym, sym.name)) // Don't look inside package members -- it's too expensive.
157157
case _ =>
158158
def appendMemberSyms(name: Name, buf: mutable.Buffer[SingleDenotation]): Unit =
159159
try buf ++= site.member(name).alternatives
160160
catch { case ex: TypeError => }
161161
site.memberDenots(takeAllFilter, appendMemberSyms).collect {
162-
case mbr if include(mbr.symbol) => mbr.accessibleFrom(site, superAccess).symbol
162+
case mbr if include(mbr.symbol, mbr.symbol.name) => mbr.accessibleFrom(site, superAccess).symbol
163163
case _ => NoSymbol
164164
}.filter(_.exists)
165165
}
166166

167167
def addAccessibleMembers(site: Type, superAccess: Boolean = true): Unit =
168-
for (mbr <- accessibleMembers(site)) addMember(site, mbr.name)
168+
for (mbr <- accessibleMembers(site)) addMember(site, mbr.name, mbr.name)
169169

170170
def getImportCompletions(ictx: Context): Unit = {
171171
implicit val ctx = ictx
172172
val imp = ctx.importInfo
173173
if (imp != null) {
174-
def addImport(name: TermName) = {
175-
addMember(imp.site, name)
176-
addMember(imp.site, name.toTypeName)
174+
def addImport(original: TermName, nameInScope: TermName) = {
175+
addMember(imp.site, original, nameInScope)
176+
addMember(imp.site, original.toTypeName, nameInScope.toTypeName)
177+
}
178+
imp.reverseMapping.foreachBinding { (nameInScope, original) =>
179+
if (original != nameInScope || !imp.excluded.contains(original))
180+
addImport(original, nameInScope)
177181
}
178-
// FIXME: We need to also take renamed items into account for completions,
179-
// That means we have to return list of a pairs (Name, Symbol) instead of a list
180-
// of symbols from `completions`.!=
181-
for (imported <- imp.originals if !imp.excluded.contains(imported)) addImport(imported)
182182
if (imp.isWildcardImport)
183183
for (mbr <- accessibleMembers(imp.site) if !imp.excluded.contains(mbr.name.toTermName))
184-
addMember(imp.site, mbr.name)
184+
addMember(imp.site, mbr.name, mbr.name)
185185
}
186186
}
187187

@@ -226,7 +226,7 @@ object Interactive {
226226
case _ => getScopeCompletions(ctx)
227227
}
228228

229-
val completionList = completions.toList
229+
val completionList = completions.toListWithNames
230230
interactiv.println(i"completion with pos = $pos, prefix = $prefix, termOnly = $termOnly, typeOnly = $typeOnly = $completionList%, %")
231231
(completionPos, completionList)
232232
}
@@ -240,7 +240,7 @@ object Interactive {
240240
def addMember(name: Name, buf: mutable.Buffer[SingleDenotation]): Unit =
241241
buf ++= prefix.member(name).altsWith(sym =>
242242
!exclude(sym) && sym.isAccessibleFrom(prefix)(boundaryCtx))
243-
prefix.memberDenots(completionsFilter, addMember).map(_.symbol).toList
243+
prefix.memberDenots(completionsFilter, addMember).map(_.symbol).toList
244244
}
245245
else Nil
246246
}
@@ -413,4 +413,24 @@ object Interactive {
413413
/** The first tree in the path that is a definition. */
414414
def enclosingDefinitionInPath(path: List[Tree])(implicit ctx: Context): Tree =
415415
path.find(_.isInstanceOf[DefTree]).getOrElse(EmptyTree)
416+
417+
/** A scope that tracks renames of the entered symbols.
418+
* Useful for providing completions for renamed symbols
419+
* in the REPL and the IDE.
420+
*/
421+
private class RenameAwareScope extends Scopes.MutableScope {
422+
private[this] val renames: mutable.Map[Symbol, Name] = mutable.Map.empty
423+
424+
/** Enter the symbol `sym` in this scope, recording a potential renaming. */
425+
def enter[T <: Symbol](sym: T, name: Name)(implicit ctx: Context): T = {
426+
if (name != sym.name) renames += sym -> name
427+
newScopeEntry(name, sym)
428+
sym
429+
}
430+
431+
/** Lists the symbols in this scope along with the name associated with them. */
432+
def toListWithNames(implicit ctx: Context): List[(Symbol, Name)] =
433+
toList.map(sym => (sym, renames.get(sym).getOrElse(sym.name)))
434+
}
435+
416436
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,8 @@ class ReplDriver(settings: Array[String],
150150

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

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ class DottyLanguageServer extends LanguageServer
234234
}
235235

236236
JEither.forRight(new CompletionList(
237-
/*isIncomplete = */ false, items.map(completionItem).asJava))
237+
/*isIncomplete = */ false, items.map(completionItem.tupled).asJava))
238238
}
239239

240240
/** If cursor is on a reference, show its definition and all overriding definitions in
@@ -461,7 +461,7 @@ object DottyLanguageServer {
461461
}
462462

463463
/** Create an lsp4j.CompletionItem from a Symbol */
464-
def completionItem(sym: Symbol)(implicit ctx: Context): lsp4j.CompletionItem = {
464+
def completionItem(sym: Symbol, name: Name)(implicit ctx: Context): lsp4j.CompletionItem = {
465465
def completionItemKind(sym: Symbol)(implicit ctx: Context): lsp4j.CompletionItemKind = {
466466
import lsp4j.{CompletionItemKind => CIK}
467467

@@ -479,7 +479,7 @@ object DottyLanguageServer {
479479
CIK.Field
480480
}
481481

482-
val label = sym.name.show
482+
val label = name.show
483483
val item = new lsp4j.CompletionItem(label)
484484
item.setDetail(sym.info.widenTermRefExpr.show)
485485
item.setKind(completionItemKind(sym))

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

Lines changed: 21 additions & 0 deletions
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)