What is the use case for this weird switch mecanism

Chris Nicholson-Sauls ibisbasenji at gmail.com
Wed Oct 31 13:33:34 PDT 2012


Some related actual code from a while back:

##################################################
ParseTree prune ( ParseTree p ) {
     p.children = p.children.dup;
     foreach ( ref child ; p.children ) {
         child = prune( child );
     }

     switch ( p.ruleName ) {
         // strip prefix/suffix terminals, then if left with only 
one child, skip over it
         case "Args"             :
         case "List"             :
         case "Params"           :
         case "Table"            :   p.children = p.children[ 1 .. 
$ - 1 ];
                                     if ( p.children.length == 1 ) 
{

         // skip over immediate child (always a "Series")
         case "QualIdent"        :
         case "Type"             :       p.children = p.children[ 
0 ].children;
                                     }
                                     break;

         // skip self if it has exactly one child
         case "Addition"         :
         case "BoolAnd"          :
         case "BoolOr"           :
         case "Comparison"       :
         case "Conditional"      :
         case "MaybeParens"      :
         case "Multiplication"   :
         case "Postfix"          :
         case "Primary"          :
         case "Unary"            :   if ( p.children.length == 1 ) 
{

         // skip self
         case "Expression"       :
         case "Field"            :
         case "Ident"            :
         case "Literal"          :
         case "PathElem"         :
         case "Statement"        :       p = p.children[ 0 ];
                                     }
                                     break;

         default:
     }

     return p;
}
##################################################

Without the loosely defined switch() statement syntax, this would 
have been a royal pain to piece together.  Especially when each 
block of cases was evolving over time.

There is also the trick of doing 'switch(val) with(EnumType) 
{...}' to bring an enum's members into scope so that cases can be 
written as 'case Foo:' rather than 'case EnumType.Foo:'.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list