跳到內容

從頭開始編寫程式語言/簡單表示式

來自華夏公益教科書,開放的書籍,為開放的世界

表示式

[編輯 | 編輯原始碼]

表示式包括所有需要使用 ALU 的命令形式,但不包括邏輯函式。它們還包括函式呼叫,但這些將在後面討論。在本章中,我們處理簡單表示式的轉換,即不包括括號、函式呼叫或任何型別的引用的表示式。

基本運算

[編輯 | 編輯原始碼]

我們都知道四則運算,即 +,-,*,/。它們組合起來形成表示式,例如:a*b+c

然而,組合語言不識別這樣的表示式,它只識別二進位制命令,例如:add a,b
mul b,c

此外,它不識別優先順序。它只是按順序執行命令。因此,我們必須自己排序這些命令。

此外,結果始終儲存在稱為暫存器的特定位置。更確切地說,它儲存在 Eax 暫存器中。

對於整數的每個操作,都有以下指令。對於字元操作,將 eax 替換為 al

賦值

Mov [operand1],[operand2]

加法

add [operand1],[operand2]

減法

sub [operand1],[operand2]

乘法

Mov Eax,[operand1]
Imul [operand2]

除法

Cdq (sign extension, mandatory but only once in the program)
Idiv [operand1],[operand2]

模數

Cdq
Idiv [operand1],[operand2]
Mov Eax,edx

增量

Inc [operand]

以下是浮點數的對應指令。

賦值

Fld [operand2]
Fstp [operand1]

加法

Fld [operand1]
Fadd [operand2]

減法

Fld [operand1]
Fsub [operand2]

乘法

Fld [operand1]
Fmul [operand2]

除法

Fld [operand1]
Fdiv [operand2]

浮點變數沒有模數。

轉換演算法

[編輯 | 編輯原始碼]

第 1 部分 乘法、除法、模數

1. While character not ; or *,/,%.
   increment index
 1.1 If character be ; goto part2
 1.2 get operand before operator and after 
 1.3 depending on operator use the appropriate instructions as given above.
 1.4 remove the operands and operator from the line 
 1.5 if next operator be add or sub replace by var[NUM] where NUM is an int and incremented. Write var[NUM] as a variable of type of expression. Assign eax to var[NUM].
 1.6 else replace by eax.
2. Repeat step 1

對於字元,將 eax 替換為 al,對於浮點數,將 st(1) 賦值給 var[NUM]。

第 2 部分 加法、減法

1. While character not ; or + or -
   increment index
 1.1 If character be ; end process
 1.2 get operand before and after the operator
 1.3 depending on operator use the appropriate instruction as given above
 (Follow steps 1.4 to 1.6)
2. Repeat step 1
華夏公益教科書