summaryrefslogtreecommitdiff
path: root/lib/model/path.ml
diff options
context:
space:
mode:
Diffstat (limited to 'lib/model/path.ml')
-rw-r--r--lib/model/path.ml61
1 files changed, 61 insertions, 0 deletions
diff --git a/lib/model/path.ml b/lib/model/path.ml
new file mode 100644
index 0000000..dd62864
--- /dev/null
+++ b/lib/model/path.ml
@@ -0,0 +1,61 @@
+(** Evaluation of a path through the fields.
+
+ A path is a list of field names (as {!Identifier.t}), like the ones parsed
+ from the DSL expressions ({!Dsl.ContentPath}, written [$a.b.c] in a
+ configuration). *)
+
+(** All the fields of a target: the fields of the content, or the fields of the
+ list *)
+let fields_of_target : Reference.target -> Reference.target Field.t list =
+ function
+ | Reference.Content ref -> List.of_seq (Content.fields (Reference.get ref))
+ | Reference.List list -> list.Data_list.fields
+
+let find_field :
+ Reference.target Field.t list ->
+ Identifier.t ->
+ Reference.target Field.t option =
+ fun fields name ->
+ List.find_opt (fun field -> Identifier.equal (Field.name field) name) fields
+
+(** The target of a reference field, [None] for the other field types *)
+let target_of_field : Reference.target Field.t -> Reference.target option =
+ fun field ->
+ let (Field.T ty) = Field.type_ field in
+ match ty with
+ | Typ.MonoReference reference | Typ.MultiReference reference ->
+ Some reference.Typ.t
+ | Typ.Text | Typ.Integer -> None
+
+(** Resolve a path from a target.
+
+ Each segment is the name of a field of the current target (a content or a
+ list). Intermediate segments must be reference fields: the evaluation then
+ moves to their target. The last segment can be any field.
+
+ The result is the field designated by the last segment — for a reference
+ field, its target is given by {!target_of_field}.
+
+ [None] when a segment does not exist, or an intermediate segment is not a
+ reference field. *)
+let rec resolve :
+ Reference.target -> Identifier.t list -> Reference.target Field.t option =
+ fun target path ->
+ match path with
+ | [] -> None
+ | [ name ] -> find_field (fields_of_target target) name
+ | name :: rest -> (
+ match find_field (fields_of_target target) name with
+ | None -> None
+ | Some field -> (
+ match target_of_field field with
+ | Some next -> resolve next rest
+ | None -> None))
+
+(** Resolve a path starting from a content *)
+let resolve_from_content :
+ Reference.target Content.t ->
+ Identifier.t list ->
+ Reference.target Field.t option =
+ fun content path ->
+ resolve (Reference.Content (Reference.v (fun () -> content))) path