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 #   $ ./subx run apps/factorial
11 # Expected result:
12 #   $ echo $?
13 #   120
14 #
15 # You can also run the automated test suite:
16 #   $ ./subx 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     b8/copy-to-eax 1/imm32/exit
56     cd/syscall 0x80/imm8
57 
58 factorial:  # n : int -> int/eax
59     # . prologue
60     55/push-ebp
61     89/<- %ebp 4/r32/esp
62     # save registers
63     53/push-ebx
64     # if (n <= 1) return 1
65     81 7/subop/compare *(ebp+8) 1/imm32
66     {
67       7f/jump-if-> break/disp8
68       b8/copy-to-eax 1/imm32
69     }
70     # if (n > 1) return n * factorial(n-1)
71     {
72       7e/jump-if-<= break/disp8
73       # var ebx : int = n-1
74       8b/-> *(ebp+8) 3/r32/ebx
75       4b/decrement-ebx
76       (factorial %ebx)  # => eax
77       f7 4/subop/multiply-into-eax *(ebp+8)
78     }
79     # restore registers
80     5b/pop-to-ebx
81     # . epilogue
82     89/<- %esp 5/r32/ebp
83     5d/pop-to-ebp
84     c3/return
85 
86 test-factorial:
87     (factorial 5)
88     (check-ints-equal %eax 0x78 "F - test-factorial")
89     c3/return