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