15.08.2013 Views

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

General Computer Science 320201 GenCS I & II Lecture ... - Kwarc

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 460 Note the order of the arguments: the program “con 4 con 7 sub” first<br />

pushes 4, and then 7, then pops x and then y (so x = 7 and y = 4) and finally pushes<br />

x − y = 7 − 4 = 3.<br />

Stack-based operations work very well with the recursive structure of arithmetic expressions:<br />

we can compute the value of the expression 4 · 3 − 7 · 2 with<br />

<br />

con 2 con 7 mul 7 · 2<br />

con 3 con 4 mul 4 · 3<br />

sub 4 · 3 − 7 · 2<br />

c○: Michael Kohlhase 283<br />

Note: A feature that we will see time and again is that every (syntactically well-formed) expression<br />

leaves only the result value on the stack. In the present case, the computation never touches the<br />

part of the stack that was present before computing the expression. This is plausible, since the<br />

computation of the value of an expression is purely functional, it should not have an effect on the<br />

state of the virtual machine VM (other than leaving the result of course).<br />

A Stack-Based VM language (Control)<br />

Definition 461 Control operators<br />

instruction effect VPC<br />

jp i VPC: = VPC + i<br />

cjp i pop x if x = 0, then VPC: = VPC + i else VPC: = VPC + 2<br />

halt —<br />

cjp is a “jump on false”-type expression.(if the condition is false, we jump else we continue)<br />

Example 462 For conditional expressions we use the conditional jump expressions: We can<br />

express “if 1 ≤ 2 then 4 − 3 else 7 · 5” by the program<br />

con 2 con 1 leq cjp 9 if 1 ≤ 2<br />

con 3 con 4 sub jp 7 then 4 − 3<br />

con 5 con 7 mul else 7 · 5<br />

halt<br />

c○: Michael Kohlhase 284<br />

In the example, we first push 2, and then 1 to the stack. Then leq pops (so x = 1), pops again<br />

(making y = 2) and computes x ≤ y (which comes out as true), so it pushes 1, then it continues<br />

(it would jump to the else case on false).<br />

Note: Again, the only effect of the conditional statement is to leave the result on the stack. It<br />

does not touch the contents of the stack at and below the original stack pointer.<br />

The next two commands break with the nice principled stack-like memory organization by giving<br />

“random access” to lower parts of the stack. We will need this to treat variables in high-level<br />

programming languages<br />

A Stack-Based VM language (Imperative Variables)<br />

Definition 463 Imperative access to variables: Let S(i) be the number at stack position i.<br />

159

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!