1 section "Stack Machine and Compilation"
3 theory ASM imports AExp begin
5 subsection "Stack Machine"
7 text_raw{*\snip{ASMinstrdef}{0}{1}{% *}
8 datatype instr = LOADI val | LOAD vname | ADD
11 text_raw{*\snip{ASMstackdef}{1}{2}{% *}
12 type_synonym stack = "val list"
15 abbreviation "hd2 xs == hd(tl xs)"
16 abbreviation "tl2 xs == tl(tl xs)"
18 text{* \noindent Abbreviations are transparent: they are unfolded after
19 parsing and folded back again before printing. Internally, they do not
22 text_raw{*\snip{ASMexeconedef}{0}{1}{% *}
23 fun exec1 :: "instr \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where
24 "exec1 (LOADI n) _ stk = n # stk" |
25 "exec1 (LOAD x) s stk = s(x) # stk" |
26 "exec1 ADD _ stk = (hd2 stk + hd stk) # tl2 stk"
29 text_raw{*\snip{ASMexecdef}{1}{2}{% *}
30 fun exec :: "instr list \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where
31 "exec [] _ stk = stk" |
32 "exec (i#is) s stk = exec is s (exec1 i s stk)"
35 value "exec [LOADI 5, LOAD ''y'', ADD] <''x'' := 42, ''y'' := 43> [50]"
37 lemma exec_append[simp]:
38 "exec (is1@is2) s stk = exec is2 s (exec is1 s stk)"
39 apply(induction is1 arbitrary: stk)
44 subsection "Compilation"
46 text_raw{*\snip{ASMcompdef}{0}{2}{% *}
47 fun comp :: "aexp \<Rightarrow> instr list" where
48 "comp (N n) = [LOADI n]" |
49 "comp (V x) = [LOAD x]" |
50 "comp (Plus e\<^sub>1 e\<^sub>2) = comp e\<^sub>1 @ comp e\<^sub>2 @ [ADD]"
53 value "comp (Plus (Plus (V ''x'') (N 1)) (V ''z''))"
55 theorem exec_comp: "exec (comp a) s stk = aval a s # stk"
56 apply(induction a arbitrary: stk)