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 == code
22 
23 Entry:  # run tests if necessary, compute `factorial(5)` if not
24     # . prologue
25     89/<- %ebp 4/r32/esp
26 
27     # initialize heap
28     (new-segment *Heap-size Heap)
29 
30     # - if argc > 1, then return run_tests()
31     {
32       # if (argc <= 1) break
33       81 7/subop/compare *ebp 1/imm32
34       7e/jump-if-<= break/disp8
35       # if (!kernel-string-equal?(argv[1], "test")) break
36       (kernel-string-equal? *(ebp+8) "test")  # => eax
37       3d/compare-eax-and 0/imm32/false
38       74/jump-if-= break/disp8
39       #
40       (run-tests)
41       # eax = *Num-test-failures
42       8b/-> *Num-test-failures 3/r32/ebx
43     }
44     # if (argc <= 1) factorial(5)
45     {
46       # if (argc > 1) break
47       81 7/subop/compare *ebp 1/imm32
48       7f/jump-if-> break/disp8
49       # eax = factorial(5)
50       (factorial 5)
51       # syscall(exit, eax)
52       89/<- %ebx 0/r32/eax
53     }
54 
55     e8/call  syscall_exit/disp32
56 
57 factorial:  # n: int -> int/eax
58     # . prologue
59     55/push-ebp
60     89/<- %ebp 4/r32/esp
61     # save registers
62     51/push-ecx
63     # if (n <= 1) return 1
64     81 7/subop/compare *(ebp+8) 1/imm32
65     {
66       7f/jump-if-> break/disp8
67       b8/copy-to-eax 1/imm32
68     }
69     # if (n > 1) return n * factorial(n-1)
70     {
71       7e/jump-if-<= break/disp8
72       # var tmp/ecx: int = n-1
73       8b/-> *(ebp+8) 1/r32/ecx
74       49/decrement-ecx
75       (factorial %ecx)  # => eax
76       f7 4/subop/multiply-into-eax *(ebp+8)
77     }
78     # restore registers
79     59/pop-to-ecx
80     # . epilogue
81     89/<- %esp 5/r32/ebp
82     5d/pop-to-ebp
83     c3/return
84 
85 test-factorial:
86     (factorial 5)
87     (check-ints-equal %eax 0x78 "F - test-factorial")
88     c3/return