@@ -125,4 +125,65 @@ partial def InfoTree.toJson (t : InfoTree) (ctx? : Option ContextInfo) : IO Json
125125 return Lean.toJson (InfoTree.HoleJson.mk (← ctx.runMetaM {} (do Meta.ppGoal mvarId)).pretty)
126126 else throw <| IO.userError "No `ContextInfo` available."
127127
128+ instance : ToJson DataValue where
129+ toJson (v : DataValue) : Json :=
130+ match v with
131+ | .ofString s => toJson s
132+ | .ofBool b => toJson b
133+ | .ofName n => toJson n
134+ | .ofNat n => toJson n
135+ | .ofInt i => toJson i
136+ | .ofSyntax _ => "<syntax>" -- TODO: syntax to json
137+
138+ instance KVMapToJson : ToJson KVMap where
139+ toJson (m : KVMap) : Json :=
140+ Json.mkObj <| m.entries.map fun (k, v) => (k.toString, toJson v)
141+
142+ instance : ToJson Options where
143+ toJson (opts : Options) : Json := KVMapToJson.toJson opts
144+
145+ def arrStrToName (arr : Array String) : Name :=
146+ if arr.isEmpty then Name.anonymous
147+ else
148+ arr.foldl (init := Name.anonymous) fun acc s =>
149+ if s.isEmpty then acc
150+ else acc.append (Name.mkSimple s)
151+
152+ instance : FromJson DataValue where
153+ fromJson? (j : Json) : Except String DataValue :=
154+ match j with
155+ | .str s => Except.ok <| DataValue.ofString s
156+ | .bool b => Except.ok <| DataValue.ofBool b
157+ | .num _ => match j.getNat? with
158+ | Except.ok n => Except.ok <| DataValue.ofNat n
159+ | Except.error _ => match j.getInt? with
160+ | Except.ok i => Except.ok <| DataValue.ofInt i
161+ | Except.error _ => Except.error "Invalid number format"
162+ | .arr a => -- we parse array of strings as a Name
163+ if a.all fun e => e.getStr? |>.isOk then
164+ Except.ok <| DataValue.ofName (arrStrToName (a.map fun e => e.getStr?.toOption.getD "" ))
165+ else
166+ Except.error "Unsupported JSON type for DataValue"
167+ | _ => Except.error "Unsupported JSON type for DataValue"
168+
169+ instance KVMapFromJson : FromJson KVMap where
170+ fromJson? (j : Json) : Except String KVMap :=
171+ match j with
172+ | .arr a => do -- array of (Name × DataValue) pairs to be converted to KVMap
173+ let entries: Array (Name × DataValue) ← a.mapM fun e => do
174+ match e with
175+ | .arr #[.arr k, v] => do
176+ let kName ← (if k.all fun e => e.getStr? |>.isOk then
177+ Except.ok <| (arrStrToName (k.map fun e => e.getStr?.toOption.getD "" ))
178+ else
179+ Except.error "Expected array of strings for Name" )
180+ let vData ← fromJson? v
181+ return (kName, vData)
182+ | _ => Except.error "Expected array of pairs for KVMap"
183+ Except.ok <| KVMap.mk entries.toList
184+ | _ => Except.error "Expected JSON object for KVMap"
185+
186+ instance : FromJson Options where
187+ fromJson? (j : Json) : Except String Options := KVMapFromJson.fromJson? j
188+
128189end Lean.Elab
0 commit comments