File tree Expand file tree Collapse file tree 3 files changed +32
-1
lines changed
compiler/src/dotty/tools/dotc Expand file tree Collapse file tree 3 files changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -118,6 +118,7 @@ public enum ErrorMessageID {
118118 StaticFieldsOnlyAllowedInObjectsID ,
119119 CyclicInheritanceID ,
120120 UnableToExtendSealedClassID ,
121+ UnableToEmitSwitchID ,
121122 ;
122123
123124 public int errorNumber () {
Original file line number Diff line number Diff line change @@ -1972,4 +1972,33 @@ object messages {
19721972 val msg = hl " Cannot extend ${" sealed" } $pclazz in a different source file "
19731973 val explanation = " A sealed class or trait can only be extended in the same file as its declaration"
19741974 }
1975+
1976+ case class UnableToEmitSwitch ()(implicit ctx : Context )
1977+ extends Message (UnableToEmitSwitchID ) {
1978+ val kind = " Syntax"
1979+ val msg = hl " Could not emit switch for ${" @switch" } annotated match "
1980+ val explanation = {
1981+ val codeExample =
1982+ """ val ConstantB = 'B'
1983+ |final val ConstantC = 'C'
1984+ |def tokenMe(ch: Char) = (ch: @switch) match {
1985+ | case '\t' | '\n' => 1
1986+ | case 'A' => 2
1987+ | case ConstantB => 3 // a non-literal may prevent switch generation: this would not compile
1988+ | case ConstantC => 4 // a constant value is allowed
1989+ | case _ => 5
1990+ |}""" .stripMargin
1991+
1992+ hl """ If annotated with ${" @switch" }, the compiler will verify that the match has been compiled to a
1993+ |tableswitch or lookupswitch and issue an error if it instead compiles into a series of conditional
1994+ |expressions. Example usage:
1995+ |
1996+ | $codeExample
1997+ |
1998+ |The compiler will not apply the optimisation if:
1999+ |- the matched value is not of type ${" Int" }, ${" Byte" }, ${" Short" } or ${" Char" }
2000+ |- the matched value is not a constant literal
2001+ |- there are less than three cases """
2002+ }
2003+ }
19752004}
Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ import Decorators._
1414import patmat .Space
1515import NameKinds .{UniqueNameKind , PatMatStdBinderName , PatMatCaseName }
1616import config .Printers .patmatch
17+ import reporting .diagnostic .messages ._
1718
1819/** The pattern matching transform.
1920 * After this phase, the only Match nodes remaining in the code are simple switches
@@ -908,7 +909,7 @@ object PatternMatcher {
908909 tpes.toSet.size: Int // without the type ascription, testPickling fails because of #2840.
909910 }
910911 if (numConsts(resultCases) < numConsts(original.cases))
911- ctx.warning(i " could not emit switch for @switch annotated match " , original.pos)
912+ ctx.warning(UnableToEmitSwitch () , original.pos)
912913 case _ =>
913914 }
914915
You can’t perform that action at this time.
0 commit comments