Advertisement
Grendizer

Error raising

Mar 17th, 2023
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 2.24 KB | None | 0 0
  1. (* open Parser *)
  2. open Location
  3.  
  4. type token =
  5.   | EOF
  6.   | ADD of Location.t
  7.   | SUB of Location.t
  8.   | MUL of Location.t
  9.   | DIV of Location.t
  10.   | REM of Location.t
  11.   | LPAR of Location.t
  12.   | RPAR of Location.t
  13.   | INT of int * Location.t
  14.  
  15. let print_token = function
  16.   | EOF -> print_string "EOF"
  17.   | ADD _ -> print_string "ADD"
  18.   | SUB _ -> print_string "SUB"
  19.   | MUL _ -> print_string "MUL"
  20.   | DIV _ -> print_string "DIV"
  21.   | REM _ -> print_string "REM"
  22.   | LPAR _ -> print_string "LPAR"
  23.   | RPAR _ -> print_string "RPAR"
  24.   | INT (n, _) -> print_int n
  25.  
  26. let mk_int nb pos =
  27.   try INT (int_of_string nb, pos)
  28.   with Failure _ -> raise (Error (Error (Printf.sprintf "Illegal integer '%s': " nb, pos)))
  29.  
  30. let newline = (['\n' '\r'] | "\r\n")
  31. let blank = [' ' '\014' '\t' '\012']
  32. let not_newline_char = [^ '\n' '\r']
  33. let digit = ['0'-'9']
  34.  
  35. rule token buf =
  36.   (* newlines *)
  37.   | newline { Location.incr_line buf; token buf }
  38.   (* blanks *)
  39.   | blank + { token buf }
  40.   (* end of file *)
  41.   | eof { EOF }
  42.   (* comments *)
  43.   | "--" not_newline_char* { token buf }
  44.   (* integers *)
  45.   | digit+ as nb { mk_int nb (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  46.   (* commands *)
  47.   | "+" { ADD (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  48.   | "-" { SUB (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  49.   | "*" { MUL (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  50.   | "/" { DIV (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  51.   | "%" { REM (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  52.   | "(" { LPAR (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  53.   | ")" { RPAR (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
  54.   (* illegal characters *)
  55.   | _ as c { raise (Error (Error (Printf.sprintf "Illegal character '%c': " c, Location.curr buf))) }
  56.  
  57. let rec examine_all lexbuf =
  58.   let result =
  59.     try token lexbuf with
  60.     | Error err -> Location.print err; print_newline (); raise (Error err)
  61.   in
  62.   print_token result;
  63.   print_string " ";
  64.   match result with
  65.   | EOF -> ()
  66.   | _ -> examine_all lexbuf
  67.  
  68. let compile file =
  69.   print_string ("File
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement