aboutsummaryrefslogtreecommitdiff
path: root/lib/fragment_graph/rdf_fragment_graph.ml
blob: 09821a2cfe14c7935553d4d90eb68c764ba79ed9 (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
(*
 * SPDX-FileCopyrightText: 2021 petites singularités <ps-dream@lesoiseaux.io>
 * SPDX-FileCopyrightText: 2021 pukkamustard <pukkamustard@posteo.net>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 *)

(* TODO this implementation uses CCMultiMaps. This is not so good as CCMultiMaps
   adds duplicate values. This must be manually checked when entering statements
   (see `add_statemen_unique`). Find a better solution.
*)

module type HASH = sig
  (*** Signature of a hash that is used to compute identifiers. *)

  val hash : string -> Rdf.Iri.t
  (** [hash v] returns the hash of [v] as an iri. *)
end

module type T = sig
  (** RDF Fragment Graph  *)

  module Predicate : sig
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t
      (** Predicate that can appear in a Fragment Graph *)

    val of_iri : Rdf.Iri.t -> t
    (** [of_iri iri] creates an Iri predicate  *)

    val make_fragment_reference : string -> t
    (** [make_fragment_reference fragment] creates a reference to [fragment] *)

  end

  module Object : sig
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t
      | Literal of Rdf.Literal.t
      (** Object that can appear in a Fragment Graph  *)

    val of_iri : Rdf.Iri.t -> t
    (** [of_iri iri] creates an iri object *)

    val of_literal : Rdf.Literal.t -> t
    (** [of_iri iri] creates an literal object *)

    val make_fragment_reference : string -> t
    (** [make_fragment_reference fragment] creates a reference to [fragment] *)
  end

  type t
  (** Type of a Fragment Graph *)

  val empty : t
  (** [empty] is the empty fragment graph *)

  val equal : t -> t -> bool
  (** [equal a b] returns true if [a] is the same Fragment Graph as [b]. *)

  val add_statement : Predicate.t -> Object.t -> t -> t
  (** [add_statement fragment_graph predicate object'] adds a statement to the fragment graph *)

  val add_fragment_statement : string -> Predicate.t -> Object.t -> t -> t
  (** [add_fragment_statement] adds a fragment statement to the fragment graph *)

  val statements : t -> (Predicate.t * Object.t) list
  (** [statements fragment_graph] returns a list of statements in
      [fragment_graph]. *)

  val fragment_statements : t -> (string * Predicate.t * Object.t) list
  (** [fragment_statements fragment_graph] returns a list of fragment statements
      in [fragment_graph]. *)

  val base_subject : t -> Rdf.Iri.t
  (** [base_subject fragment_graph] returns the base subject of the fragment graph. *)

  val canonical : t -> string
  (** [canonical fragment_graph] returns the canonical serialization of the fragment graph.  *)

  val of_canonical : string -> (t,  string) result
  (** [of_canonical s] attempts to decode the fragment graph from the canonical serialization in [s]*)

  val to_triples : t -> Rdf.Triple.t list
  (** [to_triples fragment_graph] returns a list of statements in [fragment_graph] as triples. *)

  val pp : t Fmt.t
  [@@ocaml.toplevel_printer]
  (** [pp ppf t] will output a debug output of the Fragment Graph [t] to the formatter [ppf] *)
end


module Make(H: HASH) = struct
  module Predicate = struct
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t

    let of_iri iri = Iri iri

    let make_fragment_reference id =
      FragmentReference id

    let compare a b =
      match (a, b) with
      | FragmentReference a, FragmentReference b -> String.compare a b
      | Iri a, Iri b -> Rdf.Iri.compare a b
      | FragmentReference _, _ -> -1
      | Iri _, _ -> 1

    let expand base_iri = function
      | FragmentReference fragment ->
        Rdf.Iri.with_fragment base_iri (Some fragment)
        |> Rdf.Triple.Predicate.of_iri
      | Iri iri ->
        iri
        |> Rdf.Triple.Predicate.of_iri

    (* let pp ppf = function
     *   | FragmentReference id ->
     *     Fmt.pf ppf "%s" id
     *   | Iri iri ->
     *     Fmt.pf ppf "%a" Rdf.Iri.pp iri *)
  end

  module Object = struct
    type t =
      | FragmentReference of string
      | Iri of Rdf.Iri.t
      | Literal of Rdf.Literal.t

    let of_iri iri = Iri iri

    let of_literal literal = Literal literal

    let make_fragment_reference id =
      FragmentReference id

    let compare a b =
      match (a, b) with
      | FragmentReference a, FragmentReference b -> String.compare a b
      | Iri a, Iri b -> Rdf.Iri.compare a b
      | Literal a, Literal b -> Rdf.Literal.compare a b
      | FragmentReference _, _ -> -1
      | Literal _, _ -> -1
      | Iri _, _ -> 1

    let expand base_iri = function
      | FragmentReference fragment ->
        Rdf.Iri.with_fragment base_iri (Some fragment)
        |> Rdf.Triple.Object.of_iri
      | Iri iri ->
        iri
        |> Rdf.Triple.Object.of_iri
      | Literal literal ->
        literal
        |> Rdf.Triple.Object.of_literal

    (* let pp ppf = function
     *   | FragmentReference id ->
     *     Fmt.pf ppf "%s" id
     *   | Iri iri ->
     *     Fmt.pf ppf "%a" Rdf.Iri.pp iri
     *   | Literal literal ->
     *     Fmt.pf ppf "%a" Rdf.Literal.pp literal *)
  end

  module StatementMap = CCMultiMap.Make(Predicate)(Object)
  module FragmentStatementsMap = CCHashTrie.Make(struct
      type t = string
      let equal = String.equal
      let hash = Hashtbl.hash
    end)


  type t =
    { statements : StatementMap.t;
      fragment_statements : StatementMap.t FragmentStatementsMap.t
    }

  let empty =
    { statements = StatementMap.empty;
      fragment_statements = FragmentStatementsMap.empty
    }

  (* Helper to return list of statements *)
  let list_of_statements statements =
    let l = ref [] in
    StatementMap.iter statements
      (fun p o -> l := (p,o) :: !l) ;
    !l

  (* Adds statement if it is not already present. *)
  let add_statement_unique predicate object' statements =
    let open StatementMap in
    match find statements predicate with
    | [] -> add statements predicate object'
    | objs ->
      if List.mem object' objs then
        statements
      else
        add statements predicate object'

  let add_statement predicate object' fragment_graph =
    {fragment_graph with
     statements =
       add_statement_unique
         predicate object'
         fragment_graph.statements
    }

  let statements fragment_graph =
    list_of_statements fragment_graph.statements

  let add_fragment_statement fragment_reference predicate object' fragment_graph =
    {fragment_graph with
     fragment_statements = FragmentStatementsMap.update fragment_reference
         ~f:(function
             | Some statements ->
               Some (add_statement_unique predicate object' statements)
             | None ->
               Some (StatementMap.add StatementMap.empty
                       predicate object'))
         fragment_graph.fragment_statements
    }

  let fragment_statements fragment_graph =
    FragmentStatementsMap.fold
      ~f:(fun fs fragment_id statements ->
          List.(append fs
                  (list_of_statements statements
                   |> map (fun (o,p) -> (fragment_id, o, p)))))
      ~x:[]
      fragment_graph.fragment_statements

  module Serialization = struct

    let cbor_of_predicate = function
      | Predicate.FragmentReference fragment_id ->
        Cbor.Tag (Z.of_int 302, Cbor.TextString fragment_id)
      | Predicate.Iri iri ->
        Rdf_cbor.cbor_of_iri iri

    let cbor_of_object = function
      | Object.FragmentReference fragment_id ->
        Cbor.Tag (Z.of_int 302, Cbor.TextString fragment_id)
      | Object.Iri iri ->
        Rdf_cbor.cbor_of_iri iri
      | Object.Literal literal ->
        Rdf_cbor.cbor_of_literal literal

    let compare a b =
      String.compare
        (Cbor.encode a)
        (Cbor.encode b)

    let cbor_of_statements fragment_graph =
      StatementMap.fold fragment_graph.statements []
        (fun acc predicate object' ->
           Cbor.Array [
             cbor_of_predicate predicate;
             cbor_of_object object'
           ] :: acc)

    let cbor_of_fragment_statements fragment_graph =
      let cbor_of_statements fragment_id statements =
        StatementMap.fold statements []
          (fun acc predicate object' ->
             Cbor.Array [
               Cbor.TextString fragment_id;
               cbor_of_predicate predicate;
               cbor_of_object object'
             ] :: acc)
      in
      FragmentStatementsMap.fold
        ~x:[]
        ~f:(fun acc fragment_id statements ->
            List.append (cbor_of_statements fragment_id statements) acc)
        fragment_graph.fragment_statements

    let cbor_of_fragment_graph fragment_graph =
      List.append
        (cbor_of_statements fragment_graph)
        (cbor_of_fragment_statements fragment_graph)
      |> List.sort compare
      |> (fun s -> Cbor.Array s)

    let encode fragment_graph =
      cbor_of_fragment_graph fragment_graph
      |> Cbor.encode

    module Parser = struct

      open Angstrom
      open Cbor.Parser

      let predicate =
        any_tag
          (fun z ->
             if Z.(equal z ~$302) then
               any_text_string
               >>| Predicate.make_fragment_reference
             else if Z.(equal z ~$32) then
               any_text_string
               >>| Rdf.Iri.of_string
               >>| Predicate.of_iri
             else
               fail "invalid tag")

      (* Need to redefine this here as required when decoding literals *)
      let iri =
        tag (Z.of_int 32) @@
        any_text_string
        >>| Uri.of_string

      let object' =
        any_tag
          (fun z ->
             if Z.(equal z ~$302) then
               any_text_string
               >>| Object.make_fragment_reference
             else if Z.(equal z ~$32) then
               any_text_string
               >>| Rdf.Iri.of_string
               >>| Object.of_iri
             else if Z.(equal z ~$301) then
               tuple any_text_string iri
               >>| (fun (value, datatype) -> Rdf.Literal.make value datatype)
               >>| Object.of_literal
             else
               fail "invalid tag")

      (* Parser that returns functions that modify a fragment graph.
       * Dunno about performance of this....
       *  *)
      let statement =
        Angstrom.choice
          [
            (fun (predicate, object') -> add_statement predicate object')
            <$> (tuple predicate object');

            (fun (fragment_id, predicate, object') ->
               add_fragment_statement fragment_id predicate object')
            <$> (triple any_text_string predicate object');
          ]

      let fragment_graph =
        Cbor.Parser.array statement
        >>| (fun fs ->
            List.fold_left (fun fragment_graph f  -> f fragment_graph) empty fs
          )

    end

  end

  let canonical fragment_graph =
    Serialization.encode fragment_graph

  let of_canonical s =
    Angstrom.parse_string ~consume:Angstrom.Consume.Prefix
      Serialization.Parser.fragment_graph
      s

  let base_subject fragment_graph =
    fragment_graph
    |> canonical
    |> H.hash

  (* TODO: equality is broken as CCMultiMap cares about order of inseration.
     This equality just uses the canonicalization to test equality. Think about
     if there is better way. *)
  let equal a b =
    Rdf.Iri.equal
      (base_subject a)
      (base_subject b)

  let fold_statements base_iri subject statements acc f =
    StatementMap.fold statements acc
      (fun acc predicate object' ->
         f acc @@
         Rdf.Triple.make subject
           (Predicate.expand base_iri predicate)
           (Object.expand base_iri object'))

  let fold fragment_graph acc f =
    let base_iri = base_subject fragment_graph in
    let subject = base_iri
                  |> Rdf.Triple.Subject.of_iri
    in
    FragmentStatementsMap.fold
      ~f:(fun acc fragment_id statements ->
          let subject = Rdf.Iri.with_fragment base_iri (Some fragment_id)
                        |> Rdf.Triple.Subject.of_iri
          in
          fold_statements base_iri subject statements acc f)
      ~x:(fold_statements base_iri subject
            fragment_graph.statements
            acc f)
      fragment_graph.fragment_statements


  let to_triples fragment_graph =
    fold fragment_graph []
      (fun triples triple -> triple :: triples)

  (* TODO nicer pp *)
  let pp ppf fragment_graph =
    Fmt.pf ppf "%a" Cbor.pp
    @@ Serialization.cbor_of_fragment_graph fragment_graph
end