-
Notifications
You must be signed in to change notification settings - Fork 439
Add suppress warnings & remove redudant cast quick-fix code action #8646
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
zielinsky
wants to merge
13
commits into
scalameta:main-v2
Choose a base branch
from
zielinsky:metalsv2/supress-warnings
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
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f79fc10
Add suppress warnings quick-fix code action
zielinsky e6255ce
Merge branch 'main-v2' into metalsv2/supress-warnings
zielinsky 643301c
Merge branch 'main-v2' into metalsv2/supress-warnings
zielinsky cbbcbb8
Remove redundant cast
zielinsky d263f9f
Merge branch 'main-v2' into metalsv2/supress-warnings
zielinsky 301267b
cleanup
zielinsky ddbc842
address review
zielinsky b5dcdaf
Use Java lint options from build target
zielinsky 6393911
address review
zielinsky 48c2076
Merge branch 'main-v2' into metalsv2/supress-warnings
zielinsky 67465e5
address review
zielinsky 6d545b7
cleanup
zielinsky 804a7f5
change default javac_options value from feature flags
zielinsky 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
Some comments aren't visible on the classic Files Changed page.
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
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
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
84 changes: 84 additions & 0 deletions
84
metals/src/main/scala/scala/meta/internal/metals/codeactions/RemoveRedundantCast.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,84 @@ | ||
| package scala.meta.internal.metals.codeactions | ||
|
|
||
| import scala.concurrent.ExecutionContext | ||
| import scala.concurrent.Future | ||
|
|
||
| import scala.meta.internal.metals.Buffers | ||
| import scala.meta.internal.metals.MetalsEnrichments._ | ||
| import scala.meta.internal.parsing.JavaTrees | ||
| import scala.meta.internal.parsing.JavaTypeCast | ||
| import scala.meta.pc.CancelToken | ||
|
|
||
| import org.eclipse.{lsp4j => l} | ||
|
|
||
| class RemoveRedundantCast(javaTrees: JavaTrees, buffers: Buffers) | ||
| extends CodeAction { | ||
| import RemoveRedundantCast._ | ||
|
|
||
| override def kind: String = l.CodeActionKind.QuickFix | ||
| override def isScala: Boolean = false | ||
| override def isJava: Boolean = true | ||
|
|
||
| override def contribute( | ||
| params: l.CodeActionParams, | ||
| token: CancelToken, | ||
| )(implicit ec: ExecutionContext): Future[Seq[l.CodeAction]] = Future { | ||
| val path = params.getTextDocument().getUri().toAbsolutePath | ||
| val range = params.getRange() | ||
|
|
||
| for { | ||
| text <- buffers.get(path).orElse(path.readTextOpt).toSeq | ||
| diagnostic <- params.getContext().getDiagnostics().asScala.toSeq | ||
| if isRedundantCast(diagnostic) | ||
| if range.overlapsWith(diagnostic.getRange()) | ||
| cast <- javaTrees | ||
| .findTypeCast(path, diagnostic.getRange().getStart()) | ||
| .toSeq | ||
| } yield CodeActionBuilder.build( | ||
| title, | ||
| kind, | ||
| diagnostics = List(diagnostic), | ||
| changes = Seq(path -> Seq(removeCastEdit(text, cast))), | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| object RemoveRedundantCast { | ||
| val title = "Remove redundant cast" | ||
|
|
||
| private val RedundantCastCode = "compiler.warn.redundant.cast" | ||
|
|
||
| private def isRedundantCast(diagnostic: l.Diagnostic): Boolean = | ||
| Option(diagnostic.getCode()).exists(code => | ||
| code.isLeft() && code.getLeft() == RedundantCastCode | ||
| ) | ||
|
|
||
| private def removeCastEdit(text: String, cast: JavaTypeCast): l.TextEdit = { | ||
| val castStart = cast.typeRange.startOffset | ||
| val typeEnd = cast.typeRange.endOffset | ||
| val editEnd = typeEnd + text | ||
| .substring(typeEnd, cast.exprRange.startOffset) | ||
| .takeWhile(ch => ch == ' ' || ch == '\t') | ||
| .length | ||
| val editStart = | ||
| if ( | ||
| editEnd >= text.length || text.charAt(editEnd) == '\n' || text | ||
| .charAt(editEnd) == '\r' | ||
| ) | ||
| castStart - JavaMemberInsertion | ||
| .linePrefix(text, castStart) | ||
| .reverse | ||
| .takeWhile(ch => ch == ' ' || ch == '\t') | ||
| .length | ||
| else | ||
| castStart | ||
| new l.TextEdit( | ||
| new l.Range( | ||
| text.indexToLspPosition(editStart), | ||
| text.indexToLspPosition(editEnd), | ||
| ), | ||
| "", | ||
| ) | ||
| } | ||
|
|
||
| } |
226 changes: 226 additions & 0 deletions
226
metals/src/main/scala/scala/meta/internal/metals/codeactions/SuppressWarnings.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,226 @@ | ||
| package scala.meta.internal.metals.codeactions | ||
|
|
||
| import scala.concurrent.ExecutionContext | ||
| import scala.concurrent.Future | ||
|
|
||
| import scala.meta.internal.metals.Buffers | ||
| import scala.meta.internal.metals.MetalsEnrichments._ | ||
| import scala.meta.internal.parsing.JavaAnnotation | ||
| import scala.meta.internal.parsing.JavaMember | ||
| import scala.meta.internal.parsing.JavaRange | ||
| import scala.meta.internal.parsing.JavaTrees | ||
| import scala.meta.io.AbsolutePath | ||
| import scala.meta.pc.CancelToken | ||
|
|
||
| import com.google.gson.JsonPrimitive | ||
| import org.eclipse.{lsp4j => l} | ||
|
|
||
| class SuppressWarnings( | ||
| javaTrees: JavaTrees, | ||
| buffers: Buffers, | ||
| ) extends CodeAction { | ||
| import SuppressWarnings._ | ||
|
|
||
| override def kind: String = l.CodeActionKind.QuickFix | ||
| override def isScala: Boolean = false | ||
| override def isJava: Boolean = true | ||
|
|
||
| override def contribute( | ||
| params: l.CodeActionParams, | ||
| token: CancelToken, | ||
| )(implicit ec: ExecutionContext): Future[Seq[l.CodeAction]] = Future { | ||
| val path = params.getTextDocument().getUri().toAbsolutePath | ||
| val range = params.getRange() | ||
|
|
||
| val actions = for { | ||
| text <- buffers.get(path).orElse(path.readTextOpt).toSeq | ||
| diagnostic <- params.getContext().getDiagnostics().asScala.toSeq | ||
| warningName <- warningName(diagnostic).toSeq | ||
| if range.overlapsWith(diagnostic.getRange()) || | ||
| isZeroRange(diagnostic.getRange()) | ||
| position = | ||
| if (range.overlapsWith(diagnostic.getRange())) | ||
| diagnostic.getRange().getStart() | ||
| else range.getStart() | ||
| member <- enclosingMember(path, position).toSeq | ||
| edit <- suppressEdit(text, path, member, warningName).toSeq | ||
| } yield CodeActionBuilder.build( | ||
| title(warningName), | ||
| kind, | ||
| diagnostics = List(diagnostic), | ||
| changes = Seq(path -> Seq(edit)), | ||
| ) | ||
| actions.distinctBy(_.getEdit()) | ||
| } | ||
|
|
||
| private def enclosingMember( | ||
| path: AbsolutePath, | ||
| position: l.Position, | ||
| ): Option[SuppressTarget] = | ||
| javaTrees | ||
| .findEnclosingJavaVariable(path, position, onNameOnly = false) | ||
| .filter(variable => | ||
| variable.isStandaloneDeclaration && | ||
| position <= variable.nameRange.getEnd() | ||
| ) | ||
| .map(variable => SuppressTarget(variable, variable.nameRange)) | ||
| .orElse( | ||
| javaTrees | ||
| .findEnclosingJavaMethod(path, position) | ||
| .map(method => SuppressTarget(method, method.nameRange)) | ||
| ) | ||
| .orElse( | ||
| javaTrees | ||
| .findEnclosingJavaClass(path, position) | ||
| .map(cls => SuppressTarget(cls, cls.nameRange)) | ||
| ) | ||
|
|
||
| private def suppressEdit( | ||
| text: String, | ||
| path: scala.meta.io.AbsolutePath, | ||
| target: SuppressTarget, | ||
| warningName: String, | ||
| ): Option[l.TextEdit] = { | ||
| val annotations = javaTrees.memberAnnotations(path, target.member) | ||
| existingSuppressWarnings(annotations) match { | ||
| case Some(existing) => appendWarningEdit(text, existing, warningName) | ||
| case None => | ||
| Some(insertSuppressWarningsEdit(text, target, warningName, annotations)) | ||
| } | ||
| } | ||
|
|
||
| private def insertSuppressWarningsEdit( | ||
| text: String, | ||
| target: SuppressTarget, | ||
| warningName: String, | ||
| annotations: List[JavaAnnotation], | ||
| ): l.TextEdit = { | ||
| val declarationOffset = declarationStartOffset(text, target, annotations) | ||
| val declarationStart = text.indexToLspPosition(declarationOffset) | ||
| val linePrefix = | ||
| JavaMemberInsertion.linePrefix(text, declarationOffset) | ||
| val (position, newText) = | ||
| if (linePrefix.forall(_.isWhitespace)) | ||
| ( | ||
| new l.Position(declarationStart.getLine(), 0), | ||
| s"""$linePrefix@SuppressWarnings("$warningName") | ||
| |""".stripMargin, | ||
| ) | ||
| else (declarationStart, s"""@SuppressWarnings("$warningName") """) | ||
|
|
||
| new l.TextEdit(new l.Range(position, position), newText) | ||
| } | ||
|
|
||
| private def declarationStartOffset( | ||
| text: String, | ||
| target: SuppressTarget, | ||
| annotations: List[JavaAnnotation], | ||
| ): Int = { | ||
| val afterAnnotations = annotations | ||
| .maxByOption(_.range.endOffset) | ||
| .map(_.range.endOffset) | ||
| .getOrElse(target.member.range.startOffset) | ||
| var offset = afterAnnotations | ||
| while ( | ||
| offset < target.nameRange.startOffset && text.charAt(offset).isWhitespace | ||
| ) | ||
| offset += 1 | ||
| offset | ||
| } | ||
| } | ||
|
|
||
| object SuppressWarnings { | ||
| def title(warningName: String): String = | ||
| s"""Add @SuppressWarnings("$warningName")""" | ||
|
|
||
| private def warningName(diagnostic: l.Diagnostic): Option[String] = | ||
| Option | ||
| .when(diagnostic.getSource() == "javac")(diagnostic.getData()) | ||
| .flatMap { | ||
| case value: String => Some(value) | ||
| case value: JsonPrimitive if value.isString() => | ||
| Some(value.getAsString()) | ||
| case _ => None | ||
| } | ||
|
|
||
| private def isZeroRange(range: l.Range): Boolean = | ||
| range.isOffset && | ||
| range.getStart().getLine() == 0 && | ||
| range.getStart().getCharacter() == 0 | ||
|
|
||
| private def existingSuppressWarnings( | ||
| annotations: List[JavaAnnotation] | ||
| ): Option[ExistingSuppressWarnings] = | ||
| annotations | ||
| .collectFirst { | ||
| case ann | ||
| if ann.name == "SuppressWarnings" || | ||
| ann.name.endsWith(".SuppressWarnings") => | ||
| ann.argsRange | ||
| } | ||
| .flatten | ||
| .map { case (open, close) => ExistingSuppressWarnings(open, close) } | ||
|
|
||
| private def appendWarningEdit( | ||
| text: String, | ||
| existing: ExistingSuppressWarnings, | ||
| warningName: String, | ||
| ): Option[l.TextEdit] = { | ||
| val insideStart = existing.openParenOffset + 1 | ||
| val insideEnd = existing.closeParenOffset | ||
| val inside = text.substring(insideStart, insideEnd) | ||
| if (inside.contains(s""""$warningName"""")) None | ||
| else { | ||
| val trimmed = inside.trim() | ||
| val (namedValuePrefix, value) = trimmed match { | ||
| case NamedValueArgument(prefix, value) => (prefix, value.trim()) | ||
| case _ => ("", trimmed) | ||
| } | ||
| val isArray = value.startsWith("{") && value.endsWith("}") | ||
| val arrayContents = | ||
| if (isArray) value.substring(1, value.length() - 1).trim() | ||
| else "" | ||
| val (range, newText) = | ||
| if (isArray && arrayContents.isEmpty()) { | ||
| ( | ||
| new l.Range( | ||
| text.indexToLspPosition(insideStart), | ||
| text.indexToLspPosition(insideEnd), | ||
| ), | ||
| s"""$namedValuePrefix{"$warningName"}""", | ||
| ) | ||
| } else if (isArray) { | ||
| val closeBrace = insideStart + inside.lastIndexOf('}') | ||
| val separator = if (arrayContents.endsWith(",")) " " else ", " | ||
| ( | ||
| new l.Range( | ||
| text.indexToLspPosition(closeBrace), | ||
| text.indexToLspPosition(closeBrace), | ||
| ), | ||
| s"""$separator"$warningName"""", | ||
| ) | ||
| } else { | ||
| ( | ||
| new l.Range( | ||
| text.indexToLspPosition(insideStart), | ||
| text.indexToLspPosition(insideEnd), | ||
| ), | ||
| s"""$namedValuePrefix{$value, "$warningName"}""", | ||
| ) | ||
| } | ||
| Some(new l.TextEdit(range, newText)) | ||
| } | ||
| } | ||
|
|
||
| private val NamedValueArgument = """(?s)(value\s*=\s*)(.*)""".r | ||
|
|
||
| private case class SuppressTarget( | ||
| member: JavaMember, | ||
| nameRange: JavaRange, | ||
| ) | ||
|
|
||
| private case class ExistingSuppressWarnings( | ||
| openParenOffset: Int, | ||
| closeParenOffset: Int, | ||
| ) | ||
| } | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.