@@ -2,21 +2,28 @@ open Import
2
2
3
3
module Config = struct
4
4
type loc_mode = [ `Short | `Full ]
5
- type t = { show_attrs : bool ; show_locs : bool ; loc_mode : loc_mode }
5
+
6
+ type t = {
7
+ show_attrs : bool ;
8
+ show_locs : bool ;
9
+ loc_mode : loc_mode ;
10
+ json : bool ;
11
+ }
6
12
7
13
module Default = struct
8
14
let show_attrs = false
9
15
let show_locs = false
10
16
let loc_mode = `Short
17
+ let json = false
11
18
end
12
19
13
20
let default =
14
21
let open Default in
15
- { show_attrs; show_locs; loc_mode }
22
+ { show_attrs; show_locs; loc_mode; json }
16
23
17
24
let make ?(show_attrs = Default. show_attrs) ?(show_locs = Default. show_locs)
18
- ?(loc_mode = Default. loc_mode) () =
19
- { show_attrs; show_locs; loc_mode }
25
+ ?(json = Default. json) ?( loc_mode = Default. loc_mode) () =
26
+ { show_attrs; show_locs; loc_mode; json }
20
27
end
21
28
22
29
let cnum (pos : Lexing.position ) = pos.pos_cnum - pos.pos_bol
@@ -77,6 +84,29 @@ let rec pp_simple_val fmt simple_val =
77
84
and pp_field fmt (fname , simple_val ) =
78
85
Format. fprintf fmt " @[<hv 2>%s =@ %a@]" fname pp_simple_val simple_val
79
86
87
+ let rec pp_simple_val_to_yojson = function
88
+ | Unit -> `String " null"
89
+ | Int i -> `Int i
90
+ | String s -> `String s
91
+ | Bool b -> `Bool b
92
+ | Char c -> `String (String. make 1 c)
93
+ | Array l -> `List (List. map ~f: pp_simple_val_to_yojson l)
94
+ | Float f -> `Float f
95
+ | Int32 i32 -> `Int (Int32. to_int i32)
96
+ | Int64 i64 -> `Int (Int64. to_int i64)
97
+ | Nativeint ni -> `Int (Nativeint. to_int ni)
98
+ | Record fields ->
99
+ `Assoc (List. map ~f: (fun (k , v ) -> (k, pp_simple_val_to_yojson v)) fields)
100
+ | Constr (cname , [] ) -> `String cname
101
+ | Constr (cname , [ (Constr (_ , _ :: _ ) as x ) ]) ->
102
+ `Assoc [ (cname, pp_simple_val_to_yojson x) ]
103
+ | Constr (cname , [ x ]) -> `Assoc [ (cname, pp_simple_val_to_yojson x) ]
104
+ | Constr (cname , l ) ->
105
+ `Assoc [ (cname, `List (List. map ~f: pp_simple_val_to_yojson l)) ]
106
+ | Tuple l -> `List (List. map ~f: pp_simple_val_to_yojson l)
107
+ | List l -> `List (List. map ~f: pp_simple_val_to_yojson l)
108
+ | Special s -> `String s
109
+
80
110
class lift_simple_val =
81
111
object (self )
82
112
inherit [simple_val] Ast_traverse. lift as super
@@ -271,7 +301,11 @@ let with_config ~config ~f =
271
301
272
302
let pp_with_config (type a ) (lifter : a -> simple_val )
273
303
?(config = Config. default) fmt (x : a ) =
274
- with_config ~config ~f: (fun () -> pp_simple_val fmt (lifter x))
304
+ with_config ~config ~f: (fun () ->
305
+ if config.json then
306
+ Format. fprintf fmt " %s"
307
+ (Yojson. pretty_to_string (pp_simple_val_to_yojson (lifter x)))
308
+ else pp_simple_val fmt (lifter x))
275
309
276
310
let structure = pp_with_config lift_simple_val#structure
277
311
let structure_item = pp_with_config lift_simple_val#structure_item
0 commit comments