]>
Commit | Line | Data |
---|---|---|
12aa4087 JW |
1 | (* L1 Compiler |
2 | * AST -> IR Translator | |
3 | * Author: Kaustuv Chaudhuri <kaustuv+@cs.cmu.edu> | |
4 | * Modified by: Alex Vaynberg <alv@andrew.cmu.edu> | |
5 | * Modified: Frank Pfenning <fp@cs.cmu.edu> | |
6 | *) | |
7 | ||
8 | signature TRANS = | |
9 | sig | |
10 | (* translate abstract syntax tree to IR tree *) | |
11 | val translate : Ast.program -> Tree.stm list | |
12 | end | |
13 | ||
14 | structure Trans :> TRANS = | |
15 | struct | |
16 | ||
17 | structure A = Ast | |
18 | structure T = Tree | |
19 | ||
20 | fun trans_oper A.PLUS = T.ADD | |
21 | | trans_oper A.MINUS = T.SUB | |
22 | | trans_oper A.TIMES = T.MUL | |
23 | | trans_oper A.DIVIDEDBY = T.DIV | |
24 | | trans_oper A.MODULO = T.MOD | |
25 | | trans_oper A.NEGATIVE = T.SUB (* unary to binary! *) | |
26 | ||
27 | and trans_exp env (A.Var(id)) = | |
28 | (* after type-checking, id must be declared; do not guard lookup *) | |
29 | T.TEMP (Symbol.look' env id) | |
30 | | trans_exp env (A.ConstExp c) = T.CONST(c) | |
31 | | trans_exp env (A.OpExp(oper, [e1, e2])) = | |
32 | T.BINOP(trans_oper oper, trans_exp env e1, trans_exp env e2) | |
33 | | trans_exp env (A.OpExp(A.NEGATIVE, [e])) = | |
34 | T.BINOP(trans_oper A.NEGATIVE, T.CONST(Word32Signed.ZERO), trans_exp env e) | |
35 | | trans_exp env (A.Marked(marked_exp)) = | |
36 | trans_exp env (Mark.data marked_exp) | |
37 | (* anything else should be impossible *) | |
38 | ||
39 | (* translate the statement *) | |
40 | (* trans_stms : Temp.temp Symbol.table -> A.stm list -> Tree.stm list *) | |
41 | fun trans_stms env (A.Assign(id,e)::stms) = | |
42 | let val t = Temp.new() | |
43 | val env' = Symbol.bind env (id, t) | |
44 | in | |
45 | T.MOVE(T.TEMP(t), trans_exp env e) | |
46 | :: trans_stms env' stms | |
47 | end | |
48 | | trans_stms env (A.Return e::nil) = | |
49 | (* after type-checking, return must be last statement *) | |
50 | T.RETURN (trans_exp env e) :: nil | |
51 | ||
52 | fun translate p = trans_stms Symbol.empty p | |
53 | ||
54 | end |