grew_types.ml 17.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
(**********************************************************************************)
(*    Libcaml-grew - a Graph Rewriting library dedicated to NLP applications      *)
(*                                                                                *)
(*    Copyright 2011-2013 Inria, Université de Lorraine                           *)
(*                                                                                *)
(*    Webpage: http://grew.loria.fr                                               *)
(*    License: CeCILL (see LICENSE folder or "http://www.cecill.info")            *)
(*    Authors: see AUTHORS file                                                   *)
(**********************************************************************************)

open Log
open Printf

open Grew_base

type feature_name = string (* cat, num, ... *)
type feature_atom = string (* V, N, inf, ... *)
type feature_value = string (* V, 4, "free text", ... *)
type suffix = string

bguillaum's avatar
bguillaum committed
21 22 23 24 25 26 27 28 29 30 31
type value = String of string | Float of float

let string_of_value = function
  | String s -> Str.global_replace (Str.regexp "\"") "\\\""
    (Str.global_replace (Str.regexp "\\\\") "\\\\\\\\" s)
  | Float i -> String_.of_float i

let conll_string_of_value = function
  | String s -> s
  | Float i -> String_.of_float i

32 33
type disjunction = value list

bguillaum's avatar
bguillaum committed
34 35 36 37 38 39
let dot_color string =
  match (string.[0], String.length string) with
  | ('#', 4) -> sprintf "\"#%c%c%c%c%c%c\"" string.[1] string.[1] string.[2] string.[2] string.[3] string.[3]
  | ('#', 7) -> sprintf "\"%s\"" string
  | _ -> string

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
(* ================================================================================ *)
module Pid = struct
  (* type t = int *)
  type t = Pos of int | Neg of int

  let compare = Pervasives.compare

  let to_id = function
    | Pos i -> sprintf "p_%d" i
    | Neg i -> sprintf "n_%d" i

  let to_string = function
    | Pos i -> sprintf "Pos %d" i
    | Neg i -> sprintf "Neg %d" i
end (* module Pid *)

(* ================================================================================ *)
module Pid_map =
  struct
    include Map.Make (Pid)

    exception True

    let exists fct map =
      try
        iter
          (fun key value ->
            if fct key value
            then raise True
          ) map;
        false
      with True -> true

    (* union of two maps*)
    let union_map m m' = fold (fun k v m'' -> (add k v m'')) m m'
end (* module Pid_map *)

(* ================================================================================ *)
module Pid_set = Set.Make (Pid)

(* ================================================================================ *)
module Gid = struct
82
  type t = int
83

84
  let compare = Pervasives.compare
85

86
  let to_string i = sprintf "%d" i
87 88 89 90 91 92 93 94 95 96 97 98
end (* module Gid *)

(* ================================================================================ *)
module Gid_map = Map.Make (Gid)

(* ================================================================================ *)
module Massoc_gid = Massoc_make (Gid)

(* ================================================================================ *)
module Massoc_pid = Massoc_make (Pid)

(* ================================================================================ *)
bguillaum's avatar
bguillaum committed
99
module Label_domain = struct
100 101 102 103 104 105 106 107 108 109
  (** describe the display style of a label *)
  type line = Solid | Dot | Dash
  type style = {
    text: string;
    bottom: bool;
    color: string option;
    bgcolor: string option;
    line: line;
  }

bguillaum's avatar
bguillaum committed
110
  type t = string array * style array
111 112 113 114

  (** The [default] style value *)
  let default = { text="UNSET"; bottom=false; color=None; bgcolor=None; line=Solid }

bguillaum's avatar
bguillaum committed
115 116
  (** [decl] is the type for a label declaration: the name and a list of display styles *)
  type decl = string * string list
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

  (** Computes the style of a label from its options and maybe its shape (like I:...). *)
  let parse_option string_label options =
    let init_style = match Str.bounded_split (Str.regexp ":") string_label 2 with
      | ["S"; l] -> {default with text=l; color=Some "red"}
      | ["D"; l] -> {default with text=l; color=Some "blue"; bottom=true}
      | ["I"; l] -> {default with text=l; color=Some "grey"}
      | _ -> {default with text=string_label} in
      List.fold_left
        (fun acc_style -> function
            | "@bottom" -> {acc_style with bottom=true}
            | "@dash" -> {acc_style with line=Dash}
            | "@dot" -> {acc_style with line=Dot}
            | s when String.length s > 4 && String.sub s 0 4 = "@bg_" ->
              let color = String.sub s 4 ((String.length s) - 4) in
              {acc_style with bgcolor=Some color}
            | s -> {acc_style with color=Some (String_.rm_first_char s)}
        ) init_style options

136 137
  (* [build decl_list] returns a label_domain *)
  let build decl_list =
138 139 140
    let slist = List.sort (fun (x,_) (y,_) -> compare x y) decl_list in
    let (labels, opts) = List.split slist in
    let labels_array = Array.of_list labels in
141 142 143
    (labels_array, 
      Array.mapi (fun i opt -> parse_option labels_array.(i) opt) (Array.of_list opts)
    )
144

bguillaum's avatar
bguillaum committed
145
  let to_dep ?(deco=false) style =
146 147 148 149 150 151 152 153 154 155 156
    let dep_items =
      (if style.bottom then ["bottom"] else [])
      @ (match style.color with Some c -> ["color="^c; "forecolor="^c] | None -> [])
      @ (match style.bgcolor with Some c -> ["bgcolor="^c] | None -> [])
      @ (match style.line with
        | Dot -> ["style=dot"]
        | Dash -> ["style=dash"]
        | Solid when deco -> ["bgcolor=yellow"]
        | Solid -> []) in
    sprintf "{ label = \"%s\"; %s}" style.text (String.concat "; " dep_items)

bguillaum's avatar
bguillaum committed
157
  let to_dot ?(deco=false) style =
158
    let dot_items =
bguillaum's avatar
bguillaum committed
159
      (match style.color with Some c -> let d = dot_color c in ["color="^d; "fontcolor="^d] | None -> [])
160 161 162 163 164
      @ (match style.line with
        | Dot -> ["style=dotted"]
        | Dash -> ["style=dashed"]
        | Solid when deco -> ["style=dotted"]
        | Solid -> []) in
165
      sprintf "[label=\"%s\", %s]" style.text (String.concat ", " dot_items)
166

bguillaum's avatar
bguillaum committed
167 168
end

bguillaum's avatar
bguillaum committed
169
(* ================================================================================ *)
bguillaum's avatar
bguillaum committed
170
module Feature_domain = struct
bguillaum's avatar
bguillaum committed
171 172 173
  type feature_spec =
    | Closed of feature_name * feature_atom list (* cat:V,N *)
    | Open of feature_name (* phon, lemma, ... *)
bguillaum's avatar
bguillaum committed
174
    | Num of feature_name (* position *)
bguillaum's avatar
bguillaum committed
175

bguillaum's avatar
bguillaum committed
176
  type t = feature_spec list
bguillaum's avatar
bguillaum committed
177

bguillaum's avatar
bguillaum committed
178
  let is_defined feature_name feature_domain =
bguillaum's avatar
bguillaum committed
179 180 181
    List.exists (function
      | Closed (fn,_) when fn = feature_name -> true
      | Open fn when fn = feature_name -> true
bguillaum's avatar
bguillaum committed
182
      | Num fn when fn = feature_name -> true
bguillaum's avatar
bguillaum committed
183
      | _ -> false
bguillaum's avatar
bguillaum committed
184
    ) feature_domain
bguillaum's avatar
bguillaum committed
185

186 187
  let rec build = function
    | [] -> [Num "position"]
bguillaum's avatar
bguillaum committed
188
    | (Num "position") :: tail -> Log.warning "[Feature_domain] declaration of the feature name \"position\" in useless"; build tail
189 190
    | (Open "position") :: _
    | (Closed ("position",_)) :: _ ->
bguillaum's avatar
bguillaum committed
191
      Error.build "[Feature_domain] The feature named \"position\" is reserved and must be types 'integer', you cannot not redefine it"
192
    | (Num fn) :: tail | (Open fn) :: tail | Closed (fn,_) :: tail when is_defined fn tail ->
bguillaum's avatar
bguillaum committed
193
      Error.build "[Feature_domain] The feature named \"%s\" is defined several times" fn
194 195
    | x :: tail -> x :: (build tail)

bguillaum's avatar
bguillaum committed
196 197
  let feature_names feature_domain =
    List.map (function Closed (fn, _) | Open fn | Num fn -> fn) feature_domain
198

bguillaum's avatar
bguillaum committed
199
  let get feature_name feature_domain =
200 201 202 203 204
    List.find (function
      | Closed (fn,_) when fn = feature_name -> true
      | Open fn when fn = feature_name -> true
      | Num fn when fn = feature_name -> true
      | _ -> false
bguillaum's avatar
bguillaum committed
205
    ) feature_domain
206

bguillaum's avatar
bguillaum committed
207 208
  let sub feature_domain name1 name2 =
    match (get name1 feature_domain, get name2 feature_domain) with
209 210 211 212
        | (_, Open _) -> true
        | (Closed (_,l1), Closed (_,l2)) -> List_.sort_include l1 l2
        | (Num _, Num _) -> true
        | _ -> false
213

bguillaum's avatar
bguillaum committed
214 215
  let is_open feature_domain name =
    List.exists (function Open n when n=name -> true | _ -> false) feature_domain
216

217
  (* This function is defined here because it is used by check_feature *)
bguillaum's avatar
bguillaum committed
218
  let build_disj ?loc ?feature_domain name unsorted_values =
bguillaum's avatar
bguillaum committed
219
    let values = List.sort Pervasives.compare unsorted_values in
bguillaum's avatar
bguillaum committed
220 221 222 223
    match (feature_domain, name.[0]) with
      | (None, _)
      | (Some _, '_') -> List.map (fun s -> String s) values (* no check on feat_name starting with '_' *)
      | (Some dom, _) ->
bguillaum's avatar
bguillaum committed
224 225 226 227
        let rec loop = function
          | [] -> Error.build ?loc "[GRS] Unknown feature name '%s'" name
          | ((Open n)::_) when n = name ->
            List.map (fun s -> String s) values
bguillaum's avatar
bguillaum committed
228
          | ((Num n)::_) when n = name ->
bguillaum's avatar
bguillaum committed
229 230 231 232 233 234 235
            (try List.map (fun s -> Float (String_.to_float s)) values
            with Failure _ -> Error.build ?loc "[GRS] The feature '%s' is of type int" name)
          | ((Closed (n,vs))::_) when n = name ->
            (match List_.sort_diff values vs with
              | [] -> List.map (fun s -> String s) values
              | l when List.for_all (fun x -> x.[0] = '_') l -> List.map (fun s -> String s) values
              | l -> Error.build ?loc "Unknown feature values '%s' for feature name '%s'"
236
                  (List_.to_string (fun x->x) ", " l)
bguillaum's avatar
bguillaum committed
237 238 239
          name
            )
          | _::t -> loop t in
bguillaum's avatar
bguillaum committed
240
        loop dom
bguillaum's avatar
bguillaum committed
241

242 243 244 245 246 247 248 249 250 251 252 253
  let build_closed feature_name feature_values =
    let sorted_list = List.sort Pervasives.compare feature_values in
    let without_duplicate =
      let rec loop = function
        | [] -> []
        | x::y::tail when x=y ->
          Log.fwarning "In the declaration of the feature name \"%s\", the value \"%s\" appears more than once" feature_name x;
          loop (y::tail)
        | x::tail -> x:: (loop tail)
      in loop sorted_list in
    Closed (feature_name, without_duplicate)

bguillaum's avatar
bguillaum committed
254 255
  let check_feature ?loc ?feature_domain name value =
    ignore (build_disj ?loc ?feature_domain name [value])
bguillaum's avatar
bguillaum committed
256
end (* Feature_domain *)
bguillaum's avatar
bguillaum committed
257

258 259 260 261 262 263 264 265 266

(* ================================================================================ *)
module Domain = struct
  type t = Label_domain.t * Feature_domain.t

  let build ld fd = (ld, fd)

  let feature_names (_, feature_domain) = Feature_domain.feature_names feature_domain

bguillaum's avatar
bguillaum committed
267 268 269
  let is_open_feature ?domain name = match domain with
  | Some (_, feature_domain) -> Feature_domain.is_open feature_domain name
  | None -> true
270

bguillaum's avatar
bguillaum committed
271 272 273
  let check_feature ?loc ?domain name value = match domain with
  | Some (_, feature_domain) -> Feature_domain.check_feature ?loc ~feature_domain name value
  | None -> ()
274

bguillaum's avatar
bguillaum committed
275 276 277 278 279
  let check_feature_name ?loc ?domain name = match domain with
  | None -> ()
  | Some (_, feature_domain) ->
      if not (Feature_domain.is_defined name feature_domain)
      then Error.build ?loc "The feature name \"%s\" in not defined in the domain" name
280 281 282 283 284
end

(* ================================================================================ *)
module Label = struct
  (** Internal representation of labels *)
285 286
  type t = int

bguillaum's avatar
bguillaum committed
287 288 289 290
  (* a array for no label not defined in a domain (no more than 100 labels!) *)
  let no_domain = Array.make 100 ""
  let no_domain_size = ref 0

291 292
  let match_list p_label_list g_label = List.exists (fun p_label -> p_label = g_label) p_label_list

bguillaum's avatar
bguillaum committed
293 294 295 296 297
  let to_string ?domain i =
    match domain with 
    | Some ((table,_),_) -> table.(i)
    | None when i < !no_domain_size -> no_domain.(i)
    | _ -> Log.bug "Inconsistency in [Label.to_string]"; exit 1
298

bguillaum's avatar
bguillaum committed
299 300
  let get_style ?domain i = match domain with
    | Some ((_,styles),_) -> styles.(i)
301
    | None -> Label_domain.parse_option no_domain.(i) []
302

bguillaum's avatar
bguillaum committed
303 304
  let is_void ?domain t =
    let style = get_style ?domain t in
305 306
    style.Label_domain.text = "void"

bguillaum's avatar
bguillaum committed
307 308
  let to_dep ?domain ?(deco=false) t =
    let style = get_style ?domain t in
309 310
    Label_domain.to_dep ~deco style

bguillaum's avatar
bguillaum committed
311 312
  let to_dot ?domain ?(deco=false) t =
    let style = get_style ?domain t in
313 314
    Label_domain.to_dot ~deco style

bguillaum's avatar
bguillaum committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  let from_string ?loc ?domain ?(locals=[||]) str = match domain with
    | Some ((table,_),_) ->
      begin
        try Id.build ?loc str table
        with Not_found -> Error.build "[Label.from_string] unknown edge label '%s'" str
      end
    | None ->
      let rec loop = function
        | 100 -> Log.bug "[Label.from_string] you cannot use more than 100 diff label without domain"; exit 1
        | i when i >= !no_domain_size ->
          no_domain.(i) <- str;
          incr no_domain_size;
          i
        | i when no_domain.(i) = str -> i
        | i -> loop (i+1) in
      loop 0
331 332 333 334 335
end (* module Label *)


(* ================================================================================ *)
module Feature_value = struct
bguillaum's avatar
bguillaum committed
336 337 338
  let build_disj ?loc ?domain name unsorted_values = match domain with
  | Some (_, feature_domain) -> Feature_domain.build_disj ?loc ~feature_domain name unsorted_values
  | None -> Feature_domain.build_disj ?loc name unsorted_values
339

bguillaum's avatar
bguillaum committed
340 341
  let build_value ?loc ?domain name value =
    match build_disj ?loc ?domain name [value] with
342 343 344 345
      | [x] -> x
      | _ -> Error.bug ?loc "[Feature_value.build_value]"
end (* module Feature_value *)

346 347 348 349 350 351 352 353
(* ================================================================================ *)
(* This module defines a type for lexical parameter (i.e. one line in a lexical file) *)
module Lex_par = struct

  type item = string list * string list (* first list: pattern parameters $id , second list command parameters @id *)

  type t = item list

bguillaum's avatar
bguillaum committed
354
  let size = List.length
355 356
  let append = List.append

bguillaum's avatar
bguillaum committed
357 358 359 360
  let signature = function
    | [] -> Error.bug "[Lex_par.signature] empty data"
    | (pp,cp)::_ -> (List.length pp,List.length cp)

361 362 363 364 365 366 367 368 369
  let dump t =
    printf "[Lex_par.dump] --> size = %d\n" (List.length t);
    List.iter (fun (pp,cp) ->
      printf "%s##%s\n"
        (String.concat "#" pp)
        (String.concat "#" cp)
    ) t

  let parse_line ?loc nb_p nb_c line =
bguillaum's avatar
bguillaum committed
370
    let line = String_.rm_peripheral_white line in
371 372 373
    if line = "" || line.[0] = '%'
    then None
    else
374
      let line = Str.global_replace (Str.regexp "\\\\%") "%" line in
375 376 377 378
      match Str.split (Str.regexp "##") line with
        | [args] when nb_c = 0 ->
          (match Str.split (Str.regexp "#") args with
            | l when List.length l = nb_p -> Some (l,[])
bguillaum's avatar
bguillaum committed
379
            | _ -> Error.build ?loc
380 381 382 383 384
              "Illegal lexical parameter line: \"%s\" doesn't contain %d args"
              line nb_p)
        | [args; values] ->
          (match (Str.split (Str.regexp "#") args, Str.split (Str.regexp "#") values) with
            | (lp,lc) when List.length lp = nb_p && List.length lc = nb_c -> Some (lp,lc)
bguillaum's avatar
bguillaum committed
385
            | _ -> Error.build ?loc
386 387
              "Illegal lexical parameter line: \"%s\" doesn't contain %d args and %d values"
              line nb_p nb_c)
bguillaum's avatar
bguillaum committed
388
        | _ -> Error.build ?loc "Illegal param line: '%s'" line
389

bguillaum's avatar
bguillaum committed
390 391 392 393
  let from_lines ?loc nb_p nb_c lines =
    match List_.opt_map (parse_line ?loc nb_p nb_c) lines with
    | [] -> Error.build ?loc "Empty lexical parameter list"
    | l -> l
394 395 396 397 398 399 400 401

  let load ?loc dir nb_p nb_c file =
    try
      let full_file =
        if Filename.is_relative file
        then Filename.concat dir file
        else file in
      let lines = File.read full_file in
bguillaum's avatar
bguillaum committed
402 403 404
      match List_.opt_mapi (fun i line -> parse_line ~loc:(Loc.file_line full_file i) nb_p nb_c line) lines with
      | [] -> Error.build ?loc "Empty lexical parameter file '%s'" file
      | l -> l
405 406
    with Sys_error _ -> Error.build ?loc "External lexical file '%s' not found" file

bguillaum's avatar
bguillaum committed
407
  let select index atom t =
408 409 410 411
    match
      List_.opt_map
        (fun (p_par, c_par) ->
          let par = List.nth p_par index in
bguillaum's avatar
bguillaum committed
412
          if atom = par
413
          then Some (p_par, c_par)
bguillaum's avatar
bguillaum committed
414
          else None
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        ) t
    with
    | [] -> None
    | t -> Some t

  let get_param_value index = function
    | [] -> Error.bug "[Lex_par.get_command_value] empty parameter"
    | (params,_)::_ -> List.nth params index

  let get_command_value index = function
    | [(_,one)] -> List.nth one index
    | [] -> Error.bug "[Lex_par.get_command_value] empty parameter"
    | (_,[sing])::tail when index=0 ->
        Printf.sprintf "%s/%s"
          sing
          (List_.to_string
             (function
               | (_,[s]) -> s
               | _ -> Error.bug "[Lex_par.get_command_value] inconsistent param"
             ) "/" tail
          )
    | l -> Error.run "Lexical parameter are not functionnal"
end (* module Lex_par *)
bguillaum's avatar
bguillaum committed
438 439 440 441 442 443 444 445

(* ================================================================================ *)
module Concat_item = struct
  type t =
    | Feat of (Gid.t * feature_name)
    | String of string
end (* module Concat_item *)

bguillaum's avatar
bguillaum committed
446 447 448 449 450 451 452 453
(* ================================================================================ *)
module Strategy = struct
  type def =
    | Ref of string
    | Seq of def list   (* /!\ The list must not be empty *)
    | Plus of def list  (* /!\ The list must not be empty *)
    | Star of def
    | Diamond of def
454
    | Sequence of string list (* compatibility mode with old code *)
bguillaum's avatar
bguillaum committed
455 456 457 458 459 460 461 462 463 464 465 466 467 468

  type t = {
    name:string;
    def:def;
    doc:string list;
    loc:Loc.t;
  }

  let rec to_string = function
  | Ref m -> m
  | Seq l -> "[" ^ (String.concat "; " (List.map to_string l)) ^ "]"
  | Plus l -> "[" ^ (String.concat "+" (List.map to_string l)) ^ "]"
  | Star s -> "[" ^ (to_string s) ^"]"  ^ "*"
  | Diamond s -> "◇" ^ "[" ^(to_string s)^"]"
469
  | Sequence names -> "{" ^ (String.concat ";" names) ^ "}"
bguillaum's avatar
bguillaum committed
470 471 472

  (* invariant: Seq list and Plus list are not empty in the input and so not empty in the output *)
  let rec flatten = function
473
  | Sequence l -> Sequence l
bguillaum's avatar
bguillaum committed
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  | Ref m -> Ref m
  | Star s -> Star (flatten s)
  | Diamond s -> Diamond (flatten s)
  | Seq l ->
    let fl = List.map flatten l in
    let rec loop = function
    | [] -> []
    | (Seq l) :: tail -> l @ (loop tail)
    | x :: tail -> x :: (loop tail)
    in Seq (loop fl)
  | Plus l ->
    let fl = List.map flatten l in
    let rec loop = function
    | [] -> []
    | (Plus l) :: tail -> l @ (loop tail)
    | x :: tail -> x :: (loop tail)
    in Plus (loop fl)
end (* module Strategy *)