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