Skip to content

Commit

Permalink
Preserve trailing whitespaces before part separators
Browse files Browse the repository at this point in the history
  • Loading branch information
Julow committed Aug 19, 2019
1 parent 19d3077 commit a21f0fa
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
32 changes: 20 additions & 12 deletions lib/top/part.ml
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ module Part = struct

type t =
{ name: string;
sep_indent: string; (** Whitespaces before the [@@@part] separator *)
body: string; }

let v ~name ~body = { name; body }
let v ~name ~sep_indent ~body = { name; sep_indent; body }
let name {name;_} = name
let sep_indent {sep_indent;_} = sep_indent
let body {body;_} = body

end
Expand All @@ -40,29 +42,33 @@ struct
let open Re in
let ws = rep space in
compile @@ whole_string @@ seq [
ws; str "[@@@"; ws; str "part"; ws;
group ws; str "[@@@"; ws; str "part"; ws;
str "\""; group (rep1 any); str "\"";
ws; str "]"; ws; opt (str ";;"); ws;
]

let make_part ~name ~lines =
let next_part ~name ~sep_indent = fun lines ->
let body = String.concat "\n" (List.rev (remove_empty_heads lines)) in
Part.v ~name ~body
Part.v ~name ~sep_indent ~body

let rec parse_parts input name lines =
let next_part_of_groups groups =
let sep_indent = Re.Group.get groups 1 in
let name = Re.Group.get groups 2 in
next_part ~name ~sep_indent

let rec parse_parts input make_part lines =
match input_line input with
| exception End_of_file -> [make_part ~name ~lines]
| exception End_of_file -> [make_part lines]
| line ->
match Re.exec_opt part_statement_re line with
| None -> parse_parts input name (line :: lines)
| None -> parse_parts input make_part (line :: lines)
| Some groups ->
let part = make_part ~name ~lines in
let new_name = Re.Group.get groups 1 in
part :: parse_parts input new_name []
let next_part = next_part_of_groups groups in
make_part lines :: parse_parts input next_part []

let of_file name =
let input = open_in name in
parse_parts input "" []
parse_parts input (next_part ~name:"" ~sep_indent:"") []

end

Expand Down Expand Up @@ -96,7 +102,9 @@ let contents file =
let body = Part.body p in
match Part.name p with
| "" -> body :: acc
| n -> body :: ("\n[@@@part \"" ^ n ^ "\"] ;;\n") :: acc
| n ->
let indent = Part.sep_indent p in
body :: ("\n" ^ indent ^ "[@@@part \"" ^ n ^ "\"] ;;\n") :: acc
) [] file
in
let lines = List.rev lines in
Expand Down
4 changes: 2 additions & 2 deletions test/sync_to_ml.mli
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ val f: unit -> unit
module A =
struct

[@@@part "2"] ;;
[@@@part "2"] ;;

type t = Some of int | Many

[@@@part "3"] ;;
[@@@part "3"] ;;

end

0 comments on commit a21f0fa

Please sign in to comment.