-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Fix #856: Handle try/catch cases as catch cases if possible. #1315
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
Merged
Merged
Changes from all commits
Commits
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
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,99 @@ | ||
package dotty.tools.dotc | ||
package transform | ||
|
||
import core.Symbols._ | ||
import core.StdNames._ | ||
import ast.Trees._ | ||
import core.Types._ | ||
import dotty.tools.dotc.core.Decorators._ | ||
import dotty.tools.dotc.core.Flags | ||
import dotty.tools.dotc.core.Contexts.Context | ||
import dotty.tools.dotc.transform.TreeTransforms.{MiniPhaseTransform, TransformerInfo} | ||
import dotty.tools.dotc.util.Positions.Position | ||
|
||
/** Compiles the cases that can not be handled by primitive catch cases as a common pattern match. | ||
* | ||
* The following code: | ||
* ``` | ||
* try { <code> } | ||
* catch { | ||
* <tryCases> // Cases that can be handled by catch | ||
* <patternMatchCases> // Cases starting with first one that can't be handled by catch | ||
* } | ||
* ``` | ||
* will become: | ||
* ``` | ||
* try { <code> } | ||
* catch { | ||
* <tryCases> | ||
* case e => e match { | ||
* <patternMatchCases> | ||
* } | ||
* } | ||
* ``` | ||
* | ||
* Cases that are not supported include: | ||
* - Applies and unapplies | ||
* - Idents | ||
* - Alternatives | ||
* - `case _: T =>` where `T` is not `Throwable` | ||
* | ||
*/ | ||
class TryCatchPatterns extends MiniPhaseTransform { | ||
import dotty.tools.dotc.ast.tpd._ | ||
|
||
def phaseName: String = "tryCatchPatterns" | ||
|
||
override def runsAfter = Set(classOf[ElimRepeated]) | ||
|
||
override def checkPostCondition(tree: Tree)(implicit ctx: Context): Unit = tree match { | ||
case Try(_, cases, _) => | ||
cases.foreach { | ||
case CaseDef(Typed(_, _), guard, _) => assert(guard.isEmpty, "Try case should not contain a guard.") | ||
case CaseDef(Bind(_, _), guard, _) => assert(guard.isEmpty, "Try case should not contain a guard.") | ||
case c => | ||
assert(isDefaultCase(c), "Pattern in Try should be Bind, Typed or default case.") | ||
} | ||
case _ => | ||
} | ||
|
||
override def transformTry(tree: Try)(implicit ctx: Context, info: TransformerInfo): Tree = { | ||
val (tryCases, patternMatchCases) = tree.cases.span(isCatchCase) | ||
val fallbackCase = mkFallbackPatterMatchCase(patternMatchCases, tree.pos) | ||
cpy.Try(tree)(cases = tryCases ++ fallbackCase) | ||
} | ||
|
||
/** Is this pattern node a catch-all or type-test pattern? */ | ||
private def isCatchCase(cdef: CaseDef)(implicit ctx: Context): Boolean = cdef match { | ||
case CaseDef(Typed(Ident(nme.WILDCARD), tpt), EmptyTree, _) => isSimpleThrowable(tpt.tpe) | ||
case CaseDef(Bind(_, Typed(Ident(nme.WILDCARD), tpt)), EmptyTree, _) => isSimpleThrowable(tpt.tpe) | ||
case _ => isDefaultCase(cdef) | ||
} | ||
|
||
private def isSimpleThrowable(tp: Type)(implicit ctx: Context): Boolean = tp match { | ||
case tp @ TypeRef(pre, _) => | ||
(pre == NoPrefix || pre.widen.typeSymbol.isStatic) && // Does not require outer class check | ||
!tp.symbol.is(Flags.Trait) && // Traits not supported by JVM | ||
tp.derivesFrom(defn.ThrowableClass) | ||
case _ => | ||
false | ||
} | ||
|
||
private def mkFallbackPatterMatchCase(patternMatchCases: List[CaseDef], pos: Position)( | ||
implicit ctx: Context, info: TransformerInfo): Option[CaseDef] = { | ||
if (patternMatchCases.isEmpty) None | ||
else { | ||
val exName = ctx.freshName("ex").toTermName | ||
val fallbackSelector = | ||
ctx.newSymbol(ctx.owner, exName, Flags.Synthetic | Flags.Case, defn.ThrowableType, coord = pos) | ||
val sel = Ident(fallbackSelector.termRef).withPos(pos) | ||
val rethrow = CaseDef(EmptyTree, EmptyTree, Throw(ref(fallbackSelector))) | ||
Some(CaseDef( | ||
Bind(fallbackSelector, Underscore(fallbackSelector.info).withPos(pos)), | ||
EmptyTree, | ||
transformFollowing(Match(sel, patternMatchCases ::: rethrow :: Nil))) | ||
) | ||
} | ||
} | ||
|
||
} |
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,35 @@ | ||
import java.io.IOException | ||
import java.lang.NullPointerException | ||
import java.lang.IllegalArgumentException | ||
|
||
object IAE { | ||
def unapply(e: Exception): Option[String] = | ||
if (e.isInstanceOf[IllegalArgumentException]) Some(e.getMessage) | ||
else None | ||
} | ||
|
||
object EX extends Exception | ||
|
||
trait ExceptionTrait extends Exception | ||
|
||
object Test { | ||
def main(args: Array[String]): Unit = { | ||
var a: Int = 1 | ||
try { | ||
throw new IllegalArgumentException() | ||
} catch { | ||
case e: IOException if e.getMessage == null => | ||
case e: NullPointerException => | ||
case e: IndexOutOfBoundsException => | ||
case _: NoSuchElementException => | ||
case _: ExceptionTrait => | ||
case _: NoSuchElementException if a <= 1 => | ||
case _: NullPointerException | _:IOException => | ||
case `a` => // This case should probably emmit an error | ||
case e: Int => // error | ||
case EX => | ||
case IAE(msg) => | ||
case e: IllegalArgumentException => | ||
} | ||
} | ||
} |
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,20 @@ | ||
success 1 | ||
success 2 | ||
success 3 | ||
success 4 | ||
success 5 | ||
success 6 | ||
success 7 | ||
success 8 | ||
success 9.1 | ||
success 9.2 | ||
IllegalArgumentException: abc | ||
IllegalArgumentException | ||
NullPointerException | IOException | ||
NoSuchElementException | ||
EX | ||
InnerException | ||
NullPointerException | ||
ExceptionTrait | ||
ClassCastException | ||
TimeoutException escaped |
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.
it would be nice to add a postcondition here:
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.
done