add boolean support
This commit is contained in:
parent
ab6e8c466b
commit
6f4eb269de
5 changed files with 23 additions and 4 deletions
14
ast.ml
14
ast.ml
|
@ -1,8 +1,13 @@
|
|||
type type_t = Int_t
|
||||
type type_t =
|
||||
| Int_t
|
||||
| Bool_t
|
||||
|
||||
module Syntax = struct
|
||||
type ident = string
|
||||
type value = Int of int
|
||||
|
||||
type value =
|
||||
| Int of int
|
||||
| Bool of bool
|
||||
|
||||
type expr =
|
||||
| Val of
|
||||
|
@ -31,7 +36,10 @@ end
|
|||
|
||||
module IR = struct
|
||||
type ident = string
|
||||
type value = Int of int
|
||||
|
||||
type value =
|
||||
| Int of int
|
||||
| Bool of bool
|
||||
|
||||
type expr =
|
||||
| Val of value
|
||||
|
|
|
@ -10,6 +10,7 @@ type info =
|
|||
|
||||
let compile_value = function
|
||||
| Int n -> [ Li (V0, n) ]
|
||||
| Bool b -> [ Li (V0, if b then 1 else 0) ]
|
||||
;;
|
||||
|
||||
let compile_expr env = function
|
||||
|
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
let alpha = ['a'-'z' 'A'-'Z']
|
||||
let num = ['0'-'9']
|
||||
let bool = "true" | "false"
|
||||
let ident = alpha (alpha | num | '-' | '_')*
|
||||
|
||||
rule token = parse
|
||||
|
@ -15,6 +16,8 @@ rule token = parse
|
|||
| '\n' { Lexing.new_line lexbuf; token lexbuf }
|
||||
| num+ as n { Lint (int_of_string n) }
|
||||
| "int" { Ltype (Int_t) }
|
||||
| "bool" { Ltype (Bool_t) }
|
||||
| bool as b { Lbool (bool_of_string b) }
|
||||
| '=' { Lassign }
|
||||
| ';' { Lsc }
|
||||
| ident as i { Lvar i }
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
%}
|
||||
|
||||
%token <int> Lint
|
||||
%token <bool> Lbool
|
||||
|
||||
%token <Ast.type_t> Ltype
|
||||
|
||||
|
@ -38,6 +39,9 @@ expr:
|
|||
| n = Lint {
|
||||
Val { value = Int (n) ; pos = $startpos(n) }
|
||||
}
|
||||
| b = Lbool {
|
||||
Val { value = Bool (b) ; pos = $startpos(b) }
|
||||
}
|
||||
| v = Lvar {
|
||||
Var { name = v ; pos = $startpos(v) }
|
||||
}
|
||||
|
|
|
@ -9,11 +9,12 @@ exception Error of string * Lexing.position
|
|||
let errt expected given pos =
|
||||
let str_of_type_t = function
|
||||
| Int_t -> "int"
|
||||
| Bool_t -> "bool"
|
||||
in
|
||||
raise
|
||||
(Error
|
||||
( Printf.sprintf
|
||||
"Expected %s but %s given."
|
||||
"Expected %s but given %s"
|
||||
(str_of_type_t expected)
|
||||
(str_of_type_t given)
|
||||
, pos ))
|
||||
|
@ -31,6 +32,7 @@ let warn msg (pos : Lexing.position) =
|
|||
|
||||
let analyze_value = function
|
||||
| Syntax.Int n -> Int n, Int_t
|
||||
| Syntax.Bool b -> Bool b, Bool_t
|
||||
;;
|
||||
|
||||
let analyze_expr env ua x = function
|
||||
|
@ -68,6 +70,7 @@ let analyze parsed = analyze_block _types_ [] parsed
|
|||
let emit oc ast =
|
||||
let rec fmt_v = function
|
||||
| Int n -> "Int " ^ string_of_int n
|
||||
| Bool b -> "Bool " ^ string_of_bool b
|
||||
and fmt_e = function
|
||||
| Val v -> "Val (" ^ fmt_v v ^ ")"
|
||||
| Var v -> "Var \"" ^ v ^ "\""
|
||||
|
|
Reference in a new issue