Skip to content

Instantly share code, notes, and snippets.

@jubnzv
Created January 1, 2020 10:18
Show Gist options
  • Save jubnzv/989cf5b3996dd5ee4230fd765081f636 to your computer and use it in GitHub Desktop.
Save jubnzv/989cf5b3996dd5ee4230fd765081f636 to your computer and use it in GitHub Desktop.
open Lexer
open Core_kernel
module Driver = struct
let print_position outx (lexbuf : Lexing.lexbuf) =
let pos = lexbuf.lex_curr_p in
Printf.fprintf outx "%s:%d:%d" pos.pos_fname pos.pos_lnum
(pos.pos_cnum - pos.pos_bol + 1)
let parse_with_error lexbuf =
try Parser.programs Lexer.initial lexbuf with
| Lexer.SyntaxError msg ->
fprintf stderr "%a: %s\n" print_position lexbuf msg;
[]
| Parser.Error ->
Printf.fprintf stderr "%a: syntax error\n" print_position lexbuf;
[]
| Failure msg ->
Printf.fprintf stderr "%a: %s-n" print_position lexbuf msg;
[]
let parse_and_print lexbuf : Syntax.iec_program list =
let node = parse_with_error lexbuf in
match node with
| programs ->
let num = List.length programs in
programs
| _ -> []
let parse_file (filename : string) : Syntax.iec_program list =
let inx = In_channel.create filename in
let lexbuf = Lexing.from_channel inx in
lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = filename };
let programs = parse_and_print lexbuf in
In_channel.close inx;
programs
let parse_string (text : string) : Syntax.iec_program list =
let lexbuf = Lexing.from_string text in
lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = "" };
parse_and_print lexbuf
end
let test_simple0 () =
let programs = Driver.parse_string "PROGRAM program0 END_PROGRAM" in
Alcotest.(check int) "number of programs" 1 (List.length programs)
let test_simple1 () =
let programs = Driver.parse_string "PROGRAM program0 END_PROGRAM" in
Alcotest.(check string)
"name of program" "program0"
(match programs with p0 :: _ -> p0.name | _ -> "error")
let () =
let open Alcotest in
run "Parser"
[
("test-simple0", [ test_case "" `Quick test_simple0 ]);
("test-simple1", [ test_case "" `Quick test_simple1 ]);
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment