tiny编译器使用

计算阶乘tiny源码:

{ Sample program
  in TINY language -
  computes factorial
}
read x; { input an integer }
if 0 < x then { don't compute if x <= 0 }
  fact := 1;
  repeat
    fact := fact * x;
    x := x - 1
  until x = 0;
  write fact  { output factorial of x }
end

编译生成的目标代码:

  0:     LD  6,0(0) 
  1:     ST  0,0(0) 
  2:     IN  0,0,0 
  3:     ST  0,0(5) 
  4:    LDC  0,0(0) 
  5:     ST  0,0(6) 
  6:     LD  0,0(5) 
  7:     LD  1,0(6) 
  8:    SUB  0,1,0 
  9:    JLT  0,2(7) 
 10:    LDC  0,0(0) 
 11:    LDA  7,1(7) 
 12:    LDC  0,1(0) 
 14:    LDC  0,1(0) 
 15:     ST  0,1(5) 
 16:     LD  0,1(5) 
 17:     ST  0,0(6) 
 18:     LD  0,0(5) 
 19:     LD  1,0(6) 
 20:    MUL  0,1,0 
 21:     ST  0,1(5) 
 22:     LD  0,0(5) 
 23:     ST  0,0(6) 
 24:    LDC  0,1(0) 
 25:     LD  1,0(6) 
 26:    SUB  0,1,0 
 27:     ST  0,0(5) 
 28:     LD  0,0(5) 
 29:     ST  0,0(6) 
 30:    LDC  0,0(0) 
 31:     LD  1,0(6) 
 32:    SUB  0,1,0 
 33:    JEQ  0,2(7) 
 34:    LDC  0,0(0) 
 35:    LDA  7,1(7) 
 36:    LDC  0,1(0) 
 37:    JEQ  0,-22(7) 
 38:     LD  0,1(5) 
 39:    OUT  0,0,0 
 13:    JEQ  0,27(7) 
 40:    LDA  7,0(7) 
 41:   HALT  0,0,0

执行:

$ tm SAMPLE.tm
TM  simulation (enter h for help)...
Enter command: h
Commands are:
   s(tep <n>      Execute n (default 1) TM instructions
   g(o            Execute TM instructions until HALT
   r(egs          Print the contents of the registers
   i(Mem <b <n>>  Print n iMem locations starting at b
   d(Mem <b <n>>  Print n dMem locations starting at b
   t(race         Toggle instruction trace
   p(rint         Toggle print of total instructions executed ('go' only)
   c(lear         Reset simulator for new execution of program
   h(elp          Cause this list of commands to be printed
   q(uit          Terminate the simulation
Enter command: g
Enter value for IN instruction: 5
OUT instruction prints: 120
HALT: 0,0,0
Halted
Enter command:

可以看到输出结果:OUT instruction prints: 120
寄存器值:

Enter command: r
0:  120    1:    0    2:    0    3:    0
4:    0    5:    0    6: 1023    7:   42