Linear code of Rz parse-tree   

This will be an excercise to traverse parse-tree and generate a machine-code-like linear code.  The linear code has the postfix form (suppose to be executed by a stack-based machine).  The control-flow is transformed into "jump" instructions and label similar to assembly language.

Operand (return its right value) is generated simply, retaining the deref and address operator in its coding.  How to handle the deref and address depends on the actual machine code. Please note that I do not handle the cases: *v[ex] and &v[ex] properly.

operand

  local var :         local.n
  global var :        global.a
  number :            lit.m
  string :            str.a
  &local :            &local.n
  &global :           &global.a
  *local :            *local.n
  *global :           *global.a

Operator is generated by outputting its name.  For the vector, there are two instructions: load vector (ldx) and store vector (stx).

operator

  op :                opname
  vector (v[exp]) :   exp, v, ldx
 
For assignment statement, the deref and address on the left hand side (LHS) must be considered. 

assignment

  gv = ...   :        st.a
  lv = ...   :        put.n
  v[exp] = ... :      exp, v, stx
  *gv = ...  :        *st.a
  *lv = ...  :        *put.n
  *v[exp] = ... :     illegal
  &lv = ...  :        illegal
  &gv = ...  :        illegal

For control, three instructions are used : jmp, jt (true), jf (false).  The labels are used to indicate the destination of jump similar to assembly language.

control

  do e1 e2 ... :      e1, e2, ...
  while cond body :    
     :loop
       cond
       jf exit
       body
       jmp loop
     :exit

  if cond action :
       cond
       jf exit
       action
     :exit

  if cond acT else acF :
       cond
       jf else
       acT
       jmp exit
     :else
       acF
     :exit

  fun(arg1, arg2, ...)  :
     arg1
     arg2
     ...
     call fun

function header

     ;; fname arity xx fs yy
     :fun...
       body
       ret

sample output

This is the output of compiling "inc.txt"
increment(x){
  *x = *x + 1;
}
main(){
  a = 11;
  increment(&a);
  print(a);
}

The screen output is:

C:\prabhas\bag\rz3-pre\test>rz3 inc.txt
increment
main
(fun main (do (= #1 11 )(call increment (& #1 ))(print #1 )))
(fun increment (= (* #1 )(+ (* #1 )1 )))
;; fun main, arity 0, fs 1
:fun1
  lit.11
  put.1
  &local.1
  call fun2
  local.1
  print
  ret

;; fun increment, arity 1, fs 1
:fun2
  *local.1
  lit.1
  add
  *put.1
  ret

last update 28 Nov 2010