add multiplication support

This commit is contained in:
Mylloon 2022-12-09 16:12:32 +01:00
parent cf14c64adc
commit c98231152a
Signed by: Anri
GPG key ID: A82D63DFF8D1317F
5 changed files with 18 additions and 6 deletions

View file

@ -2,11 +2,19 @@ open Ast
open Mips open Mips
module Env = Map.Make (String) module Env = Map.Make (String)
let _types_ = Env.of_seq (List.to_seq [ "%add", Func_t (Int_t, [ Int_t; Int_t ]) ]) let _types_ =
Env.of_seq
(List.to_seq
[ "%add", Func_t (Int_t, [ Int_t; Int_t ])
; "%mul", Func_t (Int_t, [ Int_t; Int_t ])
])
;;
let builtins = let builtins =
List.fold_left List.fold_left
(fun env (fn, impl) -> Env.add fn impl env) (fun env (fn, impl) -> Env.add fn impl env)
Env.empty Env.empty
[ "%add", [ Lw (T0, Mem (SP, 0)); Lw (T1, Mem (SP, 4)); Add (V0, T0, T1) ] ] [ "%add", [ Lw (T0, Mem (SP, 0)); Lw (T1, Mem (SP, 4)); Add (V0, T0, T1) ]
; "%mul", [ Lw (T0, Mem (SP, 0)); Lw (T1, Mem (SP, 4)); Mul (V0, T0, T1) ]
]
;; ;;

View file

@ -21,7 +21,8 @@ rule token = parse
| bool as b { Lbool (bool_of_string b) } | bool as b { Lbool (bool_of_string b) }
| '=' { Lassign } | '=' { Lassign }
| ';' { Lsc } | ';' { Lsc }
| '+' { Ladd} | '+' { Ladd }
| '*' { Lmul }
| ident as i { Lvar i } | ident as i { Lvar i }
| '#' { comment lexbuf } | '#' { comment lexbuf }
| _ as c { raise (Error c) } | _ as c { raise (Error c) }

View file

@ -8,9 +8,9 @@
%token <Ast.type_t> Ltype %token <Ast.type_t> Ltype
%token <string> Lvar %token <string> Lvar
%token Lend Lassign Lsc Lreturn %token Lend Lassign Lsc Lreturn
%token Ladd %token Ladd Lmul
%left Ladd %left Ladd Lmul
%start prog %start prog
@ -49,4 +49,7 @@ expr:
| a = expr ; Ladd ; b = expr { | a = expr ; Ladd ; b = expr {
Call { func = "%add" ; args = [ a ; b ] ; pos = $startpos($2) } Call { func = "%add" ; args = [ a ; b ] ; pos = $startpos($2) }
} }
| a = expr ; Lmul ; b = expr {
Call { func = "%mul" ; args = [ a ; b ] ; pos = $startpos($2) }
}
; ;

1
tests/10_add-mul.test Normal file
View file

@ -0,0 +1 @@
int res = 13 * 100 + 12;

View file

@ -1 +0,0 @@
int res = 1 + 1;