open Factotum_source let test name = Alcotest.test_case name `Quick let pos line column offset : Location.t = { line; column; offset } let scanner text = Scanner.from (Source.of_string "test" text) let position = Alcotest.testable Location.pp ( = ) let unwrap = function | Ok value -> value | Error ((`Invalid_lex message | `Invalid_syntax message), loc) -> Alcotest.failf "%s at %a" message Location.pp loc let forms = Alcotest.testable (Format.pp_print_list Sexp.pp) (List.equal Sexp.equiv) let dummy_span : Location.span = { id = Id.from_string "expected"; min = Location.empty; max = Location.empty } let node kind = kind, dummy_span let atom s = node (Sexp.Atom s) let list xs = node (Sexp.List (xs, None)) let improper xs tail = node (Sexp.List (xs, Some tail)) let group delimiter xs = node (Sexp.Group (delimiter, xs)) let quote x = node (Sexp.Quote x) let quasiquote x = node (Sexp.Quasiquote x) let unquote x = node (Sexp.Unquote x) let splice x = node (Sexp.UnquoteSplice x) let reserved x = node (Sexp.Reserved x) let expect_forms input expected = let actual = unwrap (Reader.parse_string "test" input) in Alcotest.check forms input expected actual let expect_lex_error input = match Reader.parse_string "test" input with | Error (`Invalid_lex _, _) -> () | Error (`Invalid_syntax message, loc) -> Alcotest.failf "expected lex error, got syntax error %s at %a" message Location.pp loc | Ok actual -> Alcotest.failf "%S: expected lex error, got %a" input (Format.pp_print_list Sexp.pp) actual let expect_syntax_error input = match Reader.parse_string "test" input with | Error (`Invalid_syntax _, _) -> () | Error (`Invalid_lex message, loc) -> Alcotest.failf "expected syntax error, got lexical error %s at %a" message Location.pp loc | Ok actual -> Alcotest.failf "%S: expected syntax error, got %a" input (Format.pp_print_list Sexp.pp) actual let with_channel text f = let path = Filename.temp_file "factotum-source-" ".scm" in Fun.protect ~finally:(fun () -> Sys.remove path) (fun () -> Out_channel.with_open_bin path (fun ch -> output_string ch text); In_channel.with_open_bin path f) let location_tests = [ test "ordinary character advances column and offset" (fun () -> Alcotest.check position "after a" (pos 0 1 1) (Location.delta Location.empty (Some 'a'))); test "newline advances line and resets column" (fun () -> Alcotest.check position "after newline" (pos 3 0 11) (Location.delta (pos 2 7 10) (Some '\n'))); test "EOF leaves position unchanged" (fun () -> let loc = pos 2 7 10 in Alcotest.check position "at EOF" loc (Location.delta loc None)); ] let scanner_tests = [ test "peek does not consume or advance position" (fun () -> let s = scanner "ab" in Alcotest.check (Alcotest.option Alcotest.char) "first peek" (Some 'a') (Scanner.peek s); Alcotest.check (Alcotest.option Alcotest.char) "second peek" (Some 'a') (Scanner.peek s); Alcotest.check position "before take" Location.empty (Scanner.cursor s); Alcotest.check (Alcotest.option Alcotest.char) "take" (Some 'a') (Scanner.take s); Alcotest.check Alcotest.int "offset after take" 1 (Scanner.cursor s).offset; Alcotest.check (Alcotest.option Alcotest.char) "next" (Some 'b') (Scanner.peek s)); test "position across a newline" (fun () -> let s = scanner "ab\nc" in for _ = 1 to 4 do ignore (Scanner.take s) done; Alcotest.check position "after c" (pos 1 1 4) (Scanner.cursor s)); test "take_until leaves delimiter pending" (fun () -> let s = scanner "abc)" in let buffer = Buffer.create 8 in let stop = Scanner.take_until buffer (( = ) ')') s in Alcotest.check Alcotest.string "captured" "abc" (Buffer.contents buffer); Alcotest.check (Alcotest.option Alcotest.char) "stop" (Some ')') stop; Alcotest.check (Alcotest.option Alcotest.char) "pending" (Some ')') (Scanner.take s)); test "take_while terminates on empty input" (fun () -> let buffer = Buffer.create 8 in let stop = Scanner.take_while buffer (fun _ -> true) (scanner "") in Alcotest.check (Alcotest.option Alcotest.char) "EOF" None stop); test "take_while stops before a nonmatching character" (fun () -> let s = scanner "abc)" in let buffer = Buffer.create 8 in let stop = Scanner.take_while buffer (( <> ) ')') s in Alcotest.check (Alcotest.option Alcotest.char) "stop" (Some ')') stop; Alcotest.check Alcotest.int "consumed bytes" 3 (Scanner.cursor s).offset; Alcotest.check (Alcotest.option Alcotest.char) "pending" (Some ')') (Scanner.peek s)); ] let lexer_tests = [ test "token span excludes surrounding whitespace" (fun () -> let lexer = Lexer.from (scanner " abc ") in let kind, span = unwrap (Lexer.take lexer) in Alcotest.check Alcotest.bool "atom" true (kind = Lexer.Atom "abc"); Alcotest.check position "start" (pos 0 2 2) span.min; Alcotest.check position "end, exclusive" (pos 0 5 5) span.max); test "token offsets and identity survive lookahead" (fun () -> let source = Source.of_string "tokens" "a b" in let lexer = Lexer.from (Scanner.from source) in let first = unwrap (Lexer.peek lexer) in Alcotest.check Alcotest.bool "repeated peek" true (first = unwrap (Lexer.peek lexer)); Alcotest.check Alcotest.bool "take after peek" true (first = unwrap (Lexer.take lexer)); let _, span = unwrap (Lexer.take lexer) in Alcotest.check Alcotest.bool "source identity" true (Id.equal source.id span.id); Alcotest.check Alcotest.int "second start" 2 span.min.offset; Alcotest.check Alcotest.int "second end" 3 span.max.offset); test "unterminated string reports a lexical error" (fun () -> let lexer = Lexer.from (scanner "\"abc") in match Lexer.take lexer with | Error (`Invalid_lex _, _) -> () | _ -> Alcotest.fail "expected lexical error"); ] let lexer_verbatim_tests = [ test "verbatim text retains known and unknown escapes" (fun () -> let lexer = Lexer.from (scanner "\"line\\nnext \\d\"") in match fst (unwrap (Lexer.take lexer)) with | Lexer.Verbatim raw -> Alcotest.check Alcotest.string "raw text" "line\\nnext \\d" raw | _ -> Alcotest.fail "expected verbatim text"); test "verbatim text retains escaped quotes" (fun () -> let lexer = Lexer.from (scanner "\"say \\\"hi\\\"\"") in match fst (unwrap (Lexer.take lexer)) with | Lexer.Verbatim raw -> Alcotest.check Alcotest.string "raw text" "say \\\"hi\\\"" raw | _ -> Alcotest.fail "expected verbatim text"); test "unterminated block comment reports a lexical error" (fun () -> expect_lex_error "#| never closed"); test "unterminated outer block comment reports a lexical error" (fun () -> expect_lex_error "#| outer #| inner |#"); ] let reader_tests = [ test "empty input" (fun () -> expect_forms "" []); test "top-level forms retain source order" (fun () -> expect_forms "one two three" [atom "one"; atom "two"; atom "three"]); test "nested and improper lists" (fun () -> expect_forms "(a (b) . c)" [improper [atom "a"; list [atom "b"]] (atom "c")]); test "empty bracket group" (fun () -> expect_forms "[]" [group '[' []]); test "brace group" (fun () -> expect_forms "{a b}" [group '{' [atom "a"; atom "b"]]); test "bare keyword before list close" (fun () -> expect_forms "(~x)" [list [node (Sexp.Keyword "~x")]]); test "tagged verbatim text retains regex escapes" (fun () -> expect_forms "~r\"\\d+\"" [node (Sexp.Tagged ("~r", node (Sexp.Verbatim "\\d+")))]); test "read_one skips a discarded datum" (fun () -> let actual = unwrap (Reader.read_one (Source.of_string "test" "#;a b")) in Alcotest.check (Alcotest.option (Alcotest.testable Sexp.pp Sexp.equiv)) "first surviving datum" (Some (atom "b")) actual); test "comment-only input has no datum" (fun () -> expect_forms "# comment" []); test "trailing line comment has no datum" (fun () -> expect_forms "a # comment" [atom "a"]); test "trailing block comment has no datum" (fun () -> expect_forms "a #| comment |#" [atom "a"]); test "line comment before list close" (fun () -> expect_forms "(a # comment\n)" [list [atom "a"]]); test "block comment before list close" (fun () -> expect_forms "(a #| comment |#)" [list [atom "a"]]); test "comment before improper tail close" (fun () -> expect_forms "(a . b # comment\n)" [improper [atom "a"] (atom "b")]); test "unterminated list is an error" (fun () -> expect_syntax_error "(a"); test "unterminated group is an error" (fun () -> expect_syntax_error "[a"); test "mismatched delimiter is an error" (fun () -> expect_syntax_error "(a]"); test "improper list requires a head" (fun () -> expect_syntax_error "(. x)"); test "improper list requires a tail" (fun () -> expect_syntax_error "(a .)"); test "quote prefix" (fun () -> expect_forms "'a" [node (Sexp.Quote (atom "a"))]); test "quote requires a datum" (fun () -> expect_lex_error "'"); test "nested forms retain source identity and byte spans" (fun () -> let source = Source.of_string "spans" " (a (b)) " in match unwrap (Reader.read_many source) with | [(Sexp.List ([(_, a); (Sexp.List ([(_, b)], None), inner)], None), outer)] -> List.iter (fun span -> Alcotest.check Alcotest.bool "source identity" true (Id.equal source.id span.Location.id)) [outer; a; inner; b]; List.iter (fun (name, span, start, stop) -> Alcotest.check Alcotest.int (name ^ " start") start span.Location.min.offset; Alcotest.check Alcotest.int (name ^ " end") stop span.Location.max.offset) ["outer", outer, 1, 8; "a", a, 2, 3; "inner", inner, 4, 7; "b", b, 5, 6] | actual -> Alcotest.failf "unexpected tree: %a" (Format.pp_print_list Sexp.pp) actual); test "channel-backed source reads forms" (fun () -> with_channel "(a b)" (fun channel -> let source = Source.of_channel "channel" channel in Alcotest.check forms "channel" [list [atom "a"; atom "b"]] (unwrap (Reader.read_many source)))); test "parse_channel accepts a channel and agrees with parse_string" (fun () -> let input = "(a b)" in with_channel input (fun channel -> let actual = unwrap (Reader.parse_channel "test" channel) in Alcotest.check forms "channel result" [list [atom "a"; atom "b"]] actual; Alcotest.check forms "entry points agree" (unwrap (Reader.parse_string "test" input)) actual)); ] let prefix_tests = List.concat_map (fun (name, prefix, wrap) -> [ test (name ^ " wraps exactly one datum") (fun () -> expect_forms (prefix ^ "(a b) c") [wrap (list [atom "a"; atom "b"]); atom "c"]); test (name ^ " fails when not adjacent - direct") (fun () -> expect_lex_error (prefix ^ " foo")); test (name ^ " fails when not adjacent - comment") (fun () -> expect_lex_error (prefix ^ " # line\n #| block |# a")); test (name ^ " cannot use a closing delimiter as its operand") (fun () -> expect_syntax_error ("(" ^ prefix ^ ")")); ]) [ "quote", "'", quote; "quasiquote", "`", quasiquote; "unquote", ",", unquote; "splice", ",@", splice; "reserved", "%", reserved; ] @ [ test "nested quote prefixes preserve nesting" (fun () -> expect_forms "''a" [quote (quote (atom "a"))]); test "quasiquote preserves unquote and splice" (fun () -> expect_forms "`(a ,b ,@c)" [quasiquote (list [atom "a"; unquote (atom "b"); splice (atom "c")])]); test "prefixes compose with groups and improper tails" (fun () -> expect_forms "'(a . [b %c])" [quote (improper [atom "a"] (group '[' [atom "b"; reserved (atom "c")]))]); ] let datum_comment_tests = [ test "discard one atom and preserve the following forms" (fun () -> expect_forms "#; a b c" [atom "b"; atom "c"]); test "discard a complete nested form" (fun () -> expect_forms "#; (a [b] . c) d" [atom "d"]); test "discard a quoted form" (fun () -> expect_forms "#; '(a b) c" [atom "c"]); test "a discarded form can be the entire input" (fun () -> expect_forms "#; a" []); test "ordinary comments after the discarded form may end at EOF" (fun () -> expect_forms "#; a # trailing" []); test "nested datum comments each discard a datum" (fun () -> expect_forms "#; #; a b c" [atom "c"]); test "nested datum comments may exhaust the input" (fun () -> expect_forms "#; #; a b" []); test "consecutive datum comments preserve the surviving form" (fun () -> expect_forms "#; a #; b c" [atom "c"]); test "datum comments skip intervening ordinary comments" (fun () -> expect_forms "#; # line\n #| block |# a b" [atom "b"]); test "discarded form before an empty list close" (fun () -> expect_forms "(#; a)" [list []]); test "discarded form before a nonempty list close" (fun () -> expect_forms "(a #; b)" [list [atom "a"]]); test "discarded form before bracket close" (fun () -> expect_forms "[a #; b]" [group '[' [atom "a"]]); test "discarded form before brace close" (fun () -> expect_forms "{#; a}" [group '{' []]); test "discarded form before an improper dot" (fun () -> expect_forms "(a #; b . c)" [improper [atom "a"] (atom "c")]); test "discarded form before an improper tail" (fun () -> expect_forms "(a . #; b c)" [improper [atom "a"] (atom "c")]); test "discarded form after an improper tail" (fun () -> expect_forms "(a . b #; c)" [improper [atom "a"] (atom "b")]); test "datum comment requires a datum" (fun () -> expect_syntax_error "#;"); test "nested datum comments require enough datums" (fun () -> expect_syntax_error "#; #; a"); test "datum comment cannot consume the containing close" (fun () -> expect_syntax_error "(#;)"); test "discarded forms must still have valid delimiters" (fun () -> expect_syntax_error "#; (a] b"); test "discarded strings must still lex successfully" (fun () -> match Reader.parse_string "test" "#; \"unterminated" with | Error (`Invalid_lex _, _) -> () | _ -> Alcotest.fail "expected lexical error in discarded string"); ] let boundary_tests = List.map (fun input -> test ("reject malformed delimiters/tail: " ^ input) (fun () -> expect_syntax_error input)) [ "[a)"; "{a]"; "([a)]"; "[a . b]"; "{a . b}"; "(a . b c)"; "(a . b"; "(a ."; "(a . b]"; "."; ")" ] @ [ test "mixed collections preserve source order" (fun () -> expect_forms "([a] {b (c)})" [list [group '[' [atom "a"]; group '{' [atom "b"; list [atom "c"]]]]); test "nested block comments do not consume the next form" (fun () -> expect_forms "#| outer #| inner |# tail |# (a)" [list [atom "a"]]); test "string contents do not act as reader syntax" (fun () -> expect_forms "\"#; ' ,@ () [] {}\"" [node (Sexp.Verbatim "#; ' ,@ () [] {}")]); ] let span_tests = List.map (fun (prefix, _) -> test ("prefix span includes operand: " ^ prefix) (fun () -> let source = Source.of_string "prefix-span" (" " ^ prefix ^ "(a)") in match unwrap (Reader.read_many source) with | [(_, span)] -> Alcotest.check Alcotest.bool "identity" true (Id.equal source.id span.id); Alcotest.check position "start" (pos 0 1 1) span.min; let stop = 4 + String.length prefix in Alcotest.check position "end" (pos 0 stop stop) span.max | actual -> Alcotest.failf "expected one form, got %a" (Format.pp_print_list Sexp.pp) actual)) ["'", quote; "`", quasiquote; ",", unquote; ",@", splice; "%", reserved] @ [ test "nested prefix spans include their respective operands" (fun () -> match unwrap (Reader.parse_string "test" "''a") with | [(Sexp.Quote (Sexp.Quote (_, leaf), inner), outer)] -> List.iter (fun (span, start) -> Alcotest.check position "start" (pos 0 start start) span.Location.min; Alcotest.check position "end" (pos 0 3 3) span.Location.max) [outer, 0; inner, 1; leaf, 2] | actual -> Alcotest.failf "unexpected tree: %a" (Format.pp_print_list Sexp.pp) actual); test "surviving datum span excludes discarded forms" (fun () -> match unwrap (Reader.parse_string "test" "#; a\n b") with | [(_, span)] -> Alcotest.check position "start" (pos 1 1 6) span.min; Alcotest.check position "end" (pos 1 2 7) span.max | actual -> Alcotest.failf "expected one form, got %a" (Format.pp_print_list Sexp.pp) actual); test "tagged collection span includes its entire operand" (fun () -> match unwrap (Reader.parse_string "test" "~x[10]") with | [(Sexp.Tagged ("~x", _), span)] -> Alcotest.check position "start" (pos 0 0 0) span.min; Alcotest.check position "end" (pos 0 6 6) span.max | actual -> Alcotest.failf "expected tagged form, got %a" (Format.pp_print_list Sexp.pp) actual); ] let () = Alcotest.run "factotum source" [ "location", location_tests; "scanner", scanner_tests; "lexer", lexer_tests @ lexer_verbatim_tests; "reader", reader_tests; "prefix", prefix_tests; "datum comment", datum_comment_tests; "boundary", boundary_tests; "span", span_tests; ]