-
Notifications
You must be signed in to change notification settings - Fork 408
Add imports on paste #8181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mkoteckivl
wants to merge
2
commits into
scalameta:main-v2
Choose a base branch
from
mkoteckivl:add_imports_on_paste_v2
base: main-v2
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add imports on paste #8181
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
215 changes: 215 additions & 0 deletions
215
metals/src/main/scala/scala/meta/internal/metals/MetalsPasteProvider.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| package scala.meta.internal.metals | ||
|
|
||
| import scala.concurrent.ExecutionContext | ||
| import scala.concurrent.Future | ||
|
|
||
| import scala.meta.Import | ||
| import scala.meta.Pkg | ||
| import scala.meta.Source | ||
| import scala.meta.Stat | ||
| import scala.meta.inputs.Input.VirtualFile | ||
| import scala.meta.inputs.Position | ||
| import scala.meta.internal.metals.MetalsEnrichments._ | ||
| import scala.meta.internal.metals.codeactions.MissingSymbolDiagnostic | ||
| import scala.meta.internal.parsing.Trees | ||
| import scala.meta.internal.pc.ScriptFirstImportPosition | ||
| import scala.meta.internal.semanticdb.Scala._ | ||
| import scala.meta.io.AbsolutePath | ||
| import scala.meta.pc.CancelToken | ||
|
|
||
| import org.eclipse.lsp4j | ||
| import org.eclipse.lsp4j.TextDocumentPositionParams | ||
| import org.eclipse.lsp4j.TextEdit | ||
|
|
||
| class MetalsPasteProvider( | ||
| compilers: Compilers, | ||
| buildTargets: BuildTargets, | ||
| definitions: DefinitionProvider, | ||
| trees: Trees, | ||
| )(implicit ec: ExecutionContext) { | ||
|
|
||
| def didPaste( | ||
| params: MetalsPasteParams, | ||
| cancelToken: CancelToken, | ||
| ): Future[Option[TextEdit]] = { | ||
| val path = params.textDocument.getUri.toAbsolutePath | ||
| val orginalPath = params.originDocument.getUri().toAbsolutePath | ||
| val isScala3 = | ||
| buildTargets.scalaVersion(path).exists(ScalaVersions.isScala3Version) | ||
| val MissingSymbol = new MissingSymbolDiagnostic(isScala3, path) | ||
|
|
||
| compilers | ||
| .didChangeWithDiagnostics( | ||
| path, | ||
| content = Some(params.text), | ||
| ) | ||
| .flatMap { diagnostics => | ||
| val imports = diagnostics.collect { | ||
| case d @ MissingSymbol(name, _) | ||
| if params.range.overlapsWith(d.getRange()) => | ||
|
|
||
| val offset = | ||
| if (isScala3) d.getRange().getEnd() | ||
| else d.getRange().getStart() | ||
|
|
||
| val symbolsPositionParams = | ||
| new TextDocumentPositionParams( | ||
| params.originDocument, | ||
| adjustPositionToOrigin(params, offset), | ||
| ) | ||
| for { | ||
| defnResult <- definitions.definition( | ||
| orginalPath, | ||
| symbolsPositionParams, | ||
| cancelToken, | ||
| ) | ||
| } yield { | ||
| if (defnResult.isEmpty) None | ||
| else { | ||
| val symbolDesc = defnResult.symbol.desc | ||
| val symbolName = symbolDesc.name.value | ||
| lazy val owner = defnResult.symbol.owner | ||
| lazy val ownerName = owner.desc.name.value | ||
|
|
||
| val importText = | ||
| if (name != symbolName) { | ||
| if ( | ||
| symbolDesc.isMethod && | ||
| (symbolName == "apply" || symbolName == "unapply" || symbolName == "<init>") | ||
| ) | ||
| if (ownerName == name) s"import ${symbolToFqcn(owner)}" | ||
| else | ||
| s"import ${symbolToFqcn(owner.owner)}.{${ownerName} => $name}" | ||
| else s"import ${symbolToFqcn(owner)}.{$symbolName => $name}" | ||
| } else s"import ${symbolToFqcn(defnResult.symbol)}" | ||
|
|
||
| Some(importText) | ||
| } | ||
| } | ||
| } | ||
| Future | ||
| .sequence(imports) | ||
| .map(_.flatten.distinct) | ||
| .map { imports => | ||
| Option.when(imports.nonEmpty) { | ||
| val (prefix, suffix, pos) = | ||
| autoImportPosition(path, params.text, params.range.getStart()) | ||
| new lsp4j.TextEdit( | ||
| new lsp4j.Range(pos, pos), | ||
| imports.mkString(prefix, "\n", suffix), | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Convert a semanticdb symbol to an import path. | ||
| * E.g., "scala/collection/immutable/List#" -> "scala.collection.immutable.List" | ||
| */ | ||
| private def symbolToFqcn(symbol: String): String = { | ||
| import scala.meta.internal.semanticdb.Scala.Symbols | ||
|
|
||
| // Build owner chain by recursively following .owner | ||
| @scala.annotation.tailrec | ||
| def buildOwnerChain( | ||
| sym: String, | ||
| acc: List[String], | ||
| depth: Int = 0, | ||
| ): List[String] = { | ||
| if (depth > 100) { | ||
| // Prevent infinite recursion | ||
| acc | ||
| } else { | ||
| val desc = sym.desc | ||
| if ( | ||
| desc.isNone || sym == Symbols.RootPackage || sym == Symbols.EmptyPackage | ||
| ) { | ||
| acc | ||
| } else { | ||
| buildOwnerChain(sym.owner, sym :: acc, depth + 1) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Find the term, type, or package (skip method descriptors, parameters, etc.) | ||
| @scala.annotation.tailrec | ||
| def findImportable(sym: String, depth: Int = 0): String = { | ||
| if (depth > 100) { | ||
| // Prevent infinite recursion | ||
| sym | ||
| } else { | ||
| val desc = sym.desc | ||
| if (desc.isTerm || desc.isType || desc.isPackage) sym | ||
| else findImportable(sym.owner, depth + 1) | ||
| } | ||
| } | ||
|
|
||
| val importable = findImportable(symbol) | ||
| val owners = buildOwnerChain(importable, Nil) | ||
|
|
||
| owners.map(_.desc.name.value).mkString(".") | ||
| } | ||
|
|
||
| private def adjustPositionToOrigin( | ||
| params: MetalsPasteParams, | ||
| pos: lsp4j.Position, | ||
| ): lsp4j.Position = { | ||
| val lineDiff = | ||
| params.originOffset.getLine() - params.range.getStart().getLine() | ||
| if (pos.getLine() == params.range.getStart().getLine()) { | ||
| val charDiff = params.originOffset | ||
| .getCharacter() - params.range.getStart().getCharacter() | ||
| new lsp4j.Position( | ||
| pos.getLine() + lineDiff, | ||
| pos.getCharacter() + charDiff, | ||
| ) | ||
| } else { | ||
| new lsp4j.Position(pos.getLine() + lineDiff, pos.getCharacter()) | ||
| } | ||
| } | ||
|
|
||
| private def autoImportPosition( | ||
| path: AbsolutePath, | ||
| text: String, | ||
| pos: lsp4j.Position, | ||
| ): (String, String, lsp4j.Position) = { | ||
|
|
||
| lazy val fallback = { | ||
| val inputFromText = new VirtualFile(path.toURI.toString, text) | ||
| val point = ScriptFirstImportPosition.infer(text) | ||
| val pos = Position.Range(inputFromText, point, point).toLsp.getStart() | ||
| ("", "\n\n", pos) | ||
| } | ||
|
|
||
| def afterImportsPositon(stats: List[Stat]) = | ||
| stats | ||
| .takeWhile { | ||
| case _: Import => true | ||
| case _ => false | ||
| } | ||
| .lastOption | ||
| .map { imp => | ||
| ("\n", "\n", imp.pos.toLsp.getEnd()) | ||
| } | ||
| trees.findLastEnclosingAt[Pkg](path, pos, _ => true) match { | ||
| case Some(pkg @ Pkg(_, stats)) => | ||
| afterImportsPositon(stats).getOrElse( | ||
| ( | ||
| "", | ||
| "\n\n", | ||
| stats.headOption | ||
| .map(_.pos.toLsp.getStart()) | ||
| .getOrElse(pkg.pos.toLsp.getEnd()), | ||
| ) | ||
| ) | ||
| case _ => | ||
| trees.get(path) match { | ||
| case Some(Source(stats)) => | ||
| afterImportsPositon(stats).getOrElse(fallback) | ||
| case _ => fallback | ||
| } | ||
| } | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think most of this got rewritten and replaced on main. The logic was flaky unfortunately, could you check the newest version instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've applied newer changes from the main branch.