diff --git a/ast.ml b/ast.ml index 08d1961..9a5ca57 100644 --- a/ast.ml +++ b/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 diff --git a/compiler.ml b/compiler.ml index 3257b02..f669e5c 100644 --- a/compiler.ml +++ b/compiler.ml @@ -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 diff --git a/lexer.mll b/lexer.mll index 1109e00..52c1d14 100644 --- a/lexer.mll +++ b/lexer.mll @@ -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 } diff --git a/parser.mly b/parser.mly index c6f0714..5f5f7b1 100644 --- a/parser.mly +++ b/parser.mly @@ -4,6 +4,7 @@ %} %token Lint +%token Lbool %token 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) } } diff --git a/semantics.ml b/semantics.ml index 63652c2..71c903f 100644 --- a/semantics.ml +++ b/semantics.ml @@ -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 ^ "\""