package catala

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file html.ml

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
(* This file is part of the Catala compiler, a specification language for tax and social benefits
   computation rules. Copyright (C) 2020 Inria, contributor: Denis Merigoux
   <denis.merigoux@inria.fr>

   Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
   in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software distributed under the License
   is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
   or implied. See the License for the specific language governing permissions and limitations under
   the License. *)

(** This modules weaves the source code and the legislative text together into a document that law
    professionals can understand. *)

module Pos = Utils.Pos
module Cli = Utils.Cli
module Errors = Utils.Errors
module A = Surface.Ast
module P = Printf
module R = Re.Pcre
module C = Cli

(** {1 Helpers} *)

(** Converts double lines into HTML newlines. *)
let pre_html (s : string) =
  let s = String.trim s in
  let doublenewline = R.regexp "\n\n" in
  let s = R.substitute ~rex:doublenewline ~subst:(fun _ -> "<br/>\n") s in
  s

(** Raise an error if pygments cannot be found *)
let raise_failed_pygments (command : string) (error_code : int) : 'a =
  Errors.raise_error
    (Printf.sprintf "Weaving to HTML failed: pygmentize command \"%s\" returned with error code %d"
       command error_code)

(** Usage: [wrap_html source_files custom_pygments language fmt wrapped]

    Prints an HTML complete page structure around the [wrapped] content. *)
let wrap_html (source_files : string list) (custom_pygments : string option)
    (language : Cli.backend_lang) (fmt : Format.formatter) (wrapped : Format.formatter -> unit) :
    unit =
  let pygments = match custom_pygments with Some p -> p | None -> "pygmentize" in
  let css_file = Filename.temp_file "catala_css_pygments" "" in
  let pygments_args = [| "-f"; "html"; "-S"; "colorful"; "-a"; ".catala-code" |] in
  let cmd =
    Format.sprintf "%s %s > %s" pygments (String.concat " " (Array.to_list pygments_args)) css_file
  in
  let return_code = Sys.command cmd in
  if return_code <> 0 then raise_failed_pygments cmd return_code;
  let oc = open_in css_file in
  let css_as_string = really_input_string oc (in_channel_length oc) in
  close_in oc;
  Format.fprintf fmt
    "<head>\n\
     <style>\n\
     %s\n\
     </style>\n\
     <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>\n\
     </head>\n\
     <h1>%s<br />\n\
     <small>%s Catala version %s</small>\n\
     </h1>\n\
     <p>\n\
     %s\n\
     </p>\n\
     <ul>\n\
     %s\n\
     </ul>\n"
    css_as_string
    ( match language with
    | `Fr -> "Implémentation de texte législatif"
    | `En -> "Legislative text implementation" )
    (match language with `Fr -> "Document généré par" | `En -> "Document generated by")
    ( match Build_info.V1.version () with
    | None -> "n/a"
    | Some v -> Build_info.V1.Version.to_string v )
    ( match language with
    | `Fr -> "Fichiers sources tissés dans ce document"
    | `En -> "Source files weaved in this document" )
    (String.concat "\n"
       (List.map
          (fun filename ->
            let mtime = (Unix.stat filename).Unix.st_mtime in
            let ltime = Unix.localtime mtime in
            let ftime =
              Printf.sprintf "%d-%02d-%02d, %d:%02d" (1900 + ltime.Unix.tm_year)
                (ltime.Unix.tm_mon + 1) ltime.Unix.tm_mday ltime.Unix.tm_hour ltime.Unix.tm_min
            in
            Printf.sprintf "<li><tt>%s</tt>, %s %s</li>"
              (pre_html (Filename.basename filename))
              (match language with `Fr -> "dernière modification le" | `En -> "last modification")
              ftime)
          source_files));
  wrapped fmt

(** Performs syntax highlighting on a piece of code by using Pygments and the special Catala lexer. *)
let pygmentize_code (c : string Pos.marked) (language : C.backend_lang)
    (custom_pygments : string option) : string =
  C.debug_print (Printf.sprintf "Pygmenting the code chunk %s" (Pos.to_string (Pos.get_position c)));
  let temp_file_in = Filename.temp_file "catala_html_pygments" "in" in
  let temp_file_out = Filename.temp_file "catala_html_pygments" "out" in
  let oc = open_out temp_file_in in
  Printf.fprintf oc "%s" (Pos.unmark c);
  close_out oc;
  let pygments = match custom_pygments with Some p -> p | None -> "pygmentize" in
  let pygments_lexer = match language with `Fr -> "catala_fr" | `En -> "catala_en" in
  let pygments_args =
    [|
      "-l";
      pygments_lexer;
      "-f";
      "html";
      "-O";
      "style=colorful,anchorlinenos=True,lineanchors=\""
      ^ Pos.get_file (Pos.get_position c)
      ^ "\",linenos=table,linenostart="
      ^ string_of_int (Pos.get_start_line (Pos.get_position c));
      "-o";
      temp_file_out;
      temp_file_in;
    |]
  in
  let cmd = Format.asprintf "%s %s" pygments (String.concat " " (Array.to_list pygments_args)) in
  let return_code = Sys.command cmd in
  if return_code <> 0 then raise_failed_pygments cmd return_code;
  let oc = open_in temp_file_out in
  let output = really_input_string oc (in_channel_length oc) in
  close_in oc;
  output

(** {1 Weaving} *)

let law_article_item_to_html (custom_pygments : string option) (language : C.backend_lang)
    (fmt : Format.formatter) (i : A.law_article_item) : unit =
  match i with
  | A.LawText t ->
      let t = pre_html t in
      if t = "" then () else Format.fprintf fmt "<p class='law-text'>%s</p>" t
  | A.CodeBlock (_, c) ->
      let date = "\\d\\d/\\d\\d/\\d\\d\\d\\d" in
      let syms = R.regexp (date ^ "|!=|<=|>=|--|->|\\*|\\/") in
      let syms_subst = function
        | "!=" -> "≠"
        | "<=" -> "≤"
        | ">=" -> "≥"
        | "--" -> "—"
        | "->" -> "→"
        | "*" -> "×"
        | "/" -> "÷"
        | s -> s
      in
      let pprinted_c = R.substitute ~rex:syms ~subst:syms_subst (Pos.unmark c) in
      Format.fprintf fmt "<div class='code-wrapper'>\n<div class='filename'>%s</div>\n%s\n</div>"
        (Pos.get_file (Pos.get_position c))
        (pygmentize_code (Pos.same_pos_as ("/*" ^ pprinted_c ^ "*/") c) language custom_pygments)

let rec law_structure_to_html (custom_pygments : string option) (language : C.backend_lang)
    (fmt : Format.formatter) (i : A.law_structure) : unit =
  match i with
  | A.LawHeading (heading, children) ->
      let h_number = heading.law_heading_precedence + 2 in
      Format.fprintf fmt "<h%d class='law-heading'>%s</h%d>\n" h_number
        (pre_html heading.law_heading_name)
        h_number;
      Format.pp_print_list
        ~pp_sep:(fun fmt () -> Format.fprintf fmt "\n")
        (law_structure_to_html custom_pygments language)
        fmt children
  | A.LawInclude _ -> ()
  | A.LawArticle (a, children) ->
      Format.fprintf fmt
        "<div class='article-container'>\n\n<div class='article-title'><a href='%s'>%s</a></div>\n"
        ( match (a.law_article_id, language) with
        | Some id, `Fr ->
            let ltime = Unix.localtime (Unix.time ()) in
            P.sprintf "https://legifrance.gouv.fr/codes/id/%s/%d-%02d-%02d" id
              (1900 + ltime.Unix.tm_year) (ltime.Unix.tm_mon + 1) ltime.Unix.tm_mday
        | _ -> "#" )
        (pre_html (Pos.unmark a.law_article_name));
      Format.pp_print_list
        ~pp_sep:(fun fmt () -> Format.fprintf fmt "\n")
        (law_article_item_to_html custom_pygments language)
        fmt children;
      Format.fprintf fmt "\n</div>"
  | A.MetadataBlock (b, c) ->
      law_article_item_to_html custom_pygments language fmt (A.CodeBlock (b, c))
  | A.IntermediateText t ->
      let t = pre_html t in
      if t = "" then () else Format.fprintf fmt "<p class='law-text'>%s</p>" t

let program_item_to_html (custom_pygments : string option) (language : C.backend_lang)
    (fmt : Format.formatter) (i : A.program_item) : unit =
  match i with A.LawStructure s -> law_structure_to_html custom_pygments language fmt s

(** {1 API} *)

let ast_to_html (custom_pygments : string option) (language : C.backend_lang)
    (fmt : Format.formatter) (program : A.program) : unit =
  Format.pp_print_list
    ~pp_sep:(fun fmt () -> Format.fprintf fmt "\n\n")
    (program_item_to_html custom_pygments language)
    fmt program.program_items
OCaml

Innovation. Community. Security.