Skip Refaster matches when @AfterTemplate returns a wider type
#5481
+140
−0
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.
Refaster currently does not verify that the
@AfterTemplate's return type is compatible with the@BeforeTemplate's return type. This can produce replacements that break compilation.Example
Given this Refaster rule:
Refaster would transform this code:
into:
Fix
Before generating a fix,
RefasterScannernow checks whether the@AfterTemplate's return type (erased) is a subtype of the@BeforeTemplate's return type (erased). If not, the match is skipped.Caveats
While having an
@AfterTemplatewith a wider return type than the@BeforeTemplatemay sound unusual, it can be useful in practice. For example, Error Prone Support'sAssertThatThrownByAsInstanceOfThrowablerule replacesThrowableAssertAlternative<T>with the widerAbstractThrowableAssert<?, T>:The current fix is conservative: it compares the before and after template return types directly, without considering whether the wider type would actually be compatible with the specific match context (e.g. compatible method overloads or assignment targets that accept the wider type). This means some valid replacements may be skipped. A more precise check that inspects the parent AST node for context-specific compatibility could be added in the future.