culr/lib/parse.ml
2024-12-03 14:28:08 +11:00

81 lines
2.4 KiB
OCaml

open Types
open Angstrom
open Parsers
let is_sep = function '\x20' | '\x09' -> true | _ -> false
let is_delim = function '\x0a' | '\x0d' -> true | _ -> false
let is_text c = not (is_sep c || is_delim c || c = '\x1b')
let sep = take_while is_sep >>| fun s -> Separator s
let delim = take_while is_delim >>| fun s -> Delimiter s
let text = take_while is_text >>| fun s -> Text s
let ansi = Ansi.ansi_parse
let culr_parse =
peek_char_fail >>= function
| n when is_sep n -> sep
| n when is_delim n -> delim
| n when n = '\x1b' -> ansi
| _n -> text
let conv_rgb = function [ r; g; b ] -> Types.RGB (r, g, b) | _ -> assert false
let hex_digit = take 2 >>| fun s -> int_of_string ("0x" ^ s)
let rgb_triple =
let digit_comma = digit <* char ',' in
char '(' *> list [ digit_comma; digit_comma; digit ] <* char ')' >>| conv_rgb
let hex_colour = char '#' *> count 3 hex_digit >>| conv_rgb
let simple_colour = digit >>| fun s -> Types.Simple s
let env_colours = sep_by1 skip_semi (rgb_triple <|> hex_colour <|> simple_colour)
let unpack = function Ok payload -> payload | _ -> []
let parse_env_colours s =
parse_string ~consume:Consume.All env_colours s |> unpack |> Array.of_list
let parse_env_order s =
parse_string ~consume:Consume.All Parsers.semi_digits s
|> unpack |> Array.of_list
let%test "sep_parse" =
parse_string ~consume:Consume.All sep " " |> function
| Ok (Separator " ") -> true
| _ -> false
let%test "delim_parse" =
parse_string ~consume:Consume.All delim "\n\n\n" |> function
| Ok (Delimiter "\n\n\n") -> true
| _ -> false
let%test "text_parse" =
parse_string ~consume:Consume.All text "okokyeahok" |> function
| Ok (Text "okokyeahok") -> true
| _ -> false
let%test "culr_parse" =
parse_string ~consume:Consume.All (many1 culr_parse)
"sometext \n\n\n \x1b[38;2;2m"
|> function
| Ok
[
Text "sometext";
Separator " ";
Delimiter "\n\n\n";
Separator " ";
Ansi [ Fg (Simple 2) ];
] ->
true
| Ok n ->
n |> List.fold_left (fun _acc el -> el |> Debug.debug_print) ();
false
| _ -> false
let%test "rgb" =
parse_string ~consume:Consume.All rgb_triple "(255,0,127)" |> function
| Ok s -> s = Types.RGB (255, 0, 127)
| _ -> false
let%test "hex" =
parse_string ~consume:Consume.All hex_colour "#FF007F" |> function
| Ok s -> s = Types.RGB (255, 0, 127)
| _ -> false