[Issue 17083] final switch(bool) should be lowered at least to a simple if else

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Thu Jan 12 09:48:40 PST 2017


https://issues.dlang.org/show_bug.cgi?id=17083

--- Comment #2 from b2.temp at gmx.com ---
I've seen you closed. However it is almost done in
StatementSwitchVisitor.visit(SwitchStatement ss) ; There would just be the
BreakStatement to remove in each case:


@@ -1987,10 +1987,11 @@ else
         ss.condition = ss.condition.semantic(sc);
         ss.condition = resolveProperties(sc, ss.condition);

         Type att = null;
         TypeEnum te = null;
+        Type tb = ss.condition.type;
         while (ss.condition.op != TOKerror)
         {
             // preserve enum type for final switches
             if (ss.condition.type.ty == Tenum)
                 te = cast(TypeEnum)ss.condition.type;
@@ -2146,12 +2147,82 @@ else
         {
             sc.pop();
             return setError();
         }

-        sc.pop();
         result = ss;
+
+        if (!te && tb && tb.ty == Tbool && ss.isFinal && ss.cases.dim == 2 &&
+            cast(EqualExp) ss.condition)
+        {
+            EqualExp eq = cast(EqualExp) ss.condition;
+
+            if (auto e = eq.toBoolean(sc))
+            {
+                CompoundStatement true_;
+                CompoundStatement false_;
+
+                dinteger_t c;
+                foreach (cs; *ss.cases)
+                {
+                    dinteger_t v = cs.exp.toInteger;
+                    if (v != 0)
+                    {
+                        true_ = cast(CompoundStatement) cs.statement;
+                    }
+                    else
+                    {
+                        false_ = cast(CompoundStatement) cs.statement;
+                    }
+                    c++;
+                }
+                if (true_ && false_)
+                {
+                    void removeThisSwitchBreaks(CompoundStatement cs)
+                    {
+                        if (cs.statements is null)
+                            return;
+                        // TODO: remove breaks;
+                    }
+                    removeThisSwitchBreaks(true_);
+                    removeThisSwitchBreaks(false_);
+
+                    result = new IfStatement(ss.loc, null, ss.condition,
+                        true_, false_, false_.loc);
+                }
+                else ss.error("final switch(bool) cannot be converted to a
IfStatement");
+            }
+        }
+
+        sc.pop();
     }

     override void visit(CaseStatement cs)
     {
         SwitchStatement sw = sc.sw;



Isn't this reasonable ?

--


More information about the Digitalmars-d-bugs mailing list