construct switch/case/default from if/elif/elif/else
authorLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Sun, 5 Apr 2020 16:40:01 +0000 (17:40 +0100)
committerLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Sun, 5 Apr 2020 16:40:01 +0000 (17:40 +0100)
src/soc/decoder/power_pseudo.py
src/soc/decoder/pseudo/parser.py

index 7005bd0889e9464b397679f4b876d948aea73bf1..a16c77bb1ffeb63c77eaeab828ad0f40db6f6926 100644 (file)
@@ -172,6 +172,7 @@ switch (n)
     case(2): fallthrough
     case(3):
         x <- 3
+    case(4): fallthrough
     default:
         x <- 9
 """
index 7906e82518ced4fe5a1aec09f0b998103ed9e2d0..03d56d5dca1e43bc3dd369e2e88af49abb59c6ed 100644 (file)
@@ -420,11 +420,43 @@ class PowerParser:
         print(astor.dump_tree(p[1]))
 
         cases = []
-        current_cases = []
+        current_cases = [] # for deferral
         for (case, suite) in p[8]:
-            print (case, suite)
+            print ("for", case, suite)
+            if suite is None:
+                for c in case:
+                    current_cases.append(ast.Num(c))
+                continue
+            if case == 'default': # last
+                break
+            for c in case:
+                current_cases.append(ast.Num(c))
+            print ("cases", current_cases)
+            compare = ast.Compare(switchon, [ast.In()],
+                                  [ast.List(current_cases)])
+            current_cases = []
+            cases.append((compare, suite))
+
+        print ("ended", case, current_cases)
+        if case == 'default':
+            if current_cases:
+                compare = ast.Compare(switchon, [ast.In()],
+                                      [ast.List(current_cases)])
+                cases.append((compare, suite))
+            cases.append((None, suite))
+
+        cases.reverse()
         res = []
-        p[0] = ast.If([], [], [])
+        for compare, suite in cases:
+            print ("after rev", compare, suite)
+            if compare is None:
+                assert len(res) == 0, "last case should be default"
+                res = suite
+            else:
+                if not isinstance(res, list):
+                    res = [res]
+                res = ast.If(compare, suite, res)
+        p[0] = res
 
     def p_switches(self, p):
         """switches : switch_list switch_default