https://github.com/akkartik/mu/blob/master/apps/factorial4.subx
 1 ## compute the factorial of 5, and return the result in the exit code
 2 #
 3 # Uses syntax sugar for:
 4 #   rm32 operands
 5 #   function calls
 6 #   control flow
 7 #
 8 # To run:
 9 #   $ ./translate_subx init.linux 0*.subx apps/factorial.subx -o apps/factorial
10 #   $ ./bootstrap run apps/factorial
11 # Expected result:
12 #   $ echo $?
13 #   120
14 #
15 # You can also run the automated test suite:
16 #   $ ./bootstrap run apps/factorial test
17 # Expected output:
18 #   ........
19 # Every '.' indicates a passing test. Failing tests get a 'F'.
20 #
21 # Compare apps/factorial3.subx
22 
23 == code
24 
25 factorial:  # n: int -> int/eax
26     # . prologue
27     55/push-ebp
28     89/<- %ebp 4/r32/esp
29     # save registers
30     51/push-ecx
31     # if (n <= 1) return 1
32     81 7/subop/compare *(ebp+8) 1/imm32
33     {
34       7f/jump-if-> break/disp8
35       b8/copy-to-eax 1/imm32
36     }
37     # if (n > 1) return n * factorial(n-1)
38     {
39       7e/jump-if-<= break/disp8
40       # var tmp/ecx: int = n-1
41       8b/-> *(ebp+8) 1/r32/ecx
42       49/decrement-ecx
43       (factorial %ecx)  # => eax
44       f7 4/subop/multiply-into-eax *(ebp+8)
45     }
46     # restore registers
47     59/pop-to-ecx
48     # . epilogue
49     89/<- %esp 5/r32/ebp
50     5d/pop-to-ebp
51     c3/return
52 
53 test-factorial:
54     (factorial 5)
55     (check-ints-equal %eax 0x78 "F - test-factorial")
56     c3/return
57 
58 Entry:  # run tests if necessary, compute `factorial(5)` if not
59     # . prologue
60     89/<- %ebp 4/r32/esp
61 
62     # initialize heap (needed by tests elsewhere)
63     (new-segment *Heap-size Heap)
64 
65     # if (argc <= 1) return factorial(5)
66     {
67       # if (argc > 1) break
68       81 7/subop/compare *ebp 1/imm32
69       7f/jump-if-> break/disp8
70       # ebx = factorial(5)
71       (factorial 5)  # => eax
72       89/<- %ebx 0/r32/eax
73     }
74     # otherwise if an arg exists and is "test", then return run_tests()
75     {
76       # if (argc <= 1) break
77       81 7/subop/compare *ebp 1/imm32
78       7e/jump-if-<= break/disp8
79       # if (!kernel-string-equal?(argv[1], "test")) break
80       (kernel-string-equal? *(ebp+8) "test")  # => eax
81       3d/compare-eax-and 0/imm32/false
82       74/jump-if-= break/disp8
83       #
84       (run-tests)
85       # ebx = *Num-test-failures
86       8b/-> *Num-test-failures 3/r32/ebx
87     }
88 
89     e8/call  syscall_exit/disp32