Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* open Parser *)
- open Location
- type token =
- | EOF
- | ADD of Location.t
- | SUB of Location.t
- | MUL of Location.t
- | DIV of Location.t
- | REM of Location.t
- | LPAR of Location.t
- | RPAR of Location.t
- | INT of int * Location.t
- let print_token = function
- | EOF -> print_string "EOF"
- | ADD _ -> print_string "ADD"
- | SUB _ -> print_string "SUB"
- | MUL _ -> print_string "MUL"
- | DIV _ -> print_string "DIV"
- | REM _ -> print_string "REM"
- | LPAR _ -> print_string "LPAR"
- | RPAR _ -> print_string "RPAR"
- | INT (n, _) -> print_int n
- let mk_int nb pos =
- try INT (int_of_string nb, pos)
- with Failure _ -> raise (Error (Error (Printf.sprintf "Illegal integer '%s': " nb, pos)))
- let newline = (['\n' '\r'] | "\r\n")
- let blank = [' ' '\014' '\t' '\012']
- let not_newline_char = [^ '\n' '\r']
- let digit = ['0'-'9']
- rule token buf =
- (* newlines *)
- | newline { Location.incr_line buf; token buf }
- (* blanks *)
- | blank + { token buf }
- (* end of file *)
- | eof { EOF }
- (* comments *)
- | "--" not_newline_char* { token buf }
- (* integers *)
- | digit+ as nb { mk_int nb (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- (* commands *)
- | "+" { ADD (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- | "-" { SUB (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- | "*" { MUL (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- | "/" { DIV (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- | "%" { REM (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- | "(" { LPAR (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- | ")" { RPAR (Location.mkloc (Lexing.lexeme_start_p buf) (Lexing.lexeme_end_p buf)) }
- (* illegal characters *)
- | _ as c { raise (Error (Error (Printf.sprintf "Illegal character '%c': " c, Location.curr buf))) }
- let rec examine_all lexbuf =
- let result =
- try token lexbuf with
- | Error err -> Location.print err; print_newline (); raise (Error err)
- in
- print_token result;
- print_string " ";
- match result with
- | EOF -> ()
- | _ -> examine_all lexbuf
- let compile file =
- print_string ("File
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement