From 141db078408f94c410508970d07382d4a6087f17 Mon Sep 17 00:00:00 2001 From: Chimrod <> Date: Fri, 15 Mar 2024 10:20:31 +0100 Subject: Added eq and hash functions in the Ast.Expression --- lib/syntax/t.ml | 7 +++++++ lib/syntax/tree.ml | 23 ++++++++++++++++++++++- lib/syntax/tree.mli | 10 +++++++++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/lib/syntax/t.ml b/lib/syntax/t.ml index cb9c7ce..882a375 100644 --- a/lib/syntax/t.ml +++ b/lib/syntax/t.ml @@ -7,6 +7,13 @@ type 'a literal = Text of string | Expression of 'a let map_litteral : f:('a -> 'b) -> 'a literal -> 'b literal = fun ~f -> function Text t -> Text t | Expression e -> Expression (f e) +let eq_literal : eq:('a -> 'a -> bool) -> 'a literal -> 'a literal -> bool = + fun ~eq l1 l2 -> + match (l1, l2) with + | Text s1, Text s2 -> String.equal s1 s2 + | Expression e1, Expression e2 -> eq e1 e2 + | _ -> false + type boperator = | Eq | Neq diff --git a/lib/syntax/tree.ml b/lib/syntax/tree.ml index b7d9d15..72ae754 100644 --- a/lib/syntax/tree.ml +++ b/lib/syntax/tree.ml @@ -45,10 +45,31 @@ module Ast = struct end (** Default implementation for the expression *) -module Expression : S.Expression with type t' = S.pos Ast.expression = struct +module Expression : sig + include S.Expression with type t' = S.pos Ast.expression + + val eq : (S.pos -> S.pos -> bool) -> t -> t -> bool + val hash : (S.pos -> int) -> t -> int +end = struct type t = S.pos Ast.expression type t' = t + let eq : (S.pos -> S.pos -> bool) -> t -> t -> bool = Ast.equal_expression + + let rec hash : (S.pos -> int) -> t -> int = + fun f -> function + | Integer (pos, v) -> Hashtbl.hash (f pos, v) + | Literal (pos, l) -> + let litt = List.map ~f:(T.map_litteral ~f:(hash f)) l in + Hashtbl.hash (f pos, litt) + | Ident { pos; name; index } -> + Hashtbl.hash (f pos, name, Option.map (hash f) index) + | BinaryOp (pos, op, o1, o2) -> + Hashtbl.hash (f pos, op, hash f o1, hash f o2) + | Op (pos, op, o1) -> Hashtbl.hash (f pos, op, hash f o1) + | Function (pos, name, args) -> + Hashtbl.hash (f pos, name, List.map ~f:(hash f) args) + let v : t -> t' = fun t -> t let integer : S.pos -> string -> t = fun pos i -> Ast.Integer (pos, i) diff --git a/lib/syntax/tree.mli b/lib/syntax/tree.mli index 8ce577e..a82c07c 100644 --- a/lib/syntax/tree.mli +++ b/lib/syntax/tree.mli @@ -43,9 +43,17 @@ module Ast : sig [@@deriving eq, show] end +(** Extend the default Expression module with an eq operator *) +module Expression : sig + include S.Expression with type t' = S.pos Ast.expression + + val eq : (S.pos -> S.pos -> bool) -> t -> t -> bool + val hash : (S.pos -> int) -> t -> int +end + include S.Analyzer - with type Expression.t' = S.pos Ast.expression + with module Expression := Expression and type Instruction.t' = S.pos Ast.statement and type Location.t = S.pos * S.pos Ast.statement list and type context = unit -- cgit v1.2.3