import TsmLean.Compile.Source
import TsmLean.Core.Syntax

namespace TsmLean.Compile

open TsmLean.Core (Instr Code)

/-- Compile a source expression to TSM bytecode, with the output
    placed at absolute address `offset` in the final assembled code.
    Jumps (in `ifte`) reference absolute addresses. -/
def compile : (offset : Nat) → Source.Expr → Code
  | _,      .intLit n  => #[.push n]
  | _,      .boolLit b => #[.pushB b]
  | offset, .add e1 e2 =>
      let c1 := compile offset e1
      let c2 := compile (offset + c1.size) e2
      c1 ++ c2 ++ #[.add]
  | offset, .sub e1 e2 =>
      let c1 := compile offset e1
      let c2 := compile (offset + c1.size) e2
      c1 ++ c2 ++ #[.sub]
  | offset, .mul e1 e2 =>
      let c1 := compile offset e1
      let c2 := compile (offset + c1.size) e2
      c1 ++ c2 ++ #[.mul]

end TsmLean.Compile
