自制简易编程语言 个人笔记(2)

https://github.com/lucyTheSlayer/orange

网上把tiny machine的源码下载下来,省的自己敲了,赶紧试了下自己生成的字节码,不出所料一大堆bug。

经过debug,总算是能跑个像样的程序了。

立马敲一个,就从最简单的计算阶乘开始:

#welcom to orange
#this program computes n! for the input n
#plz enjoy the fun
read n;
result := 1;
while(n>0){
	result := result*n;
	n := n-1 ;
	#write n;
}
write result;

与python一样,#为注释,用上篇的编译器编译之,得到如下字节码:

* TINY Compilation to TM Code
* File: hello.orangebc
* Standard prelude:
  0:     LD  6,0(0) 	load maxaddress from location 0
  1:     ST  0,0(0) 	clear location 0
* End of standard prelude.
  2:     IN  0,0,0 	read integer value
  3:     ST  0,0(5) 	read: store value
* -> assign
* -> Const
  4:    LDC  0,1(0) 	load const
* <- Const
  5:     ST  0,1(5) 	assign: store value
* <- assign
* -> while
* -> Op
* -> Id
  6:     LD  0,0(5) 	load id value
* <- Id
  7:     ST  0,0(6) 	op: push left
* -> Const
  8:    LDC  0,0(0) 	load const
* <- Const
  9:     LD  1,0(6) 	op: load left
 10:    SUB  0,1,0 	op >
 11:    JGT  0,2(7) 	br if true
 12:    LDC  0,0(0) 	false case
 13:    LDA  7,1(7) 	unconditional jmp
 14:    LDC  0,1(0) 	true case
* <- Op
* while: jump to end belongs here
* -> assign
* -> Op
* -> Id
 16:     LD  0,1(5) 	load id value
* <- Id
 17:     ST  0,0(6) 	op: push left
* -> Id
 18:     LD  0,0(5) 	load id value
* <- Id
 19:     LD  1,0(6) 	op: load left
 20:    MUL  0,1,0 	op *
* <- Op
 21:     ST  0,1(5) 	assign: store value
* <- assign
* -> assign
* -> Op
* -> Id
 22:     LD  0,0(5) 	load id value
* <- Id
 23:     ST  0,0(6) 	op: push left
* -> Const
 24:    LDC  0,1(0) 	load const
* <- Const
 25:     LD  1,0(6) 	op: load left
 26:    SUB  0,1,0 	op -
* <- Op
 27:     ST  0,0(5) 	assign: store value
* <- assign
 28:    LDA  7,-23(7) 	jmp back to loop
 15:    JEQ  0,13(7) 	while: jmp to end
* <- while
* -> Id
 29:     LD  0,1(5) 	load id value
* <- Id
 30:    OUT  0,0,0 	write ac
* End of execution.
 31:   HALT  0,0,0 	

看上去相当的cooooooooooooooooooooooooooooool,用tiny machine执行之,

TM  simulation (enter h for help)...
Enter command: g
Enter value for IN instruction: 5
OUT instruction prints: 120
HALT: 0,0,0
Halted
Enter command: c
Enter command: g
Enter value for IN instruction: 10
OUT instruction prints: 3628800
HALT: 0,0,0
Halted
Enter command:

5! = 120

10! = 3628800

完全okaaaaaaaaaaaaaaaay,真的coooooooooooooooooooool

一套编译执行的流程后,下一步的工作是自定义字节码,然后自己手撸一个vm,初步使其能够打印字符串。


猜你喜欢

转载自blog.csdn.net/lucytheslayer/article/details/80355509