package scfg

  1. Overview
  2. Docs

Source file pp.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
(** Module providing functions to pretty print a config or parts of a config. *)

open Types

(** The string used to print one level of indentation. Defaults to two spaces. *)
let indent_s = ref "  "

(**/**)

(** Print a given number of level indentation. *)
let rec indent fmt n =
  if n <= 0 then () else Format.fprintf fmt "%s%a" !indent_s indent (n - 1)

(**/**)

(** Print a name or a parameter on a given formatter. The function will try to
    print with as low quoting as possible. *)
let param =
  let chars_to_quote = Hashtbl.create 512 in
  Array.iter
    (fun c -> Hashtbl.add chars_to_quote c ())
    [| ' '; '{'; '}'; '"'; '\\'; '\''; '\n'; '\r'; '\t' |];
  fun fmt param ->
    if String.length param = 0 then Format.fprintf fmt {|""|}
    else if String.exists (Hashtbl.mem chars_to_quote) param then begin
      if String.contains param '"' && not (String.contains param '\'') then
        Format.fprintf fmt {|'%s'|} param
      else
        let buf = Buffer.create (String.length param) in
        String.iter
          (function
            | '\n' -> Buffer.add_string buf "\\n"
            | '\r' -> Buffer.add_string buf "\\r"
            | '\t' -> Buffer.add_string buf "\\t"
            | '"' -> Buffer.add_string buf "\\\""
            | '\\' -> Buffer.add_string buf "\\\\"
            | c -> Buffer.add_char buf c )
          param;
        let param = Buffer.contents buf in
        Format.fprintf fmt {|"%s"|} param
    end
    else Format.fprintf fmt "%s" param

(** Print a list of parameters on a given formatter. *)
let params fmt = function
  | [] -> ()
  | params ->
    Format.fprintf fmt " %a"
      (Format.pp_print_list
         ~pp_sep:(fun fmt () -> Format.fprintf fmt " ")
         param )
      params

(** Print children of a directive on a given formatter. *)
let rec children n fmt (children : Types.directive list) =
  match children with
  | [] -> ()
  | children ->
    Format.fprintf fmt " {@.%a@.%a}" (config n) children indent (max 0 (n - 1))

(** Print a directive on a given formatter. *)
and directive n fmt d =
  Format.fprintf fmt {|%a%a%a%a|} indent n param d.name params d.params
    (children (n + 1))
    d.children

(** Print a config on a given formatter. *)
and config n fmt (config : Types.config) =
  Format.pp_print_list
    ~pp_sep:(fun fmt () -> Format.fprintf fmt "@.%a" indent (max 0 (n - 2)))
    (directive n) fmt config

(** Print children of a directive on a given formatter. *)
let children = children 0

(** Print a directive on a given formatter. *)
let directive = directive 0

(** Print a config on a given formatter. *)
let config = config 0
OCaml

Innovation. Community. Security.